From dc53086c1e73d43d3a28fc4cdf161e83d09b1877 Mon Sep 17 00:00:00 2001 From: Adam <2363879+adamdotdevin@users.noreply.github.com> Date: Mon, 9 Feb 2026 11:34:35 -0600 Subject: wip(docs): i18n (#12681) --- packages/web/src/content/docs/ar/1-0.mdx | 67 + packages/web/src/content/docs/ar/acp.mdx | 154 ++ packages/web/src/content/docs/ar/agents.mdx | 746 ++++++ packages/web/src/content/docs/ar/cli.mdx | 601 +++++ packages/web/src/content/docs/ar/commands.mdx | 322 +++ packages/web/src/content/docs/ar/config.mdx | 684 ++++++ packages/web/src/content/docs/ar/custom-tools.mdx | 162 ++ packages/web/src/content/docs/ar/ecosystem.mdx | 73 + packages/web/src/content/docs/ar/enterprise.mdx | 165 ++ packages/web/src/content/docs/ar/formatters.mdx | 130 ++ packages/web/src/content/docs/ar/github.mdx | 321 +++ packages/web/src/content/docs/ar/gitlab.mdx | 195 ++ packages/web/src/content/docs/ar/ide.mdx | 48 + packages/web/src/content/docs/ar/index.mdx | 343 +++ packages/web/src/content/docs/ar/keybinds.mdx | 192 ++ packages/web/src/content/docs/ar/lsp.mdx | 188 ++ packages/web/src/content/docs/ar/mcp-servers.mdx | 492 ++++ packages/web/src/content/docs/ar/models.mdx | 222 ++ packages/web/src/content/docs/ar/modes.mdx | 331 +++ packages/web/src/content/docs/ar/network.mdx | 57 + packages/web/src/content/docs/ar/permissions.mdx | 227 ++ packages/web/src/content/docs/ar/plugins.mdx | 385 ++++ packages/web/src/content/docs/ar/providers.mdx | 1863 +++++++++++++++ packages/web/src/content/docs/ar/rules.mdx | 180 ++ packages/web/src/content/docs/ar/sdk.mdx | 391 ++++ packages/web/src/content/docs/ar/server.mdx | 287 +++ packages/web/src/content/docs/ar/share.mdx | 127 ++ packages/web/src/content/docs/ar/skills.mdx | 222 ++ packages/web/src/content/docs/ar/themes.mdx | 369 +++ packages/web/src/content/docs/ar/tools.mdx | 379 +++ .../web/src/content/docs/ar/troubleshooting.mdx | 299 +++ packages/web/src/content/docs/ar/tui.mdx | 386 ++++ packages/web/src/content/docs/ar/web.mdx | 142 ++ packages/web/src/content/docs/ar/windows-wsl.mdx | 113 + packages/web/src/content/docs/ar/zen.mdx | 243 ++ packages/web/src/content/docs/bs/1-0.mdx | 54 + packages/web/src/content/docs/bs/acp.mdx | 156 ++ packages/web/src/content/docs/bs/agents.mdx | 651 ++++++ packages/web/src/content/docs/bs/cli.mdx | 540 +++++ packages/web/src/content/docs/bs/commands.mdx | 299 +++ packages/web/src/content/docs/bs/config.mdx | 657 ++++++ packages/web/src/content/docs/bs/custom-tools.mdx | 160 ++ packages/web/src/content/docs/bs/ecosystem.mdx | 66 + packages/web/src/content/docs/bs/enterprise.mdx | 165 ++ packages/web/src/content/docs/bs/formatters.mdx | 115 + packages/web/src/content/docs/bs/github.mdx | 305 +++ packages/web/src/content/docs/bs/gitlab.mdx | 194 ++ packages/web/src/content/docs/bs/ide.mdx | 41 + packages/web/src/content/docs/bs/index.mdx | 360 +++ packages/web/src/content/docs/bs/keybinds.mdx | 182 ++ packages/web/src/content/docs/bs/lsp.mdx | 160 ++ packages/web/src/content/docs/bs/mcp-servers.mdx | 432 ++++ packages/web/src/content/docs/bs/models.mdx | 186 ++ packages/web/src/content/docs/bs/modes.mdx | 283 +++ packages/web/src/content/docs/bs/network.mdx | 48 + packages/web/src/content/docs/bs/permissions.mdx | 201 ++ packages/web/src/content/docs/bs/plugins.mdx | 309 +++ packages/web/src/content/docs/bs/providers.mdx | 2413 ++++++++++++++++++++ packages/web/src/content/docs/bs/rules.mdx | 180 ++ packages/web/src/content/docs/bs/sdk.mdx | 391 ++++ packages/web/src/content/docs/bs/server.mdx | 284 +++ packages/web/src/content/docs/bs/share.mdx | 127 ++ packages/web/src/content/docs/bs/skills.mdx | 222 ++ packages/web/src/content/docs/bs/themes.mdx | 369 +++ packages/web/src/content/docs/bs/tools.mdx | 379 +++ .../web/src/content/docs/bs/troubleshooting.mdx | 308 +++ packages/web/src/content/docs/bs/tui.mdx | 402 ++++ packages/web/src/content/docs/bs/web.mdx | 142 ++ packages/web/src/content/docs/bs/windows-wsl.mdx | 113 + packages/web/src/content/docs/bs/zen.mdx | 236 ++ packages/web/src/content/docs/da/1-0.mdx | 67 + packages/web/src/content/docs/da/acp.mdx | 156 ++ packages/web/src/content/docs/da/agents.mdx | 747 ++++++ packages/web/src/content/docs/da/cli.mdx | 601 +++++ packages/web/src/content/docs/da/commands.mdx | 323 +++ packages/web/src/content/docs/da/config.mdx | 685 ++++++ packages/web/src/content/docs/da/custom-tools.mdx | 170 ++ packages/web/src/content/docs/da/ecosystem.mdx | 76 + packages/web/src/content/docs/da/enterprise.mdx | 170 ++ packages/web/src/content/docs/da/formatters.mdx | 130 ++ packages/web/src/content/docs/da/github.mdx | 321 +++ packages/web/src/content/docs/da/gitlab.mdx | 195 ++ packages/web/src/content/docs/da/ide.mdx | 48 + packages/web/src/content/docs/da/index.mdx | 359 +++ packages/web/src/content/docs/da/keybinds.mdx | 192 ++ packages/web/src/content/docs/da/lsp.mdx | 188 ++ packages/web/src/content/docs/da/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/da/models.mdx | 223 ++ packages/web/src/content/docs/da/modes.mdx | 331 +++ packages/web/src/content/docs/da/network.mdx | 57 + packages/web/src/content/docs/da/permissions.mdx | 237 ++ packages/web/src/content/docs/da/plugins.mdx | 385 ++++ packages/web/src/content/docs/da/providers.mdx | 1889 +++++++++++++++ packages/web/src/content/docs/da/rules.mdx | 180 ++ packages/web/src/content/docs/da/sdk.mdx | 391 ++++ packages/web/src/content/docs/da/server.mdx | 287 +++ packages/web/src/content/docs/da/share.mdx | 128 ++ packages/web/src/content/docs/da/skills.mdx | 222 ++ packages/web/src/content/docs/da/themes.mdx | 369 +++ packages/web/src/content/docs/da/tools.mdx | 379 +++ .../web/src/content/docs/da/troubleshooting.mdx | 300 +++ packages/web/src/content/docs/da/tui.mdx | 390 ++++ packages/web/src/content/docs/da/web.mdx | 142 ++ packages/web/src/content/docs/da/windows-wsl.mdx | 113 + packages/web/src/content/docs/da/zen.mdx | 254 +++ packages/web/src/content/docs/de/1-0.mdx | 67 + packages/web/src/content/docs/de/acp.mdx | 156 ++ packages/web/src/content/docs/de/agents.mdx | 747 ++++++ packages/web/src/content/docs/de/cli.mdx | 601 +++++ packages/web/src/content/docs/de/commands.mdx | 323 +++ packages/web/src/content/docs/de/config.mdx | 685 ++++++ packages/web/src/content/docs/de/custom-tools.mdx | 170 ++ packages/web/src/content/docs/de/ecosystem.mdx | 76 + packages/web/src/content/docs/de/enterprise.mdx | 170 ++ packages/web/src/content/docs/de/formatters.mdx | 130 ++ packages/web/src/content/docs/de/github.mdx | 321 +++ packages/web/src/content/docs/de/gitlab.mdx | 195 ++ packages/web/src/content/docs/de/ide.mdx | 48 + packages/web/src/content/docs/de/index.mdx | 359 +++ packages/web/src/content/docs/de/keybinds.mdx | 192 ++ packages/web/src/content/docs/de/lsp.mdx | 188 ++ packages/web/src/content/docs/de/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/de/models.mdx | 223 ++ packages/web/src/content/docs/de/modes.mdx | 331 +++ packages/web/src/content/docs/de/network.mdx | 57 + packages/web/src/content/docs/de/permissions.mdx | 237 ++ packages/web/src/content/docs/de/plugins.mdx | 385 ++++ packages/web/src/content/docs/de/providers.mdx | 1889 +++++++++++++++ packages/web/src/content/docs/de/rules.mdx | 190 ++ packages/web/src/content/docs/de/sdk.mdx | 393 ++++ packages/web/src/content/docs/de/server.mdx | 291 +++ packages/web/src/content/docs/de/share.mdx | 130 ++ packages/web/src/content/docs/de/skills.mdx | 222 ++ packages/web/src/content/docs/de/themes.mdx | 372 +++ packages/web/src/content/docs/de/tools.mdx | 390 ++++ .../web/src/content/docs/de/troubleshooting.mdx | 301 +++ packages/web/src/content/docs/de/tui.mdx | 393 ++++ packages/web/src/content/docs/de/web.mdx | 142 ++ packages/web/src/content/docs/de/windows-wsl.mdx | 115 + packages/web/src/content/docs/de/zen.mdx | 247 ++ packages/web/src/content/docs/es/1-0.mdx | 67 + packages/web/src/content/docs/es/acp.mdx | 156 ++ packages/web/src/content/docs/es/agents.mdx | 747 ++++++ packages/web/src/content/docs/es/cli.mdx | 601 +++++ packages/web/src/content/docs/es/commands.mdx | 323 +++ packages/web/src/content/docs/es/config.mdx | 685 ++++++ packages/web/src/content/docs/es/custom-tools.mdx | 170 ++ packages/web/src/content/docs/es/ecosystem.mdx | 76 + packages/web/src/content/docs/es/enterprise.mdx | 170 ++ packages/web/src/content/docs/es/formatters.mdx | 130 ++ packages/web/src/content/docs/es/github.mdx | 321 +++ packages/web/src/content/docs/es/gitlab.mdx | 195 ++ packages/web/src/content/docs/es/ide.mdx | 48 + packages/web/src/content/docs/es/index.mdx | 359 +++ packages/web/src/content/docs/es/keybinds.mdx | 192 ++ packages/web/src/content/docs/es/lsp.mdx | 188 ++ packages/web/src/content/docs/es/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/es/models.mdx | 223 ++ packages/web/src/content/docs/es/modes.mdx | 331 +++ packages/web/src/content/docs/es/network.mdx | 57 + packages/web/src/content/docs/es/permissions.mdx | 237 ++ packages/web/src/content/docs/es/plugins.mdx | 385 ++++ packages/web/src/content/docs/es/providers.mdx | 1889 +++++++++++++++ packages/web/src/content/docs/es/rules.mdx | 180 ++ packages/web/src/content/docs/es/sdk.mdx | 391 ++++ packages/web/src/content/docs/es/server.mdx | 287 +++ packages/web/src/content/docs/es/share.mdx | 128 ++ packages/web/src/content/docs/es/skills.mdx | 222 ++ packages/web/src/content/docs/es/themes.mdx | 369 +++ packages/web/src/content/docs/es/tools.mdx | 379 +++ .../web/src/content/docs/es/troubleshooting.mdx | 300 +++ packages/web/src/content/docs/es/tui.mdx | 390 ++++ packages/web/src/content/docs/es/web.mdx | 142 ++ packages/web/src/content/docs/es/windows-wsl.mdx | 113 + packages/web/src/content/docs/es/zen.mdx | 254 +++ packages/web/src/content/docs/fr/1-0.mdx | 67 + packages/web/src/content/docs/fr/acp.mdx | 156 ++ packages/web/src/content/docs/fr/agents.mdx | 747 ++++++ packages/web/src/content/docs/fr/cli.mdx | 601 +++++ packages/web/src/content/docs/fr/commands.mdx | 323 +++ packages/web/src/content/docs/fr/config.mdx | 685 ++++++ packages/web/src/content/docs/fr/custom-tools.mdx | 170 ++ packages/web/src/content/docs/fr/ecosystem.mdx | 76 + packages/web/src/content/docs/fr/enterprise.mdx | 170 ++ packages/web/src/content/docs/fr/formatters.mdx | 130 ++ packages/web/src/content/docs/fr/github.mdx | 321 +++ packages/web/src/content/docs/fr/gitlab.mdx | 195 ++ packages/web/src/content/docs/fr/ide.mdx | 48 + packages/web/src/content/docs/fr/index.mdx | 359 +++ packages/web/src/content/docs/fr/keybinds.mdx | 192 ++ packages/web/src/content/docs/fr/lsp.mdx | 188 ++ packages/web/src/content/docs/fr/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/fr/models.mdx | 223 ++ packages/web/src/content/docs/fr/modes.mdx | 331 +++ packages/web/src/content/docs/fr/network.mdx | 57 + packages/web/src/content/docs/fr/permissions.mdx | 237 ++ packages/web/src/content/docs/fr/plugins.mdx | 385 ++++ packages/web/src/content/docs/fr/providers.mdx | 1895 +++++++++++++++ packages/web/src/content/docs/fr/rules.mdx | 180 ++ packages/web/src/content/docs/fr/sdk.mdx | 391 ++++ packages/web/src/content/docs/fr/server.mdx | 287 +++ packages/web/src/content/docs/fr/share.mdx | 128 ++ packages/web/src/content/docs/fr/skills.mdx | 222 ++ packages/web/src/content/docs/fr/themes.mdx | 369 +++ packages/web/src/content/docs/fr/tools.mdx | 379 +++ .../web/src/content/docs/fr/troubleshooting.mdx | 300 +++ packages/web/src/content/docs/fr/tui.mdx | 390 ++++ packages/web/src/content/docs/fr/web.mdx | 142 ++ packages/web/src/content/docs/fr/windows-wsl.mdx | 113 + packages/web/src/content/docs/fr/zen.mdx | 254 +++ packages/web/src/content/docs/it/1-0.mdx | 67 + packages/web/src/content/docs/it/acp.mdx | 156 ++ packages/web/src/content/docs/it/agents.mdx | 746 ++++++ packages/web/src/content/docs/it/cli.mdx | 601 +++++ packages/web/src/content/docs/it/commands.mdx | 322 +++ packages/web/src/content/docs/it/config.mdx | 681 ++++++ packages/web/src/content/docs/it/custom-tools.mdx | 170 ++ packages/web/src/content/docs/it/ecosystem.mdx | 76 + packages/web/src/content/docs/it/enterprise.mdx | 165 ++ packages/web/src/content/docs/it/formatters.mdx | 130 ++ packages/web/src/content/docs/it/github.mdx | 321 +++ packages/web/src/content/docs/it/gitlab.mdx | 195 ++ packages/web/src/content/docs/it/ide.mdx | 48 + packages/web/src/content/docs/it/index.mdx | 343 +++ packages/web/src/content/docs/it/keybinds.mdx | 192 ++ packages/web/src/content/docs/it/lsp.mdx | 188 ++ packages/web/src/content/docs/it/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/it/models.mdx | 222 ++ packages/web/src/content/docs/it/modes.mdx | 330 +++ packages/web/src/content/docs/it/network.mdx | 57 + packages/web/src/content/docs/it/permissions.mdx | 237 ++ packages/web/src/content/docs/it/plugins.mdx | 384 ++++ packages/web/src/content/docs/it/providers.mdx | 1888 +++++++++++++++ packages/web/src/content/docs/it/rules.mdx | 180 ++ packages/web/src/content/docs/it/sdk.mdx | 391 ++++ packages/web/src/content/docs/it/server.mdx | 284 +++ packages/web/src/content/docs/it/share.mdx | 127 ++ packages/web/src/content/docs/it/skills.mdx | 222 ++ packages/web/src/content/docs/it/themes.mdx | 369 +++ packages/web/src/content/docs/it/tools.mdx | 379 +++ .../web/src/content/docs/it/troubleshooting.mdx | 299 +++ packages/web/src/content/docs/it/tui.mdx | 387 ++++ packages/web/src/content/docs/it/web.mdx | 142 ++ packages/web/src/content/docs/it/windows-wsl.mdx | 113 + packages/web/src/content/docs/it/zen.mdx | 236 ++ packages/web/src/content/docs/ja/1-0.mdx | 67 + packages/web/src/content/docs/ja/acp.mdx | 156 ++ packages/web/src/content/docs/ja/agents.mdx | 747 ++++++ packages/web/src/content/docs/ja/cli.mdx | 601 +++++ packages/web/src/content/docs/ja/commands.mdx | 323 +++ packages/web/src/content/docs/ja/config.mdx | 685 ++++++ packages/web/src/content/docs/ja/custom-tools.mdx | 170 ++ packages/web/src/content/docs/ja/ecosystem.mdx | 76 + packages/web/src/content/docs/ja/enterprise.mdx | 170 ++ packages/web/src/content/docs/ja/formatters.mdx | 130 ++ packages/web/src/content/docs/ja/github.mdx | 321 +++ packages/web/src/content/docs/ja/gitlab.mdx | 195 ++ packages/web/src/content/docs/ja/ide.mdx | 48 + packages/web/src/content/docs/ja/index.mdx | 359 +++ packages/web/src/content/docs/ja/keybinds.mdx | 192 ++ packages/web/src/content/docs/ja/lsp.mdx | 188 ++ packages/web/src/content/docs/ja/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/ja/models.mdx | 223 ++ packages/web/src/content/docs/ja/modes.mdx | 331 +++ packages/web/src/content/docs/ja/network.mdx | 57 + packages/web/src/content/docs/ja/permissions.mdx | 237 ++ packages/web/src/content/docs/ja/plugins.mdx | 385 ++++ packages/web/src/content/docs/ja/providers.mdx | 1895 +++++++++++++++ packages/web/src/content/docs/ja/rules.mdx | 180 ++ packages/web/src/content/docs/ja/sdk.mdx | 391 ++++ packages/web/src/content/docs/ja/server.mdx | 287 +++ packages/web/src/content/docs/ja/share.mdx | 128 ++ packages/web/src/content/docs/ja/skills.mdx | 222 ++ packages/web/src/content/docs/ja/themes.mdx | 369 +++ packages/web/src/content/docs/ja/tools.mdx | 379 +++ .../web/src/content/docs/ja/troubleshooting.mdx | 300 +++ packages/web/src/content/docs/ja/tui.mdx | 390 ++++ packages/web/src/content/docs/ja/web.mdx | 142 ++ packages/web/src/content/docs/ja/windows-wsl.mdx | 119 + packages/web/src/content/docs/ja/zen.mdx | 254 +++ packages/web/src/content/docs/ko/1-0.mdx | 67 + packages/web/src/content/docs/ko/acp.mdx | 156 ++ packages/web/src/content/docs/ko/agents.mdx | 747 ++++++ packages/web/src/content/docs/ko/cli.mdx | 601 +++++ packages/web/src/content/docs/ko/commands.mdx | 323 +++ packages/web/src/content/docs/ko/config.mdx | 685 ++++++ packages/web/src/content/docs/ko/custom-tools.mdx | 170 ++ packages/web/src/content/docs/ko/ecosystem.mdx | 76 + packages/web/src/content/docs/ko/enterprise.mdx | 170 ++ packages/web/src/content/docs/ko/formatters.mdx | 130 ++ packages/web/src/content/docs/ko/github.mdx | 321 +++ packages/web/src/content/docs/ko/gitlab.mdx | 195 ++ packages/web/src/content/docs/ko/ide.mdx | 48 + packages/web/src/content/docs/ko/index.mdx | 359 +++ packages/web/src/content/docs/ko/keybinds.mdx | 192 ++ packages/web/src/content/docs/ko/lsp.mdx | 188 ++ packages/web/src/content/docs/ko/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/ko/models.mdx | 223 ++ packages/web/src/content/docs/ko/modes.mdx | 331 +++ packages/web/src/content/docs/ko/network.mdx | 57 + packages/web/src/content/docs/ko/permissions.mdx | 237 ++ packages/web/src/content/docs/ko/plugins.mdx | 385 ++++ packages/web/src/content/docs/ko/providers.mdx | 1889 +++++++++++++++ packages/web/src/content/docs/ko/rules.mdx | 180 ++ packages/web/src/content/docs/ko/sdk.mdx | 391 ++++ packages/web/src/content/docs/ko/server.mdx | 287 +++ packages/web/src/content/docs/ko/share.mdx | 128 ++ packages/web/src/content/docs/ko/skills.mdx | 222 ++ packages/web/src/content/docs/ko/themes.mdx | 369 +++ packages/web/src/content/docs/ko/tools.mdx | 379 +++ .../web/src/content/docs/ko/troubleshooting.mdx | 300 +++ packages/web/src/content/docs/ko/tui.mdx | 390 ++++ packages/web/src/content/docs/ko/web.mdx | 142 ++ packages/web/src/content/docs/ko/windows-wsl.mdx | 119 + packages/web/src/content/docs/ko/zen.mdx | 254 +++ packages/web/src/content/docs/nb/1-0.mdx | 67 + packages/web/src/content/docs/nb/acp.mdx | 156 ++ packages/web/src/content/docs/nb/agents.mdx | 747 ++++++ packages/web/src/content/docs/nb/cli.mdx | 601 +++++ packages/web/src/content/docs/nb/commands.mdx | 323 +++ packages/web/src/content/docs/nb/config.mdx | 685 ++++++ packages/web/src/content/docs/nb/custom-tools.mdx | 170 ++ packages/web/src/content/docs/nb/ecosystem.mdx | 76 + packages/web/src/content/docs/nb/enterprise.mdx | 170 ++ packages/web/src/content/docs/nb/formatters.mdx | 130 ++ packages/web/src/content/docs/nb/github.mdx | 321 +++ packages/web/src/content/docs/nb/gitlab.mdx | 195 ++ packages/web/src/content/docs/nb/ide.mdx | 48 + packages/web/src/content/docs/nb/index.mdx | 359 +++ packages/web/src/content/docs/nb/keybinds.mdx | 192 ++ packages/web/src/content/docs/nb/lsp.mdx | 188 ++ packages/web/src/content/docs/nb/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/nb/models.mdx | 223 ++ packages/web/src/content/docs/nb/modes.mdx | 331 +++ packages/web/src/content/docs/nb/network.mdx | 57 + packages/web/src/content/docs/nb/permissions.mdx | 237 ++ packages/web/src/content/docs/nb/plugins.mdx | 385 ++++ packages/web/src/content/docs/nb/providers.mdx | 1889 +++++++++++++++ packages/web/src/content/docs/nb/rules.mdx | 180 ++ packages/web/src/content/docs/nb/sdk.mdx | 391 ++++ packages/web/src/content/docs/nb/server.mdx | 287 +++ packages/web/src/content/docs/nb/share.mdx | 128 ++ packages/web/src/content/docs/nb/skills.mdx | 222 ++ packages/web/src/content/docs/nb/themes.mdx | 369 +++ packages/web/src/content/docs/nb/tools.mdx | 379 +++ .../web/src/content/docs/nb/troubleshooting.mdx | 300 +++ packages/web/src/content/docs/nb/tui.mdx | 390 ++++ packages/web/src/content/docs/nb/web.mdx | 142 ++ packages/web/src/content/docs/nb/windows-wsl.mdx | 113 + packages/web/src/content/docs/nb/zen.mdx | 254 +++ packages/web/src/content/docs/pl/1-0.mdx | 67 + packages/web/src/content/docs/pl/acp.mdx | 156 ++ packages/web/src/content/docs/pl/agents.mdx | 747 ++++++ packages/web/src/content/docs/pl/cli.mdx | 601 +++++ packages/web/src/content/docs/pl/commands.mdx | 323 +++ packages/web/src/content/docs/pl/config.mdx | 685 ++++++ packages/web/src/content/docs/pl/custom-tools.mdx | 170 ++ packages/web/src/content/docs/pl/ecosystem.mdx | 76 + packages/web/src/content/docs/pl/enterprise.mdx | 170 ++ packages/web/src/content/docs/pl/formatters.mdx | 130 ++ packages/web/src/content/docs/pl/github.mdx | 321 +++ packages/web/src/content/docs/pl/gitlab.mdx | 195 ++ packages/web/src/content/docs/pl/ide.mdx | 48 + packages/web/src/content/docs/pl/index.mdx | 359 +++ packages/web/src/content/docs/pl/keybinds.mdx | 192 ++ packages/web/src/content/docs/pl/lsp.mdx | 188 ++ packages/web/src/content/docs/pl/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/pl/models.mdx | 223 ++ packages/web/src/content/docs/pl/modes.mdx | 331 +++ packages/web/src/content/docs/pl/network.mdx | 57 + packages/web/src/content/docs/pl/permissions.mdx | 237 ++ packages/web/src/content/docs/pl/plugins.mdx | 385 ++++ packages/web/src/content/docs/pl/providers.mdx | 1888 +++++++++++++++ packages/web/src/content/docs/pl/rules.mdx | 180 ++ packages/web/src/content/docs/pl/sdk.mdx | 391 ++++ packages/web/src/content/docs/pl/server.mdx | 287 +++ packages/web/src/content/docs/pl/share.mdx | 128 ++ packages/web/src/content/docs/pl/skills.mdx | 222 ++ packages/web/src/content/docs/pl/themes.mdx | 369 +++ packages/web/src/content/docs/pl/tools.mdx | 379 +++ .../web/src/content/docs/pl/troubleshooting.mdx | 300 +++ packages/web/src/content/docs/pl/tui.mdx | 390 ++++ packages/web/src/content/docs/pl/web.mdx | 142 ++ packages/web/src/content/docs/pl/windows-wsl.mdx | 113 + packages/web/src/content/docs/pl/zen.mdx | 254 +++ packages/web/src/content/docs/pt-br/1-0.mdx | 66 + packages/web/src/content/docs/pt-br/acp.mdx | 156 ++ packages/web/src/content/docs/pt-br/agents.mdx | 747 ++++++ packages/web/src/content/docs/pt-br/cli.mdx | 601 +++++ packages/web/src/content/docs/pt-br/commands.mdx | 322 +++ packages/web/src/content/docs/pt-br/config.mdx | 681 ++++++ .../web/src/content/docs/pt-br/custom-tools.mdx | 170 ++ packages/web/src/content/docs/pt-br/ecosystem.mdx | 76 + packages/web/src/content/docs/pt-br/enterprise.mdx | 166 ++ packages/web/src/content/docs/pt-br/formatters.mdx | 130 ++ packages/web/src/content/docs/pt-br/github.mdx | 321 +++ packages/web/src/content/docs/pt-br/gitlab.mdx | 195 ++ packages/web/src/content/docs/pt-br/ide.mdx | 48 + packages/web/src/content/docs/pt-br/index.mdx | 341 +++ packages/web/src/content/docs/pt-br/keybinds.mdx | 192 ++ packages/web/src/content/docs/pt-br/lsp.mdx | 188 ++ .../web/src/content/docs/pt-br/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/pt-br/models.mdx | 222 ++ packages/web/src/content/docs/pt-br/modes.mdx | 328 +++ packages/web/src/content/docs/pt-br/network.mdx | 57 + .../web/src/content/docs/pt-br/permissions.mdx | 237 ++ packages/web/src/content/docs/pt-br/plugins.mdx | 384 ++++ packages/web/src/content/docs/pt-br/providers.mdx | 1881 +++++++++++++++ packages/web/src/content/docs/pt-br/rules.mdx | 180 ++ packages/web/src/content/docs/pt-br/sdk.mdx | 391 ++++ packages/web/src/content/docs/pt-br/server.mdx | 284 +++ packages/web/src/content/docs/pt-br/share.mdx | 127 ++ packages/web/src/content/docs/pt-br/skills.mdx | 222 ++ packages/web/src/content/docs/pt-br/themes.mdx | 369 +++ packages/web/src/content/docs/pt-br/tools.mdx | 379 +++ .../web/src/content/docs/pt-br/troubleshooting.mdx | 299 +++ packages/web/src/content/docs/pt-br/tui.mdx | 387 ++++ packages/web/src/content/docs/pt-br/web.mdx | 142 ++ .../web/src/content/docs/pt-br/windows-wsl.mdx | 113 + packages/web/src/content/docs/pt-br/zen.mdx | 236 ++ packages/web/src/content/docs/ru/1-0.mdx | 67 + packages/web/src/content/docs/ru/acp.mdx | 156 ++ packages/web/src/content/docs/ru/agents.mdx | 747 ++++++ packages/web/src/content/docs/ru/cli.mdx | 601 +++++ packages/web/src/content/docs/ru/commands.mdx | 323 +++ packages/web/src/content/docs/ru/config.mdx | 685 ++++++ packages/web/src/content/docs/ru/custom-tools.mdx | 170 ++ packages/web/src/content/docs/ru/ecosystem.mdx | 76 + packages/web/src/content/docs/ru/enterprise.mdx | 170 ++ packages/web/src/content/docs/ru/formatters.mdx | 130 ++ packages/web/src/content/docs/ru/github.mdx | 321 +++ packages/web/src/content/docs/ru/gitlab.mdx | 195 ++ packages/web/src/content/docs/ru/ide.mdx | 48 + packages/web/src/content/docs/ru/index.mdx | 359 +++ packages/web/src/content/docs/ru/keybinds.mdx | 192 ++ packages/web/src/content/docs/ru/lsp.mdx | 188 ++ packages/web/src/content/docs/ru/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/ru/models.mdx | 223 ++ packages/web/src/content/docs/ru/modes.mdx | 331 +++ packages/web/src/content/docs/ru/network.mdx | 57 + packages/web/src/content/docs/ru/permissions.mdx | 237 ++ packages/web/src/content/docs/ru/plugins.mdx | 385 ++++ packages/web/src/content/docs/ru/providers.mdx | 1889 +++++++++++++++ packages/web/src/content/docs/ru/rules.mdx | 180 ++ packages/web/src/content/docs/ru/sdk.mdx | 391 ++++ packages/web/src/content/docs/ru/server.mdx | 287 +++ packages/web/src/content/docs/ru/share.mdx | 128 ++ packages/web/src/content/docs/ru/skills.mdx | 222 ++ packages/web/src/content/docs/ru/themes.mdx | 369 +++ packages/web/src/content/docs/ru/tools.mdx | 379 +++ .../web/src/content/docs/ru/troubleshooting.mdx | 300 +++ packages/web/src/content/docs/ru/tui.mdx | 390 ++++ packages/web/src/content/docs/ru/web.mdx | 142 ++ packages/web/src/content/docs/ru/windows-wsl.mdx | 113 + packages/web/src/content/docs/ru/zen.mdx | 254 +++ packages/web/src/content/docs/th/1-0.mdx | 67 + packages/web/src/content/docs/th/acp.mdx | 156 ++ packages/web/src/content/docs/th/agents.mdx | 747 ++++++ packages/web/src/content/docs/th/cli.mdx | 601 +++++ packages/web/src/content/docs/th/commands.mdx | 323 +++ packages/web/src/content/docs/th/config.mdx | 685 ++++++ packages/web/src/content/docs/th/custom-tools.mdx | 170 ++ packages/web/src/content/docs/th/ecosystem.mdx | 76 + packages/web/src/content/docs/th/enterprise.mdx | 170 ++ packages/web/src/content/docs/th/formatters.mdx | 130 ++ packages/web/src/content/docs/th/github.mdx | 321 +++ packages/web/src/content/docs/th/gitlab.mdx | 195 ++ packages/web/src/content/docs/th/ide.mdx | 48 + packages/web/src/content/docs/th/index.mdx | 359 +++ packages/web/src/content/docs/th/keybinds.mdx | 192 ++ packages/web/src/content/docs/th/lsp.mdx | 188 ++ packages/web/src/content/docs/th/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/th/models.mdx | 223 ++ packages/web/src/content/docs/th/modes.mdx | 331 +++ packages/web/src/content/docs/th/network.mdx | 57 + packages/web/src/content/docs/th/permissions.mdx | 237 ++ packages/web/src/content/docs/th/plugins.mdx | 385 ++++ packages/web/src/content/docs/th/providers.mdx | 1889 +++++++++++++++ packages/web/src/content/docs/th/rules.mdx | 180 ++ packages/web/src/content/docs/th/sdk.mdx | 391 ++++ packages/web/src/content/docs/th/server.mdx | 287 +++ packages/web/src/content/docs/th/share.mdx | 128 ++ packages/web/src/content/docs/th/skills.mdx | 222 ++ packages/web/src/content/docs/th/themes.mdx | 369 +++ packages/web/src/content/docs/th/tools.mdx | 379 +++ .../web/src/content/docs/th/troubleshooting.mdx | 300 +++ packages/web/src/content/docs/th/tui.mdx | 390 ++++ packages/web/src/content/docs/th/web.mdx | 142 ++ packages/web/src/content/docs/th/windows-wsl.mdx | 113 + packages/web/src/content/docs/th/zen.mdx | 254 +++ packages/web/src/content/docs/tr/1-0.mdx | 67 + packages/web/src/content/docs/tr/acp.mdx | 156 ++ packages/web/src/content/docs/tr/agents.mdx | 747 ++++++ packages/web/src/content/docs/tr/cli.mdx | 601 +++++ packages/web/src/content/docs/tr/commands.mdx | 323 +++ packages/web/src/content/docs/tr/config.mdx | 685 ++++++ packages/web/src/content/docs/tr/custom-tools.mdx | 170 ++ packages/web/src/content/docs/tr/ecosystem.mdx | 76 + packages/web/src/content/docs/tr/enterprise.mdx | 170 ++ packages/web/src/content/docs/tr/formatters.mdx | 130 ++ packages/web/src/content/docs/tr/github.mdx | 321 +++ packages/web/src/content/docs/tr/gitlab.mdx | 195 ++ packages/web/src/content/docs/tr/ide.mdx | 48 + packages/web/src/content/docs/tr/index.mdx | 359 +++ packages/web/src/content/docs/tr/keybinds.mdx | 192 ++ packages/web/src/content/docs/tr/lsp.mdx | 188 ++ packages/web/src/content/docs/tr/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/tr/models.mdx | 223 ++ packages/web/src/content/docs/tr/modes.mdx | 331 +++ packages/web/src/content/docs/tr/network.mdx | 57 + packages/web/src/content/docs/tr/permissions.mdx | 237 ++ packages/web/src/content/docs/tr/plugins.mdx | 385 ++++ packages/web/src/content/docs/tr/providers.mdx | 1888 +++++++++++++++ packages/web/src/content/docs/tr/rules.mdx | 180 ++ packages/web/src/content/docs/tr/sdk.mdx | 22 + packages/web/src/content/docs/tr/server.mdx | 285 +++ packages/web/src/content/docs/tr/share.mdx | 127 ++ packages/web/src/content/docs/tr/skills.mdx | 222 ++ packages/web/src/content/docs/tr/themes.mdx | 369 +++ packages/web/src/content/docs/tr/tools.mdx | 379 +++ .../web/src/content/docs/tr/troubleshooting.mdx | 299 +++ packages/web/src/content/docs/tr/tui.mdx | 387 ++++ packages/web/src/content/docs/tr/web.mdx | 142 ++ packages/web/src/content/docs/tr/windows-wsl.mdx | 113 + packages/web/src/content/docs/tr/zen.mdx | 238 ++ packages/web/src/content/docs/zh-cn/1-0.mdx | 67 + packages/web/src/content/docs/zh-cn/acp.mdx | 156 ++ packages/web/src/content/docs/zh-cn/agents.mdx | 747 ++++++ packages/web/src/content/docs/zh-cn/cli.mdx | 601 +++++ packages/web/src/content/docs/zh-cn/commands.mdx | 323 +++ packages/web/src/content/docs/zh-cn/config.mdx | 685 ++++++ .../web/src/content/docs/zh-cn/custom-tools.mdx | 170 ++ packages/web/src/content/docs/zh-cn/ecosystem.mdx | 76 + packages/web/src/content/docs/zh-cn/enterprise.mdx | 170 ++ packages/web/src/content/docs/zh-cn/formatters.mdx | 130 ++ packages/web/src/content/docs/zh-cn/github.mdx | 321 +++ packages/web/src/content/docs/zh-cn/gitlab.mdx | 195 ++ packages/web/src/content/docs/zh-cn/ide.mdx | 48 + packages/web/src/content/docs/zh-cn/index.mdx | 359 +++ packages/web/src/content/docs/zh-cn/keybinds.mdx | 192 ++ packages/web/src/content/docs/zh-cn/lsp.mdx | 188 ++ .../web/src/content/docs/zh-cn/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/zh-cn/models.mdx | 223 ++ packages/web/src/content/docs/zh-cn/modes.mdx | 331 +++ packages/web/src/content/docs/zh-cn/network.mdx | 57 + .../web/src/content/docs/zh-cn/permissions.mdx | 237 ++ packages/web/src/content/docs/zh-cn/plugins.mdx | 385 ++++ packages/web/src/content/docs/zh-cn/providers.mdx | 1889 +++++++++++++++ packages/web/src/content/docs/zh-cn/rules.mdx | 180 ++ packages/web/src/content/docs/zh-cn/sdk.mdx | 391 ++++ packages/web/src/content/docs/zh-cn/server.mdx | 287 +++ packages/web/src/content/docs/zh-cn/share.mdx | 128 ++ packages/web/src/content/docs/zh-cn/skills.mdx | 222 ++ packages/web/src/content/docs/zh-cn/themes.mdx | 369 +++ packages/web/src/content/docs/zh-cn/tools.mdx | 379 +++ .../web/src/content/docs/zh-cn/troubleshooting.mdx | 300 +++ packages/web/src/content/docs/zh-cn/tui.mdx | 390 ++++ packages/web/src/content/docs/zh-cn/web.mdx | 142 ++ .../web/src/content/docs/zh-cn/windows-wsl.mdx | 113 + packages/web/src/content/docs/zh-cn/zen.mdx | 254 +++ packages/web/src/content/docs/zh-tw/1-0.mdx | 67 + packages/web/src/content/docs/zh-tw/acp.mdx | 156 ++ packages/web/src/content/docs/zh-tw/agents.mdx | 747 ++++++ packages/web/src/content/docs/zh-tw/cli.mdx | 601 +++++ packages/web/src/content/docs/zh-tw/commands.mdx | 323 +++ packages/web/src/content/docs/zh-tw/config.mdx | 685 ++++++ .../web/src/content/docs/zh-tw/custom-tools.mdx | 170 ++ packages/web/src/content/docs/zh-tw/ecosystem.mdx | 76 + packages/web/src/content/docs/zh-tw/enterprise.mdx | 170 ++ packages/web/src/content/docs/zh-tw/formatters.mdx | 130 ++ packages/web/src/content/docs/zh-tw/github.mdx | 321 +++ packages/web/src/content/docs/zh-tw/gitlab.mdx | 195 ++ packages/web/src/content/docs/zh-tw/ide.mdx | 48 + packages/web/src/content/docs/zh-tw/index.mdx | 359 +++ packages/web/src/content/docs/zh-tw/keybinds.mdx | 192 ++ packages/web/src/content/docs/zh-tw/lsp.mdx | 188 ++ .../web/src/content/docs/zh-tw/mcp-servers.mdx | 511 +++++ packages/web/src/content/docs/zh-tw/models.mdx | 223 ++ packages/web/src/content/docs/zh-tw/modes.mdx | 331 +++ packages/web/src/content/docs/zh-tw/network.mdx | 57 + .../web/src/content/docs/zh-tw/permissions.mdx | 237 ++ packages/web/src/content/docs/zh-tw/plugins.mdx | 385 ++++ packages/web/src/content/docs/zh-tw/providers.mdx | 1889 +++++++++++++++ packages/web/src/content/docs/zh-tw/rules.mdx | 180 ++ packages/web/src/content/docs/zh-tw/sdk.mdx | 391 ++++ packages/web/src/content/docs/zh-tw/server.mdx | 287 +++ packages/web/src/content/docs/zh-tw/share.mdx | 128 ++ packages/web/src/content/docs/zh-tw/skills.mdx | 222 ++ packages/web/src/content/docs/zh-tw/themes.mdx | 369 +++ packages/web/src/content/docs/zh-tw/tools.mdx | 379 +++ .../web/src/content/docs/zh-tw/troubleshooting.mdx | 300 +++ packages/web/src/content/docs/zh-tw/tui.mdx | 390 ++++ packages/web/src/content/docs/zh-tw/web.mdx | 142 ++ .../web/src/content/docs/zh-tw/windows-wsl.mdx | 113 + packages/web/src/content/docs/zh-tw/zen.mdx | 254 +++ packages/web/src/content/i18n/ar.json | 75 + packages/web/src/content/i18n/bs.json | 75 + packages/web/src/content/i18n/da.json | 75 + packages/web/src/content/i18n/de.json | 75 + packages/web/src/content/i18n/en.json | 75 + packages/web/src/content/i18n/es.json | 75 + packages/web/src/content/i18n/fr.json | 75 + packages/web/src/content/i18n/it.json | 75 + packages/web/src/content/i18n/ja.json | 75 + packages/web/src/content/i18n/ko.json | 75 + packages/web/src/content/i18n/nb.json | 75 + packages/web/src/content/i18n/pl.json | 75 + packages/web/src/content/i18n/pt-BR.json | 75 + packages/web/src/content/i18n/ru.json | 75 + packages/web/src/content/i18n/th.json | 75 + packages/web/src/content/i18n/tr.json | 75 + packages/web/src/content/i18n/zh-CN.json | 75 + packages/web/src/content/i18n/zh-TW.json | 75 + 613 files changed, 191363 insertions(+) create mode 100644 packages/web/src/content/docs/ar/1-0.mdx create mode 100644 packages/web/src/content/docs/ar/acp.mdx create mode 100644 packages/web/src/content/docs/ar/agents.mdx create mode 100644 packages/web/src/content/docs/ar/cli.mdx create mode 100644 packages/web/src/content/docs/ar/commands.mdx create mode 100644 packages/web/src/content/docs/ar/config.mdx create mode 100644 packages/web/src/content/docs/ar/custom-tools.mdx create mode 100644 packages/web/src/content/docs/ar/ecosystem.mdx create mode 100644 packages/web/src/content/docs/ar/enterprise.mdx create mode 100644 packages/web/src/content/docs/ar/formatters.mdx create mode 100644 packages/web/src/content/docs/ar/github.mdx create mode 100644 packages/web/src/content/docs/ar/gitlab.mdx create mode 100644 packages/web/src/content/docs/ar/ide.mdx create mode 100644 packages/web/src/content/docs/ar/index.mdx create mode 100644 packages/web/src/content/docs/ar/keybinds.mdx create mode 100644 packages/web/src/content/docs/ar/lsp.mdx create mode 100644 packages/web/src/content/docs/ar/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/ar/models.mdx create mode 100644 packages/web/src/content/docs/ar/modes.mdx create mode 100644 packages/web/src/content/docs/ar/network.mdx create mode 100644 packages/web/src/content/docs/ar/permissions.mdx create mode 100644 packages/web/src/content/docs/ar/plugins.mdx create mode 100644 packages/web/src/content/docs/ar/providers.mdx create mode 100644 packages/web/src/content/docs/ar/rules.mdx create mode 100644 packages/web/src/content/docs/ar/sdk.mdx create mode 100644 packages/web/src/content/docs/ar/server.mdx create mode 100644 packages/web/src/content/docs/ar/share.mdx create mode 100644 packages/web/src/content/docs/ar/skills.mdx create mode 100644 packages/web/src/content/docs/ar/themes.mdx create mode 100644 packages/web/src/content/docs/ar/tools.mdx create mode 100644 packages/web/src/content/docs/ar/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/ar/tui.mdx create mode 100644 packages/web/src/content/docs/ar/web.mdx create mode 100644 packages/web/src/content/docs/ar/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/ar/zen.mdx create mode 100644 packages/web/src/content/docs/bs/1-0.mdx create mode 100644 packages/web/src/content/docs/bs/acp.mdx create mode 100644 packages/web/src/content/docs/bs/agents.mdx create mode 100644 packages/web/src/content/docs/bs/cli.mdx create mode 100644 packages/web/src/content/docs/bs/commands.mdx create mode 100644 packages/web/src/content/docs/bs/config.mdx create mode 100644 packages/web/src/content/docs/bs/custom-tools.mdx create mode 100644 packages/web/src/content/docs/bs/ecosystem.mdx create mode 100644 packages/web/src/content/docs/bs/enterprise.mdx create mode 100644 packages/web/src/content/docs/bs/formatters.mdx create mode 100644 packages/web/src/content/docs/bs/github.mdx create mode 100644 packages/web/src/content/docs/bs/gitlab.mdx create mode 100644 packages/web/src/content/docs/bs/ide.mdx create mode 100644 packages/web/src/content/docs/bs/index.mdx create mode 100644 packages/web/src/content/docs/bs/keybinds.mdx create mode 100644 packages/web/src/content/docs/bs/lsp.mdx create mode 100644 packages/web/src/content/docs/bs/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/bs/models.mdx create mode 100644 packages/web/src/content/docs/bs/modes.mdx create mode 100644 packages/web/src/content/docs/bs/network.mdx create mode 100644 packages/web/src/content/docs/bs/permissions.mdx create mode 100644 packages/web/src/content/docs/bs/plugins.mdx create mode 100644 packages/web/src/content/docs/bs/providers.mdx create mode 100644 packages/web/src/content/docs/bs/rules.mdx create mode 100644 packages/web/src/content/docs/bs/sdk.mdx create mode 100644 packages/web/src/content/docs/bs/server.mdx create mode 100644 packages/web/src/content/docs/bs/share.mdx create mode 100644 packages/web/src/content/docs/bs/skills.mdx create mode 100644 packages/web/src/content/docs/bs/themes.mdx create mode 100644 packages/web/src/content/docs/bs/tools.mdx create mode 100644 packages/web/src/content/docs/bs/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/bs/tui.mdx create mode 100644 packages/web/src/content/docs/bs/web.mdx create mode 100644 packages/web/src/content/docs/bs/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/bs/zen.mdx create mode 100644 packages/web/src/content/docs/da/1-0.mdx create mode 100644 packages/web/src/content/docs/da/acp.mdx create mode 100644 packages/web/src/content/docs/da/agents.mdx create mode 100644 packages/web/src/content/docs/da/cli.mdx create mode 100644 packages/web/src/content/docs/da/commands.mdx create mode 100644 packages/web/src/content/docs/da/config.mdx create mode 100644 packages/web/src/content/docs/da/custom-tools.mdx create mode 100644 packages/web/src/content/docs/da/ecosystem.mdx create mode 100644 packages/web/src/content/docs/da/enterprise.mdx create mode 100644 packages/web/src/content/docs/da/formatters.mdx create mode 100644 packages/web/src/content/docs/da/github.mdx create mode 100644 packages/web/src/content/docs/da/gitlab.mdx create mode 100644 packages/web/src/content/docs/da/ide.mdx create mode 100644 packages/web/src/content/docs/da/index.mdx create mode 100644 packages/web/src/content/docs/da/keybinds.mdx create mode 100644 packages/web/src/content/docs/da/lsp.mdx create mode 100644 packages/web/src/content/docs/da/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/da/models.mdx create mode 100644 packages/web/src/content/docs/da/modes.mdx create mode 100644 packages/web/src/content/docs/da/network.mdx create mode 100644 packages/web/src/content/docs/da/permissions.mdx create mode 100644 packages/web/src/content/docs/da/plugins.mdx create mode 100644 packages/web/src/content/docs/da/providers.mdx create mode 100644 packages/web/src/content/docs/da/rules.mdx create mode 100644 packages/web/src/content/docs/da/sdk.mdx create mode 100644 packages/web/src/content/docs/da/server.mdx create mode 100644 packages/web/src/content/docs/da/share.mdx create mode 100644 packages/web/src/content/docs/da/skills.mdx create mode 100644 packages/web/src/content/docs/da/themes.mdx create mode 100644 packages/web/src/content/docs/da/tools.mdx create mode 100644 packages/web/src/content/docs/da/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/da/tui.mdx create mode 100644 packages/web/src/content/docs/da/web.mdx create mode 100644 packages/web/src/content/docs/da/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/da/zen.mdx create mode 100644 packages/web/src/content/docs/de/1-0.mdx create mode 100644 packages/web/src/content/docs/de/acp.mdx create mode 100644 packages/web/src/content/docs/de/agents.mdx create mode 100644 packages/web/src/content/docs/de/cli.mdx create mode 100644 packages/web/src/content/docs/de/commands.mdx create mode 100644 packages/web/src/content/docs/de/config.mdx create mode 100644 packages/web/src/content/docs/de/custom-tools.mdx create mode 100644 packages/web/src/content/docs/de/ecosystem.mdx create mode 100644 packages/web/src/content/docs/de/enterprise.mdx create mode 100644 packages/web/src/content/docs/de/formatters.mdx create mode 100644 packages/web/src/content/docs/de/github.mdx create mode 100644 packages/web/src/content/docs/de/gitlab.mdx create mode 100644 packages/web/src/content/docs/de/ide.mdx create mode 100644 packages/web/src/content/docs/de/index.mdx create mode 100644 packages/web/src/content/docs/de/keybinds.mdx create mode 100644 packages/web/src/content/docs/de/lsp.mdx create mode 100644 packages/web/src/content/docs/de/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/de/models.mdx create mode 100644 packages/web/src/content/docs/de/modes.mdx create mode 100644 packages/web/src/content/docs/de/network.mdx create mode 100644 packages/web/src/content/docs/de/permissions.mdx create mode 100644 packages/web/src/content/docs/de/plugins.mdx create mode 100644 packages/web/src/content/docs/de/providers.mdx create mode 100644 packages/web/src/content/docs/de/rules.mdx create mode 100644 packages/web/src/content/docs/de/sdk.mdx create mode 100644 packages/web/src/content/docs/de/server.mdx create mode 100644 packages/web/src/content/docs/de/share.mdx create mode 100644 packages/web/src/content/docs/de/skills.mdx create mode 100644 packages/web/src/content/docs/de/themes.mdx create mode 100644 packages/web/src/content/docs/de/tools.mdx create mode 100644 packages/web/src/content/docs/de/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/de/tui.mdx create mode 100644 packages/web/src/content/docs/de/web.mdx create mode 100644 packages/web/src/content/docs/de/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/de/zen.mdx create mode 100644 packages/web/src/content/docs/es/1-0.mdx create mode 100644 packages/web/src/content/docs/es/acp.mdx create mode 100644 packages/web/src/content/docs/es/agents.mdx create mode 100644 packages/web/src/content/docs/es/cli.mdx create mode 100644 packages/web/src/content/docs/es/commands.mdx create mode 100644 packages/web/src/content/docs/es/config.mdx create mode 100644 packages/web/src/content/docs/es/custom-tools.mdx create mode 100644 packages/web/src/content/docs/es/ecosystem.mdx create mode 100644 packages/web/src/content/docs/es/enterprise.mdx create mode 100644 packages/web/src/content/docs/es/formatters.mdx create mode 100644 packages/web/src/content/docs/es/github.mdx create mode 100644 packages/web/src/content/docs/es/gitlab.mdx create mode 100644 packages/web/src/content/docs/es/ide.mdx create mode 100644 packages/web/src/content/docs/es/index.mdx create mode 100644 packages/web/src/content/docs/es/keybinds.mdx create mode 100644 packages/web/src/content/docs/es/lsp.mdx create mode 100644 packages/web/src/content/docs/es/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/es/models.mdx create mode 100644 packages/web/src/content/docs/es/modes.mdx create mode 100644 packages/web/src/content/docs/es/network.mdx create mode 100644 packages/web/src/content/docs/es/permissions.mdx create mode 100644 packages/web/src/content/docs/es/plugins.mdx create mode 100644 packages/web/src/content/docs/es/providers.mdx create mode 100644 packages/web/src/content/docs/es/rules.mdx create mode 100644 packages/web/src/content/docs/es/sdk.mdx create mode 100644 packages/web/src/content/docs/es/server.mdx create mode 100644 packages/web/src/content/docs/es/share.mdx create mode 100644 packages/web/src/content/docs/es/skills.mdx create mode 100644 packages/web/src/content/docs/es/themes.mdx create mode 100644 packages/web/src/content/docs/es/tools.mdx create mode 100644 packages/web/src/content/docs/es/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/es/tui.mdx create mode 100644 packages/web/src/content/docs/es/web.mdx create mode 100644 packages/web/src/content/docs/es/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/es/zen.mdx create mode 100644 packages/web/src/content/docs/fr/1-0.mdx create mode 100644 packages/web/src/content/docs/fr/acp.mdx create mode 100644 packages/web/src/content/docs/fr/agents.mdx create mode 100644 packages/web/src/content/docs/fr/cli.mdx create mode 100644 packages/web/src/content/docs/fr/commands.mdx create mode 100644 packages/web/src/content/docs/fr/config.mdx create mode 100644 packages/web/src/content/docs/fr/custom-tools.mdx create mode 100644 packages/web/src/content/docs/fr/ecosystem.mdx create mode 100644 packages/web/src/content/docs/fr/enterprise.mdx create mode 100644 packages/web/src/content/docs/fr/formatters.mdx create mode 100644 packages/web/src/content/docs/fr/github.mdx create mode 100644 packages/web/src/content/docs/fr/gitlab.mdx create mode 100644 packages/web/src/content/docs/fr/ide.mdx create mode 100644 packages/web/src/content/docs/fr/index.mdx create mode 100644 packages/web/src/content/docs/fr/keybinds.mdx create mode 100644 packages/web/src/content/docs/fr/lsp.mdx create mode 100644 packages/web/src/content/docs/fr/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/fr/models.mdx create mode 100644 packages/web/src/content/docs/fr/modes.mdx create mode 100644 packages/web/src/content/docs/fr/network.mdx create mode 100644 packages/web/src/content/docs/fr/permissions.mdx create mode 100644 packages/web/src/content/docs/fr/plugins.mdx create mode 100644 packages/web/src/content/docs/fr/providers.mdx create mode 100644 packages/web/src/content/docs/fr/rules.mdx create mode 100644 packages/web/src/content/docs/fr/sdk.mdx create mode 100644 packages/web/src/content/docs/fr/server.mdx create mode 100644 packages/web/src/content/docs/fr/share.mdx create mode 100644 packages/web/src/content/docs/fr/skills.mdx create mode 100644 packages/web/src/content/docs/fr/themes.mdx create mode 100644 packages/web/src/content/docs/fr/tools.mdx create mode 100644 packages/web/src/content/docs/fr/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/fr/tui.mdx create mode 100644 packages/web/src/content/docs/fr/web.mdx create mode 100644 packages/web/src/content/docs/fr/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/fr/zen.mdx create mode 100644 packages/web/src/content/docs/it/1-0.mdx create mode 100644 packages/web/src/content/docs/it/acp.mdx create mode 100644 packages/web/src/content/docs/it/agents.mdx create mode 100644 packages/web/src/content/docs/it/cli.mdx create mode 100644 packages/web/src/content/docs/it/commands.mdx create mode 100644 packages/web/src/content/docs/it/config.mdx create mode 100644 packages/web/src/content/docs/it/custom-tools.mdx create mode 100644 packages/web/src/content/docs/it/ecosystem.mdx create mode 100644 packages/web/src/content/docs/it/enterprise.mdx create mode 100644 packages/web/src/content/docs/it/formatters.mdx create mode 100644 packages/web/src/content/docs/it/github.mdx create mode 100644 packages/web/src/content/docs/it/gitlab.mdx create mode 100644 packages/web/src/content/docs/it/ide.mdx create mode 100644 packages/web/src/content/docs/it/index.mdx create mode 100644 packages/web/src/content/docs/it/keybinds.mdx create mode 100644 packages/web/src/content/docs/it/lsp.mdx create mode 100644 packages/web/src/content/docs/it/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/it/models.mdx create mode 100644 packages/web/src/content/docs/it/modes.mdx create mode 100644 packages/web/src/content/docs/it/network.mdx create mode 100644 packages/web/src/content/docs/it/permissions.mdx create mode 100644 packages/web/src/content/docs/it/plugins.mdx create mode 100644 packages/web/src/content/docs/it/providers.mdx create mode 100644 packages/web/src/content/docs/it/rules.mdx create mode 100644 packages/web/src/content/docs/it/sdk.mdx create mode 100644 packages/web/src/content/docs/it/server.mdx create mode 100644 packages/web/src/content/docs/it/share.mdx create mode 100644 packages/web/src/content/docs/it/skills.mdx create mode 100644 packages/web/src/content/docs/it/themes.mdx create mode 100644 packages/web/src/content/docs/it/tools.mdx create mode 100644 packages/web/src/content/docs/it/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/it/tui.mdx create mode 100644 packages/web/src/content/docs/it/web.mdx create mode 100644 packages/web/src/content/docs/it/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/it/zen.mdx create mode 100644 packages/web/src/content/docs/ja/1-0.mdx create mode 100644 packages/web/src/content/docs/ja/acp.mdx create mode 100644 packages/web/src/content/docs/ja/agents.mdx create mode 100644 packages/web/src/content/docs/ja/cli.mdx create mode 100644 packages/web/src/content/docs/ja/commands.mdx create mode 100644 packages/web/src/content/docs/ja/config.mdx create mode 100644 packages/web/src/content/docs/ja/custom-tools.mdx create mode 100644 packages/web/src/content/docs/ja/ecosystem.mdx create mode 100644 packages/web/src/content/docs/ja/enterprise.mdx create mode 100644 packages/web/src/content/docs/ja/formatters.mdx create mode 100644 packages/web/src/content/docs/ja/github.mdx create mode 100644 packages/web/src/content/docs/ja/gitlab.mdx create mode 100644 packages/web/src/content/docs/ja/ide.mdx create mode 100644 packages/web/src/content/docs/ja/index.mdx create mode 100644 packages/web/src/content/docs/ja/keybinds.mdx create mode 100644 packages/web/src/content/docs/ja/lsp.mdx create mode 100644 packages/web/src/content/docs/ja/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/ja/models.mdx create mode 100644 packages/web/src/content/docs/ja/modes.mdx create mode 100644 packages/web/src/content/docs/ja/network.mdx create mode 100644 packages/web/src/content/docs/ja/permissions.mdx create mode 100644 packages/web/src/content/docs/ja/plugins.mdx create mode 100644 packages/web/src/content/docs/ja/providers.mdx create mode 100644 packages/web/src/content/docs/ja/rules.mdx create mode 100644 packages/web/src/content/docs/ja/sdk.mdx create mode 100644 packages/web/src/content/docs/ja/server.mdx create mode 100644 packages/web/src/content/docs/ja/share.mdx create mode 100644 packages/web/src/content/docs/ja/skills.mdx create mode 100644 packages/web/src/content/docs/ja/themes.mdx create mode 100644 packages/web/src/content/docs/ja/tools.mdx create mode 100644 packages/web/src/content/docs/ja/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/ja/tui.mdx create mode 100644 packages/web/src/content/docs/ja/web.mdx create mode 100644 packages/web/src/content/docs/ja/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/ja/zen.mdx create mode 100644 packages/web/src/content/docs/ko/1-0.mdx create mode 100644 packages/web/src/content/docs/ko/acp.mdx create mode 100644 packages/web/src/content/docs/ko/agents.mdx create mode 100644 packages/web/src/content/docs/ko/cli.mdx create mode 100644 packages/web/src/content/docs/ko/commands.mdx create mode 100644 packages/web/src/content/docs/ko/config.mdx create mode 100644 packages/web/src/content/docs/ko/custom-tools.mdx create mode 100644 packages/web/src/content/docs/ko/ecosystem.mdx create mode 100644 packages/web/src/content/docs/ko/enterprise.mdx create mode 100644 packages/web/src/content/docs/ko/formatters.mdx create mode 100644 packages/web/src/content/docs/ko/github.mdx create mode 100644 packages/web/src/content/docs/ko/gitlab.mdx create mode 100644 packages/web/src/content/docs/ko/ide.mdx create mode 100644 packages/web/src/content/docs/ko/index.mdx create mode 100644 packages/web/src/content/docs/ko/keybinds.mdx create mode 100644 packages/web/src/content/docs/ko/lsp.mdx create mode 100644 packages/web/src/content/docs/ko/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/ko/models.mdx create mode 100644 packages/web/src/content/docs/ko/modes.mdx create mode 100644 packages/web/src/content/docs/ko/network.mdx create mode 100644 packages/web/src/content/docs/ko/permissions.mdx create mode 100644 packages/web/src/content/docs/ko/plugins.mdx create mode 100644 packages/web/src/content/docs/ko/providers.mdx create mode 100644 packages/web/src/content/docs/ko/rules.mdx create mode 100644 packages/web/src/content/docs/ko/sdk.mdx create mode 100644 packages/web/src/content/docs/ko/server.mdx create mode 100644 packages/web/src/content/docs/ko/share.mdx create mode 100644 packages/web/src/content/docs/ko/skills.mdx create mode 100644 packages/web/src/content/docs/ko/themes.mdx create mode 100644 packages/web/src/content/docs/ko/tools.mdx create mode 100644 packages/web/src/content/docs/ko/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/ko/tui.mdx create mode 100644 packages/web/src/content/docs/ko/web.mdx create mode 100644 packages/web/src/content/docs/ko/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/ko/zen.mdx create mode 100644 packages/web/src/content/docs/nb/1-0.mdx create mode 100644 packages/web/src/content/docs/nb/acp.mdx create mode 100644 packages/web/src/content/docs/nb/agents.mdx create mode 100644 packages/web/src/content/docs/nb/cli.mdx create mode 100644 packages/web/src/content/docs/nb/commands.mdx create mode 100644 packages/web/src/content/docs/nb/config.mdx create mode 100644 packages/web/src/content/docs/nb/custom-tools.mdx create mode 100644 packages/web/src/content/docs/nb/ecosystem.mdx create mode 100644 packages/web/src/content/docs/nb/enterprise.mdx create mode 100644 packages/web/src/content/docs/nb/formatters.mdx create mode 100644 packages/web/src/content/docs/nb/github.mdx create mode 100644 packages/web/src/content/docs/nb/gitlab.mdx create mode 100644 packages/web/src/content/docs/nb/ide.mdx create mode 100644 packages/web/src/content/docs/nb/index.mdx create mode 100644 packages/web/src/content/docs/nb/keybinds.mdx create mode 100644 packages/web/src/content/docs/nb/lsp.mdx create mode 100644 packages/web/src/content/docs/nb/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/nb/models.mdx create mode 100644 packages/web/src/content/docs/nb/modes.mdx create mode 100644 packages/web/src/content/docs/nb/network.mdx create mode 100644 packages/web/src/content/docs/nb/permissions.mdx create mode 100644 packages/web/src/content/docs/nb/plugins.mdx create mode 100644 packages/web/src/content/docs/nb/providers.mdx create mode 100644 packages/web/src/content/docs/nb/rules.mdx create mode 100644 packages/web/src/content/docs/nb/sdk.mdx create mode 100644 packages/web/src/content/docs/nb/server.mdx create mode 100644 packages/web/src/content/docs/nb/share.mdx create mode 100644 packages/web/src/content/docs/nb/skills.mdx create mode 100644 packages/web/src/content/docs/nb/themes.mdx create mode 100644 packages/web/src/content/docs/nb/tools.mdx create mode 100644 packages/web/src/content/docs/nb/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/nb/tui.mdx create mode 100644 packages/web/src/content/docs/nb/web.mdx create mode 100644 packages/web/src/content/docs/nb/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/nb/zen.mdx create mode 100644 packages/web/src/content/docs/pl/1-0.mdx create mode 100644 packages/web/src/content/docs/pl/acp.mdx create mode 100644 packages/web/src/content/docs/pl/agents.mdx create mode 100644 packages/web/src/content/docs/pl/cli.mdx create mode 100644 packages/web/src/content/docs/pl/commands.mdx create mode 100644 packages/web/src/content/docs/pl/config.mdx create mode 100644 packages/web/src/content/docs/pl/custom-tools.mdx create mode 100644 packages/web/src/content/docs/pl/ecosystem.mdx create mode 100644 packages/web/src/content/docs/pl/enterprise.mdx create mode 100644 packages/web/src/content/docs/pl/formatters.mdx create mode 100644 packages/web/src/content/docs/pl/github.mdx create mode 100644 packages/web/src/content/docs/pl/gitlab.mdx create mode 100644 packages/web/src/content/docs/pl/ide.mdx create mode 100644 packages/web/src/content/docs/pl/index.mdx create mode 100644 packages/web/src/content/docs/pl/keybinds.mdx create mode 100644 packages/web/src/content/docs/pl/lsp.mdx create mode 100644 packages/web/src/content/docs/pl/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/pl/models.mdx create mode 100644 packages/web/src/content/docs/pl/modes.mdx create mode 100644 packages/web/src/content/docs/pl/network.mdx create mode 100644 packages/web/src/content/docs/pl/permissions.mdx create mode 100644 packages/web/src/content/docs/pl/plugins.mdx create mode 100644 packages/web/src/content/docs/pl/providers.mdx create mode 100644 packages/web/src/content/docs/pl/rules.mdx create mode 100644 packages/web/src/content/docs/pl/sdk.mdx create mode 100644 packages/web/src/content/docs/pl/server.mdx create mode 100644 packages/web/src/content/docs/pl/share.mdx create mode 100644 packages/web/src/content/docs/pl/skills.mdx create mode 100644 packages/web/src/content/docs/pl/themes.mdx create mode 100644 packages/web/src/content/docs/pl/tools.mdx create mode 100644 packages/web/src/content/docs/pl/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/pl/tui.mdx create mode 100644 packages/web/src/content/docs/pl/web.mdx create mode 100644 packages/web/src/content/docs/pl/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/pl/zen.mdx create mode 100644 packages/web/src/content/docs/pt-br/1-0.mdx create mode 100644 packages/web/src/content/docs/pt-br/acp.mdx create mode 100644 packages/web/src/content/docs/pt-br/agents.mdx create mode 100644 packages/web/src/content/docs/pt-br/cli.mdx create mode 100644 packages/web/src/content/docs/pt-br/commands.mdx create mode 100644 packages/web/src/content/docs/pt-br/config.mdx create mode 100644 packages/web/src/content/docs/pt-br/custom-tools.mdx create mode 100644 packages/web/src/content/docs/pt-br/ecosystem.mdx create mode 100644 packages/web/src/content/docs/pt-br/enterprise.mdx create mode 100644 packages/web/src/content/docs/pt-br/formatters.mdx create mode 100644 packages/web/src/content/docs/pt-br/github.mdx create mode 100644 packages/web/src/content/docs/pt-br/gitlab.mdx create mode 100644 packages/web/src/content/docs/pt-br/ide.mdx create mode 100644 packages/web/src/content/docs/pt-br/index.mdx create mode 100644 packages/web/src/content/docs/pt-br/keybinds.mdx create mode 100644 packages/web/src/content/docs/pt-br/lsp.mdx create mode 100644 packages/web/src/content/docs/pt-br/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/pt-br/models.mdx create mode 100644 packages/web/src/content/docs/pt-br/modes.mdx create mode 100644 packages/web/src/content/docs/pt-br/network.mdx create mode 100644 packages/web/src/content/docs/pt-br/permissions.mdx create mode 100644 packages/web/src/content/docs/pt-br/plugins.mdx create mode 100644 packages/web/src/content/docs/pt-br/providers.mdx create mode 100644 packages/web/src/content/docs/pt-br/rules.mdx create mode 100644 packages/web/src/content/docs/pt-br/sdk.mdx create mode 100644 packages/web/src/content/docs/pt-br/server.mdx create mode 100644 packages/web/src/content/docs/pt-br/share.mdx create mode 100644 packages/web/src/content/docs/pt-br/skills.mdx create mode 100644 packages/web/src/content/docs/pt-br/themes.mdx create mode 100644 packages/web/src/content/docs/pt-br/tools.mdx create mode 100644 packages/web/src/content/docs/pt-br/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/pt-br/tui.mdx create mode 100644 packages/web/src/content/docs/pt-br/web.mdx create mode 100644 packages/web/src/content/docs/pt-br/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/pt-br/zen.mdx create mode 100644 packages/web/src/content/docs/ru/1-0.mdx create mode 100644 packages/web/src/content/docs/ru/acp.mdx create mode 100644 packages/web/src/content/docs/ru/agents.mdx create mode 100644 packages/web/src/content/docs/ru/cli.mdx create mode 100644 packages/web/src/content/docs/ru/commands.mdx create mode 100644 packages/web/src/content/docs/ru/config.mdx create mode 100644 packages/web/src/content/docs/ru/custom-tools.mdx create mode 100644 packages/web/src/content/docs/ru/ecosystem.mdx create mode 100644 packages/web/src/content/docs/ru/enterprise.mdx create mode 100644 packages/web/src/content/docs/ru/formatters.mdx create mode 100644 packages/web/src/content/docs/ru/github.mdx create mode 100644 packages/web/src/content/docs/ru/gitlab.mdx create mode 100644 packages/web/src/content/docs/ru/ide.mdx create mode 100644 packages/web/src/content/docs/ru/index.mdx create mode 100644 packages/web/src/content/docs/ru/keybinds.mdx create mode 100644 packages/web/src/content/docs/ru/lsp.mdx create mode 100644 packages/web/src/content/docs/ru/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/ru/models.mdx create mode 100644 packages/web/src/content/docs/ru/modes.mdx create mode 100644 packages/web/src/content/docs/ru/network.mdx create mode 100644 packages/web/src/content/docs/ru/permissions.mdx create mode 100644 packages/web/src/content/docs/ru/plugins.mdx create mode 100644 packages/web/src/content/docs/ru/providers.mdx create mode 100644 packages/web/src/content/docs/ru/rules.mdx create mode 100644 packages/web/src/content/docs/ru/sdk.mdx create mode 100644 packages/web/src/content/docs/ru/server.mdx create mode 100644 packages/web/src/content/docs/ru/share.mdx create mode 100644 packages/web/src/content/docs/ru/skills.mdx create mode 100644 packages/web/src/content/docs/ru/themes.mdx create mode 100644 packages/web/src/content/docs/ru/tools.mdx create mode 100644 packages/web/src/content/docs/ru/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/ru/tui.mdx create mode 100644 packages/web/src/content/docs/ru/web.mdx create mode 100644 packages/web/src/content/docs/ru/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/ru/zen.mdx create mode 100644 packages/web/src/content/docs/th/1-0.mdx create mode 100644 packages/web/src/content/docs/th/acp.mdx create mode 100644 packages/web/src/content/docs/th/agents.mdx create mode 100644 packages/web/src/content/docs/th/cli.mdx create mode 100644 packages/web/src/content/docs/th/commands.mdx create mode 100644 packages/web/src/content/docs/th/config.mdx create mode 100644 packages/web/src/content/docs/th/custom-tools.mdx create mode 100644 packages/web/src/content/docs/th/ecosystem.mdx create mode 100644 packages/web/src/content/docs/th/enterprise.mdx create mode 100644 packages/web/src/content/docs/th/formatters.mdx create mode 100644 packages/web/src/content/docs/th/github.mdx create mode 100644 packages/web/src/content/docs/th/gitlab.mdx create mode 100644 packages/web/src/content/docs/th/ide.mdx create mode 100644 packages/web/src/content/docs/th/index.mdx create mode 100644 packages/web/src/content/docs/th/keybinds.mdx create mode 100644 packages/web/src/content/docs/th/lsp.mdx create mode 100644 packages/web/src/content/docs/th/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/th/models.mdx create mode 100644 packages/web/src/content/docs/th/modes.mdx create mode 100644 packages/web/src/content/docs/th/network.mdx create mode 100644 packages/web/src/content/docs/th/permissions.mdx create mode 100644 packages/web/src/content/docs/th/plugins.mdx create mode 100644 packages/web/src/content/docs/th/providers.mdx create mode 100644 packages/web/src/content/docs/th/rules.mdx create mode 100644 packages/web/src/content/docs/th/sdk.mdx create mode 100644 packages/web/src/content/docs/th/server.mdx create mode 100644 packages/web/src/content/docs/th/share.mdx create mode 100644 packages/web/src/content/docs/th/skills.mdx create mode 100644 packages/web/src/content/docs/th/themes.mdx create mode 100644 packages/web/src/content/docs/th/tools.mdx create mode 100644 packages/web/src/content/docs/th/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/th/tui.mdx create mode 100644 packages/web/src/content/docs/th/web.mdx create mode 100644 packages/web/src/content/docs/th/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/th/zen.mdx create mode 100644 packages/web/src/content/docs/tr/1-0.mdx create mode 100644 packages/web/src/content/docs/tr/acp.mdx create mode 100644 packages/web/src/content/docs/tr/agents.mdx create mode 100644 packages/web/src/content/docs/tr/cli.mdx create mode 100644 packages/web/src/content/docs/tr/commands.mdx create mode 100644 packages/web/src/content/docs/tr/config.mdx create mode 100644 packages/web/src/content/docs/tr/custom-tools.mdx create mode 100644 packages/web/src/content/docs/tr/ecosystem.mdx create mode 100644 packages/web/src/content/docs/tr/enterprise.mdx create mode 100644 packages/web/src/content/docs/tr/formatters.mdx create mode 100644 packages/web/src/content/docs/tr/github.mdx create mode 100644 packages/web/src/content/docs/tr/gitlab.mdx create mode 100644 packages/web/src/content/docs/tr/ide.mdx create mode 100644 packages/web/src/content/docs/tr/index.mdx create mode 100644 packages/web/src/content/docs/tr/keybinds.mdx create mode 100644 packages/web/src/content/docs/tr/lsp.mdx create mode 100644 packages/web/src/content/docs/tr/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/tr/models.mdx create mode 100644 packages/web/src/content/docs/tr/modes.mdx create mode 100644 packages/web/src/content/docs/tr/network.mdx create mode 100644 packages/web/src/content/docs/tr/permissions.mdx create mode 100644 packages/web/src/content/docs/tr/plugins.mdx create mode 100644 packages/web/src/content/docs/tr/providers.mdx create mode 100644 packages/web/src/content/docs/tr/rules.mdx create mode 100644 packages/web/src/content/docs/tr/sdk.mdx create mode 100644 packages/web/src/content/docs/tr/server.mdx create mode 100644 packages/web/src/content/docs/tr/share.mdx create mode 100644 packages/web/src/content/docs/tr/skills.mdx create mode 100644 packages/web/src/content/docs/tr/themes.mdx create mode 100644 packages/web/src/content/docs/tr/tools.mdx create mode 100644 packages/web/src/content/docs/tr/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/tr/tui.mdx create mode 100644 packages/web/src/content/docs/tr/web.mdx create mode 100644 packages/web/src/content/docs/tr/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/tr/zen.mdx create mode 100644 packages/web/src/content/docs/zh-cn/1-0.mdx create mode 100644 packages/web/src/content/docs/zh-cn/acp.mdx create mode 100644 packages/web/src/content/docs/zh-cn/agents.mdx create mode 100644 packages/web/src/content/docs/zh-cn/cli.mdx create mode 100644 packages/web/src/content/docs/zh-cn/commands.mdx create mode 100644 packages/web/src/content/docs/zh-cn/config.mdx create mode 100644 packages/web/src/content/docs/zh-cn/custom-tools.mdx create mode 100644 packages/web/src/content/docs/zh-cn/ecosystem.mdx create mode 100644 packages/web/src/content/docs/zh-cn/enterprise.mdx create mode 100644 packages/web/src/content/docs/zh-cn/formatters.mdx create mode 100644 packages/web/src/content/docs/zh-cn/github.mdx create mode 100644 packages/web/src/content/docs/zh-cn/gitlab.mdx create mode 100644 packages/web/src/content/docs/zh-cn/ide.mdx create mode 100644 packages/web/src/content/docs/zh-cn/index.mdx create mode 100644 packages/web/src/content/docs/zh-cn/keybinds.mdx create mode 100644 packages/web/src/content/docs/zh-cn/lsp.mdx create mode 100644 packages/web/src/content/docs/zh-cn/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/zh-cn/models.mdx create mode 100644 packages/web/src/content/docs/zh-cn/modes.mdx create mode 100644 packages/web/src/content/docs/zh-cn/network.mdx create mode 100644 packages/web/src/content/docs/zh-cn/permissions.mdx create mode 100644 packages/web/src/content/docs/zh-cn/plugins.mdx create mode 100644 packages/web/src/content/docs/zh-cn/providers.mdx create mode 100644 packages/web/src/content/docs/zh-cn/rules.mdx create mode 100644 packages/web/src/content/docs/zh-cn/sdk.mdx create mode 100644 packages/web/src/content/docs/zh-cn/server.mdx create mode 100644 packages/web/src/content/docs/zh-cn/share.mdx create mode 100644 packages/web/src/content/docs/zh-cn/skills.mdx create mode 100644 packages/web/src/content/docs/zh-cn/themes.mdx create mode 100644 packages/web/src/content/docs/zh-cn/tools.mdx create mode 100644 packages/web/src/content/docs/zh-cn/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/zh-cn/tui.mdx create mode 100644 packages/web/src/content/docs/zh-cn/web.mdx create mode 100644 packages/web/src/content/docs/zh-cn/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/zh-cn/zen.mdx create mode 100644 packages/web/src/content/docs/zh-tw/1-0.mdx create mode 100644 packages/web/src/content/docs/zh-tw/acp.mdx create mode 100644 packages/web/src/content/docs/zh-tw/agents.mdx create mode 100644 packages/web/src/content/docs/zh-tw/cli.mdx create mode 100644 packages/web/src/content/docs/zh-tw/commands.mdx create mode 100644 packages/web/src/content/docs/zh-tw/config.mdx create mode 100644 packages/web/src/content/docs/zh-tw/custom-tools.mdx create mode 100644 packages/web/src/content/docs/zh-tw/ecosystem.mdx create mode 100644 packages/web/src/content/docs/zh-tw/enterprise.mdx create mode 100644 packages/web/src/content/docs/zh-tw/formatters.mdx create mode 100644 packages/web/src/content/docs/zh-tw/github.mdx create mode 100644 packages/web/src/content/docs/zh-tw/gitlab.mdx create mode 100644 packages/web/src/content/docs/zh-tw/ide.mdx create mode 100644 packages/web/src/content/docs/zh-tw/index.mdx create mode 100644 packages/web/src/content/docs/zh-tw/keybinds.mdx create mode 100644 packages/web/src/content/docs/zh-tw/lsp.mdx create mode 100644 packages/web/src/content/docs/zh-tw/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/zh-tw/models.mdx create mode 100644 packages/web/src/content/docs/zh-tw/modes.mdx create mode 100644 packages/web/src/content/docs/zh-tw/network.mdx create mode 100644 packages/web/src/content/docs/zh-tw/permissions.mdx create mode 100644 packages/web/src/content/docs/zh-tw/plugins.mdx create mode 100644 packages/web/src/content/docs/zh-tw/providers.mdx create mode 100644 packages/web/src/content/docs/zh-tw/rules.mdx create mode 100644 packages/web/src/content/docs/zh-tw/sdk.mdx create mode 100644 packages/web/src/content/docs/zh-tw/server.mdx create mode 100644 packages/web/src/content/docs/zh-tw/share.mdx create mode 100644 packages/web/src/content/docs/zh-tw/skills.mdx create mode 100644 packages/web/src/content/docs/zh-tw/themes.mdx create mode 100644 packages/web/src/content/docs/zh-tw/tools.mdx create mode 100644 packages/web/src/content/docs/zh-tw/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/zh-tw/tui.mdx create mode 100644 packages/web/src/content/docs/zh-tw/web.mdx create mode 100644 packages/web/src/content/docs/zh-tw/windows-wsl.mdx create mode 100644 packages/web/src/content/docs/zh-tw/zen.mdx create mode 100644 packages/web/src/content/i18n/ar.json create mode 100644 packages/web/src/content/i18n/bs.json create mode 100644 packages/web/src/content/i18n/da.json create mode 100644 packages/web/src/content/i18n/de.json create mode 100644 packages/web/src/content/i18n/en.json create mode 100644 packages/web/src/content/i18n/es.json create mode 100644 packages/web/src/content/i18n/fr.json create mode 100644 packages/web/src/content/i18n/it.json create mode 100644 packages/web/src/content/i18n/ja.json create mode 100644 packages/web/src/content/i18n/ko.json create mode 100644 packages/web/src/content/i18n/nb.json create mode 100644 packages/web/src/content/i18n/pl.json create mode 100644 packages/web/src/content/i18n/pt-BR.json create mode 100644 packages/web/src/content/i18n/ru.json create mode 100644 packages/web/src/content/i18n/th.json create mode 100644 packages/web/src/content/i18n/tr.json create mode 100644 packages/web/src/content/i18n/zh-CN.json create mode 100644 packages/web/src/content/i18n/zh-TW.json (limited to 'packages/web/src/content') diff --git a/packages/web/src/content/docs/ar/1-0.mdx b/packages/web/src/content/docs/ar/1-0.mdx new file mode 100644 index 000000000..3587dd770 --- /dev/null +++ b/packages/web/src/content/docs/ar/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: الانتقال إلى 1.0 +description: ما الجديد في OpenCode 1.0. +--- + +OpenCode 1.0 هو إعادة كتابة كاملة لواجهة TUI. + +انتقلنا من واجهة TUI المبنية على go+bubbletea، والتي كانت تعاني من مشاكل في الأداء والإمكانات، إلى إطار عمل داخلي (OpenTUI) مكتوب بـ zig+solidjs. + +تعمل واجهة TUI الجديدة مثل القديمة لأنها تتصل بخادم opencode نفسه. + +--- + +## الترقية + +لا يفترض أن تتم ترقيتك تلقائيا إلى 1.0 إذا كنت تستخدم حاليا إصدارا أقدم. +لكن بعض الإصدارات القديمة من OpenCode كانت تجلب دائما أحدث إصدار. + +للترقية يدويا، شغّل + +```bash +$ opencode upgrade 1.0.0 +``` + +للرجوع إلى 0.x، شغّل + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## تغييرات تجربة الاستخدام + +أصبح سجل الجلسة أكثر اختصارا، ولا يعرض التفاصيل الكاملة إلا لأداتي edit و bash. + +أضفنا شريط أوامر تمر عبره تقريبا كل العمليات. اضغط ctrl+p لإظهاره في أي سياق ولرؤية كل ما يمكنك فعله. + +أضفنا شريطا جانبيا للجلسة (يمكن إظهاره/إخفاؤه) يحتوي على معلومات مفيدة. + +أزلنا بعض الوظائف التي لم نكن متأكدين أن أحدا يستخدمها فعلا. إذا كانت هناك ميزة مهمة مفقودة، فالرجاء فتح issue وسنعيدها بسرعة. + +--- + +## تغييرات غير متوافقة + +### إعادة تسمية اختصارات المفاتيح + +- messages_revert -> messages_undo +- switch_agent -> agent_cycle +- switch_agent_reverse -> agent_cycle_reverse +- switch_mode -> agent_cycle +- switch_mode_reverse -> agent_cycle_reverse + +### إزالة اختصارات المفاتيح + +- messages_layout_toggle +- messages_next +- messages_previous +- file_diff_toggle +- file_search +- file_close +- file_list +- app_help +- project_init +- tool_details +- thinking_blocks diff --git a/packages/web/src/content/docs/ar/acp.mdx b/packages/web/src/content/docs/ar/acp.mdx new file mode 100644 index 000000000..35b20b2d6 --- /dev/null +++ b/packages/web/src/content/docs/ar/acp.mdx @@ -0,0 +1,154 @@ +--- +title: دعم ACP +description: استخدم OpenCode في أي محرر متوافق مع ACP. +--- + +يدعم OpenCode بروتوكول [Agent Client Protocol](https://agentclientprotocol.com) أو (ACP)، مما يتيح لك استخدامه مباشرة في المحررات وبيئات التطوير المتكاملة (IDEs) المتوافقة. + +:::tip +للاطلاع على قائمة بالمحررات والأدوات التي تدعم ACP، راجع [ACP progress report](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP بروتوكول مفتوح يوحّد آلية التواصل بين محررات الشيفرة ووكلاء البرمجة بالذكاء الاصطناعي. + +--- + +## الإعداد +لاستخدام OpenCode عبر ACP، اضبط محررك ليشغّل الأمر `opencode acp`. + +يشغّل هذا الأمر OpenCode كعملية فرعية متوافقة مع ACP تتواصل مع محررك عبر JSON-RPC باستخدام stdio. + +فيما يلي أمثلة لمحررات شائعة تدعم ACP. + +--- + +### Zed + +أضف إلى إعدادات [Zed](https://zed.dev) (`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +لفتحه، استخدم الإجراء `agent: new thread` في **Command Palette**. + +يمكنك أيضا ربط اختصار لوحة مفاتيح عبر تعديل `keymap.json`: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### JetBrains IDEs + +أضف إلى ملف acp.json الخاص بـ [JetBrains IDE](https://www.jetbrains.com/) وفقا لـ [documentation](https://www.jetbrains.com/help/ai-assistant/acp.html): + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +لفتحه، اختر الوكيل الجديد 'OpenCode' من محدد الوكلاء في AI Chat. + +--- + +### Avante.nvim + +أضف إلى إعدادات [Avante.nvim](https://github.com/yetone/avante.nvim): + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +إذا احتجت إلى تمرير متغيرات البيئة: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +لاستخدام OpenCode كوكيل ACP في [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim)، أضف التالي إلى إعدادات Neovim: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +يضبط هذا الإعداد CodeCompanion لاستخدام OpenCode كوكيل ACP للدردشة. + +إذا احتجت إلى تمرير متغيرات البيئة (مثل `OPENCODE_API_KEY`)، فارجع إلى [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) ضمن توثيق CodeCompanion.nvim للاطلاع على التفاصيل كاملة. + +## الدعم +يعمل OpenCode عبر ACP بالطريقة نفسها التي يعمل بها في الطرفية. جميع الميزات مدعومة: + +:::note +بعض أوامر الشرطة المائلة المضمنة مثل `/undo` و`/redo` غير مدعومة حاليا. +::: + +- الأدوات المضمنة (عمليات الملفات، أوامر الطرفية، إلخ.) +- الأدوات المخصصة وأوامر الشرطة المائلة +- خوادم MCP المضبوطة في إعدادات OpenCode +- قواعد خاصة بالمشروع من `AGENTS.md` +- المنسقات (formatters) والمدققات (linters) المخصصة +- نظام الوكلاء والأذونات diff --git a/packages/web/src/content/docs/ar/agents.mdx b/packages/web/src/content/docs/ar/agents.mdx new file mode 100644 index 000000000..59d43d313 --- /dev/null +++ b/packages/web/src/content/docs/ar/agents.mdx @@ -0,0 +1,746 @@ +--- +title: الوكلاء +description: هيّئ الوكلاء المتخصصين واستخدمهم. +--- + +الوكلاء هم مساعدون متخصصون بالذكاء الاصطناعي يمكن تهيئتهم لمهام وسير عمل محدد. يتيحون لك إنشاء أدوات مركزة مع موجّهات مخصصة ونماذج وصلاحية وصول للأدوات. + +:::tip +استخدم وكيل plan لتحليل الشفرة ومراجعة الاقتراحات بدون إجراء أي تغييرات على الشفرة. +::: + +يمكنك التبديل بين الوكلاء أثناء الجلسة أو استدعاؤهم عبر الإشارة بـ `@`. + +--- + +## الأنواع + +يوجد نوعان من الوكلاء في OpenCode: وكلاء أساسيون ووكلاء فرعيون. + +--- + +### الوكلاء الأساسيون + +الوكلاء الأساسيون هم المساعدون الرئيسيون الذين تتفاعل معهم مباشرة. يمكنك التنقل بينهم باستخدام مفتاح **Tab** أو اختصار `switch_agent` الذي قمت بتهيئته. يتولى هؤلاء الوكلاء محادثتك الرئيسية. يتم ضبط وصول الأدوات عبر الأذونات — على سبيل المثال، يمتلك Build جميع الأدوات مفعلة بينما يكون Plan مقيّدا. + +:::tip +يمكنك استخدام مفتاح **Tab** للتبديل بين الوكلاء الأساسيين أثناء الجلسة. +::: + +يأتي OpenCode مع وكيلين أساسيين مدمجين: **Build** و **Plan**. سنلقي نظرة عليهما أدناه. + +--- + +### الوكلاء الفرعيون + +الوكلاء الفرعيون هم مساعدين متخصصين يمكن للوكلاء الأساسيين استدعاؤهم لمهام محددة. يمكنك أيضا استدعاؤهم يدويا عبر **الإشارة بـ @** في رسائلك. + +يأتي OpenCode مع وكيلين فرعيين مدمجين: **General** و **Explore**. سنلقي نظرة على ذلك أدناه. + +--- + +## المدمجة + +يأتي OpenCode مع وكيلين أساسيين مدمجين ووكيلين فرعيين مدمجين. + +--- + +### استخدام build + +_الوضع_: `primary` + +Build هو الوكيل الأساسي **الافتراضي** مع تفعيل جميع الأدوات. هذا هو الوكيل القياسي لأعمال التطوير عندما تحتاج إلى وصول كامل لعمليات الملفات وأوامر النظام. + +--- + +### استخدام plan + +_الوضع_: `primary` + +وكيل مقيّد صُمم للتخطيط والتحليل. نستخدم نظام أذونات لمنحك تحكما أكبر ومنع التغييرات غير المقصودة. +افتراضيا، يتم ضبط كل ما يلي على `ask`: + +- `file edits`: جميع عمليات الكتابة والتصحيح (patches) والتحرير +- `bash`: جميع أوامر bash + +يفيد هذا الوكيل عندما تريد من النموذج تحليل الشفرة أو اقتراح تغييرات أو إنشاء خطط بدون إجراء أي تعديلات فعلية على قاعدة الشفرة. + +--- + +### استخدام general + +_الوضع_: `subagent` + +وكيل عام الغرض للبحث في أسئلة معقدة وتنفيذ مهام متعددة الخطوات. لديه وصول كامل للأدوات (باستثناء todo)، لذا يمكنه إجراء تغييرات على الملفات عند الحاجة. استخدمه لتشغيل عدة وحدات عمل بالتوازي. + +--- + +### استخدام explore + +_الوضع_: `subagent` + +وكيل سريع للقراءة فقط لاستكشاف قواعد الشفرة. لا يستطيع تعديل الملفات. استخدمه عندما تحتاج إلى العثور بسرعة على ملفات عبر أنماط، أو البحث في الشفرة عن كلمات مفتاحية، أو الإجابة عن أسئلة حول قاعدة الشفرة. + +--- + +### استخدام compaction + +_الوضع_: `primary` + +وكيل نظام مخفي يضغط السياق الطويل إلى ملخص أصغر. يعمل تلقائيا عند الحاجة ولا يمكن اختياره من واجهة المستخدم. + +--- + +### استخدام title + +_الوضع_: `primary` + +وكيل نظام مخفي ينشئ عناوين قصيرة للجلسات. يعمل تلقائيا ولا يمكن اختياره من واجهة المستخدم. + +--- + +### استخدام summary + +_الوضع_: `primary` + +وكيل نظام مخفي ينشئ ملخصات للجلسات. يعمل تلقائيا ولا يمكن اختياره من واجهة المستخدم. + +--- + +## الاستخدام + +1. للوكلاء الأساسيين، استخدم مفتاح **Tab** للتنقل بينهم أثناء الجلسة. يمكنك أيضا استخدام اختصار `switch_agent` الذي قمت بتهيئته. + +2. يمكن استدعاء الوكلاء الفرعيين: + - **تلقائيا** بواسطة الوكلاء الأساسيين لمهام متخصصة بناء على أوصافهم. + - يدويا عبر **الإشارة بـ @** إلى وكيل فرعي في رسالتك. على سبيل المثال: + + ```txt frame="none" + @general help me search for this function + ``` + +3. **التنقل بين الجلسات**: عندما ينشئ الوكلاء الفرعيون جلسات فرعية خاصة بهم، يمكنك التنقل بين الجلسة الأم وجميع الجلسات الفرعية باستخدام: + - **\+Right** (أو اختصار `session_child_cycle` الذي قمت بتهيئته) للتنقل للأمام عبر parent → child1 → child2 → ... → parent + - **\+Left** (أو اختصار `session_child_cycle_reverse` الذي قمت بتهيئته) للتنقل للخلف عبر parent ← child1 ← child2 ← ... ← parent + + يتيح لك ذلك التبديل بسلاسة بين المحادثة الرئيسية وعمل الوكلاء الفرعيين المتخصص. + +--- + +## التهيئة + +يمكنك تخصيص الوكلاء المدمجين أو إنشاء وكلائك عبر التهيئة. يمكن تهيئة الوكلاء بطريقتين: + +--- + +### JSON + +هيّئ الوكلاء في ملف إعدادات `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Markdown + +يمكنك أيضا تعريف الوكلاء باستخدام ملفات Markdown. ضعها في: + +- عام: `~/.config/opencode/agents/` +- لكل مشروع: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +يصبح اسم ملف Markdown هو اسم الوكيل. على سبيل المثال، ينشئ `review.md` وكيلا باسم `review`. + +--- + +## الخيارات + +لنلق نظرة على خيارات التهيئة هذه بمزيد من التفصيل. + +--- + +### الوصف + +استخدم خيار `description` لتقديم وصف موجز لما يفعله الوكيل ومتى ينبغي استخدامه. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +هذا خيار تهيئة **إلزامي**. + +--- + +### درجة الحرارة + +تحكم في العشوائية والإبداع في ردود النموذج عبر إعداد `temperature`. + +القيم الأقل تجعل الردود أكثر تركيزا وحتمية، بينما تزيد القيم الأعلى من الإبداع والتنوع. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +عادة تتراوح قيم `temperature` بين 0.0 و 1.0: + +- **0.0-0.2**: ردود شديدة التركيز وحتمية، مثالية لتحليل الشفرة والتخطيط +- **0.3-0.5**: ردود متوازنة مع قدر من الإبداع، مناسبة لمهام التطوير العامة +- **0.6-1.0**: ردود أكثر إبداعا وتنوعا، مفيدة للعصف الذهني والاستكشاف + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +إذا لم يتم تحديد temperature، يستخدم OpenCode القيم الافتراضية الخاصة بالنموذج؛ عادة 0 لمعظم النماذج و 0.55 لنماذج Qwen. + +--- + +### الحد الأقصى للخطوات + +تحكم في الحد الأقصى لعدد التكرارات الوكيلة التي يمكن لوكيل تنفيذها قبل أن يُجبر على الرد بنص فقط. يتيح ذلك للمستخدمين الذين يرغبون في التحكم بالتكاليف وضع حد للإجراءات الوكيلة. + +إذا لم يتم ضبط هذا الخيار، سيستمر الوكيل بالتكرار حتى يقرر النموذج التوقف أو يقاطع المستخدم الجلسة. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +عند بلوغ الحد، يتلقى الوكيل موجّها نظاميا خاصا يطلب منه الرد بملخص لعمله والمهام المتبقية الموصى بها. + +:::caution +الحقل القديم `maxSteps` متقادم. استخدم `steps` بدلا منه. +::: + +--- + +### التعطيل + +اضبطه على `true` لتعطيل الوكيل. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### الموجّه + +حدد ملف موجّه نظامي مخصص لهذا الوكيل عبر إعداد `prompt`. يجب أن يحتوي ملف الموجّه على تعليمات خاصة بهدف الوكيل. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +هذا المسار نسبي لمكان وجود ملف الإعدادات. لذلك يعمل هذا لكل من إعدادات OpenCode العامة وإعدادات المشروع. + +--- + +### النموذج + +استخدم إعداد `model` لتجاوز (override) النموذج لهذا الوكيل. يفيد ذلك لاستخدام نماذج مختلفة مُحسّنة لمهام مختلفة. على سبيل المثال، نموذج أسرع للتخطيط ونموذج أقدر للتنفيذ. + +:::tip +إذا لم تحدد نموذجا، يستخدم الوكلاء الأساسيون [النموذج المُهيأ عالميا](/docs/config#models)، بينما يستخدم الوكلاء الفرعيون نموذج الوكيل الأساسي الذي استدعاهم. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +يستخدم معرّف النموذج في إعدادات OpenCode الصيغة `provider/model-id`. على سبيل المثال، إذا كنت تستخدم [OpenCode Zen](/docs/zen)، فستستخدم `opencode/gpt-5.1-codex` لـ GPT 5.1 Codex. + +--- + +### الأدوات + +تحكم في الأدوات المتاحة لهذا الوكيل عبر إعداد `tools`. يمكنك تفعيل أو تعطيل أدوات محددة بضبطها على `true` أو `false`. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +إعدادات الوكيل الخاصة تتجاوز الإعدادات العامة. +::: + +يمكنك أيضا استخدام المحارف البديلة (wildcards) للتحكم في عدة أدوات دفعة واحدة. على سبيل المثال، لتعطيل جميع الأدوات القادمة من خادم MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[اعرف المزيد عن الأدوات](/docs/tools). + +--- + +### الأذونات + +يمكنك تهيئة الأذونات لإدارة الإجراءات التي يستطيع الوكيل تنفيذها. حاليا، يمكن تهيئة أذونات أدوات `edit` و `bash` و `webfetch` إلى: + +- `"ask"` — طلب الموافقة قبل تشغيل الأداة +- `"allow"` — السماح بكل العمليات بدون موافقة +- `"deny"` — تعطيل الأداة + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +يمكنك تجاوز هذه الأذونات لكل وكيل. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +يمكنك أيضا ضبط الأذونات في وكلاء Markdown. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +حلل الشفرة فقط واقترح التغييرات. +``` + +يمكنك ضبط الأذونات لأوامر bash محددة. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +يمكن لهذا أن يقبل نمط glob. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +ويمكنك أيضا استخدام المحرف البديل `*` لإدارة الأذونات لكل الأوامر. +وبما أن آخر قاعدة مطابقة لها الأولوية، ضع قاعدة `*` أولا ثم القواعد الأكثر تخصيصا بعدها. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[اعرف المزيد عن الأذونات](/docs/permissions). + +--- + +### الوضع + +تحكم في وضع الوكيل عبر إعداد `mode`. يُستخدم خيار `mode` لتحديد كيفية استخدام الوكيل. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +يمكن ضبط خيار `mode` على `primary` أو `subagent` أو `all`. إذا لم يتم تحديد `mode`، فالقيمة الافتراضية هي `all`. + +--- + +### مخفي + +أخفِ وكيلا فرعيا من قائمة الإكمال التلقائي لـ `@` عبر `hidden: true`. يفيد ذلك للوكلاء الفرعيين الداخليين الذين ينبغي استدعاؤهم برمجيا فقط بواسطة وكلاء آخرين عبر أداة Task. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +يؤثر هذا فقط على ظهور الوكيل للمستخدم في قائمة الإكمال التلقائي. لا يزال بإمكان النموذج استدعاء الوكلاء المخفيين عبر أداة Task إذا سمحت الأذونات. + +:::note +ينطبق فقط على الوكلاء ذوي `mode: subagent`. +::: + +--- + +### أذونات Task + +تحكم في أي الوكلاء الفرعيين يمكن لوكيل استدعاؤهم عبر أداة Task باستخدام `permission.task`. يستخدم أنماط glob لمطابقة مرنة. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +عند ضبطها على `deny`، تتم إزالة الوكيل الفرعي بالكامل من وصف أداة Task، لذا لن يحاول النموذج استدعاءه. + +:::tip +تُقيّم القواعد بالترتيب، و **آخر قاعدة مطابقة هي التي تفوز**. في المثال أعلاه، يطابق `orchestrator-planner` كلا من `*` (deny) و `orchestrator-*` (allow)، ولكن بما أن `orchestrator-*` تأتي بعد `*` فالنتيجة هي `allow`. +::: + +:::tip +يمكن للمستخدمين دائما استدعاء أي وكيل فرعي مباشرة عبر قائمة الإكمال التلقائي لـ `@`، حتى لو كانت أذونات task للوكيل سترفض ذلك. +::: + +--- + +### اللون + +خصص المظهر البصري للوكيل في واجهة المستخدم عبر خيار `color`. يؤثر ذلك على كيفية ظهور الوكيل في الواجهة. + +استخدم لونا سداسيا صالحا (مثل `#FF5733`) أو لون سمة: `primary` و `secondary` و `accent` و `success` و `warning` و `error` و `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### Top P + +تحكم في تنوع الردود عبر خيار `top_p`. بديل عن temperature للتحكم بالعشوائية. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +تتراوح القيم من 0.0 إلى 1.0. القيم الأقل أكثر تركيزا، والقيم الأعلى أكثر تنوعا. + +--- + +### خيارات إضافية + +أي خيارات أخرى تحددها في تهيئة الوكيل سيتم **تمريرها مباشرة** إلى مزود النموذج كخيارات للنموذج. يتيح لك ذلك استخدام ميزات ومعاملات خاصة بالمزود. + +على سبيل المثال، مع نماذج الاستدلال من OpenAI يمكنك التحكم في مجهود الاستدلال: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +هذه الخيارات الإضافية تعتمد على النموذج والمزود. راجع توثيق مزودك لمعرفة المعاملات المتاحة. + +:::tip +شغّل `opencode models` لعرض قائمة بالنماذج المتاحة. +::: + +--- + +## إنشاء وكلاء + +يمكنك إنشاء وكلاء جدد باستخدام الأمر التالي: + +```bash +opencode agent create +``` + +سيقوم هذا الأمر التفاعلي بما يلي: + +1. سيسألك أين تريد حفظ الوكيل: عام (global) أو خاص بالمشروع. +2. سيطلب وصفا لما ينبغي أن يفعله الوكيل. +3. سيولّد موجّها نظاميا ومعرّفا مناسبا. +4. سيتيح لك اختيار الأدوات التي يمكن للوكيل الوصول إليها. +5. أخيرا، سينشئ ملف Markdown يحتوي تهيئة الوكيل. + +--- + +## حالات الاستخدام + +فيما يلي بعض حالات الاستخدام الشائعة لوكلاء مختلفين. + +- **Build agent**: أعمال تطوير كاملة مع تفعيل جميع الأدوات +- **Plan agent**: تحليل وتخطيط بدون إجراء تغييرات +- **Review agent**: مراجعة الشفرة مع وصول للقراءة فقط بالإضافة إلى أدوات التوثيق +- **Debug agent**: يركز على التحقيق مع تفعيل أدوات bash والقراءة +- **Docs agent**: كتابة التوثيق مع عمليات الملفات بدون أوامر النظام + +--- + +## أمثلة + +فيما يلي بعض أمثلة الوكلاء التي قد تجدها مفيدة. + +:::tip +هل لديك وكيل تود مشاركته؟ [قدّم PR](https://github.com/anomalyco/opencode). +::: + +--- + +### وكيل التوثيق + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### مدقق أمني + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/ar/cli.mdx b/packages/web/src/content/docs/ar/cli.mdx new file mode 100644 index 000000000..e98579f6d --- /dev/null +++ b/packages/web/src/content/docs/ar/cli.mdx @@ -0,0 +1,601 @@ +--- +title: سطر الأوامر +description: خيارات وأوامر سطر أوامر OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +يبدأ سطر أوامر OpenCode افتراضيا واجهة [TUI](/docs/tui) عند تشغيله بدون أي معاملات. + +```bash +opencode +``` + +كما يدعم أيضا أوامر موثقة في هذه الصفحة، ما يتيح لك التفاعل مع OpenCode برمجيا. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui + +بدء واجهة المستخدم الطرفية (TUI) الخاصة بـ OpenCode. + +```bash +opencode [project] +``` + +#### الخيارات + +| الخيار | المختصر | الوصف | +| ------------ | ------- | -------------------------------------------- | +| `--continue` | `-c` | متابعة الجلسة الأخيرة | +| `--session` | `-s` | معرّف الجلسة للمتابعة | +| `--prompt` | | الموجّه المراد استخدامه | +| `--model` | `-m` | النموذج المراد استخدامه بصيغة provider/model | +| `--agent` | | الوكيل المراد استخدامه | +| `--port` | | المنفذ الذي يتم الاستماع عليه | +| `--hostname` | | اسم المضيف الذي يتم الاستماع عليه | + +--- + +## الأوامر + +يتضمن سطر أوامر OpenCode أيضا الأوامر التالية. + +--- + +### agent + +إدارة وكلاء OpenCode. + +```bash +opencode agent [command] +``` + +--- + +### attach + +إرفاق طرفية بخادم الواجهة الخلفية لـ OpenCode قيد التشغيل بالفعل، والذي تم تشغيله عبر الأمرين `serve` أو `web`. + +```bash +opencode attach [url] +``` + +يتيح ذلك استخدام واجهة TUI مع واجهة خلفية لـ OpenCode تعمل عن بعد. على سبيل المثال: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### الرايات + +| الراية | المختصر | الوصف | +| ----------- | ------- | ----------------------------------- | +| `--dir` | | دليل العمل الذي ستبدأ منه واجهة TUI | +| `--session` | `-s` | معرّف الجلسة للمتابعة | + +--- + +#### create + +إنشاء وكيل جديد بإعدادات مخصصة. + +```bash +opencode agent create +``` + +سيرشدك هذا الأمر خلال إنشاء وكيل جديد مع موجه نظام مخصص وإعدادات الأدوات. + +--- + +#### list + +عرض جميع الوكلاء المتاحين. + +```bash +opencode agent list +``` + +--- + +### auth + +أمر لإدارة بيانات الاعتماد وتسجيل الدخول لمزودي الخدمة. + +```bash +opencode auth [command] +``` + +--- + +#### login + +يعتمد OpenCode على قائمة المزودين في [Models.dev](https://models.dev)، لذا يمكنك استخدام `opencode auth login` لتهيئة مفاتيح API لأي مزود ترغب باستخدامه. يتم حفظ ذلك في `~/.local/share/opencode/auth.json`. + +```bash +opencode auth login +``` + +عند تشغيل OpenCode يقوم بتحميل المزودين من ملف بيانات الاعتماد، وكذلك أي مفاتيح معرّفة في متغيرات البيئة لديك أو في ملف `.env` ضمن مشروعك. + +--- + +#### list + +يسرد جميع المزودين الذين تم توثيقهم كما هم محفوظون في ملف بيانات الاعتماد. + +```bash +opencode auth list +``` + +أو النسخة المختصرة. + +```bash +opencode auth ls +``` + +--- + +#### logout + +يسجلك خارج مزود عبر حذفه من ملف بيانات الاعتماد. + +```bash +opencode auth logout +``` + +--- + +### github + +إدارة وكيل GitHub لأتمتة المستودع. + +```bash +opencode github [command] +``` + +--- + +#### install + +تثبيت وكيل GitHub في مستودعك. + +```bash +opencode github install +``` + +يقوم ذلك بإعداد سير عمل GitHub Actions اللازم ويرشدك خلال عملية التهيئة. [اعرف المزيد](/docs/github). + +--- + +#### run + +تشغيل وكيل GitHub. يُستخدم هذا عادة ضمن GitHub Actions. + +```bash +opencode github run +``` + +##### الرايات + +| الراية | الوصف | +| --------- | ------------------------------------ | +| `--event` | حدث GitHub مُحاكى لتشغيل الوكيل عليه | +| `--token` | رمز وصول شخصي لـ GitHub | + +--- + +### mcp + +إدارة خوادم Model Context Protocol. + +```bash +opencode mcp [command] +``` + +--- + +#### add + +إضافة خادم MCP إلى تهيئتك. + +```bash +opencode mcp add +``` + +سيرشدك هذا الأمر خلال إضافة خادم MCP محلي أو بعيد. + +--- + +#### list + +عرض جميع خوادم MCP المُهيأة وحالة اتصالها. + +```bash +opencode mcp list +``` + +أو استخدم النسخة المختصرة. + +```bash +opencode mcp ls +``` + +--- + +#### auth + +إجراء المصادقة مع خادم MCP يدعم OAuth. + +```bash +opencode mcp auth [name] +``` + +إذا لم تُحدِّد اسم خادم، فسيُطلب منك الاختيار من الخوادم المتاحة الداعمة لـ OAuth. + +يمكنك أيضا عرض الخوادم الداعمة لـ OAuth وحالة المصادقة الخاصة بها. + +```bash +opencode mcp auth list +``` + +أو استخدم النسخة المختصرة. + +```bash +opencode mcp auth ls +``` + +--- + +#### logout + +إزالة بيانات اعتماد OAuth لخادم MCP. + +```bash +opencode mcp logout [name] +``` + +--- + +#### debug + +تشخيص مشاكل اتصال OAuth لخادم MCP. + +```bash +opencode mcp debug +``` + +--- + +### models + +عرض جميع النماذج المتاحة من المزودين المُهيأين. + +```bash +opencode models [provider] +``` + +يعرض هذا الأمر جميع النماذج المتاحة عبر المزودين المُهيأين لديك بصيغة `provider/model`. + +هذا مفيد لتحديد اسم النموذج الدقيق الذي ستستخدمه في [تهيئتك](/docs/config/). + +يمكنك اختياريا تمرير معرّف مزود لتصفية النماذج حسب ذلك المزود. + +```bash +opencode models anthropic +``` + +#### الرايات + +| الراية | الوصف | +| ----------- | ------------------------------------------------------------- | +| `--refresh` | تحديث ذاكرة التخزين المؤقت للنماذج من models.dev | +| `--verbose` | استخدام مخرجات أكثر تفصيلا للنماذج (تشمل بيانات مثل التكاليف) | + +استخدم الراية `--refresh` لتحديث قائمة النماذج المخزنة مؤقتا. يفيد ذلك عند إضافة نماذج جديدة إلى مزود وتريد رؤيتها في OpenCode. + +```bash +opencode models --refresh +``` + +--- + +### run + +تشغيل opencode في وضع غير تفاعلي عبر تمرير موجه مباشرة. + +```bash +opencode run [message..] +``` + +هذا مفيد للبرمجة النصية والأتمتة، أو عندما تريد إجابة سريعة دون تشغيل واجهة TUI كاملة. على سبيل المثال. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +يمكنك أيضا الإرفاق بمثيل `opencode serve` قيد التشغيل لتجنّب زمن الإقلاع البارد لخوادم MCP في كل تشغيل: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### الرايات + +| الراية | المختصر | الوصف | +| ------------ | ------- | -------------------------------------------------------------- | +| `--command` | | الأمر المراد تشغيله؛ استخدم الرسالة كوسائط | +| `--continue` | `-c` | متابعة الجلسة الأخيرة | +| `--session` | `-s` | معرّف الجلسة للمتابعة | +| `--share` | | مشاركة الجلسة | +| `--model` | `-m` | النموذج المراد استخدامه بصيغة provider/model | +| `--agent` | | الوكيل المراد استخدامه | +| `--file` | `-f` | ملف/ملفات لإرفاقها بالرسالة | +| `--format` | | التنسيق: default (منسق) أو json (أحداث JSON خام) | +| `--title` | | عنوان للجلسة (يستخدم موجهًا مقتطعًا إن لم تُحدَّد قيمة) | +| `--attach` | | الإرفاق بخادم opencode قيد التشغيل (مثل http://localhost:4096) | +| `--port` | | منفذ الخادم المحلي (الافتراضي منفذ عشوائي) | + +--- + +### serve + +بدء خادم OpenCode بدون واجهة للوصول عبر API. راجع [توثيق الخادم](/docs/server) لواجهة HTTP الكاملة. + +```bash +opencode serve +``` + +يشغّل هذا خادم HTTP يوفّر وصولا عبر API لوظائف opencode دون واجهة TUI. اضبط `OPENCODE_SERVER_PASSWORD` لتفعيل مصادقة HTTP الأساسية (اسم المستخدم الافتراضي `opencode`). + +#### الرايات + +| الراية | الوصف | +| ------------ | ----------------------------------------- | +| `--port` | المنفذ الذي يتم الاستماع عليه | +| `--hostname` | اسم المضيف الذي يتم الاستماع عليه | +| `--mdns` | تفعيل اكتشاف mDNS | +| `--cors` | أصول/منشأات إضافية للمتصفح للسماح بـ CORS | + +--- + +### session + +إدارة جلسات OpenCode. + +```bash +opencode session [command] +``` + +--- + +#### list + +عرض جميع جلسات OpenCode. + +```bash +opencode session list +``` + +##### الرايات + +| الراية | المختصر | الوصف | +| ------------- | ------- | ------------------------------------- | +| `--max-count` | `-n` | حصر النتائج في أحدث N جلسات | +| `--format` | | تنسيق المخرجات: table أو json (table) | + +--- + +### stats + +عرض إحصاءات استخدام الرموز والتكلفة لجلسات OpenCode لديك. + +```bash +opencode stats +``` + +#### الرايات + +| الراية | الوصف | +| ----------- | ------------------------------------------------------------------------- | +| `--days` | عرض الإحصاءات لآخر N يومًا (الافتراضي: كل الوقت) | +| `--tools` | عدد الأدوات المطلوب عرضها (الافتراضي: الكل) | +| `--models` | عرض تفصيل استخدام النماذج (مخفي افتراضيا). مرّر رقمًا لعرض أعلى N | +| `--project` | التصفية حسب المشروع (الافتراضي: كل المشاريع، سلسلة فارغة: المشروع الحالي) | + +--- + +### export + +تصدير بيانات الجلسة بصيغة JSON. + +```bash +opencode export [sessionID] +``` + +إذا لم تُقدّم معرّف جلسة، فسيُطلب منك الاختيار من الجلسات المتاحة. + +--- + +### import + +استيراد بيانات الجلسة من ملف JSON أو رابط مشاركة OpenCode. + +```bash +opencode import +``` + +يمكنك الاستيراد من ملف محلي أو من رابط مشاركة OpenCode. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### web + +بدء خادم OpenCode بدون واجهة مع واجهة ويب. + +```bash +opencode web +``` + +يشغّل هذا خادم HTTP ويفتح متصفح ويب للوصول إلى OpenCode عبر واجهة ويب. اضبط `OPENCODE_SERVER_PASSWORD` لتفعيل مصادقة HTTP الأساسية (اسم المستخدم الافتراضي `opencode`). + +#### الرايات + +| الراية | الوصف | +| ------------ | ----------------------------------------- | +| `--port` | المنفذ الذي يتم الاستماع عليه | +| `--hostname` | اسم المضيف الذي يتم الاستماع عليه | +| `--mdns` | تفعيل اكتشاف mDNS | +| `--cors` | أصول/منشأات إضافية للمتصفح للسماح بـ CORS | + +--- + +### acp + +بدء خادم ACP (Agent Client Protocol). + +```bash +opencode acp +``` + +يشغّل هذا الأمر خادم ACP يتواصل عبر stdin/stdout باستخدام nd-JSON. + +#### الرايات + +| الراية | الوصف | +| ------------ | --------------------------------- | +| `--cwd` | دليل العمل | +| `--port` | المنفذ الذي يتم الاستماع عليه | +| `--hostname` | اسم المضيف الذي يتم الاستماع عليه | + +--- + +### uninstall + +إلغاء تثبيت OpenCode وإزالة جميع الملفات ذات الصلة. + +```bash +opencode uninstall +``` + +#### الرايات + +| الراية | المختصر | الوصف | +| --------------- | ------- | ----------------------------------- | +| `--keep-config` | `-c` | الإبقاء على ملفات التهيئة | +| `--keep-data` | `-d` | الإبقاء على بيانات الجلسات واللقطات | +| `--dry-run` | | عرض ما سيتم حذفه دون تنفيذ الحذف | +| `--force` | `-f` | تخطي مطالبات التأكيد | + +--- + +### upgrade + +تحديث opencode إلى أحدث إصدار أو إلى إصدار محدد. + +```bash +opencode upgrade [target] +``` + +للترقية إلى أحدث إصدار. + +```bash +opencode upgrade +``` + +للترقية إلى إصدار محدد. + +```bash +opencode upgrade v0.1.48 +``` + +#### الرايات + +| الراية | المختصر | الوصف | +| ---------- | ------- | ----------------------------------------------------------- | +| `--method` | `-m` | طريقة التثبيت المستخدمة: curl أو npm أو pnpm أو bun أو brew | + +--- + +## الخيارات العامة + +يدعم سطر أوامر opencode الخيارات العامة التالية. + +| الراية | المختصر | الوصف | +| -------------- | ------- | -------------------------------------- | +| `--help` | `-h` | عرض المساعدة | +| `--version` | `-v` | طباعة رقم الإصدار | +| `--print-logs` | | طباعة السجلات إلى stderr | +| `--log-level` | | مستوى السجل (DEBUG, INFO, WARN, ERROR) | + +--- + +## متغيرات البيئة + +يمكن تهيئة OpenCode باستخدام متغيرات البيئة. + +| المتغير | النوع | الوصف | +| ------------------------------------- | ------- | --------------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | boolean | مشاركة الجلسات تلقائيا | +| `OPENCODE_GIT_BASH_PATH` | string | مسار ملف Git Bash التنفيذي على Windows | +| `OPENCODE_CONFIG` | string | مسار ملف التهيئة | +| `OPENCODE_CONFIG_DIR` | string | مسار دليل التهيئة | +| `OPENCODE_CONFIG_CONTENT` | string | محتوى تهيئة JSON مُضمّن | +| `OPENCODE_DISABLE_AUTOUPDATE` | boolean | تعطيل التحقق التلقائي من التحديثات | +| `OPENCODE_DISABLE_PRUNE` | boolean | تعطيل تنقية البيانات القديمة | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | boolean | تعطيل تحديث عنوان الطرفية تلقائيا | +| `OPENCODE_PERMISSION` | string | تهيئة أذونات JSON مُضمّنة | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | boolean | تعطيل الإضافات الافتراضية | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | boolean | تعطيل تنزيل خوادم LSP تلقائيا | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | boolean | تفعيل النماذج التجريبية | +| `OPENCODE_DISABLE_AUTOCOMPACT` | boolean | تعطيل ضغط السياق تلقائيا | +| `OPENCODE_DISABLE_CLAUDE_CODE` | boolean | تعطيل القراءة من `.claude` (الموجه + المهارات) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | boolean | تعطيل قراءة `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | boolean | تعطيل تحميل `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | boolean | تعطيل جلب النماذج من مصادر بعيدة | +| `OPENCODE_FAKE_VCS` | string | مزود VCS وهمي لأغراض الاختبار | +| `OPENCODE_DISABLE_FILETIME_CHECK` | boolean | تعطيل التحقق من وقت الملف لتحسين الأداء | +| `OPENCODE_CLIENT` | string | معرّف العميل (الافتراضي `cli`) | +| `OPENCODE_ENABLE_EXA` | boolean | تفعيل أدوات بحث الويب من Exa | +| `OPENCODE_SERVER_PASSWORD` | string | تفعيل المصادقة الأساسية لخادمي `serve`/`web` | +| `OPENCODE_SERVER_USERNAME` | string | تجاوز اسم مستخدم المصادقة الأساسية (الافتراضي `opencode`) | +| `OPENCODE_MODELS_URL` | string | رابط مخصص لجلب تهيئة النماذج | + +--- + +### تجريبي + +تقوم متغيرات البيئة التالية بتفعيل ميزات تجريبية قد تتغير أو تتم إزالتها. + +| المتغير | النوع | الوصف | +| ----------------------------------------------- | ------- | ------------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | boolean | تفعيل جميع الميزات التجريبية | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | boolean | تفعيل اكتشاف الأيقونات | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | boolean | تعطيل النسخ عند التحديد في TUI | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | number | المهلة الافتراضية لأوامر bash بالميلي ثانية | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | number | الحد الأقصى لرموز المخرجات لاستجابات LLM | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | boolean | تفعيل مراقب الملفات لكامل الدليل | +| `OPENCODE_EXPERIMENTAL_OXFMT` | boolean | تفعيل مُنسّق oxfmt | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | boolean | تفعيل أداة LSP تجريبية | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | boolean | تعطيل مراقب الملفات | +| `OPENCODE_EXPERIMENTAL_EXA` | boolean | تفعيل ميزات Exa التجريبية | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | boolean | تفعيل تدقيق أنواع LSP تجريبي | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | boolean | تفعيل ميزات markdown تجريبية | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | boolean | تفعيل وضع الخطة | diff --git a/packages/web/src/content/docs/ar/commands.mdx b/packages/web/src/content/docs/ar/commands.mdx new file mode 100644 index 000000000..323bb32ef --- /dev/null +++ b/packages/web/src/content/docs/ar/commands.mdx @@ -0,0 +1,322 @@ +--- +title: الأوامر +description: أنشئ أوامر مخصصة للمهام المتكررة. +--- + +تتيح لك الأوامر المخصصة تحديد مُطالبة (prompt) تريد تشغيلها عند تنفيذ ذلك الأمر في واجهة TUI. + +```bash frame="none" +/my-command +``` + +تُعدّ الأوامر المخصصة إضافةً إلى الأوامر المضمنة مثل `/init` و`/undo` و`/redo` و`/share` و`/help`. [اعرف المزيد](/docs/tui#commands). + +--- + +## إنشاء ملفات الأوامر + +أنشئ ملفات Markdown داخل الدليل `commands/` لتعريف أوامر مخصصة. + +أنشئ الملف `.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +تُعرِّف ترويسة Frontmatter خصائص الأمر، بينما يصبح المحتوى هو القالب. + +استخدم الأمر بكتابة `/` ثم اسم الأمر. + +```bash frame="none" +"/test" +``` + +--- + +## الإعداد + +يمكنك إضافة أوامر مخصصة عبر إعدادات OpenCode أو بإنشاء ملفات Markdown داخل الدليل `commands/`. + +--- + +### JSON + +استخدم خيار `command` في [config](/docs/config) الخاص بـ OpenCode: + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +يمكنك الآن تشغيل هذا الأمر في واجهة TUI: + +```bash frame="none" +/test +``` + +--- + +### Markdown + +يمكنك أيضًا تعريف الأوامر باستخدام ملفات Markdown. ضعها في: + +- على مستوى النظام: `~/.config/opencode/commands/` +- لكل مشروع: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +يصبح اسم ملف Markdown هو اسم الأمر. على سبيل المثال، يتيح لك `test.md` تشغيل: + +```bash frame="none" +/test +``` + +--- + +## إعداد المُطالبة + +تدعم مُطالبات الأوامر المخصصة عدة عناصر نائبة (placeholders) وبنى خاصة. + +--- + +### الوسائط + +مرِّر وسائط إلى الأوامر باستخدام العنصر النائب `$ARGUMENTS`. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +شغِّل الأمر مع وسائط: + +```bash frame="none" +/component Button +``` + +وسيُستبدل `$ARGUMENTS` بالقيمة `Button`. + +يمكنك أيضًا الوصول إلى كل وسيط على حدة باستخدام المعاملات الموضعية: + +- `$1` - الوسيط الأول +- `$2` - الوسيط الثاني +- `$3` - الوسيط الثالث +- وهكذا... + +على سبيل المثال: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +شغِّل الأمر: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +سيؤدي ذلك إلى استبدال: + +- `$1` بـ `config.json` +- `$2` بـ `src` +- `$3` بـ `{ "key": "value" }` + +--- + +### خرج الصدفة (Shell) + +استخدم _!`command`_ لحقن خرج [أمر bash](/docs/tui#bash-commands) داخل مُطالبتك. + +على سبيل المثال، لإنشاء أمر مخصص يُحلل تغطية الاختبارات: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +أو لمراجعة التغييرات الأخيرة: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +تُشغَّل الأوامر في دليل جذر مشروعك ويصبح خرجها جزءًا من المُطالبة. + +--- + +### مراجع الملفات + +ضمِّن الملفات في أمرك باستخدام `@` ثم اسم الملف. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +يُدرج محتوى الملف في المُطالبة تلقائيًا. + +--- + +## الخيارات + +لنلقِ نظرةً على خيارات الإعداد بالتفصيل. + +--- + +### القالب (`template`) + +يُعرِّف خيار `template` المُطالبة التي ستُرسل إلى نموذج اللغة (LLM) عند تنفيذ الأمر. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +هذا خيار إعداد **إلزامي**. + +--- + +### الوصف (`description`) + +استخدم خيار `description` لتقديم وصف موجز لما يفعله الأمر. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +يظهر هذا الوصف في واجهة TUI عند كتابة الأمر. + +--- + +### الوكيل (`agent`) + +استخدم إعداد `agent` لتحديد أي [agent](/docs/agents) ينبغي أن ينفّذ هذا الأمر (اختياريًا). +إذا كان هذا [subagent](/docs/agents/#subagents)، فسيؤدي الأمر افتراضيًا إلى تشغيل استدعاء subagent. +لإيقاف هذا السلوك، عيِّن `subtask` إلى `false`. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +هذا خيار إعداد **اختياري**. إن لم تُحدده، فسيُستخدم agent الحالي افتراضيًا. + +--- + +### مهمة فرعية (`subtask`) + +استخدم القيمة المنطقية `subtask` لفرض أن يُشغِّل الأمر استدعاء [subagent](/docs/agents/#subagents). +يفيد هذا إذا أردت ألا يلوّث الأمر السياق الأساسي لديك، إذ سيُجبر (**force**) الـ agent على العمل كـ subagent، +حتى لو كان `mode` مضبوطًا على `primary` في إعدادات [agent](/docs/agents). + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +هذا خيار إعداد **اختياري**. + +--- + +### النموذج (`model`) + +استخدم إعداد `model` لتجاوز النموذج الافتراضي لهذا الأمر. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +هذا خيار إعداد **اختياري**. + +--- + +## الأوامر المضمنة + +يتضمن opencode عدة أوامر مضمنة مثل `/init` و`/undo` و`/redo` و`/share` و`/help`؛ [اعرف المزيد](/docs/tui#commands). + +:::note +يمكن للأوامر المخصصة تجاوز الأوامر المضمنة. +::: + +إذا عرّفت أمرًا مخصصًا بالاسم نفسه، فسيستبدل الأمر المضمن. diff --git a/packages/web/src/content/docs/ar/config.mdx b/packages/web/src/content/docs/ar/config.mdx new file mode 100644 index 000000000..24b7869d0 --- /dev/null +++ b/packages/web/src/content/docs/ar/config.mdx @@ -0,0 +1,684 @@ +--- +title: الإعدادات +description: استخدام ملف إعدادات OpenCode بصيغة JSON. +--- + +يمكنك ضبط OpenCode باستخدام ملف إعدادات بصيغة JSON. + +--- + +## التنسيق + +يدعم OpenCode تنسيقي **JSON** و**JSONC** (JSON مع تعليقات). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## المواقع + +يمكنك وضع ملف الإعدادات في عدة مواقع مختلفة، ولكل موقع +ترتيب أولوية مختلف. + +:::note +تُدمَج ملفات الإعدادات **معًا** ولا تُستبدَل. +::: + +تُدمَج ملفات الإعدادات معًا ولا تُستبدَل. يتم جمع الإعدادات من مواقع الإعدادات التالية. تتجاوز الإعدادات اللاحقة الإعدادات السابقة فقط عند تعارض المفاتيح. أما الإعدادات غير المتعارضة فتبقى محفوظة من جميع الملفات. + +على سبيل المثال، إذا كان الإعداد العام يضبط `theme: "opencode"` و`autoupdate: true`، وكان إعداد المشروع يضبط `model: "anthropic/claude-sonnet-4-5"`، فستتضمن الإعدادات النهائية الخيارات الثلاثة جميعها. + +--- + +### ترتيب الأولوية + +تُحمَّل مصادر الإعدادات بهذا الترتيب (المصادر اللاحقة تتجاوز السابقة): + +1. **الإعدادات البعيدة** (من `.well-known/opencode`) - الإعدادات الافتراضية على مستوى المؤسسة +2. **الإعدادات العامة** (`~/.config/opencode/opencode.json`) - تفضيلات المستخدم +3. **إعدادات مخصصة** (`OPENCODE_CONFIG` env var) - تجاوزات مخصصة +4. **إعدادات المشروع** (`opencode.json` داخل المشروع) - إعدادات خاصة بالمشروع +5. **أدلة `.opencode`** - الوكلاء، الأوامر، الإضافات +6. **إعدادات ضمنية** (`OPENCODE_CONFIG_CONTENT` env var) - تجاوزات وقت التشغيل + +هذا يعني أن إعدادات المشروع يمكنها تجاوز الإعدادات العامة، وأن الإعدادات العامة يمكنها تجاوز الإعدادات الافتراضية البعيدة على مستوى المؤسسة. + +:::note +يستخدم الدليلان `.opencode` و`~/.config/opencode` **أسماء جمع** للأدلة الفرعية: `agents/` و`commands/` و`modes/` و`plugins/` و`skills/` و`tools/` و`themes/`. كما تُدعَم أسماء المفرد (مثل `agent/`) للتوافق مع الإصدارات السابقة. +::: + +--- + +### عن بُعد + +يمكن للمؤسسات توفير إعدادات افتراضية عبر نقطة النهاية `.well-known/opencode`. يتم جلب ذلك تلقائيًا عندما تقوم بالمصادقة مع مزوّد يدعم هذه الميزة. + +تُحمَّل الإعدادات البعيدة أولًا لتكون طبقة الأساس. ويمكن لجميع مصادر الإعدادات الأخرى (العامة، وإعدادات المشروع) تجاوز هذه القيم الافتراضية. + +على سبيل المثال، إذا كانت مؤسستك توفر خوادم MCP معطّلة افتراضيًا: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +يمكنك تفعيل خوادم محددة في إعداداتك المحلية: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### عام + +ضع إعدادات OpenCode العامة في `~/.config/opencode/opencode.json`. استخدم الإعدادات العامة للتفضيلات على مستوى المستخدم مثل السمات، والمزوّدين، أو اختصارات المفاتيح. + +تتجاوز الإعدادات العامة القيم الافتراضية البعيدة الخاصة بالمؤسسة. + +--- + +### لكل مشروع + +أضف `opencode.json` في جذر مشروعك. تمتلك إعدادات المشروع أعلى أولوية بين ملفات الإعدادات القياسية، إذ تتجاوز الإعدادات العامة والبعيدة معًا. + +:::tip +ضع إعدادات المشروع الخاصة في جذر مشروعك. +::: + +عند تشغيل OpenCode، يبحث عن ملف إعدادات في الدليل الحالي أو يصعد حتى أقرب دليل Git. + +ومن الآمن أيضًا تضمينه في Git، كما يستخدم نفس المخطط الخاص بالإعدادات العامة. + +--- + +### مسار مخصص + +حدّد مسار ملف إعدادات مخصصًا باستخدام متغير البيئة `OPENCODE_CONFIG`. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +تُحمَّل الإعدادات المخصصة بين الإعدادات العامة وإعدادات المشروع ضمن ترتيب الأولوية. + +--- + +### دليل مخصص + +حدّد دليل إعدادات مخصصًا باستخدام متغير البيئة `OPENCODE_CONFIG_DIR`. +سيتم البحث داخل هذا الدليل عن الوكلاء والأوامر والأوضاع والإضافات تمامًا مثل +الدليل القياسي `.opencode`، ويجب أن يتبع نفس البنية. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +يُحمَّل الدليل المخصص بعد الإعدادات العامة وأدلة `.opencode`، لذلك **يمكنه تجاوز** إعداداتها. + +--- + +## المخطط + +يحتوي ملف الإعدادات على مخطط مُعرَّف في [**`opencode.ai/config.json`**](https://opencode.ai/config.json). + +يفترض أن يتمكن محررك من التحقق والإكمال التلقائي اعتمادًا على هذا المخطط. + +--- + +### TUI + +يمكنك ضبط الإعدادات الخاصة بـ TUI عبر الخيار `tui`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +الخيارات المتاحة: + +- `scroll_acceleration.enabled` - تفعيل تسارع التمرير بأسلوب macOS. **له أولوية على `scroll_speed`.** +- `scroll_speed` - مُضاعِف سرعة تمرير مخصص (الافتراضي: `3`، الحد الأدنى: `1`). يتم تجاهله إذا كان `scroll_acceleration.enabled` مساويًا لـ `true`. +- `diff_style` - التحكم في عرض `diff`. القيمة `"auto"` تتكيف مع عرض الطرفية، و`"stacked"` تعرض عمودًا واحدًا دائمًا. + +[تعرف على المزيد حول استخدام TUI هنا](/docs/tui). + +--- + +### الخادم + +يمكنك ضبط إعدادات الخادم لأوامر `opencode serve` و`opencode web` عبر الخيار `server`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +الخيارات المتاحة: + +- `port` - المنفذ الذي سيتم الاستماع عليه. +- `hostname` - اسم المضيف الذي سيتم الاستماع عليه. عند تفعيل `mdns` وعدم ضبط اسم مضيف، تكون القيمة الافتراضية `0.0.0.0`. +- `mdns` - تفعيل اكتشاف الخدمة عبر mDNS. يتيح ذلك للأجهزة الأخرى على الشبكة اكتشاف خادم OpenCode. +- `mdnsDomain` - اسم نطاق مخصص لخدمة mDNS. القيمة الافتراضية هي `opencode.local`. مفيد لتشغيل عدة نُسخ على نفس الشبكة. +- `cors` - أصول إضافية مسموح بها لـ CORS عند استخدام خادم HTTP من عميل يعتمد على المتصفح. يجب أن تكون القيم أصولًا كاملة (البروتوكول + المضيف + منفذ اختياري)، مثل `https://app.example.com`. + +[تعرف على المزيد حول الخادم هنا](/docs/server). + +--- + +### الأدوات + +يمكنك إدارة الأدوات التي يمكن لـ LLM استخدامها عبر الخيار `tools`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[تعرف على المزيد حول الأدوات هنا](/docs/tools). + +--- + +### النماذج + +يمكنك ضبط المزوّدين والنماذج التي تريد استخدامها في إعدادات OpenCode عبر الخيارات `provider` و`model` و`small_model`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +يضبط الخيار `small_model` نموذجًا منفصلًا للمهام الخفيفة مثل توليد العناوين. افتراضيًا يحاول OpenCode استخدام نموذج أقل تكلفة إذا كان متاحًا لدى مزوّدك، وإلا فسيعود إلى النموذج الرئيسي. + +قد تتضمن خيارات المزوّد `timeout` و`setCacheKey`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - مهلة الطلب بالميلي ثانية (الافتراضي: 300000). اضبطه إلى `false` لتعطيله. +- `setCacheKey` - يضمن تعيين مفتاح التخزين المؤقت دائمًا للمزوّد المحدد. + +يمكنك أيضًا ضبط [النماذج المحلية](/docs/models#local). [تعرف على المزيد](/docs/models). + +--- + +#### خيارات خاصة بالمزوّد + +يدعم بعض المزوّدين خيارات إعداد إضافية تتجاوز الإعدادات العامة مثل `timeout` و`apiKey`. + +##### Amazon Bedrock + +يدعم Amazon Bedrock إعدادات خاصة بـ AWS: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - منطقة AWS لـ Bedrock (الافتراضي: متغير البيئة `AWS_REGION` أو `us-east-1`) +- `profile` - ملف تعريف AWS المُسمّى من `~/.aws/credentials` (الافتراضي: متغير البيئة `AWS_PROFILE`) +- `endpoint` - عنوان URL لنقطة نهاية مخصصة لنقاط نهاية VPC. هذا اسم بديل للخيار العام `baseURL` باستخدام مصطلحات AWS. إذا تم تحديدهما معًا، تكون أولوية `endpoint` أعلى. + +:::note +لرموز Bearer (`AWS_BEARER_TOKEN_BEDROCK` أو `/connect`) أولوية أعلى من المصادقة القائمة على ملف التعريف. راجع [أولوية المصادقة](/docs/providers#authentication-precedence) للتفاصيل. +::: + +[تعرف على المزيد حول إعداد Amazon Bedrock](/docs/providers#amazon-bedrock). + +--- + +### السمات + +يمكنك ضبط السمة التي تريد استخدامها في إعدادات OpenCode عبر الخيار `theme`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[تعرف على المزيد هنا](/docs/themes). + +--- + +### الوكلاء + +يمكنك ضبط وكلاء متخصصين لمهام محددة عبر الخيار `agent`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +يمكنك أيضًا تعريف الوكلاء باستخدام ملفات markdown في `~/.config/opencode/agents/` أو `.opencode/agents/`. [تعرف على المزيد هنا](/docs/agents). + +--- + +### الوكيل الافتراضي + +يمكنك تعيين الوكيل الافتراضي باستخدام الخيار `default_agent`. يحدد ذلك أي وكيل سيتم استخدامه عندما لا يتم تحديد وكيل صراحةً. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +يجب أن يكون الوكيل الافتراضي وكيلًا أساسيًا (وليس وكيلًا فرعيًا). يمكن أن يكون وكيلًا مدمجًا مثل `"build"` أو `"plan"`، أو [وكيلًا مخصصًا](/docs/agents) قمت بتعريفه. إذا لم يكن الوكيل المحدد موجودًا أو كان وكيلًا فرعيًا، فسيعود OpenCode إلى `"build"` مع تحذير. + +ينطبق هذا الإعداد على جميع الواجهات: TUI وCLI (`opencode run`) وتطبيق سطح المكتب وGitHub Action. + +--- + +### المشاركة + +يمكنك ضبط ميزة [share](/docs/share) عبر الخيار `share`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +يقبل هذا الإعداد القيم التالية: + +- `"manual"` - السماح بالمشاركة اليدوية عبر الأوامر (الافتراضي) +- `"auto"` - مشاركة المحادثات الجديدة تلقائيًا +- `"disabled"` - تعطيل المشاركة بالكامل + +افتراضيًا تكون المشاركة في الوضع اليدوي، حيث تحتاج إلى مشاركة المحادثات صراحةً باستخدام الأمر `/share`. + +--- + +### الأوامر + +يمكنك ضبط أوامر مخصصة للمهام المتكررة عبر الخيار `command`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +يمكنك أيضًا تعريف الأوامر باستخدام ملفات markdown في `~/.config/opencode/commands/` أو `.opencode/commands/`. [تعرف على المزيد هنا](/docs/commands). + +--- + +### اختصارات المفاتيح + +يمكنك تخصيص اختصارات المفاتيح عبر الخيار `keybinds`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[تعرف على المزيد هنا](/docs/keybinds). + +--- + +### التحديث التلقائي + +سيقوم OpenCode بتنزيل أي تحديثات جديدة تلقائيًا عند بدء التشغيل. يمكنك تعطيل ذلك عبر الخيار `autoupdate`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +إذا لم تكن تريد التحديثات لكنك تريد الإشعار عند توفر نسخة جديدة، فاضبط `autoupdate` على `"notify"`. +لاحظ أن هذا يعمل فقط إذا لم يتم تثبيته عبر مدير حزم مثل Homebrew. + +--- + +### المنسّقات + +يمكنك ضبط منسّقات الشفرة عبر الخيار `formatter`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[تعرف على المزيد حول المنسّقات هنا](/docs/formatters). + +--- + +### الأذونات + +افتراضيًا يسمح opencode **بجميع العمليات** دون الحاجة إلى موافقة صريحة. يمكنك تغيير ذلك عبر الخيار `permission`. + +على سبيل المثال، لضمان أن أداتي `edit` و`bash` تتطلبان موافقة المستخدم: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[تعرف على المزيد حول الأذونات هنا](/docs/permissions). + +--- + +### ضغط السياق + +يمكنك التحكم في سلوك ضغط السياق عبر الخيار `compaction`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - ضغط الجلسة تلقائيًا عند امتلاء السياق (الافتراضي: `true`). +- `prune` - إزالة مخرجات الأدوات القديمة لتوفير الرموز (tokens) (الافتراضي: `true`). + +--- + +### المراقِب + +يمكنك ضبط أنماط التجاهل لمراقِب الملفات عبر الخيار `watcher`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +تتبع الأنماط صياغة `glob`. استخدم ذلك لاستبعاد الأدلة المزدحمة من مراقبة الملفات. + +--- + +### خوادم MCP + +يمكنك ضبط خوادم MCP التي تريد استخدامها عبر الخيار `mcp`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[تعرف على المزيد هنا](/docs/mcp-servers). + +--- + +### الإضافات + +[الإضافات](/docs/plugins) توسّع OpenCode بأدوات وخُطافات وتكاملات مخصصة. + +ضع ملفات الإضافات في `.opencode/plugins/` أو `~/.config/opencode/plugins/`. يمكنك أيضًا تحميل إضافات من npm عبر الخيار `plugin`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[تعرف على المزيد هنا](/docs/plugins). + +--- + +### التعليمات + +يمكنك ضبط التعليمات الخاصة بالنموذج الذي تستخدمه عبر الخيار `instructions`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +يقبل هذا مصفوفة من المسارات وأنماط `glob` لملفات التعليمات. [تعرف على المزيد +حول القواعد هنا](/docs/rules). + +--- + +### المزوّدون المعطّلون + +يمكنك تعطيل المزوّدين الذين يتم تحميلهم تلقائيًا عبر الخيار `disabled_providers`. هذا مفيد عندما تريد منع تحميل مزوّدين معينين حتى لو كانت بيانات الاعتماد الخاصة بهم متاحة. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +الخيار `disabled_providers` له أولوية على `enabled_providers`. +::: + +يقبل الخيار `disabled_providers` مصفوفة من معرفات المزوّدين. عند تعطيل مزوّد: + +- لن يتم تحميله حتى لو كانت متغيرات البيئة مضبوطة. +- لن يتم تحميله حتى لو كانت مفاتيح API مضبوطة عبر الأمر `/connect`. +- لن تظهر نماذج هذا المزوّد في قائمة اختيار النموذج. + +--- + +### المزوّدون المفعّلون + +يمكنك تحديد قائمة سماح للمزوّدين عبر الخيار `enabled_providers`. عند ضبطه، سيتم تفعيل المزوّدين المحددين فقط وسيتم تجاهل البقية. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +هذا مفيد عندما تريد تقييد OpenCode لاستخدام مزوّدين محددين بدلًا من تعطيلهم واحدًا تلو الآخر. + +:::note +الخيار `disabled_providers` له أولوية على `enabled_providers`. +::: + +إذا ظهر مزوّد ضمن كل من `enabled_providers` و`disabled_providers`، تكون أولوية `disabled_providers` أعلى للتوافق مع الإصدارات السابقة. + +--- + +### تجريبي + +يحتوي المفتاح `experimental` على خيارات قيد التطوير النشط. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::caution +الخيارات التجريبية غير مستقرة. قد تتغير أو تُزال دون إشعار. +::: + +--- + +## المتغيرات + +يمكنك استخدام استبدال المتغيرات في ملفات الإعدادات للإشارة إلى متغيرات البيئة ومحتويات الملفات. + +--- + +### متغيرات البيئة + +استخدم `{env:VARIABLE_NAME}` لاستبدال متغيرات البيئة: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +إذا لم يكن متغير البيئة مضبوطًا، فسيتم استبداله بسلسلة فارغة. + +--- + +### الملفات + +استخدم `{file:path/to/file}` لاستبدال محتويات ملف: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +يمكن أن تكون مسارات الملفات: + +- نسبية إلى دليل ملف الإعدادات +- أو مسارات مطلقة تبدأ بـ `/` أو `~` + +يُفيد ذلك في: + +- الاحتفاظ بالبيانات الحساسة مثل مفاتيح API في ملفات منفصلة. +- تضمين ملفات تعليمات كبيرة دون تشويش ملف الإعدادات. +- مشاركة مقتطفات إعدادات مشتركة عبر عدة ملفات إعدادات. diff --git a/packages/web/src/content/docs/ar/custom-tools.mdx b/packages/web/src/content/docs/ar/custom-tools.mdx new file mode 100644 index 000000000..a0409255a --- /dev/null +++ b/packages/web/src/content/docs/ar/custom-tools.mdx @@ -0,0 +1,162 @@ +--- +title: الأدوات المخصصة +description: أنشئ أدوات يمكن لـ LLM استدعاؤها في opencode. +--- + +الأدوات المخصصة هي دوال تنشئها يمكن لـ LLM استدعاؤها أثناء المحادثات. تعمل جنبا إلى جنب مع [الأدوات المدمجة](/docs/tools) في opencode مثل `read` و`write` و`bash`. + +--- + +## إنشاء أداة +تُعرّف الأدوات كملفات **TypeScript** أو **JavaScript**. لكن تعريف الأداة يمكنه استدعاء سكربتات مكتوبة **بأي لغة** — إذ تُستخدم TypeScript أو JavaScript فقط لتعريف الأداة نفسه. + +--- + +### الموقع +يمكن تعريفها: + +- محليا بوضعها في مجلد `.opencode/tools/` داخل مشروعك. +- أو عالميا بوضعها في `~/.config/opencode/tools/`. + +--- + +### البنية +أسهل طريقة لإنشاء أدوات هي استخدام المساعد `tool()` الذي يوفر أمان الأنواع والتحقق. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +يصبح **اسم الملف** هو **اسم الأداة**. المثال أعلاه ينشئ أداة باسم `database`. + +--- + +#### عدة أدوات في ملف واحد +يمكنك أيضا تصدير عدة أدوات من ملف واحد. يصبح كل تصدير **أداة مستقلة** باسم **`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +ينشئ هذا أداتين: `math_add` و`math_multiply`. + +--- + +### الوسائط +يمكنك استخدام `tool.schema`، وهو في الأساس [Zod](https://zod.dev)، لتعريف أنواع الوسائط. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +يمكنك أيضا استيراد [Zod](https://zod.dev) مباشرة وإرجاع كائن عادي: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### السياق +تستقبل الأدوات سياقا حول الجلسة الحالية: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +استخدم `context.directory` لدليل العمل الخاص بالجلسة. +استخدم `context.worktree` لجذر شجرة العمل (worktree) في git. + +--- + +## أمثلة +### كتابة أداة بلغة Python +يمكنك كتابة أدواتك بأي لغة تريدها. إليك مثالا يجمع رقمين باستخدام Python. + +أولا، أنشئ الأداة كسكربت Python: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +ثم أنشئ تعريف الأداة الذي يستدعيه: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +هنا نستخدم أداة [`Bun.$`](https://bun.com/docs/runtime/shell) لتشغيل سكربت Python. diff --git a/packages/web/src/content/docs/ar/ecosystem.mdx b/packages/web/src/content/docs/ar/ecosystem.mdx new file mode 100644 index 000000000..4bf9af0c6 --- /dev/null +++ b/packages/web/src/content/docs/ar/ecosystem.mdx @@ -0,0 +1,73 @@ +--- +title: النظام البيئي +description: مشاريع وتكاملات مبنية باستخدام OpenCode. +--- + +مجموعة من مشاريع المجتمع المبنية على OpenCode. + +:::note +هل تريد إضافة مشروع مرتبط بـ OpenCode إلى هذه القائمة؟ قدّم PR. +::: + +يمكنك أيضا الاطلاع على [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) و [opencode.cafe](https://opencode.cafe)؛ وهو مجتمع يجمع روابط النظام البيئي والمجتمع. + +--- + +## الإضافات +| الاسم | الوصف | +| --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | تشغيل جلسات OpenCode تلقائيا داخل بيئات Daytona معزولة مع مزامنة git ومعاينات حية | +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | حقن ترويسات جلسة Helicone تلقائيا لتجميع الطلبات | +| [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | حقن أنواع TypeScript/Svelte تلقائيا في قراءات الملفات باستخدام أدوات البحث | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | استخدام اشتراك ChatGPT Plus/Pro بدلا من أرصدة واجهة API | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | استخدام خطة Gemini الحالية بدلا من فوترة API | +| [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | استخدام نماذج Antigravity المجانية بدلا من فوترة API | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | عزل devcontainer متعدد الفروع مع استنساخات shallow ومنافذ تُعيَّن تلقائيا | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | ملحق Google Antigravity OAuth مع دعم Google Search ومعالجة API أكثر متانة | +| [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | تحسين استخدام الرموز (tokens) عبر تقليم مخرجات الأدوات القديمة | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | إضافة دعم websearch أصلي للمزوّدين المدعومين بأسلوب مستند إلى Google | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | تمكين وكلاء الذكاء الاصطناعي من تشغيل عمليات بالخلفية داخل PTY وإرسال إدخال تفاعلي إليها. | +| [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | إرشادات لأوامر shell غير التفاعلية - تمنع التعليق الناتج عن عمليات تعتمد على TTY | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | تتبع استخدام OpenCode عبر Wakatime | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | تنظيف جداول Markdown التي تنتجها نماذج LLM | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | تحرير الشيفرة أسرع بـ 10x باستخدام Morph Fast Apply API وعلامات تعديل كسولة | +| [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | وكلاء خلفية وأدوات LSP/AST/MCP جاهزة ووكلاء منتقون وتوافق مع Claude Code | +| [opencode-notificator](https://github.com/panta82/opencode-notificator) | إشعارات سطح المكتب وتنبيهات صوتية لجلسات OpenCode | +| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | إشعارات سطح المكتب وتنبيهات صوتية لأحداث الأذونات والإكمال والأخطاء | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | تسمية جلسات Zellij تلقائيا بالاعتماد على سياق OpenCode وبمساعدة الذكاء الاصطناعي | +| [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | تمكين وكلاء OpenCode من تحميل الموجهات عند الطلب عبر اكتشاف المهارات وحقنها | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | ذاكرة مستمرة عبر الجلسات باستخدام Supermemory | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | مراجعة تفاعلية للخطة مع تعليقات توضيحية مرئية ومشاركة خاصة/دون اتصال | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | توسيع /commands في opencode إلى نظام تنسيق قوي مع تحكم دقيق في التدفق | +| [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | جدولة مهام متكررة باستخدام launchd (Mac) أو systemd (Linux) بصياغة cron | +| [micode](https://github.com/vtemian/micode) | سير عمل منظم: عصف ذهني → خطة → تنفيذ مع استمرارية الجلسة | +| [octto](https://github.com/vtemian/octto) | واجهة متصفح تفاعلية للعصف الذهني بالذكاء الاصطناعي مع نماذج متعددة الأسئلة | +| [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | وكلاء خلفية على نمط Claude Code مع تفويض غير متزامن واستمرارية للسياق | +| [opencode-notify](https://github.com/kdcokenny/opencode-notify) | إشعارات نظام تشغيل أصلية لـ OpenCode - اعرف متى تكتمل المهام | +| [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | حزمة تنسيق متعددة الوكلاء - 16 مكوّنا، تثبيت واحد | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | git worktrees بلا تعقيد لـ OpenCode | + +--- + +## المشاريع +| الاسم | الوصف | +| ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | بوت Discord للتحكم بجلسات OpenCode، مبني على SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | ملحق Neovim لموجهات تراعي المحرر، مبني على API | +| [portal](https://github.com/hosenur/portal) | واجهة ويب تركز على الجوال لـ OpenCode عبر Tailscale/VPN | +| [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | قالب لبناء ملحقات OpenCode | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | واجهة Neovim لـ opencode - وكيل برمجة بالذكاء الاصطناعي يعمل في الطرفية | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | موفر Vercel AI SDK لاستخدام OpenCode عبر @opencode-ai/sdk | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | تطبيق ويب/سطح مكتب وامتداد VS Code لـ OpenCode | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | ملحق Obsidian يدمج OpenCode داخل واجهة Obsidian | +| [OpenWork](https://github.com/different-ai/openwork) | بديل مفتوح المصدر لـ Claude Cowork، مدعوم بـ OpenCode | +| [ocx](https://github.com/kdcokenny/ocx) | مدير امتدادات OpenCode مع ملفات تعريف محمولة ومعزولة. | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | تطبيق عميل لسطح المكتب والويب والجوال وعن بُعد لـ OpenCode | + +--- + +## الوكلاء +| الاسم | الوصف | +| ----------------------------------------------------------------- | --------------------------------------------- | +| [Agentic](https://github.com/Cluster444/agentic) | وكلاء وأوامر ذكاء اصطناعي معيارية لتطوير منظم | +| [opencode-agents](https://github.com/darrenhinde/opencode-agents) | إعدادات وموجهات ووكلاء وملحقات لسير عمل محسّن | diff --git a/packages/web/src/content/docs/ar/enterprise.mdx b/packages/web/src/content/docs/ar/enterprise.mdx new file mode 100644 index 000000000..b7b188ede --- /dev/null +++ b/packages/web/src/content/docs/ar/enterprise.mdx @@ -0,0 +1,165 @@ +--- +title: المؤسسات +description: استخدام OpenCode بأمان داخل مؤسستك. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise مخصص للمؤسسات التي تريد التأكد من أن الشيفرة والبيانات لا تغادر بنيتها التحتية مطلقا. ويمكن تحقيق ذلك عبر استخدام إعدادات مركزية تتكامل مع SSO وبوابة AI الداخلية لديك. + +:::note +لا يقوم OpenCode بتخزين أي من شيفرتك أو بيانات السياق. +::: + +لبدء استخدام OpenCode Enterprise: + +1. أجرِ تجربة داخلية مع فريقك. +2. **اتصل بنا** لمناقشة التسعير وخيارات التنفيذ. + +--- + +## تجربة + +OpenCode مفتوح المصدر ولا يخزن أي من شيفرتك أو بيانات السياق، لذا يمكن للمطورين لديك ببساطة [البدء](/docs/) وإجراء تجربة. + +--- + +### التعامل مع البيانات + +**لا يقوم OpenCode بتخزين شيفرتك أو بيانات السياق.** تتم جميع المعالجة محليا أو عبر استدعاءات API مباشرة إلى مزود AI لديك. + +وهذا يعني أنه طالما أنك تستخدم مزودا تثق به، أو بوابة AI داخلية، يمكنك استخدام OpenCode بأمان. + +الاستثناء الوحيد هنا هو ميزة `/share` الاختيارية. + +--- + +#### مشاركة المحادثات + +إذا فعّل المستخدم ميزة `/share`، فسيتم إرسال المحادثة والبيانات المرتبطة بها إلى الخدمة التي نستخدمها لاستضافة صفحات المشاركة هذه على opencode.ai. + +يتم تقديم البيانات حاليا عبر شبكة الحافة الخاصة بـ CDN لدينا، وتُخزّن مؤقتا على الحافة بالقرب من مستخدميك. + +نوصي بتعطيل ذلك أثناء التجربة. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[تعرّف على المزيد حول المشاركة](/docs/share). + +--- + +### ملكية الشيفرة + +**أنت تملك كل الشيفرة التي ينتجها OpenCode.** لا توجد قيود ترخيص أو مطالبات بالملكية. + +--- + +## التسعير + +نستخدم نموذج تسعير لكل مقعد في OpenCode Enterprise. إذا كانت لديك بوابة LLM خاصة بك، فلن نفرض رسوما على الرموز (tokens) المستخدمة. لمزيد من التفاصيل حول التسعير وخيارات التنفيذ، **اتصل بنا**. + +--- + +## النشر + +بعد إكمال التجربة وعندما تكون جاهزا لاستخدام OpenCode داخل مؤسستك، يمكنك **الاتصال بنا** لمناقشة التسعير وخيارات التنفيذ. + +--- + +### الإعدادات المركزية + +يمكننا إعداد OpenCode لاستخدام إعدادات مركزية واحدة لكامل مؤسستك. + +يمكن لهذه الإعدادات المركزية أن تتكامل مع مزود SSO لديك، وتضمن أن جميع المستخدمين يصلون فقط إلى بوابة AI الداخلية لديك. + +--- + +### تكامل SSO + +عبر الإعدادات المركزية، يمكن لـ OpenCode التكامل مع مزود SSO في مؤسستك لأغراض المصادقة. + +يتيح ذلك لـ OpenCode الحصول على بيانات الاعتماد لبوابة AI الداخلية لديك عبر نظام إدارة الهوية الحالي لديك. + +--- + +### بوابة AI الداخلية + +مع الإعدادات المركزية، يمكن أيضا تهيئة OpenCode لاستخدام بوابة AI الداخلية لديك فقط. + +يمكنك أيضا تعطيل جميع مزودي AI الآخرين، لضمان مرور جميع الطلبات عبر البنية التحتية المعتمدة في مؤسستك. + +--- + +### الاستضافة الذاتية + +بينما نوصي بتعطيل صفحات المشاركة لضمان ألا تغادر بياناتك مؤسستك مطلقا، يمكننا أيضا مساعدتك على استضافتها ذاتيا على بنيتك التحتية. + +هذا موجود حاليا على خارطة طريقنا. إذا كنت مهتما، **أخبرنا**. + +--- + +## الأسئلة الشائعة + +
+ما هو OpenCode Enterprise؟ + +OpenCode Enterprise مخصص للمؤسسات التي تريد التأكد من أن الشيفرة والبيانات لا تغادر بنيتها التحتية مطلقا. ويمكن تحقيق ذلك عبر استخدام إعدادات مركزية تتكامل مع SSO وبوابة AI الداخلية لديك. + +
+ +
+كيف أبدأ باستخدام OpenCode Enterprise؟ + +ابدأ ببساطة بتجربة داخلية مع فريقك. لا يقوم OpenCode افتراضيا بتخزين شيفرتك أو بيانات السياق، مما يجعل البدء سهلا. + +ثم **اتصل بنا** لمناقشة التسعير وخيارات التنفيذ. + +
+ +
+كيف يعمل تسعير المؤسسات؟ + +نقدم تسعيرا للمؤسسات لكل مقعد. إذا كانت لديك بوابة LLM خاصة بك، فلن نفرض رسوما على الرموز (tokens) المستخدمة. لمزيد من التفاصيل، **اتصل بنا** للحصول على عرض سعر مخصص بناء على احتياجات مؤسستك. + +
+ +
+هل بياناتي آمنة مع OpenCode Enterprise؟ + +نعم. لا يقوم OpenCode بتخزين شيفرتك أو بيانات السياق. تتم جميع المعالجة محليا أو عبر استدعاءات API مباشرة إلى مزود AI لديك. ومع الإعدادات المركزية وتكامل SSO، تظل بياناتك آمنة داخل البنية التحتية لمؤسستك. + +
+ +
+هل يمكننا استخدام سجل NPM خاص بنا؟ + +يدعم OpenCode سجلات npm الخاصة عبر دعم Bun الأصلي لملف `.npmrc`. إذا كانت مؤسستك تستخدم سجلا خاصا مثل JFrog Artifactory أو Nexus أو ما شابه ذلك، فتأكد من مصادقة المطورين قبل تشغيل OpenCode. + +لإعداد المصادقة مع السجل الخاص بك: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +سيؤدي ذلك إلى إنشاء `~/.npmrc` مع تفاصيل المصادقة. سيلتقط OpenCode هذا تلقائيا. + +:::caution +يجب أن تكون مسجلا الدخول إلى السجل الخاص قبل تشغيل OpenCode. +::: + +بدلا من ذلك، يمكنك تهيئة ملف `.npmrc` يدويا: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +يجب أن يكون المطورون مسجلين الدخول إلى السجل الخاص قبل تشغيل OpenCode لضمان إمكانية تثبيت الحزم من سجل مؤسستك. + +
diff --git a/packages/web/src/content/docs/ar/formatters.mdx b/packages/web/src/content/docs/ar/formatters.mdx new file mode 100644 index 000000000..a17e6ad2c --- /dev/null +++ b/packages/web/src/content/docs/ar/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: المُنسِّقات +description: يستخدم OpenCode مُنسِّقات خاصة بكل لغة. +--- + +يُنسِّق OpenCode الملفات تلقائيا بعد كتابتها أو تعديلها باستخدام مُنسِّقات خاصة بكل لغة. يضمن ذلك أن الشيفرة التي يتم توليدها تتبع أساليب التنسيق المعتمدة في مشروعك. + +--- + +## مُضمَّنة + +يأتي OpenCode مع عدة مُنسِّقات مُضمَّنة للغات وأطر العمل الشائعة. فيما يلي قائمة بالمُنسِّقات وامتدادات الملفات المدعومة والأوامر أو خيارات الإعداد التي تحتاجها. + +| المُنسِّق | الامتدادات | المتطلبات | +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| gofmt | .go | يتوفر أمر `gofmt` | +| mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | يتوفر أمر `mix` | +| prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml، و[غير ذلك](https://prettier.io/docs/en/index.html) | وجود اعتماد `prettier` في `package.json` | +| biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml، و[غير ذلك](https://biomejs.dev/) | ملف إعداد `biome.json(c)` | +| zig | .zig, .zon | يتوفر أمر `zig` | +| clang-format | .c, .cpp, .h, .hpp, .ino، و[غير ذلك](https://clang.llvm.org/docs/ClangFormat.html) | ملف إعداد `.clang-format` | +| ktlint | .kt, .kts | يتوفر أمر `ktlint` | +| ruff | .py, .pyi | يتوفر أمر `ruff` مع إعداد | +| rustfmt | .rs | يتوفر أمر `rustfmt` | +| cargofmt | .rs | يتوفر أمر `cargo fmt` | +| uv | .py, .pyi | يتوفر أمر `uv` | +| rubocop | .rb, .rake, .gemspec, .ru | يتوفر أمر `rubocop` | +| standardrb | .rb, .rake, .gemspec, .ru | يتوفر أمر `standardrb` | +| htmlbeautifier | .erb, .html.erb | يتوفر أمر `htmlbeautifier` | +| air | .R | يتوفر أمر `air` | +| dart | .dart | يتوفر أمر `dart` | +| ocamlformat | .ml, .mli | يتوفر أمر `ocamlformat` وملف إعداد `.ocamlformat` | +| terraform | .tf, .tfvars | يتوفر أمر `terraform` | +| gleam | .gleam | يتوفر أمر `gleam` | +| nixfmt | .nix | يتوفر أمر `nixfmt` | +| shfmt | .sh, .bash | يتوفر أمر `shfmt` | +| pint | .php | وجود اعتماد `laravel/pint` في `composer.json` | +| oxfmt (Experimental) | .js, .jsx, .ts, .tsx | وجود اعتماد `oxfmt` في `package.json` و[علم متغير بيئة تجريبي](/docs/cli/#experimental) | +| ormolu | .hs | يتوفر أمر `ormolu` | + +لذا إذا كان مشروعك يتضمن `prettier` ضمن `package.json`، فسيستخدمه OpenCode تلقائيا. + +--- + +## كيف يعمل + +عندما يكتب OpenCode ملفا أو يحرره، فإنه: + +1. يتحقق من امتداد الملف مقابل جميع المُنسِّقات المفعّلة. +2. يشغّل أمر المُنسِّق المناسب على الملف. +3. يطبق تغييرات التنسيق تلقائيا. + +تتم هذه العملية في الخلفية لضمان الحفاظ على أساليب تنسيق الشيفرة دون أي خطوات يدوية. + +--- + +## الإعداد + +يمكنك تخصيص المُنسِّقات عبر قسم `formatter` في إعدادات OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +يدعم إعداد كل مُنسِّق ما يلي: + +| الخاصية | النوع | الوصف | +| ------------- | -------- | ------------------------------------------------------ | +| `disabled` | boolean | اضبطها على `true` لتعطيل المُنسِّق | +| `command` | string[] | الأمر الذي سيتم تشغيله للتنسيق | +| `environment` | object | متغيرات البيئة التي يتم ضبطها عند تشغيل المُنسِّق | +| `extensions` | string[] | امتدادات الملفات التي يجب أن يتعامل معها هذا المُنسِّق | + +لنلقِ نظرة على بعض الأمثلة. + +--- + +### تعطيل المُنسِّقات + +لتعطيل **جميع** المُنسِّقات على مستوى عام، اضبط `formatter` على `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +لتعطيل مُنسِّق **محدد**، اضبط `disabled` على `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### مُنسِّقات مخصّصة + +يمكنك تجاوز المُنسِّقات المُضمَّنة أو إضافة مُنسِّقات جديدة عبر تحديد الأمر ومتغيرات البيئة وامتدادات الملفات: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +سيتم استبدال **العنصر النائب `$FILE`** في الأمر بمسار الملف الذي يجري تنسيقه. diff --git a/packages/web/src/content/docs/ar/github.mdx b/packages/web/src/content/docs/ar/github.mdx new file mode 100644 index 000000000..1365b74e5 --- /dev/null +++ b/packages/web/src/content/docs/ar/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: استخدم OpenCode في GitHub Issues وPull Requests. +--- + +يتكامل OpenCode مع سير عمل GitHub لديك. اذكر `/opencode` أو `/oc` في تعليقك، وسيقوم OpenCode بتنفيذ المهام داخل GitHub Actions runner لديك. + +--- + +## الميزات + +- **فرز Issues**: اطلب من OpenCode الاطلاع على Issue وشرحها لك. +- **إصلاح وتنفيذ**: اطلب من OpenCode إصلاح Issue أو تنفيذ ميزة. وسيعمل على فرع جديد ويقدّم PR يضم كل التغييرات. +- **آمن**: يعمل OpenCode داخل GitHub runners لديك. + +--- + +## التثبيت + +شغّل الأمر التالي داخل مشروع موجود في مستودع GitHub: + +```bash +opencode github install +``` + +سيأخذك هذا خلال تثبيت GitHub app، وإنشاء workflow، وإعداد secrets. + +--- + +### الإعداد اليدوي + +أو يمكنك إعداده يدويًا. + +1. **تثبيت GitHub app** + + انتقل إلى [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). تأكد من تثبيته على المستودع الهدف. + +2. **إضافة الـworkflow** + + أضف ملف الـworkflow التالي إلى `.github/workflows/opencode.yml` في مستودعك. تأكد من ضبط `model` المناسب ومفاتيح API المطلوبة ضمن `env`. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **تخزين مفاتيح API ضمن secrets** + + في **settings** الخاصة بالمؤسسة أو المشروع، وسّع **Secrets and variables** في الشريط الجانبي الأيسر ثم اختر **Actions**، وأضف مفاتيح API المطلوبة. + +--- + +## الإعدادات + +- `model`: النموذج الذي سيستخدمه OpenCode. يأخذ الصيغة `provider/model`. هذا **مطلوب**. +- `agent`: الـagent الذي سيتم استخدامه. يجب أن يكون agent أساسيًا. يعود افتراضيًا إلى `default_agent` من الإعدادات أو `"build"` إذا لم يُعثر عليه. +- `share`: هل تتم مشاركة جلسة OpenCode. القيمة الافتراضية **true** للمستودعات العامة. +- `prompt`: موجه مخصص اختياري لتجاوز السلوك الافتراضي. استخدمه لتخصيص كيفية معالجة OpenCode للطلبات. +- `token`: GitHub access token اختياري لتنفيذ عمليات مثل إنشاء التعليقات، وcommit للتغييرات، وفتح Pull Requests. افتراضيًا يستخدم OpenCode installation access token الخاص بـOpenCode GitHub App، لذا تظهر commits والتعليقات وPull Requests وكأنها صادرة من التطبيق. + + بدلًا من ذلك، يمكنك استخدام [`GITHUB_TOKEN` المدمج](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) في GitHub Action runner دون تثبيت OpenCode GitHub App. فقط تأكد من منح الأذونات المطلوبة في الـworkflow: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + يمكنك أيضًا استخدام [رموز الوصول الشخصية](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) إن فضّلت ذلك. + +--- + +## الأحداث المدعومة + +يمكن تشغيل OpenCode عبر أحداث GitHub التالية: + +| نوع الحدث | يتم تشغيله عبر | التفاصيل | +| ----------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------- | +| `issue_comment` | تعليق على Issue أو PR | اذكر `/opencode` أو `/oc` في تعليقك. يقرأ OpenCode السياق ويمكنه إنشاء فروع، وفتح PRs، أو الرد. | +| `pull_request_review_comment` | تعليق على أسطر كود محددة في PR | اذكر `/opencode` أو `/oc` أثناء مراجعة الكود. يستلم OpenCode مسار الملف وأرقام الأسطر وسياق الـdiff. | +| `issues` | فتح Issue أو تعديلها | تشغيل OpenCode تلقائيًا عند إنشاء Issues أو تعديلها. يتطلب إدخال `prompt`. | +| `pull_request` | فتح PR أو تحديثه | تشغيل OpenCode تلقائيًا عند فتح PRs أو مزامنتها أو إعادة فتحها. مفيد للمراجعات الآلية. | +| `schedule` | جدول يعتمد على Cron | تشغيل OpenCode وفق جدول. يتطلب إدخال `prompt`. يذهب الناتج إلى logs وPRs (لا يوجد Issue للتعليق عليها). | +| `workflow_dispatch` | تشغيل يدوي من واجهة GitHub | تشغيل OpenCode عند الطلب عبر Actions tab. يتطلب إدخال `prompt`. يذهب الناتج إلى logs وPRs. | + +### مثال للجدولة + +شغّل OpenCode وفق جدول لتنفيذ مهام آلية: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +بالنسبة لأحداث `schedule`، يكون إدخال `prompt` **مطلوبًا** لعدم وجود تعليق لاستخراج التعليمات منه. تعمل عمليات الـworkflow المجدولة دون سياق مستخدم للتحقق من الأذونات، لذا يجب أن يمنح الـworkflow صلاحيات `contents: write` و`pull-requests: write` إذا كنت تتوقع أن ينشئ OpenCode فروعًا أو PRs. + +--- + +### مثال Pull Request + +راجع PRs تلقائيًا عند فتحها أو تحديثها: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +بالنسبة لأحداث `pull_request`، إذا لم يتم توفير `prompt`، فإن OpenCode يراجع Pull Request افتراضيًا. + +--- + +### مثال فرز Issues + +قم بفرز Issues الجديدة تلقائيًا. يقوم هذا المثال بتصفية الحسابات الأقدم من 30 يومًا لتقليل الرسائل المزعجة: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +بالنسبة لأحداث `issues`، يكون إدخال `prompt` **مطلوبًا** لعدم وجود تعليق لاستخراج التعليمات منه. + +--- + +## الموجهات المخصصة + +قم بتجاوز الموجه الافتراضي لتخصيص سلوك OpenCode ضمن الـworkflow لديك. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +يفيد ذلك في فرض معايير مراجعة محددة، أو معايير كتابة الكود، أو مجالات تركيز تناسب مشروعك. + +--- + +## أمثلة + +إليك بعض الأمثلة على كيفية استخدام OpenCode في GitHub. + +- **شرح Issue** + + أضف هذا التعليق داخل GitHub Issue. + + ``` + /opencode explain this issue + ``` + + سيقرأ OpenCode كامل النقاش، بما في ذلك جميع التعليقات، ويرد بشرح واضح. + +- **إصلاح Issue** + + داخل GitHub Issue، اكتب: + + ``` + /opencode fix this + ``` + + وسيُنشئ OpenCode فرعًا جديدًا، وينفّذ التغييرات، ويفتح PR يتضمنها. + +- **مراجعة PRs وإجراء تغييرات** + + اترك التعليق التالي على GitHub PR. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + سينفّذ OpenCode التغيير المطلوب ويعمل له commit إلى نفس PR. + +- **مراجعة أسطر كود محددة** + + اترك تعليقًا مباشرة على أسطر الكود في تبويب "Files" داخل PR. يكتشف OpenCode تلقائيًا الملف وأرقام الأسطر وسياق الـdiff لتقديم ردود دقيقة. + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + عند التعليق على أسطر محددة، يستلم OpenCode: + - الملف الدقيق الذي تتم مراجعته + - أسطر الكود المحددة + - سياق الـdiff المحيط + - معلومات أرقام الأسطر + + يسمح ذلك بطلبات أكثر تحديدًا دون الحاجة لذكر مسارات الملفات أو أرقام الأسطر يدويًا. diff --git a/packages/web/src/content/docs/ar/gitlab.mdx b/packages/web/src/content/docs/ar/gitlab.mdx new file mode 100644 index 000000000..12e36de10 --- /dev/null +++ b/packages/web/src/content/docs/ar/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: استخدم OpenCode في مشكلات GitLab وطلبات الدمج. +--- + +يتكامل OpenCode مع سير عمل GitLab لديك عبر خط أنابيب GitLab CI/CD أو عبر GitLab Duo. + +في كلتا الحالتين، سيعمل OpenCode على مشغّلات GitLab لديك. + +--- + +## GitLab CI + +يعمل OpenCode ضمن خط أنابيب GitLab عادي. يمكنك دمجه في الخط كمكوّن [CI](https://docs.gitlab.com/ee/ci/components/). + +هنا نستخدم مكوّن CI/CD أنشأه المجتمع لـ OpenCode — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### الميزات + +- **استخدام إعدادات مخصّصة لكل مهمة**: يمكنك إعداد OpenCode باستخدام دليل إعدادات مخصّص، مثل `./config/#custom-directory`، لتفعيل الوظائف أو تعطيلها في كل تشغيل لـ OpenCode. +- **إعداد بسيط**: يقوم مكوّن CI بإعداد OpenCode في الخلفية؛ كل ما عليك هو إنشاء إعدادات OpenCode والمطالبة (prompt) الأولية. +- **مرن**: يدعم مكوّن CI عدة مُدخلات لتخصيص سلوكه. + +--- + +### الإعداد + +1. احفظ JSON مصادقة OpenCode كمتغيرات بيئة CI من نوع File ضمن **Settings** > **CI/CD** > **Variables**. تأكد من تعيينها على "Masked and hidden". +2. أضف ما يلي إلى ملف `.gitlab-ci.yml`. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +لمزيد من المُدخلات وحالات الاستخدام، [اطّلع على الوثائق](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) الخاصة بهذا المكوّن. + +--- + +## GitLab Duo + +يتكامل OpenCode مع سير عمل GitLab لديك. +اذكر `@opencode` في تعليق، وسينفّذ OpenCode المهام ضمن خط أنابيب GitLab CI لديك. + +--- + +### الميزات + +- **فرز المشكلات**: اطلب من OpenCode النظر في مشكلة وشرحها لك. +- **الإصلاح والتنفيذ**: اطلب من OpenCode إصلاح مشكلة أو تنفيذ ميزة. + سيُنشئ فرعًا جديدًا ويرفع طلب دمج بالتغييرات. +- **آمن**: يعمل OpenCode على مشغّلات GitLab لديك. + +--- + +### الإعداد + +يعمل OpenCode ضمن خط أنابيب GitLab CI/CD لديك، وإليك ما ستحتاجه لإعداده: + +:::tip +اطّلع على [**وثائق GitLab**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) للحصول على تعليمات محدّثة. +::: + +1. قم بتهيئة بيئة GitLab لديك +2. أعد إعداد CI/CD +3. احصل على مفتاح API من مزوّد نموذج ذكاء اصطناعي +4. أنشئ حساب خدمة +5. اضبط متغيرات CI/CD +6. أنشئ ملف إعداد للتدفق، وإليك مثالًا: + +
+ + إعدادات التدفق + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +يمكنك الرجوع إلى [وثائق GitLab CLI agents](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) للحصول على تعليمات مفصلة. + +--- + +### أمثلة + +فيما يلي بعض الأمثلة على كيفية استخدام OpenCode في GitLab. + +:::tip +يمكنك ضبطه لاستخدام عبارة تشغيل مختلفة عن `@opencode`. +::: + +- **شرح مشكلة** + + أضف هذا التعليق في مشكلة على GitLab. + + ``` + @opencode explain this issue + ``` + + سيقرأ OpenCode المشكلة ويرد بشرح واضح. + +- **إصلاح مشكلة** + + في مشكلة على GitLab، قل: + + ``` + @opencode fix this + ``` + + سيُنشئ OpenCode فرعًا جديدًا، وينفّذ التغييرات، ويفتح طلب دمج بالتغييرات. + +- **مراجعة طلبات الدمج** + + اترك التعليق التالي على طلب دمج في GitLab. + + ``` + @opencode review this merge request + ``` + + سيُراجع OpenCode طلب الدمج ويقدّم ملاحظات. diff --git a/packages/web/src/content/docs/ar/ide.mdx b/packages/web/src/content/docs/ar/ide.mdx new file mode 100644 index 000000000..676c5717a --- /dev/null +++ b/packages/web/src/content/docs/ar/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: امتداد OpenCode لـ VS Code و Cursor وغيرها من بيئات التطوير +--- + +يتكامل OpenCode مع VS Code و Cursor أو أي IDE يدعم الطرفية. ما عليك سوى تشغيل `opencode` في الطرفية للبدء. + +--- + +## الاستخدام + +- **تشغيل سريع**: استخدم `Cmd+Esc` (Mac) أو `Ctrl+Esc` (Windows/Linux) لفتح OpenCode في عرض طرفية مقسّم، أو للتركيز على جلسة طرفية موجودة إذا كانت قيد التشغيل بالفعل. +- **جلسة جديدة**: استخدم `Cmd+Shift+Esc` (Mac) أو `Ctrl+Shift+Esc` (Windows/Linux) لبدء جلسة طرفية جديدة لـ OpenCode حتى لو كانت هناك جلسة مفتوحة. يمكنك أيضا النقر على زر OpenCode في واجهة المستخدم. +- **وعي بالسياق**: شارك تلقائيا تحديدك الحالي أو تبويبك مع OpenCode. +- **اختصارات الإشارة إلى الملفات**: استخدم `Cmd+Option+K` (Mac) أو `Alt+Ctrl+K` (Linux/Windows) لإدراج مراجع الملفات. مثلا: `@File#L37-42`. + +--- + +## التثبيت + +لتثبيت OpenCode على VS Code والتفرعات الشائعة مثل Cursor و Windsurf و VSCodium: + +1. افتح VS Code +2. افتح الطرفية المدمجة +3. شغّل `opencode` - سيتم تثبيت الامتداد تلقائيا + +أما إذا كنت تريد استخدام IDE الخاص بك عند تشغيل `/editor` أو `/export` من واجهة TUI، فستحتاج إلى ضبط `export EDITOR="code --wait"`. [اعرف المزيد](/docs/tui/#editor-setup). + +--- + +### التثبيت اليدوي + +ابحث عن **OpenCode** في Extension Marketplace وانقر **Install**. + +--- + +### استكشاف الأخطاء وإصلاحها + +إذا فشل تثبيت الامتداد تلقائيا: + +- تأكد من أنك تشغّل `opencode` داخل الطرفية المدمجة. +- تأكد من تثبيت واجهة سطر الأوامر (CLI) الخاصة بـ IDE لديك: + - لـ VS Code: أمر `code` + - لـ Cursor: أمر `cursor` + - لـ Windsurf: أمر `windsurf` + - لـ VSCodium: أمر `codium` + - إذا لم تكن مثبتة، شغّل `Cmd+Shift+P` (Mac) أو `Ctrl+Shift+P` (Windows/Linux) وابحث عن "Shell Command: Install 'code' command in PATH" (أو ما يعادله في IDE لديك) +- تأكد من أن VS Code لديه الصلاحية لتثبيت الامتدادات diff --git a/packages/web/src/content/docs/ar/index.mdx b/packages/web/src/content/docs/ar/index.mdx new file mode 100644 index 000000000..41198d0c7 --- /dev/null +++ b/packages/web/src/content/docs/ar/index.mdx @@ -0,0 +1,343 @@ +--- +title: مقدمة +description: ابدأ باستخدام OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) هو وكيل ترميز بالذكاء الاصطناعي مفتوح المصدر. يتوفر كواجهة طرفية، وتطبيق لسطح المكتب، أو إضافة لبيئة تطوير متكاملة (IDE). + +![واجهة OpenCode الطرفية مع سمة opencode](../../../assets/lander/screenshot.png) + +لنبدأ. + +--- + +#### المتطلبات + +لاستخدام OpenCode في الطرفية، ستحتاج إلى: + +1. محاكي طرفية حديث مثل: + - [WezTerm](https://wezterm.org) متعدد المنصات + - [Alacritty](https://alacritty.org) متعدد المنصات + - [Ghostty](https://ghostty.org) على Linux وmacOS + - [Kitty](https://sw.kovidgoyal.net/kitty/) على Linux وmacOS + +2. مفاتيح API لمزوّدي نماذج اللغة (LLM) الذين تريد استخدامهم. + +--- + +## التثبيت + +أسهل طريقة لتثبيت OpenCode هي عبر سكربت التثبيت. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +يمكنك أيضا تثبيته عبر الأوامر التالية: + +- **باستخدام Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **باستخدام Homebrew على macOS وLinux** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > نوصي باستخدام tap الخاص بـ OpenCode للحصول على أحدث الإصدارات. صيغة `brew install opencode` الرسمية تُدار بواسطة فريق Homebrew ويتم تحديثها بوتيرة أقل. + +- **باستخدام Paru على Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### Windows + +:::tip[موصى به: استخدم WSL] +لأفضل تجربة على Windows، نوصي باستخدام [Windows Subsystem for Linux (WSL)](/docs/windows-wsl). يوفر أداء أفضل وتوافقا كاملا مع ميزات OpenCode. +::: + +- **باستخدام Chocolatey** + + ```bash + choco install opencode + ``` + +- **باستخدام Scoop** + + ```bash + scoop install opencode + ``` + +- **باستخدام NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **باستخدام Mise** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **باستخدام Docker** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +دعم تثبيت OpenCode على Windows باستخدام Bun قيد العمل حاليا. + +يمكنك أيضا تنزيل الملف التنفيذي من صفحة [Releases](https://github.com/anomalyco/opencode/releases). + +--- + +## الإعداد + +مع OpenCode يمكنك استخدام أي مزود LLM عبر إعداد مفاتيح API الخاصة به. + +إذا كنت جديدا على استخدام مزوّدي LLM، فنوصي باستخدام [OpenCode Zen](/docs/zen). +إنها قائمة منتقاة من النماذج تم اختبارها والتحقق منها بواسطة فريق OpenCode. + +1. شغّل الأمر `/connect` في واجهة TUI، واختر opencode، ثم انتقل إلى [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. سجّل الدخول، وأضف تفاصيل الدفع، ثم انسخ مفتاح API. + +3. الصق مفتاح API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +بدلا من ذلك يمكنك اختيار أحد المزوّدين الآخرين. [اعرف المزيد](/docs/providers#directory). + +--- + +## التهيئة + +بعد أن قمت بإعداد مزوّد، يمكنك الانتقال إلى المشروع الذي تريد العمل عليه. + +```bash +cd /path/to/project +``` + +ثم شغّل OpenCode. + +```bash +opencode +``` + +بعد ذلك، هيّئ OpenCode للمشروع عبر تشغيل الأمر التالي. + +```bash frame="none" +/init +``` + +سيجعل هذا OpenCode يحلل مشروعك ويُنشئ ملف `AGENTS.md` في جذر المشروع. + +:::tip +يستحسن أن تقوم بعمل commit لملف `AGENTS.md` الخاص بمشروعك إلى Git. +::: + +يساعد هذا OpenCode على فهم بنية المشروع وأنماط الترميز المستخدمة. + +--- + +## الاستخدام + +أصبحت الآن جاهزا لاستخدام OpenCode للعمل على مشروعك. لا تتردد في سؤاله أي شيء! + +إذا كنت جديدا على استخدام وكيل ترميز بالذكاء الاصطناعي، فإليك بعض الأمثلة التي قد تساعد. + +--- + +### اطرح أسئلة + +يمكنك أن تطلب من OpenCode شرح قاعدة الشيفرة لك. + +:::tip +استخدم المفتاح `@` للبحث التقريبي عن الملفات داخل المشروع. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +يفيد هذا عندما تكون هناك أجزاء من قاعدة الشيفرة لم تعمل عليها. + +--- + +### أضف ميزات + +يمكنك أن تطلب من OpenCode إضافة ميزات جديدة إلى مشروعك، لكننا نوصي أولا بطلب إنشاء خطة. + +1. **أنشئ خطة** + + لدى OpenCode _وضع Plan_ يعطل قدرته على إجراء التغييرات، ويقترح بدلا من ذلك _كيف_ سينفّذ الميزة. + + انتقل إليه باستخدام مفتاح **Tab**. سترى مؤشرا لذلك في الزاوية السفلية اليمنى. + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + الآن لنصف ما نريده أن يفعله. + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + احرص على تزويد OpenCode بتفاصيل كافية ليفهم ما تريد. يساعد أن تتحدث إليه كما لو كنت تتحدث إلى مطور مبتدئ ضمن فريقك. + + :::tip + أعطِ OpenCode سياقا وأمثلة كافية لمساعدته على فهم ما تريد. + ::: + +2. **حسّن الخطة** + + بعد أن يقدم لك خطة، يمكنك إعطاؤه ملاحظات أو إضافة تفاصيل أكثر. + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::tip + اسحب الصور وأفلِتها داخل الطرفية لإضافتها إلى الطلب. + ::: + + يستطيع OpenCode فحص أي صور تزوده بها وإضافتها إلى الطلب. يمكنك فعل ذلك عبر سحب الصورة وإفلاتها داخل الطرفية. + +3. **ابنِ الميزة** + + عندما تشعر بالارتياح للخطة، عد إلى _وضع Build_ بالضغط على مفتاح **Tab** مرة أخرى. + + ```bash frame="none" + + ``` + + ثم اطلب منه تنفيذ التغييرات. + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### نفّذ تغييرات + +للتغييرات الأبسط، يمكنك أن تطلب من OpenCode تنفيذها مباشرة دون الحاجة لمراجعة خطة أولا. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +تأكد من تقديم قدر مناسب من التفاصيل لكي يجري OpenCode التغييرات الصحيحة. + +--- + +### تراجع عن التغييرات + +لنفترض أنك طلبت من OpenCode إجراء بعض التغييرات. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +لكن تتضح لك لاحقا أنها ليست ما تريده. يمكنك **التراجع** عن التغييرات باستخدام الأمر `/undo`. + +```bash frame="none" +/undo +``` + +سيقوم OpenCode الآن بعكس التغييرات التي أُجريت ويعرض رسالتك الأصلية مجددا. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +من هنا يمكنك تعديل الطلب وطلب المحاولة مرة أخرى. + +:::tip +يمكنك تشغيل `/undo` عدة مرات للتراجع عن عدة تغييرات. +::: + +أو يمكنك **إعادة تنفيذ** التغييرات باستخدام الأمر `/redo`. + +```bash frame="none" +/redo +``` + +--- + +## المشاركة + +يمكن [مشاركة المحادثات](/docs/share) التي تجريها مع OpenCode مع فريقك. + +```bash frame="none" +/share +``` + +سيقوم هذا بإنشاء رابط للمحادثة الحالية ونسخه إلى الحافظة. + +:::note +لا تتم مشاركة المحادثات افتراضيا. +::: + +إليك [مثالا لمحادثة](https://opencode.ai/s/4XP1fce5) مع OpenCode. + +--- + +## التخصيص + +وهذا كل شيء! أصبحت الآن محترفا في استخدام OpenCode. + +لتجعله مناسبا لك، نوصي بـ [اختيار سمة](/docs/themes)، و[تخصيص اختصارات لوحة المفاتيح](/docs/keybinds)، و[إعداد منسقات الشيفرة](/docs/formatters)، و[إنشاء أوامر مخصصة](/docs/commands)، أو التجربة مع [إعدادات OpenCode](/docs/config). diff --git a/packages/web/src/content/docs/ar/keybinds.mdx b/packages/web/src/content/docs/ar/keybinds.mdx new file mode 100644 index 000000000..f4d278f46 --- /dev/null +++ b/packages/web/src/content/docs/ar/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: اختصارات لوحة المفاتيح +description: خصّص اختصارات لوحة المفاتيح. +--- + +يوفّر OpenCode قائمة باختصارات لوحة المفاتيح يمكنك تخصيصها عبر إعدادات OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## مفتاح القائد + +يستخدم OpenCode مفتاح `leader` لمعظم اختصارات لوحة المفاتيح. يساعد ذلك على تجنّب التعارضات في الطرفية لديك. + +افتراضيا، يكون `ctrl+x` هو مفتاح القائد، وتتطلّب معظم الإجراءات أن تضغط أولا مفتاح القائد ثم الاختصار. على سبيل المثال، لبدء جلسة جديدة اضغط `ctrl+x` أولا ثم اضغط `n`. + +لا يلزم استخدام مفتاح قائد لاختصاراتك، لكننا نوصي بذلك. + +--- + +## تعطيل اختصار + +يمكنك تعطيل أي اختصار بإضافة معرّف الاختصار إلى ملف الإعدادات بقيمة "none". + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## اختصارات موجّه سطح المكتب + +يدعم حقل إدخال الموجّه في تطبيق OpenCode لسطح المكتب اختصارات شائعة لتحرير النص على نمط Readline/Emacs. هذه الاختصارات مدمجة حاليا ولا يمكن تخصيصها عبر `opencode.json`. + +| الاختصار | الإجراء | +| -------- | ------------------------------------------ | +| `ctrl+a` | الانتقال إلى بداية السطر الحالي | +| `ctrl+e` | الانتقال إلى نهاية السطر الحالي | +| `ctrl+b` | تحريك المؤشر للخلف حرفا واحدا | +| `ctrl+f` | تحريك المؤشر للأمام حرفا واحدا | +| `alt+b` | تحريك المؤشر للخلف كلمة واحدة | +| `alt+f` | تحريك المؤشر للأمام كلمة واحدة | +| `ctrl+d` | حذف الحرف الموجود تحت المؤشر | +| `ctrl+k` | حذف حتى نهاية السطر | +| `ctrl+u` | حذف حتى بداية السطر | +| `ctrl+w` | حذف الكلمة السابقة | +| `alt+d` | حذف الكلمة التالية | +| `ctrl+t` | تبديل موضعي حرفين | +| `ctrl+g` | إلغاء النوافذ المنبثقة / إيقاف الرد الجاري | + +--- + +## مفتاح Shift+Enter + +بعض الطرفيات لا ترسل مفاتيح التعديل مع Enter افتراضيا. قد تحتاج إلى ضبط طرفيتك لإرسال `Shift+Enter` كسلسلة هروب. + +### Windows Terminal + +افتح ملف `settings.json` الموجود في: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +أضف هذا إلى مصفوفة `actions` على مستوى الجذر: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +أضف هذا إلى مصفوفة `keybindings` على مستوى الجذر: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +احفظ الملف ثم أعد تشغيل Windows Terminal أو افتح علامة تبويب جديدة. diff --git a/packages/web/src/content/docs/ar/lsp.mdx b/packages/web/src/content/docs/ar/lsp.mdx new file mode 100644 index 000000000..1e8b013e4 --- /dev/null +++ b/packages/web/src/content/docs/ar/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: خوادم LSP +description: يتكامل OpenCode مع خوادم LSP لديك. +--- + +يتكامل OpenCode مع بروتوكول خادم اللغة (LSP) لمساعدة النموذج اللغوي الكبير على التفاعل مع قاعدة الشيفرة لديك. ويستخدم التشخيصات لتزويد النموذج بتغذية راجعة. + +--- + +## المدمجة + +يأتي OpenCode مع عدة خوادم LSP مدمجة للغات الشائعة: + +| خادم LSP | الامتدادات | المتطلبات | +| ------------------ | ------------------------------------------------------------------- | ---------------------------------------------------- | +| astro | .astro | يثبت تلقائيا لمشاريع Astro | +| bash | .sh, .bash, .zsh, .ksh | يثبت `bash-language-server` تلقائيا | +| clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | يثبت تلقائيا لمشاريع C/C++ | +| csharp | .cs | تثبيت `.NET SDK` | +| clojure-lsp | .clj, .cljs, .cljc, .edn | توفر أمر `clojure-lsp` | +| dart | .dart | توفر أمر `dart` | +| deno | .ts, .tsx, .js, .jsx, .mjs | توفر أمر `deno` (يكتشف تلقائيا deno.json/deno.jsonc) | +| elixir-ls | .ex, .exs | توفر أمر `elixir` | +| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | وجود تبعية `eslint` في المشروع | +| fsharp | .fs, .fsi, .fsx, .fsscript | تثبيت `.NET SDK` | +| gleam | .gleam | توفر أمر `gleam` | +| gopls | .go | توفر أمر `go` | +| hls | .hs, .lhs | توفر أمر `haskell-language-server-wrapper` | +| jdtls | .java | تثبيت `Java SDK (version 21+)` | +| kotlin-ls | .kt, .kts | يثبت تلقائيا لمشاريع Kotlin | +| lua-ls | .lua | يثبت تلقائيا لمشاريع Lua | +| nixd | .nix | توفر أمر `nixd` | +| ocaml-lsp | .ml, .mli | توفر أمر `ocamllsp` | +| oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | وجود تبعية `oxlint` في المشروع | +| php intelephense | .php | يثبت تلقائيا لمشاريع PHP | +| prisma | .prisma | توفر أمر `prisma` | +| pyright | .py, .pyi | تثبيت تبعية `pyright` | +| ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | توفر أمري `ruby` و `gem` | +| rust | .rs | توفر أمر `rust-analyzer` | +| sourcekit-lsp | .swift, .objc, .objcpp | تثبيت `swift` (على macOS عبر `xcode`) | +| svelte | .svelte | يثبت تلقائيا لمشاريع Svelte | +| terraform | .tf, .tfvars | يثبت تلقائيا من إصدارات GitHub | +| tinymist | .typ, .typc | يثبت تلقائيا من إصدارات GitHub | +| typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | وجود تبعية `typescript` في المشروع | +| vue | .vue | يثبت تلقائيا لمشاريع Vue | +| yaml-ls | .yaml, .yml | يثبت `yaml-language-server` من Red Hat تلقائيا | +| zls | .zig, .zon | توفر أمر `zig` | + +تُفعَّل خوادم LSP تلقائيا عند اكتشاف أحد امتدادات الملفات المذكورة أعلاه واستيفاء المتطلبات. + +:::note +يمكنك تعطيل تنزيلات خوادم LSP التلقائية عبر ضبط متغير البيئة `OPENCODE_DISABLE_LSP_DOWNLOAD` على `true`. +::: + +--- + +## كيف يعمل + +عندما يفتح opencode ملفا، فإنه: + +1. يفحص امتداد الملف مقابل جميع خوادم LSP المفعّلة. +2. يشغّل خادم LSP المناسب إذا لم يكن قيد التشغيل بالفعل. + +--- + +## الإعداد + +يمكنك تخصيص خوادم LSP عبر قسم `lsp` في إعدادات opencode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +يدعم كل خادم LSP ما يلي: + +| الخاصية | النوع | الوصف | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` | boolean | اضبطها على `true` لتعطيل خادم LSP | +| `command` | string[] | الأمر المستخدم لتشغيل خادم LSP | +| `extensions` | string[] | امتدادات الملفات التي يجب أن يعالجها خادم LSP هذا | +| `env` | object | متغيرات البيئة التي تُضبط عند تشغيل الخادم | +| `initialization` | object | خيارات التهيئة التي تُرسل إلى خادم LSP | + +لنلق نظرة على بعض الأمثلة. + +--- + +### متغيرات البيئة + +استخدم الخاصية `env` لضبط متغيرات البيئة عند تشغيل خادم LSP: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### خيارات التهيئة + +استخدم الخاصية `initialization` لتمرير خيارات التهيئة إلى خادم LSP. هذه إعدادات خاصة بالخادم تُرسل أثناء طلب LSP `initialize`: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +تختلف خيارات التهيئة بحسب خادم LSP. راجع توثيق خادم LSP لديك لمعرفة الخيارات المتاحة. +::: + +--- + +### تعطيل خوادم LSP + +لتعطيل **جميع** خوادم LSP على مستوى التطبيق، اضبط `lsp` على `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +لتعطيل خادم LSP **بعينه**، اضبط `disabled` على `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### خوادم LSP مخصصة + +يمكنك إضافة خوادم LSP مخصصة عبر تحديد الأمر وامتدادات الملفات: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## معلومات إضافية + +### PHP Intelephense + +يوفر PHP Intelephense ميزات مدفوعة عبر مفتاح ترخيص. يمكنك تزويده بمفتاح الترخيص عبر وضع (فقط) المفتاح داخل ملف نصي في: + +- على macOS/Linux: `$HOME/intelephense/licence.txt` +- على Windows: `%USERPROFILE%/intelephense/licence.txt` + +يجب أن يحتوي الملف على مفتاح الترخيص فقط دون أي محتوى إضافي. diff --git a/packages/web/src/content/docs/ar/mcp-servers.mdx b/packages/web/src/content/docs/ar/mcp-servers.mdx new file mode 100644 index 000000000..f457de524 --- /dev/null +++ b/packages/web/src/content/docs/ar/mcp-servers.mdx @@ -0,0 +1,492 @@ +--- +title: خوادم MCP +description: أضف أدوات MCP محلية وبعيدة. +--- + +يمكنك إضافة أدوات خارجية إلى OpenCode باستخدام _Model Context Protocol_، أو MCP. يدعم OpenCode خوادم محلية وبعيدة. + +بعد إضافتها، تصبح أدوات MCP متاحة تلقائيا للـ LLM إلى جانب الأدوات المضمنة. + +--- + +#### تنبيهات +عند استخدام خادم MCP فإنه يضيف إلى السياق. وقد يتراكم ذلك بسرعة إذا كان لديك الكثير من الأدوات. لذلك نوصي بالتحلّي بالحذر عند اختيار خوادم MCP التي تستخدمها. + +:::tip +تضيف خوادم MCP إلى سياقك، لذا احرص على اختيار ما تفعّله منها بعناية. +::: + +تميل بعض خوادم MCP، مثل خادم GitHub MCP، إلى إضافة الكثير من الرموز (tokens) وقد تتجاوز حد السياق بسهولة. + +--- + +## التمكين +يمكنك تعريف خوادم MCP في [إعدادات OpenCode](https://opencode.ai/docs/config/) ضمن `mcp`. أضف كل خادم MCP باسم فريد. ويمكنك الإشارة إلى ذلك الخادم بالاسم عند توجيه الطلب إلى الـ LLM. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +يمكنك أيضا تعطيل خادم عبر ضبط `enabled` على `false`. يفيد ذلك إذا أردت تعطيله مؤقتا دون إزالته من إعداداتك. + +--- + +### تجاوز القيم الافتراضية البعيدة +يمكن للمنظمات توفير خوادم MCP الافتراضية عبر نقطة النهاية `.well-known/opencode` الخاصة بها. قد تكون هذه الخوادم معطّلة افتراضيا، مما يتيح للمستخدمين تفعيل ما يحتاجونه فقط. + +لتفعيل خادم معيّن من الإعدادات البعيدة الخاصة بمؤسستك، أضفه إلى إعداداتك المحلية مع `enabled: true`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +تتغلب قيم إعداداتك المحلية على القيم الافتراضية البعيدة. راجع [أولوية الإعدادات](/docs/config#precedence-order) لمزيد من التفاصيل. + +--- + +## محلي +أضف خوادم MCP المحلية عبر ضبط `type` على `"local"` ضمن كائن `mcp`. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +الأمر `command` هو الطريقة التي يتم بها تشغيل خادم MCP المحلي. ويمكنك أيضا تمرير قائمة بمتغيرات البيئة. + +على سبيل المثال، إليك كيفية إضافة خادم MCP التجريبي [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +ولاستخدامه يمكنني إضافة `use the mcp_everything tool` إلى طلباتي. + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### الخيارات +فيما يلي جميع الخيارات المتاحة لتهيئة خادم MCP محلي. + +| الخيار | النوع | مطلوب | الوصف | +| ------------- | ------- | ----- | -------------------------------------------------------------------------------- | +| `type` | String | Y | نوع اتصال خادم MCP، ويجب أن يكون `"local"`. | +| `command` | Array | Y | الأمر والوسائط اللازمة لتشغيل خادم MCP. | +| `environment` | Object | | متغيرات البيئة التي يتم تعيينها عند تشغيل الخادم. | +| `enabled` | Boolean | | تفعيل خادم MCP أو تعطيله عند بدء التشغيل. | +| `timeout` | Number | | المهلة بالمللي ثانية لجلب الأدوات من خادم MCP. القيمة الافتراضية 5000 (5 ثوانٍ). | + +--- + +## بعيد +أضف خوادم MCP البعيدة عبر ضبط `type` على `"remote"`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +يمثل `url` عنوان URL لخادم MCP البعيد، وباستخدام خيار `headers` يمكنك تمرير قائمة من الرؤوس (headers). + +--- + +#### الخيارات +| الخيار | النوع | مطلوب | الوصف | +| --------- | ------- | ----- | -------------------------------------------------------------------------------- | +| `type` | String | Y | نوع اتصال خادم MCP، ويجب أن يكون `"remote"`. | +| `url` | String | Y | عنوان URL لخادم MCP البعيد. | +| `enabled` | Boolean | | تفعيل خادم MCP أو تعطيله عند بدء التشغيل. | +| `headers` | Object | | الرؤوس التي يتم إرسالها مع الطلب. | +| `oauth` | Object | | إعدادات مصادقة OAuth. راجع قسم [OAuth](#oauth) أدناه. | +| `timeout` | Number | | المهلة بالمللي ثانية لجلب الأدوات من خادم MCP. القيمة الافتراضية 5000 (5 ثوانٍ). | + +--- + +## OAuth +يتولى OpenCode تلقائيا معالجة مصادقة OAuth لخوادم MCP البعيدة. عندما يتطلب خادم ما المصادقة، سيقوم OpenCode بما يلي: + +1. اكتشاف استجابة 401 وبدء تدفق OAuth +2. استخدام **Dynamic Client Registration (RFC 7591)** إذا كان الخادم يدعمه +3. تخزين الرموز (tokens) بشكل آمن للطلبات المستقبلية + +--- + +### تلقائي +بالنسبة لمعظم خوادم MCP التي تدعم OAuth، لا تحتاج إلى إعدادات خاصة. ما عليك سوى تهيئة الخادم البعيد: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +إذا كان الخادم يتطلب المصادقة، فسيطلب منك OpenCode المصادقة عند أول محاولة لاستخدامه. وإذا لم يحدث ذلك، يمكنك [تشغيل التدفق يدويا](#authenticating) باستخدام `opencode mcp auth `. + +--- + +### مُسجَّل مسبقا +إذا كانت لديك بيانات اعتماد العميل من موفّر خادم MCP، يمكنك تهيئتها: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### المصادقة +يمكنك تشغيل المصادقة يدويا أو إدارة بيانات الاعتماد. + +صادِق مع خادم MCP معيّن: + +```bash +opencode mcp auth my-oauth-server +``` + +اعرض جميع خوادم MCP وحالة المصادقة الخاصة بها: + +```bash +opencode mcp list +``` + +احذف بيانات الاعتماد المخزنة: + +```bash +opencode mcp logout my-oauth-server +``` + +سيفتح أمر `mcp auth` متصفحك للتفويض. بعد إكمال التفويض، سيخزّن OpenCode الرموز بشكل آمن في `~/.local/share/opencode/mcp-auth.json`. + +--- + +#### تعطيل OAuth +إذا أردت تعطيل OAuth التلقائي لخادم ما (على سبيل المثال، للخوادم التي تستخدم مفاتيح API بدلا من ذلك)، فاضبط `oauth` على `false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### خيارات OAuth +| الخيار | النوع | الوصف | +| -------------- | --------------- | ------------------------------------------------------------------------ | +| `oauth` | Object \| false | كائن إعدادات OAuth، أو `false` لتعطيل الاكتشاف التلقائي لـ OAuth. | +| `clientId` | String | معرّف عميل OAuth. إذا لم يُحدَّد، ستتم محاولة التسجيل الديناميكي للعميل. | +| `clientSecret` | String | سرّ عميل OAuth، إذا كان مطلوبا من خادم التفويض. | +| `scope` | String | نطاقات OAuth المطلوبة أثناء التفويض. | + +#### تصحيح الأخطاء +إذا فشل خادم MCP بعيد في المصادقة، يمكنك تشخيص المشكلة باستخدام: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +يعرض أمر `mcp debug` حالة المصادقة الحالية، ويختبر اتصال HTTP، ويحاول تنفيذ تدفق اكتشاف OAuth. + +--- + +## الإدارة +تتوفر خوادم MCP لديك كأدوات داخل OpenCode إلى جانب الأدوات المضمنة. لذا يمكنك إدارتها عبر إعدادات OpenCode مثل أي أداة أخرى. + +--- + +### عام +هذا يعني أنه يمكنك تفعيلها أو تعطيلها على مستوى عام. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +يمكننا أيضا استخدام نمط glob لتعطيل جميع خوادم MCP المطابقة. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +هنا نستخدم نمط glob `my-mcp*` لتعطيل جميع خوادم MCP. + +--- + +### لكل وكيل +إذا كان لديك عدد كبير من خوادم MCP فقد ترغب في تفعيلها لكل وكيل على حدة وتعطيلها على المستوى العام. للقيام بذلك: + +1. عطّلها كأداة على المستوى العام. +2. في [إعدادات الوكيل](/docs/agents#tools)، فعّل خادم MCP كأداة. + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### أنماط Glob +يستخدم نمط glob أنماطا بسيطة من مطابقة glob: + +- `*` يطابق صفرا أو أكثر من أي محرف (على سبيل المثال، `"my-mcp*"` يطابق `my-mcp_search` و`my-mcp_list` وغيرها.) +- `?` يطابق محرفا واحدا بالضبط +- جميع المحارف الأخرى تُطابق حرفيا + +:::note +تُسجَّل أدوات خادم MCP مع اسم الخادم كبادئة، لذا لتعطيل جميع أدوات خادم ما استخدم ببساطة: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## أمثلة +فيما يلي أمثلة لبعض خوادم MCP الشائعة. يمكنك إرسال PR إذا أردت توثيق خوادم أخرى. + +--- + +### Sentry + +أضف [خادم MCP الخاص بـ Sentry](https://mcp.sentry.dev) للتفاعل مع مشاريع Sentry والقضايا (issues) الخاصة بك. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +بعد إضافة الإعدادات، قم بالمصادقة مع Sentry: + +```bash +opencode mcp auth sentry +``` + +سيؤدي ذلك إلى فتح نافذة متصفح لإكمال تدفق OAuth وربط OpenCode بحساب Sentry الخاص بك. + +بعد المصادقة، يمكنك استخدام أدوات Sentry في طلباتك للاستعلام عن القضايا والمشاريع وبيانات الأخطاء. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Context7 + +أضف [خادم MCP الخاص بـ Context7](https://github.com/upstash/context7) للبحث في المستندات. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +إذا كنت قد سجلت للحصول على حساب مجاني، يمكنك استخدام مفتاح API للحصول على حدود أعلى لمعدل الطلبات. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +هنا نفترض أنك عيّنت متغير البيئة `CONTEXT7_API_KEY`. + +أضف `use context7` إلى طلباتك لاستخدام خادم MCP الخاص بـ Context7. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +بدلا من ذلك، يمكنك إضافة شيء مثل هذا إلى [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep by Vercel + +أضف خادم MCP الخاص بـ [Grep by Vercel](https://grep.app) للبحث في مقتطفات الشيفرة على GitHub. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +وبما أننا سمّينا خادم MCP الخاص بنا `gh_grep`، يمكنك إضافة `use the gh_grep tool` إلى طلباتك لجعل الوكيل يستخدمه. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +بدلا من ذلك، يمكنك إضافة شيء مثل هذا إلى [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/ar/models.mdx b/packages/web/src/content/docs/ar/models.mdx new file mode 100644 index 000000000..64cd96bfe --- /dev/null +++ b/packages/web/src/content/docs/ar/models.mdx @@ -0,0 +1,222 @@ +--- +title: النماذج +description: تهيئة مزوّد LLM والنموذج. +--- + +يستخدم OpenCode كلاً من [AI SDK](https://ai-sdk.dev/) و[Models.dev](https://models.dev) لدعم **أكثر من 75 مزوّداً لنماذج LLM**، كما يدعم تشغيل النماذج محلياً. + +--- + +## المزوّدون + +أكثر المزوّدين شيوعاً مُحمَّلون مسبقاً افتراضياً. إذا أضفت بيانات اعتماد أحد المزوّدين عبر الأمر `/connect` فستكون متاحة عند تشغيل OpenCode. + +تعرّف على المزيد حول [المزوّدين](/docs/providers). + +--- + +## اختر نموذجاً + +بعد تهيئة المزوّد يمكنك اختيار النموذج الذي تريده بكتابة: + +```bash frame="none" +/models +``` + +--- + +## النماذج الموصى بها + +هناك الكثير من النماذج المتاحة، وتظهر نماذج جديدة كل أسبوع. + +:::tip +ننصح باستخدام أحد النماذج التي نوصي بها. +::: + +لكن القليل منها فقط يكون جيداً في كلٍ من توليد الشيفرة واستدعاء الأدوات. + +فيما يلي عدة نماذج تعمل جيداً مع OpenCode، دون ترتيب معيّن. (هذه ليست قائمة شاملة وقد لا تكون محدَّثة دائماً): + +- GPT 5.2 +- GPT 5.1 Codex +- Claude Opus 4.5 +- Claude Sonnet 4.5 +- Minimax M2.1 +- Gemini 3 Pro + +--- + +## تعيين الافتراضي + +لتعيين أحد هذه النماذج كنموذج افتراضي، يمكنك ضبط المفتاح `model` في ملف إعدادات OpenCode. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +المعرّف الكامل هنا يكون بالشكل `provider_id/model_id`. على سبيل المثال، إذا كنت تستخدم [OpenCode Zen](/docs/zen) فستستخدم `opencode/gpt-5.1-codex` لنموذج GPT 5.1 Codex. + +إذا كنت قد هيّأت [مزوّداً مخصّصاً](/docs/providers#custom)، فإن `provider_id` هو المفتاح الموجود ضمن قسم `provider` في إعداداتك، و`model_id` هو المفتاح الموجود ضمن `provider.models`. + +--- + +## إعداد النماذج + +يمكنك ضبط خيارات النموذج على مستوى عام عبر ملف الإعدادات. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +هنا نقوم بضبط إعدادات عامة لنموذجين مدمجين: `gpt-5` عند الوصول إليه عبر مزوّد `openai`، و`claude-sonnet-4-20250514` عند الوصول إليه عبر مزوّد `anthropic`. +يمكن العثور على أسماء المزوّدين والنماذج المدمجة على [Models.dev](https://models.dev). + +يمكنك أيضاً ضبط هذه الخيارات لأي وكلاء تستخدمهم. تتجاوز إعدادات الوكيل أي خيارات عامة هنا. [اعرف المزيد](/docs/agents/#additional). + +كما يمكنك تعريف متغيّرات مخصّصة تُوسّع المتغيّرات المدمجة. تتيح لك المتغيّرات ضبط إعدادات مختلفة للنموذج نفسه دون إنشاء إدخالات مكرّرة: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## المتغيّرات + +تدعم العديد من النماذج عدة متغيّرات بإعدادات مختلفة. يأتي OpenCode مع متغيّرات افتراضية مدمجة للمزوّدين الشائعين. + +### المتغيّرات المدمجة + +يأتي OpenCode مع متغيّرات افتراضية لعدد كبير من المزوّدين: + +**Anthropic**: + +- `high` - ميزانية تفكير مرتفعة (الافتراضي) +- `max` - أقصى ميزانية تفكير + +**OpenAI**: + +تختلف حسب النموذج، لكن بشكل عام: + +- `none` - بدون استدلال +- `minimal` - أقل جهد للاستدلال +- `low` - جهد استدلال منخفض +- `medium` - جهد استدلال متوسط +- `high` - جهد استدلال مرتفع +- `xhigh` - جهد استدلال مرتفع جداً + +**Google**: + +- `low` - جهد/ميزانية رموز أقل +- `high` - جهد/ميزانية رموز أعلى + +:::tip +هذه القائمة ليست شاملة. لدى العديد من المزوّدين الآخرين إعدادات افتراضية مدمجة أيضاً. +::: + +### متغيّرات مخصّصة + +يمكنك تجاوز المتغيّرات الموجودة أو إضافة متغيّراتك الخاصة: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### التبديل بين المتغيّرات + +استخدم اختصار لوحة المفاتيح `variant_cycle` للتبديل بسرعة بين المتغيّرات. [اعرف المزيد](/docs/keybinds). + +--- + +## تحميل النماذج + +عند بدء تشغيل OpenCode، يتحقق من النماذج وفق ترتيب الأولوية التالي: + +1. خيار سطر الأوامر `--model` أو `-m`. الصيغة هي نفسها الموجودة في ملف الإعدادات: `provider_id/model_id`. + +2. قائمة النماذج في إعدادات OpenCode. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + الصيغة هنا هي `provider/model`. + +3. آخر نموذج تم استخدامه. + +4. أول نموذج وفق أولوية داخلية. diff --git a/packages/web/src/content/docs/ar/modes.mdx b/packages/web/src/content/docs/ar/modes.mdx new file mode 100644 index 000000000..767fcb414 --- /dev/null +++ b/packages/web/src/content/docs/ar/modes.mdx @@ -0,0 +1,331 @@ +--- +title: الأوضاع +description: أوضاع مختلفة لحالات استخدام مختلفة. +--- + +:::caution +يتم الآن ضبط الأوضاع عبر خيار `agent` في إعدادات opencode. أصبح خيار +`mode` مُهمَلًا الآن. [اعرف المزيد](/docs/agents). +::: + +تتيح لك الأوضاع في opencode تخصيص السلوك والأدوات والمطالبات لحالات استخدام مختلفة. + +يأتي مع وضعين مدمجين: **build** و **plan**. يمكنك تخصيصهما أو إعداد +أوضاعك الخاصة عبر إعدادات opencode. + +يمكنك التبديل بين الأوضاع أثناء الجلسة أو إعدادها في ملف الإعدادات لديك. + +--- + +## الأوضاع المدمجة + +يأتي opencode مع وضعين مدمجين. + +--- + +### Build + +وضع Build هو الوضع **الافتراضي** مع تفعيل جميع الأدوات. هذا هو الوضع القياسي لأعمال التطوير عندما تحتاج إلى وصول كامل لعمليات الملفات وأوامر النظام. + +--- + +### Plan + +وضع مقيَّد مُصمَّم للتخطيط والتحليل. في وضع plan، تكون الأدوات التالية مُعطَّلة افتراضيًا: + +- `write` - لا يمكن إنشاء ملفات جديدة +- `edit` - لا يمكن تعديل الملفات الموجودة، باستثناء الملفات الموجودة في `.opencode/plans/*.md` لتفصيل الخطة نفسها +- `patch` - لا يمكن تطبيق التصحيحات +- `bash` - لا يمكن تنفيذ أوامر الصدفة + +يكون هذا الوضع مفيدًا عندما تريد من الذكاء الاصطناعي تحليل الشيفرة، أو اقتراح تغييرات، أو إنشاء خطط دون إجراء أي تعديلات فعلية على قاعدة الشيفرة لديك. + +--- + +## التبديل + +يمكنك التبديل بين الأوضاع أثناء الجلسة باستخدام مفتاح _Tab_، أو اختصار `switch_mode` الذي قمت بإعداده. + +انظر أيضًا: [Formatters](/docs/formatters) لمعلومات حول إعدادات تنسيق الشيفرة. + +--- + +## الإعداد + +يمكنك تخصيص الأوضاع المدمجة أو إنشاء أوضاعك الخاصة عبر الإعدادات. يمكن إعداد الأوضاع بطريقتين: + +### إعدادات JSON + +قم بإعداد الأوضاع في ملف الإعدادات `opencode.json` لديك: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### إعدادات Markdown + +يمكنك أيضًا تعريف الأوضاع باستخدام ملفات markdown. ضعها في: + +- عالمي: `~/.config/opencode/modes/` +- للمشروع: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +يصبح اسم ملف markdown هو اسم الوضع (على سبيل المثال، `review.md` ينشئ وضعًا باسم `review`). + +لنلقِ نظرة على خيارات الإعداد هذه بمزيد من التفصيل. + +--- + +### النموذج + +استخدم إعداد `model` لتجاوز النموذج الافتراضي لهذا الوضع. يفيد ذلك عند استخدام نماذج مختلفة مُحسَّنة لمهام مختلفة؛ مثل نموذج أسرع للتخطيط ونموذج أكثر قدرة للتنفيذ. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### درجة الحرارة + +تحكَّم في العشوائية والإبداع في ردود الذكاء الاصطناعي عبر إعداد `temperature`. القيم الأقل تجعل الردود أكثر تركيزًا وحتمية، بينما تزيد القيم الأعلى الإبداع والتنوّع. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +تتراوح قيم درجة الحرارة عادةً بين 0.0 و 1.0: + +- **0.0-0.2**: ردود شديدة التركيز وحتمية، مثالية لتحليل الشيفرة والتخطيط +- **0.3-0.5**: ردود متوازنة مع قدر من الإبداع، مناسبة لمهام التطوير العامة +- **0.6-1.0**: ردود أكثر إبداعًا وتنوّعًا، مفيدة للعصف الذهني والاستكشاف + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +إذا لم يتم تحديد درجة الحرارة، يستخدم opencode القيم الافتراضية الخاصة بكل نموذج (عادةً 0 لمعظم النماذج و 0.55 لنماذج Qwen). + +--- + +### الموجّه + +حدِّد ملف موجّه نظام (system prompt) مخصص لهذا الوضع عبر إعداد `prompt`. ينبغي أن يحتوي ملف الموجّه على تعليمات مرتبطة بهدف هذا الوضع. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +هذا المسار نسبي بالنسبة لموقع ملف الإعدادات. لذلك يعمل مع +إعدادات opencode العالمية وكذلك إعدادات المشروع. + +--- + +### الأدوات + +تحكَّم في الأدوات المتاحة في هذا الوضع عبر إعداد `tools`. يمكنك تفعيل أدوات محددة أو تعطيلها بضبطها على `true` أو `false`. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +إذا لم يتم تحديد أدوات، فستكون جميع الأدوات مفعّلة افتراضيًا. + +--- + +#### الأدوات المتاحة + +فيما يلي جميع الأدوات التي يمكن التحكم بها عبر إعدادات الوضع. + +| الأداة | الوصف | +| ----------- | -------------------------- | +| `bash` | تنفيذ أوامر الصدفة | +| `edit` | تعديل الملفات الموجودة | +| `write` | إنشاء ملفات جديدة | +| `read` | قراءة محتويات الملفات | +| `grep` | البحث في محتويات الملفات | +| `glob` | العثور على الملفات حسب نمط | +| `list` | سرد محتويات الدليل | +| `patch` | تطبيق تصحيحات على الملفات | +| `todowrite` | إدارة قوائم المهام | +| `todoread` | قراءة قوائم المهام | +| `webfetch` | جلب محتوى الويب | + +--- + +## أوضاع مخصصة + +يمكنك إنشاء أوضاعك المخصصة بإضافتها إلى الإعدادات. فيما يلي أمثلة باستخدام كلا الأسلوبين: + +### باستخدام إعدادات JSON + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### باستخدام ملفات markdown + +أنشئ ملفات الأوضاع في `.opencode/modes/` لأوضاع خاصة بالمشروع أو في `~/.config/opencode/modes/` لأوضاع عالمية: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### حالات الاستخدام + +فيما يلي بعض حالات الاستخدام الشائعة لأوضاع مختلفة. + +- **Build mode**: أعمال تطوير كاملة مع تفعيل جميع الأدوات +- **Plan mode**: التحليل والتخطيط دون إجراء تغييرات +- **Review mode**: مراجعة الشيفرة مع وصول للقراءة فقط بالإضافة إلى أدوات التوثيق +- **Debug mode**: تركيز على الاستقصاء مع تفعيل أدوات `bash` و `read` +- **Docs mode**: كتابة التوثيق مع عمليات الملفات لكن دون أوامر النظام + +قد تجد أيضًا أن نماذج مختلفة تكون أنسب لحالات استخدام مختلفة. diff --git a/packages/web/src/content/docs/ar/network.mdx b/packages/web/src/content/docs/ar/network.mdx new file mode 100644 index 000000000..5abb90175 --- /dev/null +++ b/packages/web/src/content/docs/ar/network.mdx @@ -0,0 +1,57 @@ +--- +title: الشبكة +description: إعداد الوكلاء والشهادات المخصصة. +--- + +يدعم OpenCode متغيرات بيئة الوكيل (proxy) القياسية والشهادات المخصصة لبيئات الشبكات المؤسسية. + +--- + +## الوكيل + +يتبع OpenCode متغيرات بيئة الوكيل القياسية. + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::caution +تتواصل واجهة TUI مع خادم HTTP محلي. يجب تجاوز الوكيل لهذا الاتصال لمنع حلقات التوجيه. +::: + +يمكنك إعداد منفذ الخادم واسم المضيف باستخدام [أعلام سطر الأوامر](/docs/cli#run). + +--- + +### المصادقة + +إذا كان الوكيل يتطلب مصادقة أساسية، فأدرج بيانات الاعتماد في عنوان URL. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::caution +تجنّب تضمين كلمات المرور بشكل ثابت. استخدم متغيرات البيئة أو تخزين بيانات اعتماد آمن. +::: + +بالنسبة للوكلاء الذين يتطلبون مصادقة متقدمة مثل NTLM أو Kerberos، فكّر في استخدام بوابة LLM تدعم طريقة المصادقة لديك. + +--- + +## الشهادات المخصصة + +إذا كانت مؤسستك تستخدم سلطات تصديق (CA) مخصصة لاتصالات HTTPS، فقم بإعداد OpenCode ليثق بها. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +يعمل ذلك لكل من اتصالات الوكيل والوصول المباشر إلى واجهات برمجة التطبيقات. diff --git a/packages/web/src/content/docs/ar/permissions.mdx b/packages/web/src/content/docs/ar/permissions.mdx new file mode 100644 index 000000000..37b53db5d --- /dev/null +++ b/packages/web/src/content/docs/ar/permissions.mdx @@ -0,0 +1,227 @@ +--- +title: الأذونات +description: تحكّم في الإجراءات التي تتطلب موافقة قبل تنفيذها. +--- + +يستخدم OpenCode إعداد `permission` لتحديد ما إذا كان إجراءٌ ما سيُنفّذ تلقائيًا، أو سيطلب موافقتك، أو سيتم حظره. + +اعتبارًا من `v1.1.1`، تم إهمال إعداد `tools` القديم (المنطقي) ودمجه ضمن `permission`. ولا يزال إعداد `tools` القديم مدعومًا للتوافق مع الإصدارات السابقة. + +--- + +## الإجراءات +يؤول كل حكم أذونات إلى إحدى القيم التالية: + +- `"allow"` — تشغيل دون موافقة +- `"ask"` — طلب الموافقة +- `"deny"` — حظر الإجراء + +--- + +## الإعداد +يمكنك تعيين الأذونات بشكل عام (باستخدام `*`) ثم تجاوزها لأدوات محددة. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +يمكنك أيضًا تعيين جميع الأذونات دفعة واحدة: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## قواعد دقيقة (صيغة الكائن) +في معظم الأذونات، يمكنك استخدام كائن لتطبيق إجراءات مختلفة بناءً على مُدخلات الأداة. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +تُقيَّم القواعد عبر مطابقة الأنماط، مع كون **آخر قاعدة مطابقة هي التي تُطبَّق**. من الشائع وضع قاعدة الشمول `"*"` أولًا ثم القواعد الأكثر تحديدًا بعدها. + +### أحرف البدل +تستخدم أنماط الأذونات مطابقة بسيطة لأحرف البدل: + +- `*` يطابق صفرًا أو أكثر من أي حرف +- `?` يطابق حرفًا واحدًا بالضبط +- جميع الأحرف الأخرى تُطابق حرفيًا + +### توسيع مجلد المنزل +يمكنك استخدام `~` أو `$HOME` في بداية النمط للإشارة إلى مجلد المنزل. هذا مفيد خصوصًا لقواعد [`external_directory`](#external-directories). + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### الأدلة الخارجية +استخدم `external_directory` للسماح باستدعاءات الأدوات التي تلمس مسارات خارج دليل العمل الذي بدأ منه OpenCode. ينطبق ذلك على أي أداة تأخذ مسارًا كمدخل (مثل `read` و`edit` و`list` و`glob` و`grep` والعديد من أوامر `bash`). + +توسيع المنزل (مثل `~/...`) يؤثر فقط على طريقة كتابة النمط. لا يجعل ذلك المسار الخارجي جزءًا من مساحة العمل الحالية، لذا يجب السماح بالمسارات خارج دليل العمل عبر `external_directory` أيضًا. + +على سبيل المثال، يتيح هذا الوصول إلى كل ما يقع تحت `~/projects/personal/`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +أي دليل مسموح به هنا يرث نفس القيم الافتراضية لمساحة العمل الحالية. وبما أن [`read` افتراضيًا هو `allow`](#defaults)، فإن عمليات القراءة تكون مسموحة أيضًا للعناصر ضمن `external_directory` ما لم يتم تجاوز ذلك. أضِف قواعد صريحة عندما يجب تقييد أداة ما في هذه المسارات، مثل حظر التعديلات مع الإبقاء على القراءة: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +اجعل القائمة مقتصرة على المسارات الموثوقة، ثم أضِف طبقات إضافية من قواعد `allow` أو `deny` حسب الحاجة لأدوات أخرى (مثل `bash`). + +--- + +## الأذونات المتاحة +تُعرَّف أذونات OpenCode بأسماء الأدوات، بالإضافة إلى بعض حواجز الأمان: + +- `read` — قراءة ملف (يطابق مسار الملف) +- `edit` — جميع تعديلات الملفات (يشمل `edit` و`write` و`patch` و`multiedit`) +- `glob` — مطابقة أسماء الملفات (يطابق نمط الـ glob) +- `grep` — البحث في المحتوى (يطابق نمط regex) +- `list` — سرد الملفات في دليل (يطابق مسار الدليل) +- `bash` — تشغيل أوامر الصدفة (يطابق الأوامر المُحلَّلة مثل `git status --porcelain`) +- `task` — تشغيل وكلاء فرعيين (يطابق نوع الوكيل الفرعي) +- `skill` — تحميل مهارة (يطابق اسم المهارة) +- `lsp` — تشغيل استعلامات LSP (حاليًا دون قواعد دقيقة) +- `todoread`, `todowrite` — قراءة/تحديث قائمة المهام +- `webfetch` — جلب عنوان URL (يطابق الـ URL) +- `websearch`, `codesearch` — بحث الويب/الكود (يطابق الاستعلام) +- `external_directory` — يُفعَّل عندما تلمس أداة مسارات خارج دليل عمل المشروع +- `doom_loop` — يُفعَّل عندما يتكرر نفس استدعاء الأداة 3 مرات مع نفس المُدخلات + +--- + +## القيم الافتراضية +إذا لم تحدد شيئًا، يبدأ OpenCode بقيم افتراضية متساهلة: + +- معظم الأذونات افتراضيًا تكون `"allow"`. +- `doom_loop` و`external_directory` افتراضيًا تكون `"ask"`. +- `read` هو `"allow"`، لكن ملفات `.env` تكون مرفوضة افتراضيًا: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## ماذا تفعل `"ask"` +عندما يطلب OpenCode الموافقة، تعرض الواجهة ثلاث نتائج ممكنة: + +- `once` — الموافقة على هذا الطلب فقط +- `always` — الموافقة على الطلبات المستقبلية المطابقة للأنماط المقترحة (لباقي جلسة OpenCode الحالية) +- `reject` — رفض الطلب + +مجموعة الأنماط التي ستوافق عليها `always` تُوفَّر من الأداة نفسها (على سبيل المثال، موافقات `bash` عادةً ما تُدرج بادئة أمر آمنة في القائمة البيضاء مثل `git status*`). + +--- + +## الوكلاء +يمكنك تجاوز الأذونات لكل وكيل. تُدمَج أذونات الوكلاء مع الإعداد العام، وتكون قواعد الوكيل هي ذات الأولوية. [تعرّف أكثر](/docs/agents#permissions) على أذونات الوكلاء. + +:::note +ارجع إلى قسم [قواعد دقيقة (صيغة الكائن)](#granular-rules-object-syntax) للحصول على أمثلة أكثر تفصيلًا حول مطابقة الأنماط. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +يمكنك أيضًا ضبط أذونات الوكيل في Markdown: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tip +استخدم مطابقة الأنماط للأوامر التي تحتوي على معاملات. يسمح `"grep *"` بتنفيذ `grep pattern file.txt`، بينما سيحظر `"grep"` وحده ذلك. تعمل أوامر مثل `git status` للسلوك الافتراضي، لكنها تتطلب إذنًا صريحًا (مثل `"git status *"`) عند تمرير معاملات. +::: diff --git a/packages/web/src/content/docs/ar/plugins.mdx b/packages/web/src/content/docs/ar/plugins.mdx new file mode 100644 index 000000000..5191a0ab6 --- /dev/null +++ b/packages/web/src/content/docs/ar/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: الإضافات +description: اكتب إضافاتك الخاصة لتوسيع OpenCode. +--- + +تتيح لك الإضافات توسيع OpenCode عبر ربطها بأحداث مختلفة وتخصيص السلوك. يمكنك إنشاء إضافات لإضافة ميزات جديدة، أو التكامل مع خدمات خارجية، أو تعديل السلوك الافتراضي لـ OpenCode. + +للاطلاع على أمثلة، راجع [الإضافات](/docs/ecosystem#plugins) التي أنشأها المجتمع. + +--- + +## استخدام إضافة + +هناك طريقتان لتحميل الإضافات. + +--- + +### من ملفات محلية + +ضع ملفات JavaScript أو TypeScript في دليل الإضافات. + +- `.opencode/plugins/` - إضافات على مستوى المشروع +- `~/.config/opencode/plugins/` - إضافات عامة + +تُحمَّل الملفات في هذه الأدلة تلقائيا عند بدء التشغيل. + +--- + +### من npm + +حدّد حزم npm في ملف الإعدادات. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +يتم دعم حزم npm العادية والحزم ذات النطاق (scoped). + +تصفّح الإضافات المتاحة في [النظام البيئي](/docs/ecosystem#plugins). + +--- + +### كيفية تثبيت الإضافات + +**إضافات npm** تُثبَّت تلقائيا باستخدام Bun عند بدء التشغيل. تُخزَّن الحزم واعتمادياتها مؤقتا في `~/.cache/opencode/node_modules/`. + +**الإضافات المحلية** تُحمَّل مباشرة من دليل الإضافات. لاستخدام حزم خارجية، يجب إنشاء `package.json` داخل دليل الإعدادات لديك (راجع [الاعتماديات](#dependencies))، أو نشر الإضافة على npm ثم [إضافتها إلى إعداداتك](/docs/config#plugins). + +--- + +### ترتيب التحميل + +تُحمَّل الإضافات من جميع المصادر وتعمل جميع الخطافات بالتتابع. ترتيب التحميل هو: + +1. إعدادات عامة (`~/.config/opencode/opencode.json`) +2. إعدادات المشروع (`opencode.json`) +3. دليل الإضافات العام (`~/.config/opencode/plugins/`) +4. دليل إضافات المشروع (`.opencode/plugins/`) + +تُحمَّل حزم npm المكررة ذات الاسم والإصدار نفسيهما مرة واحدة. ومع ذلك، تُحمَّل الإضافة المحلية وإضافة npm ذات الاسم المشابه كلتاهما بشكل مستقل. + +--- + +## إنشاء إضافة + +الإضافة هي **وحدة JavaScript/TypeScript** تصدّر دالة إضافة واحدة أو أكثر. +تستقبل كل دالة كائنا للسياق وتعيد كائنا للخطافات. + +--- + +### الاعتماديات + +يمكن للإضافات المحلية والأدوات المخصصة استخدام حزم npm خارجية. أضف `package.json` إلى دليل الإعدادات لديك متضمنا الاعتماديات التي تحتاجها. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +يشغّل OpenCode الأمر `bun install` عند بدء التشغيل لتثبيتها. بعد ذلك يمكن لإضافاتك وأدواتك استيرادها. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### البنية الأساسية + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +تستقبل دالة الإضافة ما يلي: + +- `project`: معلومات المشروع الحالي. +- `directory`: دليل العمل الحالي. +- `worktree`: مسار git worktree. +- `client`: عميل SDK لـ opencode للتفاعل مع الذكاء الاصطناعي. +- `$`: واجهة [shell API](https://bun.com/docs/runtime/shell) الخاصة بـ Bun لتنفيذ الأوامر. + +--- + +### دعم TypeScript + +بالنسبة لإضافات TypeScript، يمكنك استيراد الأنواع من حزمة الإضافة: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### الأحداث + +يمكن للإضافات الاشتراك في الأحداث كما هو موضح أدناه في قسم الأمثلة. فيما يلي قائمة بالأحداث المتاحة. + +#### أحداث الأوامر + +- `command.executed` + +#### أحداث الملفات + +- `file.edited` +- `file.watcher.updated` + +#### أحداث التثبيت + +- `installation.updated` + +#### أحداث LSP + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### أحداث الرسائل + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### أحداث الأذونات + +- `permission.asked` +- `permission.replied` + +#### أحداث الخادم + +- `server.connected` + +#### أحداث الجلسة + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### أحداث Todo + +- `todo.updated` + +#### أحداث الصدفة + +- `shell.env` + +#### أحداث الأدوات + +- `tool.execute.after` +- `tool.execute.before` + +#### أحداث واجهة TUI + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## أمثلة + +فيما يلي بعض أمثلة الإضافات التي يمكنك استخدامها لتوسيع opencode. + +--- + +### إرسال إشعارات + +أرسل إشعارات عند وقوع أحداث معينة: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +نستخدم `osascript` لتشغيل AppleScript على macOS. هنا نستخدمه لإرسال إشعارات. + +:::note +إذا كنت تستخدم تطبيق OpenCode لسطح المكتب، فيمكنه إرسال إشعارات النظام تلقائيا عند جاهزية الرد أو عند حدوث خطأ في جلسة. +::: + +--- + +### حماية .env + +امنع opencode من قراءة ملفات `.env`: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### حقن متغيرات البيئة + +احقن متغيرات البيئة في جميع عمليات تنفيذ الصدفة (أدوات الذكاء الاصطناعي وطرفيات المستخدم): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### أدوات مخصصة + +يمكن للإضافات أيضا إضافة أدوات مخصصة إلى opencode: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +تقوم الدالة المساعدة `tool` بإنشاء أداة مخصصة يمكن لـ opencode استدعاؤها. تأخذ دالة مخطط Zod وتعيد تعريف أداة يتضمن: + +- `description`: ما الذي تفعله الأداة +- `args`: مخطط Zod لوسائط الأداة +- `execute`: الدالة التي تُشغَّل عند استدعاء الأداة + +ستكون أدواتك المخصصة متاحة لـ opencode إلى جانب الأدوات المضمنة. + +--- + +### التسجيل + +استخدم `client.app.log()` بدلا من `console.log` للتسجيل البنيوي: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +المستويات: `debug`, `info`, `warn`, `error`. راجع [توثيق SDK](https://opencode.ai/docs/sdk) للتفاصيل. + +--- + +### خطافات الضغط + +خصّص السياق الذي يتم تضمينه عند ضغط جلسة: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +يعمل الخطاف `experimental.session.compacting` قبل أن ينشئ نموذج اللغة الكبير (LLM) ملخص المتابعة. استخدمه لحقن سياق خاص بالمجال قد يفوته موجّه الضغط الافتراضي. + +يمكنك أيضا استبدال موجّه الضغط بالكامل عبر ضبط `output.prompt`: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +عند ضبط `output.prompt` فإنه يستبدل موجّه الضغط الافتراضي بالكامل. يتم تجاهل المصفوفة `output.context` في هذه الحالة. diff --git a/packages/web/src/content/docs/ar/providers.mdx b/packages/web/src/content/docs/ar/providers.mdx new file mode 100644 index 000000000..b3b7c44a3 --- /dev/null +++ b/packages/web/src/content/docs/ar/providers.mdx @@ -0,0 +1,1863 @@ +--- +title: المزوّدون +description: استخدام أي موفّر LLM في OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +يستخدم OpenCode ‏[AI SDK](https://ai-sdk.dev/) و[Models.dev](https://models.dev) لدعم **أكثر من 75 موفّر LLM**، كما يدعم تشغيل النماذج المحلية. + +لإضافة مزوّد تحتاج إلى: + +1. أضف مفاتيح API الخاصة بالمزوّد باستخدام الأمر `/connect`. +2. اضبط المزوّد في ملف إعدادات OpenCode. + +--- + +### بيانات الاعتماد +عند إضافة مفاتيح API الخاصة بمزوّد عبر الأمر `/connect`، يتم تخزينها +في `~/.local/share/opencode/auth.json`. + +--- + +### الإعدادات +يمكنك تخصيص المزوّدات عبر قسم `provider` في ملف إعدادات OpenCode. + +--- + +#### عنوان URL الأساسي +يمكنك تخصيص عنوان URL الأساسي لأي مزوّد عبر خيار `baseURL`. يفيد ذلك عند استخدام خدمات وسيطة (proxy) أو نقاط نهاية مخصّصة. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen هي قائمة نماذج يوفّرها فريق OpenCode وقد تم +اختبارها والتحقق من أنها تعمل بشكل جيد مع OpenCode. [اعرف المزيد](/docs/zen). + +:::tip +إذا كنت جديدا، فننصح بالبدء مع OpenCode Zen. +::: + +1. شغّل الأمر `/connect` في TUI، واختر opencode، ثم انتقل إلى [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. سجّل الدخول، وأضف تفاصيل الفوترة، ثم انسخ مفتاح API الخاص بك. + +3. الصق مفتاح API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل `/models` في TUI لعرض قائمة النماذج التي نوصي بها. + + ```txt + /models + ``` + +يعمل مثل أي مزوّد آخر في OpenCode واستخدامه اختياري بالكامل. + +--- + +## الدليل +لنلقِ نظرة على بعض المزوّدات بالتفصيل. إذا رغبت في إضافة مزوّد إلى القائمة، +فلا تتردد في فتح PR. + +:::note +ألا ترى مزوّدا هنا؟ أرسل PR. +::: + +--- + +### 302.AI + +1. توجّه إلى [302.AI console](https://302.ai/)، وأنشئ حسابا، ثم أنشئ مفتاح API. + +2. شغّل الأمر `/connect` وابحث عن **302.AI**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ 302.AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج. + + ```txt + /models + ``` + +--- + +### Amazon Bedrock + +لاستخدام Amazon Bedrock مع OpenCode: + +1. توجّه إلى **Model catalog** في Amazon Bedrock console واطلب + الوصول إلى النماذج التي تريدها. + + :::tip + يجب أن يكون لديك وصول إلى النموذج الذي تريده في Amazon Bedrock. + ::: + +2. **اضبط المصادقة** باستخدام إحدى الطرق التالية: + + #### متغيرات البيئة (بدء سريع) + عيّن أحد متغيرات البيئة التالية أثناء تشغيل opencode: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + أو أضفها إلى bash profile: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### ملف الإعدادات (موصى به) + للإعداد الخاص بالمشروع أو الإعداد الدائم، استخدم `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **الخيارات المتاحة:** + - `region` - منطقة AWS (مثل `us-east-1`، `eu-west-1`) + - `profile` - ملف تعريف AWS المسمّى من `~/.aws/credentials` + - `endpoint` - عنوان URL لنقطة نهاية مخصّصة لنقاط نهاية VPC (اسم بديل لخيار `baseURL` العام) + + :::tip + خيارات ملف الإعدادات لها أولوية على متغيرات البيئة. + ::: + + #### متقدم: نقاط نهاية VPC + إذا كنت تستخدم نقاط نهاية VPC لـ Bedrock: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::note + خيار `endpoint` هو اسم بديل لخيار `baseURL` العام باستخدام مصطلحات AWS. إذا تم تحديد كل من `endpoint` و`baseURL`، فستكون الأولوية لـ `endpoint`. + ::: + + #### طرق المصادقة - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: أنشئ مستخدم IAM وأنشئ مفاتيح وصول من AWS Console + - **`AWS_PROFILE`**: استخدم ملفات تعريف مسمّاة من `~/.aws/credentials`. اضبط أولا عبر `aws configure --profile my-profile` أو `aws sso login` + - **`AWS_BEARER_TOKEN_BEDROCK`**: أنشئ مفاتيح API طويلة الأجل من Amazon Bedrock console + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: لـ EKS IRSA (IAM Roles for Service Accounts) أو بيئات Kubernetes أخرى مع اتحاد OIDC. يتم حقن متغيرات البيئة هذه تلقائيا بواسطة Kubernetes عند استخدام تعليقات حساب الخدمة. + + #### أولوية المصادقة + يستخدم Amazon Bedrock أولوية المصادقة التالية: + 1. **Bearer Token** - متغير البيئة `AWS_BEARER_TOKEN_BEDROCK` أو الرمز من الأمر `/connect` + 2. **AWS Credential Chain** - الملف الشخصي، مفاتيح الوصول، بيانات الاعتماد المشتركة، أدوار IAM، رموز Web Identity (EKS IRSA)، بيانات تعريف المثيل + + :::note + عند تعيين bearer token (عبر `/connect` أو `AWS_BEARER_TOKEN_BEDROCK`)، ستكون له أولوية على جميع طرق بيانات اعتماد AWS بما في ذلك ملفات التعريف المضبوطة. + ::: + +3. شغّل الأمر `/models` لاختيار النموذج الذي تريده. + + ```txt + /models + ``` + +:::note +بالنسبة إلى ملفات تعريف الاستدلال المخصّصة، استخدم اسم النموذج واسم المزوّد في المفتاح وعيّن الخاصية `id` إلى arn. يضمن ذلك التخزين المؤقت الصحيح: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### Anthropic + +1. بعد إنشاء حسابك، شغّل الأمر `/connect` واختر Anthropic. + + ```txt + /connect + ``` + +2. هنا يمكنك اختيار خيار **Claude Pro/Max** وسيتم فتح المتصفح + وسيطلب منك المصادقة. + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. الآن يجب أن تكون جميع نماذج Anthropic متاحة عند استخدام الأمر `/models`. + + ```txt + /models + ``` + +:::info +استخدام اشتراك Claude Pro/Max داخل OpenCode غير مدعوم رسميا من [Anthropic](https://anthropic.com). +::: + +##### استخدام مفاتيح API +يمكنك أيضا اختيار **Create an API Key** إذا لم يكن لديك اشتراك Pro/Max. سيفتح ذلك المتصفح أيضا ويطلب منك تسجيل الدخول إلى Anthropic ويعطيك رمزا يمكنك لصقه في الطرفية. + +أو إذا كان لديك مفتاح API بالفعل، يمكنك اختيار **Manually enter API Key** ولصقه في الطرفية. + +--- + +### Azure OpenAI + +:::note +إذا واجهت أخطاء "I'm sorry, but I cannot assist with that request"، فجرّب تغيير مرشح المحتوى من **DefaultV2** إلى **Default** في مورد Azure الخاص بك. +::: + +1. توجّه إلى [Azure portal](https://portal.azure.com/) وأنشئ موردا من نوع **Azure OpenAI**. ستحتاج إلى: + - **Resource name**: يصبح جزءا من نقطة نهاية API لديك (`https://RESOURCE_NAME.openai.azure.com/`) + - **API key**: إما `KEY 1` أو `KEY 2` من موردك + +2. اذهب إلى [Azure AI Foundry](https://ai.azure.com/) وانشر نموذجا. + + :::note + يجب أن يطابق اسم النشر اسم النموذج كي يعمل opencode بشكل صحيح. + ::: + +3. شغّل الأمر `/connect` وابحث عن **Azure**. + + ```txt + /connect + ``` + +4. أدخل مفتاح API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. عيّن اسم المورد كمتغير بيئة: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + أو أضفه إلى bash profile: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. شغّل الأمر `/models` لاختيار النموذج الذي قمت بنشره. + + ```txt + /models + ``` + +--- + +### Azure Cognitive Services + +1. توجّه إلى [Azure portal](https://portal.azure.com/) وأنشئ موردا من نوع **Azure OpenAI**. ستحتاج إلى: + - **Resource name**: يصبح جزءا من نقطة نهاية API لديك (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) + - **API key**: إما `KEY 1` أو `KEY 2` من موردك + +2. اذهب إلى [Azure AI Foundry](https://ai.azure.com/) وانشر نموذجا. + + :::note + يجب أن يطابق اسم النشر اسم النموذج كي يعمل opencode بشكل صحيح. + ::: + +3. شغّل الأمر `/connect` وابحث عن **Azure Cognitive Services**. + + ```txt + /connect + ``` + +4. أدخل مفتاح API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. عيّن اسم المورد كمتغير بيئة: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + أو أضفه إلى bash profile: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. شغّل الأمر `/models` لاختيار النموذج الذي قمت بنشره. + + ```txt + /models + ``` + +--- + +### Baseten + +1. توجّه إلى [Baseten](https://app.baseten.co/)، وأنشئ حسابا، ثم أنشئ مفتاح API. + +2. شغّل الأمر `/connect` وابحث عن **Baseten**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Baseten. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج. + + ```txt + /models + ``` + +--- + +### Cerebras + +1. توجّه إلى [Cerebras console](https://inference.cerebras.ai/)، وأنشئ حسابا، ثم أنشئ مفتاح API. + +2. شغّل الأمر `/connect` وابحث عن **Cerebras**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Cerebras. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### Cloudflare AI Gateway + +تتيح Cloudflare AI Gateway الوصول إلى نماذج من OpenAI وAnthropic وWorkers AI وغيرها عبر نقطة نهاية موحّدة. مع [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) لن تحتاج إلى مفاتيح API منفصلة لكل مزوّد. + +1. توجّه إلى [Cloudflare dashboard](https://dash.cloudflare.com/)، وانتقل إلى **AI** > **AI Gateway**، وأنشئ بوابة جديدة. + +2. عيّن Account ID وGateway ID كمتغيرات بيئة. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. شغّل الأمر `/connect` وابحث عن **Cloudflare AI Gateway**. + + ```txt + /connect + ``` + +4. أدخل Cloudflare API token. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + أو عيّنه كمتغير بيئة. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. شغّل الأمر `/models` لاختيار نموذج. + + ```txt + /models + ``` + + يمكنك أيضا إضافة نماذج عبر إعدادات opencode. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### Cortecs + +1. توجّه إلى [Cortecs console](https://cortecs.ai/)، وأنشئ حسابا، ثم أنشئ مفتاح API. + +2. شغّل الأمر `/connect` وابحث عن **Cortecs**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Cortecs. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### DeepSeek + +1. توجّه إلى [DeepSeek console](https://platform.deepseek.com/)، وأنشئ حسابا، ثم انقر **Create new API key**. + +2. شغّل الأمر `/connect` وابحث عن **DeepSeek**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ DeepSeek. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج من DeepSeek مثل _DeepSeek Reasoner_. + + ```txt + /models + ``` + +--- + +### Deep Infra + +1. توجّه إلى [Deep Infra dashboard](https://deepinfra.com/dash)، وأنشئ حسابا، ثم أنشئ مفتاح API. + +2. شغّل الأمر `/connect` وابحث عن **Deep Infra**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Deep Infra. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج. + + ```txt + /models + ``` + +--- + +### Firmware + +1. توجّه إلى [Firmware dashboard](https://app.firmware.ai/signup)، وأنشئ حسابا، ثم أنشئ مفتاح API. + +2. شغّل الأمر `/connect` وابحث عن **Firmware**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Firmware. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج. + + ```txt + /models + ``` + +--- + +### Fireworks AI + +1. توجّه إلى [Fireworks AI console](https://app.fireworks.ai/)، وأنشئ حسابا، ثم انقر **Create API Key**. + +2. شغّل الأمر `/connect` وابحث عن **Fireworks AI**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Fireworks AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### GitLab Duo + +يوفّر GitLab Duo دردشة وكيلة (agentic) مدعومة بالذكاء الاصطناعي مع قدرات استدعاء أدوات بشكل مدمج عبر Anthropic proxy الخاصة بـ GitLab. + +1. شغّل الأمر `/connect` واختر GitLab. + + ```txt + /connect + ``` + +2. اختر طريقة المصادقة: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### استخدام OAuth (موصى به) + اختر **OAuth** وسيفتح المتصفح لإتمام التفويض. + + #### استخدام Personal Access Token 1. اذهب إلى [GitLab User Settings > Access Tokens](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. انقر **Add new token** + 3. Name: `OpenCode`، Scopes: `api` + 4. انسخ الرمز (يبدأ بـ `glpat-`) + 5. أدخله في الطرفية + +3. شغّل الأمر `/models` لعرض النماذج المتاحة. + + ```txt + /models + ``` + + تتوفر ثلاثة نماذج مبنية على Claude: + - **duo-chat-haiku-4-5** (Default) - استجابات سريعة للمهام السريعة + - **duo-chat-sonnet-4-5** - أداء متوازن لمعظم سير العمل + - **duo-chat-opus-4-5** - الأكثر قدرة للتحليل المعقّد + +:::note +يمكنك أيضا تعيين متغير البيئة 'GITLAB_TOKEN' إذا لم تكن تريد +تخزين الرمز في مساحة تخزين مصادقة opencode. +::: + +##### GitLab مستضاف ذاتيا +:::note[ملاحظة امتثال] +يستخدم OpenCode نموذجا صغيرا لبعض مهام الذكاء الاصطناعي مثل إنشاء عنوان الجلسة. +تم ضبطه لاستخدام gpt-5-nano افتراضيا، مستضافا عبر Zen. لحصر OpenCode +على استخدام مثيل GitLab المستضاف لديك فقط، أضف ما يلي إلى ملف +`opencode.json` لديك. يوصى أيضا بتعطيل مشاركة الجلسات. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +لمثيلات GitLab المستضافة ذاتيا: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +إذا كان مثيلك يشغّل AI Gateway مخصّصة: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +أو أضفها إلى bash profile: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +يجب على مدير GitLab لديك تفعيل ما يلي: + +1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) للمستخدم أو المجموعة أو المثيل +2. Feature flags (عبر Rails console): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### OAuth للمثيلات المستضافة ذاتيا +لكي يعمل Oauth مع مثيلك المستضاف ذاتيا، تحتاج إلى إنشاء +تطبيق جديد (Settings → Applications) مع +callback URL ‏`http://127.0.0.1:8080/callback` ونطاقات الصلاحيات التالية: + +- api (Access the API on your behalf) +- read_user (Read your personal information) +- read_repository (Allows read-only access to the repository) + +ثم عرّض application ID كمتغير بيئة: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +مزيد من التوثيق على صفحة [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth). + +##### التهيئة +خصّص عبر `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### أدوات GitLab API (اختياري، لكن موصى به بشدة) +للوصول إلى أدوات GitLab (merge requests وissues وpipelines وCI/CD وغيرها): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +يوفّر هذا الملحق قدرات شاملة لإدارة مستودعات GitLab بما في ذلك مراجعات MR وتتبع issues ومراقبة pipelines وغير ذلك. + +--- + +### GitHub Copilot + +لاستخدام اشتراك GitHub Copilot مع opencode: + +:::note +قد تتطلب بعض النماذج اشتراك [Pro+](https://github.com/features/copilot/plans) للاستخدام. + +تحتاج بعض النماذج إلى تفعيل يدوي من [إعدادات GitHub Copilot](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. شغّل الأمر `/connect` وابحث عن GitHub Copilot. + + ```txt + /connect + ``` + +2. انتقل إلى [github.com/login/device](https://github.com/login/device) وأدخل الرمز. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. الآن شغّل الأمر `/models` لاختيار النموذج الذي تريده. + + ```txt + /models + ``` + +--- + +### Google Vertex AI + +لاستخدام Google Vertex AI مع OpenCode: + +1. توجّه إلى **Model Garden** في Google Cloud Console وتحقق من + النماذج المتاحة في منطقتك. + + :::note + تحتاج إلى مشروع Google Cloud مع تفعيل Vertex AI API. + ::: + +2. عيّن متغيرات البيئة المطلوبة: + - `GOOGLE_CLOUD_PROJECT`: معرّف مشروع Google Cloud لديك + - `VERTEX_LOCATION` (اختياري): منطقة Vertex AI (الافتراضي `global`) + - المصادقة (اختر واحدا): + - `GOOGLE_APPLICATION_CREDENTIALS`: مسار ملف مفتاح حساب الخدمة بصيغة JSON + - المصادقة عبر gcloud CLI: ‏`gcloud auth application-default login` + + عيّنها أثناء تشغيل opencode. + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + أو أضفها إلى bash profile. + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::tip +تساعد منطقة `global` على تحسين التوفر وتقليل الأخطاء دون تكلفة إضافية. استخدم نقاط نهاية إقليمية (مثل `us-central1`) لمتطلبات موضع البيانات. [اعرف المزيد](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. شغّل الأمر `/models` لاختيار النموذج الذي تريده. + + ```txt + /models + ``` + +--- + +### Groq + +1. توجّه إلى [Groq console](https://console.groq.com/)، وانقر **Create API Key**، ثم انسخ المفتاح. + +2. شغّل الأمر `/connect` وابحث عن Groq. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بالمزوّد. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار ما تريده. + + ```txt + /models + ``` + +--- + +### Hugging Face + +توفّر [Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers) وصولا إلى نماذج مفتوحة مدعومة من أكثر من 17 مزوّدا. + +1. توجّه إلى [Hugging Face settings](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) لإنشاء رمز (token) بصلاحية إجراء طلبات إلى Inference Providers. + +2. شغّل الأمر `/connect` وابحث عن **Hugging Face**. + + ```txt + /connect + ``` + +3. أدخل token الخاص بـ Hugging Face. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _Kimi-K2-Instruct_ أو _GLM-4.6_. + + ```txt + /models + ``` + +--- + +### Helicone + +[Helicone](https://helicone.ai) منصة لملاحظة LLM (observability) توفّر التسجيل والمراقبة والتحليلات لتطبيقات الذكاء الاصطناعي لديك. تقوم Helicone AI Gateway بتوجيه طلباتك تلقائيا إلى المزوّد المناسب بناء على النموذج. + +1. توجّه إلى [Helicone](https://helicone.ai)، وأنشئ حسابا، ثم أنشئ مفتاح API من لوحة التحكم. + +2. شغّل الأمر `/connect` وابحث عن **Helicone**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Helicone. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج. + + ```txt + /models + ``` + +لمزيد من المزوّدات والميزات المتقدمة مثل التخزين المؤقت (caching) وتحديد المعدّل (rate limiting)، راجع [توثيق Helicone](https://docs.helicone.ai). + +#### إعدادات اختيارية +إذا رأيت ميزة أو نموذجا في Helicone لم يتم ضبطه تلقائيا عبر opencode، فيمكنك دائما ضبطه بنفسك. + +هذه هي [Helicone's Model Directory](https://helicone.ai/models)، وستحتاجها للحصول على IDs الخاصة بالنماذج التي تريد إضافتها. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### ترويسات مخصّصة +تدعم Helicone ترويسات مخصّصة لميزات مثل التخزين المؤقت وتتبع المستخدم وإدارة الجلسات. أضفها إلى إعداد المزوّد عبر `options.headers`: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### تتبع الجلسات +تتيح ميزة [Sessions](https://docs.helicone.ai/features/sessions) في Helicone تجميع طلبات LLM المرتبطة معا. استخدم ملحق [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) لتسجيل كل محادثة OpenCode تلقائيا كجلسة في Helicone. + +```bash +npm install -g opencode-helicone-session +``` + +أضفه إلى إعداداتك. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +يقوم الملحق بحقن ترويسات `Helicone-Session-Id` و`Helicone-Session-Name` ضمن طلباتك. في صفحة Sessions داخل Helicone، سترى كل محادثة OpenCode مدرجة كجلسة مستقلة. + +##### ترويسات Helicone الشائعة +| Header | الوصف | +| -------------------------- | -------------------------------------------------------- | +| `Helicone-Cache-Enabled` | تفعيل التخزين المؤقت للاستجابات (`true`/`false`) | +| `Helicone-User-Id` | تتبع المقاييس حسب المستخدم | +| `Helicone-Property-[Name]` | إضافة خصائص مخصّصة (مثل `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | ربط الطلبات بإصدارات prompt | + +راجع [Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory) لعرض جميع الترويسات المتاحة. + +--- + +### llama.cpp + +يمكنك ضبط opencode لاستخدام نماذج محلية عبر أداة llama-server ضمن [llama.cpp](https://github.com/ggml-org/llama.cpp) + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +في هذا المثال: + +- `llama.cpp` هو ID مزوّد مخصّص. يمكن أن يكون أي سلسلة نصية تريدها. +- `npm` يحدد الحزمة المستخدمة لهذا المزوّد. هنا يتم استخدام `@ai-sdk/openai-compatible` لأي API متوافق مع OpenAI. +- `name` هو اسم العرض للمزوّد في واجهة المستخدم. +- `options.baseURL` هو نقطة نهاية الخادم المحلي. +- `models` هو خريطة من IDs النماذج إلى إعداداتها. سيتم عرض اسم النموذج ضمن قائمة اختيار النماذج. + +--- + +### IO.NET + +تقدّم IO.NET ‏17 نموذجا محسّنا لاستخدامات متعددة: + +1. توجّه إلى [IO.NET console](https://ai.io.net/)، وأنشئ حسابا، ثم أنشئ مفتاح API. + +2. شغّل الأمر `/connect` وابحث عن **IO.NET**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ IO.NET. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج. + + ```txt + /models + ``` + +--- + +### LM Studio + +يمكنك ضبط opencode لاستخدام نماذج محلية عبر LM Studio. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +في هذا المثال: + +- `lmstudio` هو ID مزوّد مخصّص. يمكن أن يكون أي سلسلة نصية تريدها. +- `npm` يحدد الحزمة المستخدمة لهذا المزوّد. هنا يتم استخدام `@ai-sdk/openai-compatible` لأي API متوافق مع OpenAI. +- `name` هو اسم العرض للمزوّد في واجهة المستخدم. +- `options.baseURL` هو نقطة نهاية الخادم المحلي. +- `models` هو خريطة من IDs النماذج إلى إعداداتها. سيتم عرض اسم النموذج ضمن قائمة اختيار النماذج. + +--- + +### Moonshot AI + +لاستخدام Kimi K2 من Moonshot AI: + +1. توجّه إلى [Moonshot AI console](https://platform.moonshot.ai/console)، وأنشئ حسابا، ثم انقر **Create API key**. + +2. شغّل الأمر `/connect` وابحث عن **Moonshot AI**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Moonshot. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار _Kimi K2_. + + ```txt + /models + ``` + +--- + +### MiniMax + +1. توجّه إلى [MiniMax API Console](https://platform.minimax.io/login)، وأنشئ حسابا، ثم أنشئ مفتاح API. + +2. شغّل الأمر `/connect` وابحث عن **MiniMax**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ MiniMax. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _M2.1_. + + ```txt + /models + ``` + +--- + +### Nebius Token Factory + +1. توجّه إلى [Nebius Token Factory console](https://tokenfactory.nebius.com/)، وأنشئ حسابا، ثم انقر **Add Key**. + +2. شغّل الأمر `/connect` وابحث عن **Nebius Token Factory**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Nebius Token Factory. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Ollama + +يمكنك ضبط opencode لاستخدام نماذج محلية عبر Ollama. + +:::tip +يمكن لـ Ollama ضبط نفسه تلقائيا للعمل مع OpenCode. راجع [توثيق تكامل Ollama](https://docs.ollama.com/integrations/opencode) للتفاصيل. +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +في هذا المثال: + +- `ollama` هو ID مزوّد مخصّص. يمكن أن يكون أي سلسلة نصية تريدها. +- `npm` يحدد الحزمة المستخدمة لهذا المزوّد. هنا يتم استخدام `@ai-sdk/openai-compatible` لأي API متوافق مع OpenAI. +- `name` هو اسم العرض للمزوّد في واجهة المستخدم. +- `options.baseURL` هو نقطة نهاية الخادم المحلي. +- `models` هو خريطة من IDs النماذج إلى إعداداتها. سيتم عرض اسم النموذج ضمن قائمة اختيار النماذج. + +:::tip +إذا لم تكن tool calls تعمل، جرّب زيادة `num_ctx` في Ollama. ابدأ بنحو 16k - 32k. +::: + +--- + +### Ollama Cloud + +لاستخدام Ollama Cloud مع OpenCode: + +1. توجّه إلى [https://ollama.com/](https://ollama.com/) وسجّل الدخول أو أنشئ حسابا. + +2. انتقل إلى **Settings** > **Keys** وانقر **Add API Key** لإنشاء مفتاح API جديد. + +3. انسخ مفتاح API لاستخدامه في OpenCode. + +4. شغّل الأمر `/connect` وابحث عن **Ollama Cloud**. + + ```txt + /connect + ``` + +5. أدخل مفتاح API الخاص بـ Ollama Cloud. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **مهم**: قبل استخدام نماذج السحابة في OpenCode، يجب سحب معلومات النموذج محليا: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. شغّل الأمر `/models` لاختيار نموذج Ollama Cloud. + + ```txt + /models + ``` + +--- + +### OpenAI + +نوصي بالاشتراك في [ChatGPT Plus أو Pro](https://chatgpt.com/pricing). + +1. بعد الاشتراك، شغّل الأمر `/connect` واختر OpenAI. + + ```txt + /connect + ``` + +2. هنا يمكنك اختيار خيار **ChatGPT Plus/Pro** وسيتم فتح المتصفح + وسيطلب منك المصادقة. + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. الآن يجب أن تكون جميع نماذج OpenAI متاحة عند استخدام الأمر `/models`. + + ```txt + /models + ``` + +##### استخدام مفاتيح API +إذا كان لديك مفتاح API بالفعل، يمكنك اختيار **Manually enter API Key** ولصقه في الطرفية. + +--- + +### OpenCode Zen + +OpenCode Zen هي قائمة من النماذج التي تم اختبارها والتحقق منها مقدّمة من فريق OpenCode. [اعرف المزيد](/docs/zen). + +1. سجّل الدخول إلى **OpenCode Zen** وانقر **Create API Key**. + +2. شغّل الأمر `/connect` وابحث عن **OpenCode Zen**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ OpenCode. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### OpenRouter + +1. توجّه إلى [OpenRouter dashboard](https://openrouter.ai/settings/keys)، وانقر **Create API Key**، ثم انسخ المفتاح. + +2. شغّل الأمر `/connect` وابحث عن OpenRouter. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بالمزوّد. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. يتم تحميل العديد من نماذج OpenRouter مسبقا بشكل افتراضي؛ شغّل الأمر `/models` لاختيار ما تريده. + + ```txt + /models + ``` + + يمكنك أيضا إضافة نماذج إضافية عبر إعدادات opencode. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. يمكنك أيضا تخصيصها عبر إعدادات opencode. إليك مثالا على تحديد مزوّد + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP AI Core + +يوفّر SAP AI Core وصولا إلى أكثر من 40 نموذجا من OpenAI وAnthropic وGoogle وAmazon وMeta وMistral وAI21 عبر منصة موحّدة. + +1. اذهب إلى [SAP BTP Cockpit](https://account.hana.ondemand.com/)، وانتقل إلى مثيل خدمة SAP AI Core لديك، ثم أنشئ service key. + + :::tip + service key هو كائن JSON يحتوي على `clientid` و`clientsecret` و`url` و`serviceurls.AI_API_URL`. يمكنك العثور على مثيل AI Core ضمن **Services** > **Instances and Subscriptions** في BTP Cockpit. + ::: + +2. شغّل الأمر `/connect` وابحث عن **SAP AI Core**. + + ```txt + /connect + ``` + +3. أدخل JSON الخاص بـ service key. + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + أو عيّن متغير البيئة `AICORE_SERVICE_KEY`: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + أو أضفه إلى bash profile: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. اختياريا، عيّن deployment ID وresource group: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::note + هذه الإعدادات اختيارية ويجب ضبطها وفقا لإعداد SAP AI Core لديك. + ::: + +5. شغّل الأمر `/models` للاختيار من بين أكثر من 40 نموذجا متاحا. + + ```txt + /models + ``` + +--- + +### OVHcloud AI Endpoints + +1. توجّه إلى [OVHcloud panel](https://ovh.com/manager). انتقل إلى قسم `Public Cloud`، ثم `AI & Machine Learning` > `AI Endpoints`، وفي تبويب `API Keys` انقر **Create a new API key**. + +2. شغّل الأمر `/connect` وابحث عن **OVHcloud AI Endpoints**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ OVHcloud AI Endpoints. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Scaleway + +لاستخدام [Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/) مع Opencode: + +1. توجّه إلى [Scaleway Console IAM settings](https://console.scaleway.com/iam/api-keys) لإنشاء مفتاح API جديد. + +2. شغّل الأمر `/connect` وابحث عن **Scaleway**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Scaleway. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _devstral-2-123b-instruct-2512_ أو _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Together AI + +1. توجّه إلى [Together AI console](https://api.together.ai)، وأنشئ حسابا، ثم انقر **Add Key**. + +2. شغّل الأمر `/connect` وابحث عن **Together AI**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Together AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Venice AI + +1. توجّه إلى [Venice AI console](https://venice.ai)، وأنشئ حسابا، ثم أنشئ مفتاح API. + +2. شغّل الأمر `/connect` وابحث عن **Venice AI**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Venice AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _Llama 3.3 70B_. + + ```txt + /models + ``` + +--- + +### Vercel AI Gateway + +تتيح Vercel AI Gateway الوصول إلى نماذج من OpenAI وAnthropic وGoogle وxAI وغيرها عبر نقطة نهاية موحّدة. تُقدّم النماذج بسعر القائمة دون أي زيادة. + +1. توجّه إلى [Vercel dashboard](https://vercel.com/)، وانتقل إلى تبويب **AI Gateway**، ثم انقر **API keys** لإنشاء مفتاح API جديد. + +2. شغّل الأمر `/connect` وابحث عن **Vercel AI Gateway**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ Vercel AI Gateway. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج. + + ```txt + /models + ``` + +يمكنك أيضا تخصيص النماذج عبر إعدادات opencode. إليك مثالا على تحديد ترتيب توجيه المزوّدات. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +بعض خيارات التوجيه المفيدة: + +| Option | الوصف | +| ------------------- | ----------------------------------------------- | +| `order` | تسلسل المزوّدات التي سيتم تجربتها | +| `only` | تقييد الاستخدام على مزوّدات محددة | +| `zeroDataRetention` | استخدام مزوّدات بسياسات احتفاظ بيانات صفرية فقط | + +--- + +### xAI + +1. توجّه إلى [xAI console](https://console.x.ai/)، وأنشئ حسابا، ثم أنشئ مفتاح API. + +2. شغّل الأمر `/connect` وابحث عن **xAI**. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بـ xAI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _Grok Beta_. + + ```txt + /models + ``` + +--- + +### Z.AI + +1. توجّه إلى [Z.AI API console](https://z.ai/manage-apikey/apikey-list)، وأنشئ حسابا، ثم انقر **Create a new API key**. + +2. شغّل الأمر `/connect` وابحث عن **Z.AI**. + + ```txt + /connect + ``` + + إذا كنت مشتركا في **GLM Coding Plan**، فاختر **Z.AI Coding Plan**. + +3. أدخل مفتاح API الخاص بـ Z.AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. شغّل الأمر `/models` لاختيار نموذج مثل _GLM-4.7_. + + ```txt + /models + ``` + +--- + +### ZenMux + +1. توجّه إلى [ZenMux dashboard](https://zenmux.ai/settings/keys)، وانقر **Create API Key**، ثم انسخ المفتاح. + +2. شغّل الأمر `/connect` وابحث عن ZenMux. + + ```txt + /connect + ``` + +3. أدخل مفتاح API الخاص بالمزوّد. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. يتم تحميل العديد من نماذج ZenMux مسبقا بشكل افتراضي؛ شغّل الأمر `/models` لاختيار ما تريده. + + ```txt + /models + ``` + + يمكنك أيضا إضافة نماذج إضافية عبر إعدادات opencode. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## موفّر مخصّص +لإضافة أي مزوّد **OpenAI-compatible** غير موجود ضمن الأمر `/connect`: + +:::tip +يمكنك استخدام أي مزوّد OpenAI-compatible مع opencode. معظم مزوّدي الذكاء الاصطناعي الحديثة يقدّمون APIs متوافقة مع OpenAI. +::: + +1. شغّل الأمر `/connect` ومرّر للأسفل حتى **Other**. + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. أدخل ID فريدا للمزوّد. + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note + اختر ID سهل التذكر؛ ستستخدمه في ملف الإعدادات. + ::: + +3. أدخل مفتاح API الخاص بالمزوّد. + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. أنشئ أو حدّث ملف `opencode.json` في دليل مشروعك: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + خيارات التهيئة هي: + - **npm**: حزمة AI SDK المستخدمة؛ استخدم `@ai-sdk/openai-compatible` للمزوّدات OpenAI-compatible + - **name**: اسم العرض في واجهة المستخدم. + - **models**: النماذج المتاحة. + - **options.baseURL**: عنوان URL لنقطة نهاية API. + - **options.apiKey**: تعيين مفتاح API اختياريا إذا لم تكن تستخدم auth. + - **options.headers**: تعيين ترويسات مخصّصة اختياريا. + + مزيد من التفاصيل حول الخيارات المتقدمة في المثال التالي. + +5. شغّل الأمر `/models` وستظهر المزوّدات والنماذج المخصّصة في قائمة الاختيار. + +--- + +##### مثال +إليك مثالا يضبط خيارات `apiKey` و`headers` وخيارات `limit` الخاصة بالنموذج. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +تفاصيل التهيئة: + +- **apiKey**: يتم تعيينه عبر صيغة متغيرات `env`، [اعرف المزيد](/docs/config#env-vars). +- **headers**: ترويسات مخصّصة تُرسل مع كل طلب. +- **limit.context**: الحد الأقصى لرموز الإدخال التي يقبلها النموذج. +- **limit.output**: الحد الأقصى للرموز التي يمكن للنموذج توليدها. + +تسمح حقول `limit` لـ OpenCode بفهم مقدار السياق المتبقي لديك. تسحب المزوّدات القياسية هذه القيم تلقائيا من models.dev. + +--- + +## استكشاف الأخطاء وإصلاحها +إذا كنت تواجه مشكلة في تهيئة مزوّد، فتحقق مما يلي: + +1. **تحقق من إعداد auth**: شغّل `opencode auth list` لمعرفة ما إذا كانت بيانات الاعتماد + الخاصة بالمزوّد قد أضيفت إلى إعداداتك. + + لا ينطبق هذا على مزوّدات مثل Amazon Bedrock التي تعتمد على متغيرات البيئة لـ auth. + +2. للمزوّدات المخصّصة، راجع إعدادات opencode وتأكد من: + - أن provider ID المستخدم في الأمر `/connect` يطابق الـ ID في إعدادات opencode. + - استخدام حزمة npm الصحيحة للمزوّد. على سبيل المثال استخدم `@ai-sdk/cerebras` لـ Cerebras. ولكل المزوّدات الأخرى المتوافقة مع OpenAI استخدم `@ai-sdk/openai-compatible`. + - استخدام نقطة نهاية API الصحيحة في الحقل `options.baseURL`. diff --git a/packages/web/src/content/docs/ar/rules.mdx b/packages/web/src/content/docs/ar/rules.mdx new file mode 100644 index 000000000..8e3d9886d --- /dev/null +++ b/packages/web/src/content/docs/ar/rules.mdx @@ -0,0 +1,180 @@ +--- +title: القواعد +description: اضبط تعليمات مخصصة لـ opencode. +--- + +يمكنك تزويد opencode بتعليمات مخصصة عبر إنشاء ملف `AGENTS.md`. هذا مشابه لقواعد Cursor. يحتوي هذا الملف على تعليمات تُضاف إلى سياق نموذج اللغة (LLM) لتخصيص سلوكه لمشروعك المحدد. + +--- + +## التهيئة + +لإنشاء ملف `AGENTS.md` جديد، يمكنك تشغيل الأمر `/init` في opencode. + +:::tip +يُستحسن عمل commit لملف `AGENTS.md` الخاص بمشروعك إلى Git. +::: + +سيقوم ذلك بفحص مشروعك وكل محتوياته لفهم طبيعة المشروع وتوليد ملف `AGENTS.md` بناءً على ذلك. يساعد هذا opencode على التنقّل داخل المشروع بشكل أفضل. + +إذا كان لديك ملف `AGENTS.md` موجود بالفعل، فسيحاول هذا إضافة محتوى إليه. + +--- + +## مثال + +يمكنك أيضًا إنشاء هذا الملف يدويًا. إليك مثالًا على بعض الأمور التي يمكنك وضعها في ملف `AGENTS.md`. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +نضيف هنا تعليمات خاصة بالمشروع، وسيتم مشاركتها عبر فريقك. + +--- + +## الأنواع + +يدعم opencode أيضًا قراءة ملف `AGENTS.md` من مواقع متعددة، ولكل موقع غرض مختلف. + +### المشروع + +ضع ملف `AGENTS.md` في جذر مشروعك للقواعد الخاصة بالمشروع. لا تُطبَّق هذه القواعد إلا عند العمل داخل هذا المجلد أو مجلداته الفرعية. + +### عام + +يمكنك أيضًا وضع قواعد عامة في ملف `~/.config/opencode/AGENTS.md`. تُطبَّق هذه القواعد على جميع جلسات opencode. + +وبما أن هذا الملف لا يتم عمل commit له إلى Git ولا تتم مشاركته مع فريقك، نوصي باستخدامه لتحديد أي قواعد شخصية يجب أن يلتزم بها نموذج اللغة. + +### التوافق مع Claude Code + +للمستخدمين الذين ينتقلون من Claude Code، يدعم OpenCode اصطلاحات ملفات Claude Code كبدائل احتياطية: + +- **قواعد المشروع**: `CLAUDE.md` في دليل مشروعك (يُستخدم إذا لم يوجد `AGENTS.md`) +- **قواعد عامة**: `~/.claude/CLAUDE.md` (يُستخدم إذا لم يوجد `~/.config/opencode/AGENTS.md`) +- **المهارات**: `~/.claude/skills/` — راجع [مهارات الوكيل](/docs/skills/) للتفاصيل + +لإيقاف التوافق مع Claude Code، عيّن أحد متغيرات البيئة التالية: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## الأولوية + +عند بدء opencode، يبحث عن ملفات القواعد بهذا الترتيب: + +1. **ملفات محلية** عبر التنقّل صعودًا من الدليل الحالي (`AGENTS.md`, `CLAUDE.md`) +2. **ملف عام** في `~/.config/opencode/AGENTS.md` +3. **ملف Claude Code** في `~/.claude/CLAUDE.md` (ما لم يتم تعطيله) + +يتم اعتماد أول ملف مطابق ضمن كل فئة. على سبيل المثال، إذا كان لديك كل من `AGENTS.md` و`CLAUDE.md` فسيتم استخدام `AGENTS.md` فقط. وبالمثل، تكون الأولوية لملف `~/.config/opencode/AGENTS.md` على `~/.claude/CLAUDE.md`. + +--- + +## تعليمات مخصصة + +يمكنك تحديد ملفات تعليمات مخصصة في `opencode.json` أو في الملف العام `~/.config/opencode/opencode.json`. يتيح ذلك لك ولفريقك إعادة استخدام القواعد الموجودة بدلًا من تكرارها داخل AGENTS.md. + +مثال: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +يمكنك أيضًا استخدام عناوين URL بعيدة لتحميل التعليمات من الويب. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +يتم جلب التعليمات البعيدة بمهلة قدرها 5 ثوانٍ. + +تُدمَج جميع ملفات التعليمات مع ملفات `AGENTS.md` لديك. + +--- + +## الإشارة إلى ملفات خارجية + +على الرغم من أن opencode لا يقوم تلقائيًا بتحليل مراجع الملفات داخل `AGENTS.md`، يمكنك تحقيق وظيفة مشابهة بطريقتين: + +### استخدام opencode.json + +النهج الموصى به هو استخدام الحقل `instructions` في `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### تعليمات يدوية في AGENTS.md + +يمكنك تعليم opencode قراءة ملفات خارجية عبر تقديم تعليمات صريحة داخل `AGENTS.md`. إليك مثالًا عمليًا: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +يتيح لك هذا النهج ما يلي: + +- إنشاء ملفات قواعد معيارية قابلة لإعادة الاستخدام +- مشاركة القواعد عبر المشاريع باستخدام symlinks أو git submodules +- إبقاء AGENTS.md موجزًا مع الإشارة إلى إرشادات تفصيلية +- ضمان أن opencode يحمّل الملفات فقط عند الحاجة للمهمة المحددة + +:::tip +بالنسبة للمستودعات متعددة الحزم (monorepos) أو المشاريع ذات المعايير المشتركة، فإن استخدام `opencode.json` مع أنماط glob (مثل `packages/*/AGENTS.md`) أسهل للصيانة من التعليمات اليدوية. +::: diff --git a/packages/web/src/content/docs/ar/sdk.mdx b/packages/web/src/content/docs/ar/sdk.mdx new file mode 100644 index 000000000..e806e27e6 --- /dev/null +++ b/packages/web/src/content/docs/ar/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: مجموعة تطوير البرمجيات (SDK) +description: عميل JavaScript آمن الأنواع لخادم opencode. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +توفر SDK الخاصة بـ opencode لـ JS/TS عميلا آمنا للأنواع للتفاعل مع الخادم. +استخدمها لبناء التكاملات والتحكم في opencode برمجيا. + +[اعرف المزيد](/docs/server) حول كيفية عمل الخادم. للاطلاع على أمثلة، تفقد [المشاريع](/docs/ecosystem#projects) التي أنشأها المجتمع. + +--- + +## التثبيت + +ثبّت SDK من npm: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## إنشاء عميل + +أنشئ مثيلا من opencode: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +هذا يشغّل خادما وعميلا معا. + +#### الخيارات + +| الخيار | النوع | الوصف | الافتراضي | +| ---------- | ------------- | ----------------------------- | ----------- | +| `hostname` | `string` | اسم مضيف الخادم | `127.0.0.1` | +| `port` | `number` | منفذ الخادم | `4096` | +| `signal` | `AbortSignal` | إشارة إلغاء للإيقاف | `undefined` | +| `timeout` | `number` | مهلة بدء الخادم بالمللي ثانية | `5000` | +| `config` | `Config` | كائن الإعدادات | `{}` | + +--- + +## الإعدادات + +يمكنك تمرير كائن إعدادات لتخصيص السلوك. سيستمر المثيل في التقاط `opencode.json` لديك، لكن يمكنك تجاوز الإعدادات أو إضافة إعدادات مباشرة: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## العميل فقط + +إذا كان لديك مثيل opencode يعمل بالفعل، يمكنك إنشاء مثيل عميل للاتصال به: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### الخيارات + +| الخيار | النوع | الوصف | الافتراضي | +| --------------- | ---------- | --------------------------------- | ----------------------- | +| `baseUrl` | `string` | عنوان URL للخادم | `http://localhost:4096` | +| `fetch` | `function` | تنفيذ fetch مخصص | `globalThis.fetch` | +| `parseAs` | `string` | طريقة تحليل الاستجابة | `auto` | +| `responseStyle` | `string` | أسلوب الإرجاع: `data` أو `fields` | `fields` | +| `throwOnError` | `boolean` | رمي الأخطاء بدلا من إرجاعها | `false` | + +--- + +## الأنواع + +تتضمن SDK تعريفات TypeScript لجميع أنواع واجهات برمجة التطبيقات. استوردها مباشرة: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +جميع الأنواع مولّدة من مواصفات OpenAPI الخاصة بالخادم ومتاحة في ملف الأنواع. + +--- + +## الأخطاء + +يمكن أن ترمي SDK أخطاء يمكنك التقاطها ومعالجتها: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## واجهات برمجة التطبيقات + +توفر SDK جميع واجهات الخادم عبر عميل آمن للأنواع. + +--- + +### عام (`global`) + +| الطريقة | الوصف | الاستجابة | +| ----------------- | ---------------------------- | ------------------------------------ | +| `global.health()` | التحقق من صحة الخادم وإصداره | `{ healthy: true, version: string }` | + +--- + +#### أمثلة + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### التطبيق (`app`) + +| الطريقة | الوصف | الاستجابة | +| -------------- | ------------------------- | ------------------------------------------- | +| `app.log()` | كتابة إدخال في السجل | `boolean` | +| `app.agents()` | سرد جميع الوكلاء المتاحين | Agent[] | + +--- + +#### أمثلة + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### المشروع (`project`) + +| الطريقة | الوصف | الاستجابة | +| ------------------- | ------------------ | --------------------------------------------- | +| `project.list()` | سرد جميع المشاريع | Project[] | +| `project.current()` | جلب المشروع الحالي | Project | + +--- + +#### أمثلة + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### المسار (`path`) + +| الطريقة | الوصف | الاستجابة | +| ------------ | ----------------- | ---------------------------------------- | +| `path.get()` | جلب المسار الحالي | Path | + +--- + +#### أمثلة + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### الإعدادات (`config`) + +| الطريقة | الوصف | الاستجابة | +| -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` | جلب معلومات الإعدادات | Config | +| `config.providers()` | سرد المزوّدين والنماذج الافتراضية | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +#### أمثلة + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### الجلسات (`session`) + +| الطريقة | الوصف | ملاحظات | +| ---------------------------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` | سرد الجلسات | يعيد Session[] | +| `session.get({ path })` | جلب جلسة | يعيد Session | +| `session.children({ path })` | سرد الجلسات الفرعية | يعيد Session[] | +| `session.create({ body })` | إنشاء جلسة | يعيد Session | +| `session.delete({ path })` | حذف جلسة | يعيد `boolean` | +| `session.update({ path, body })` | تحديث خصائص الجلسة | يعيد Session | +| `session.init({ path, body })` | تحليل التطبيق وإنشاء `AGENTS.md` | يعيد `boolean` | +| `session.abort({ path })` | إيقاف جلسة قيد التشغيل | يعيد `boolean` | +| `session.share({ path })` | مشاركة جلسة | يعيد Session | +| `session.unshare({ path })` | إلغاء مشاركة جلسة | يعيد Session | +| `session.summarize({ path, body })` | تلخيص جلسة | يعيد `boolean` | +| `session.messages({ path })` | سرد الرسائل في جلسة | يعيد `{ info: `Message`, parts: `Part[]`}[]` | +| `session.message({ path })` | جلب تفاصيل الرسالة | يعيد `{ info: `Message`, parts: `Part[]`}` | +| `session.prompt({ path, body })` | إرسال رسالة مطالبة | `body.noReply: true` يعيد UserMessage (للسياق فقط). الافتراضي يعيد AssistantMessage مع استجابة AI | +| `session.command({ path, body })` | إرسال أمر إلى الجلسة | يعيد `{ info: `AssistantMessage`, parts: `Part[]`}` | +| `session.shell({ path, body })` | تشغيل أمر shell | يعيد AssistantMessage | +| `session.revert({ path, body })` | التراجع عن رسالة | يعيد Session | +| `session.unrevert({ path })` | استعادة الرسائل المتراجع عنها | يعيد Session | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | الاستجابة لطلب إذن | يعيد `boolean` | + +--- + +#### أمثلة + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### الملفات + +| الطريقة | الوصف | الاستجابة | +| ------------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------- | +| `find.text({ query })` | البحث عن نص داخل الملفات | مصفوفة من كائنات المطابقة مع `path` و`lines` و`line_number` و`absolute_offset` و`submatches` | +| `find.files({ query })` | العثور على الملفات والمجلدات بالاسم | `string[]` (مسارات) | +| `find.symbols({ query })` | العثور على رموز مساحة العمل | Symbol[] | +| `file.read({ query })` | قراءة ملف | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | جلب حالة الملفات المتتبَّعة | File[] | + +يدعم `find.files` بعض حقول الاستعلام الاختيارية: + +- `type`: `"file"` أو `"directory"` +- `directory`: تجاوز جذر المشروع لعملية البحث +- `limit`: الحد الأقصى للنتائج (1–200) + +--- + +#### أمثلة + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### واجهة TUI (`tui`) + +| الطريقة | الوصف | الاستجابة | +| ------------------------------ | ---------------------- | --------- | +| `tui.appendPrompt({ body })` | إلحاق نص بالمطالبة | `boolean` | +| `tui.openHelp()` | فتح مربع حوار المساعدة | `boolean` | +| `tui.openSessions()` | فتح محدد الجلسات | `boolean` | +| `tui.openThemes()` | فتح محدد السمات | `boolean` | +| `tui.openModels()` | فتح محدد النماذج | `boolean` | +| `tui.submitPrompt()` | إرسال المطالبة الحالية | `boolean` | +| `tui.clearPrompt()` | مسح المطالبة | `boolean` | +| `tui.executeCommand({ body })` | تنفيذ أمر | `boolean` | +| `tui.showToast({ body })` | عرض إشعار toast | `boolean` | + +--- + +#### أمثلة + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### المصادقة (`auth`) + +| الطريقة | الوصف | الاستجابة | +| ------------------- | ---------------------------- | --------- | +| `auth.set({ ... })` | تعيين بيانات اعتماد المصادقة | `boolean` | + +--- + +#### أمثلة + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### الأحداث (`event`) + +| الطريقة | الوصف | الاستجابة | +| ------------------- | -------------------------- | -------------------------- | +| `event.subscribe()` | تدفق أحداث مرسلة من الخادم | تدفق أحداث مرسلة من الخادم | + +--- + +#### أمثلة + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/ar/server.mdx b/packages/web/src/content/docs/ar/server.mdx new file mode 100644 index 000000000..d72412106 --- /dev/null +++ b/packages/web/src/content/docs/ar/server.mdx @@ -0,0 +1,287 @@ +--- +title: الخادم +description: تفاعل مع خادم opencode عبر HTTP. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +يشغّل الأمر `opencode serve` خادما HTTP دون واجهة ويعرض نقطة نهاية OpenAPI يمكن لعميل opencode استخدامها. + +--- + +### الاستخدام + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### الخيارات + +| الخيار | الوصف | الافتراضي | +| --------------- | ------------------------------------- | ---------------- | +| `--port` | المنفذ الذي يستمع عليه | `4096` | +| `--hostname` | اسم المضيف الذي يستمع عليه | `127.0.0.1` | +| `--mdns` | تفعيل اكتشاف mDNS | `false` | +| `--mdns-domain` | اسم نطاق مخصص لخدمة mDNS | `opencode.local` | +| `--cors` | أصول (Origins) متصفح إضافية مسموح بها | `[]` | + +يمكن تمرير `--cors` عدة مرات: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### المصادقة + +عيّن `OPENCODE_SERVER_PASSWORD` لحماية الخادم باستخدام مصادقة HTTP الأساسية. اسم المستخدم افتراضيا هو `opencode`، أو عيّن `OPENCODE_SERVER_USERNAME` لتغييره. ينطبق ذلك على كل من `opencode serve` و `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### كيف يعمل + +عند تشغيل `opencode` يبدأ تشغيل واجهة طرفية تفاعلية (TUI) وخادما. تكون الـ TUI هي +العميل الذي يتحدث إلى الخادم. يوفّر الخادم نقطة نهاية لمواصفة OpenAPI 3.1. +وتُستخدم هذه النقطة أيضا لتوليد [SDK](/docs/sdk). + +:::tip +استخدم خادم opencode للتفاعل مع opencode برمجيا. +::: + +تتيح هذه البنية لـ opencode دعم عدة عملاء وتمكّنك من التفاعل مع opencode برمجيا. + +يمكنك تشغيل `opencode serve` لبدء خادم مستقل. إذا كانت واجهة opencode الطرفية (TUI) +قيد التشغيل، فسيبدأ `opencode serve` خادما جديدا. + +--- + +#### الاتصال بخادم موجود + +عند بدء الـ TUI تقوم بتعيين منفذ واسم مضيف عشوائيا. يمكنك بدلا من ذلك تمرير [الخيارات](/docs/cli) `--hostname` و `--port`، ثم استخدامهما للاتصال بخادمها. + +يمكن استخدام نقطة النهاية [`/tui`](#tui) للتحكم في الـ TUI عبر الخادم. على سبيل المثال، يمكنك تعبئة الموجّه مسبقا أو تشغيله. يُستخدم هذا الإعداد بواسطة ملحقات OpenCode لـ [IDE](/docs/ide). + +--- + +## المواصفات + +ينشر الخادم مواصفة OpenAPI 3.1 ويمكن عرضها على: + +``` +http://:/doc +``` + +على سبيل المثال: `http://localhost:4096/doc`. استخدم المواصفة لتوليد عملاء أو لفحص أنواع الطلبات والاستجابات. أو اعرضها في مستكشف Swagger. + +--- + +## واجهات API + +يعرض خادم opencode واجهات API التالية. + +--- + +### عام + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ---------------- | ------------------------------------ | ------------------------------------ | +| `GET` | `/global/health` | الحصول على صحة الخادم وإصداره | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | الحصول على الأحداث العامة (تدفق SSE) | تدفق أحداث | + +--- + +### المشروع + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ------------------ | ------------------------- | --------------------------------------------- | +| `GET` | `/project` | سرد جميع المشاريع | Project[] | +| `GET` | `/project/current` | الحصول على المشروع الحالي | Project | + +--- + +### المسار و VCS + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ------- | ------------------------------------- | ------------------------------------------- | +| `GET` | `/path` | الحصول على المسار الحالي | Path | +| `GET` | `/vcs` | الحصول على معلومات VCS للمشروع الحالي | VcsInfo | + +--- + +### المثيل + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ------------------- | ----------------------- | --------- | +| `POST` | `/instance/dispose` | التخلص من المثيل الحالي | `boolean` | + +--- + +### الإعدادات + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ------------------- | --------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` | الحصول على معلومات الإعدادات | Config | +| `PATCH` | `/config` | تحديث الإعدادات | Config | +| `GET` | `/config/providers` | سرد المزوّدين والنماذج الافتراضية | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +### المزوّد + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | -------------------------------- | ----------------------------- | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` | سرد جميع المزوّدين | `{ all: `Provider[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | الحصول على طرق مصادقة المزوّد | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | تفويض مزوّد باستخدام OAuth | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | معالجة رد نداء OAuth لمزوّد | `boolean` | + +--- + +### الجلسات + +| الطريقة | المسار | الوصف | الملاحظات | +| -------- | ---------------------------------------- | ------------------------------------- | -------------------------------------------------------------------------------- | +| `GET` | `/session` | سرد جميع الجلسات | يعيد Session[] | +| `POST` | `/session` | إنشاء جلسة جديدة | المتن: `{ parentID?, title? }`، يعيد Session | +| `GET` | `/session/status` | الحصول على حالة الجلسات جميعها | يعيد `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | الحصول على تفاصيل الجلسة | يعيد Session | +| `DELETE` | `/session/:id` | حذف جلسة وجميع بياناتها | يعيد `boolean` | +| `PATCH` | `/session/:id` | تحديث خصائص الجلسة | المتن: `{ title? }`، يعيد Session | +| `GET` | `/session/:id/children` | الحصول على الجلسات الفرعية لجلسة | يعيد Session[] | +| `GET` | `/session/:id/todo` | الحصول على قائمة المهام (todo) للجلسة | يعيد Todo[] | +| `POST` | `/session/:id/init` | تحليل التطبيق وإنشاء `AGENTS.md` | المتن: `{ messageID, providerID, modelID }`، يعيد `boolean` | +| `POST` | `/session/:id/fork` | تفريع جلسة موجودة عند رسالة | المتن: `{ messageID? }`، يعيد Session | +| `POST` | `/session/:id/abort` | إلغاء جلسة قيد التشغيل | يعيد `boolean` | +| `POST` | `/session/:id/share` | مشاركة جلسة | يعيد Session | +| `DELETE` | `/session/:id/share` | إلغاء مشاركة جلسة | يعيد Session | +| `GET` | `/session/:id/diff` | الحصول على diff لهذه الجلسة | الاستعلام: `messageID?`، يعيد FileDiff[] | +| `POST` | `/session/:id/summarize` | تلخيص الجلسة | المتن: `{ providerID, modelID }`، يعيد `boolean` | +| `POST` | `/session/:id/revert` | التراجع عن رسالة | المتن: `{ messageID, partID? }`، يعيد `boolean` | +| `POST` | `/session/:id/unrevert` | استعادة جميع الرسائل المتراجع عنها | يعيد `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | الرد على طلب إذن | المتن: `{ response, remember? }`، يعيد `boolean` | + +--- + +### الرسائل + +| الطريقة | المسار | الوصف | الملاحظات | +| ------- | --------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` | سرد رسائل جلسة | الاستعلام: `limit?`، يعيد `{ info: `Message`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` | إرسال رسالة والانتظار للحصول على رد | المتن: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`، يعيد `{ info: `Message`, parts: `Part[]`}` | +| `GET` | `/session/:id/message/:messageID` | الحصول على تفاصيل الرسالة | يعيد `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/prompt_async` | إرسال رسالة بشكل غير متزامن (بدون انتظار) | المتن: مثل `/session/:id/message`، يعيد `204 No Content` | +| `POST` | `/session/:id/command` | تنفيذ أمر شرطة مائلة (slash) | المتن: `{ messageID?, agent?, model?, command, arguments }`، يعيد `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/shell` | تشغيل أمر في الصدفة (shell) | المتن: `{ agent, model?, command }`، يعيد `{ info: `Message`, parts: `Part[]`}` | + +--- + +### الأوامر + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ---------- | ---------------- | --------------------------------------------- | +| `GET` | `/command` | سرد جميع الأوامر | Command[] | + +--- + +### الملفات + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ------------------------ | ----------------------------------- | --------------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | البحث عن نص داخل الملفات | مصفوفة من كائنات المطابقة تحتوي على `path` و`lines` و`line_number` و`absolute_offset` و`submatches` | +| `GET` | `/find/file?query=` | العثور على الملفات والمجلدات بالاسم | `string[]` (مسارات) | +| `GET` | `/find/symbol?query=` | العثور على رموز مساحة العمل | Symbol[] | +| `GET` | `/file?path=` | سرد الملفات والمجلدات | FileNode[] | +| `GET` | `/file/content?path=

` | قراءة ملف | FileContent | +| `GET` | `/file/status` | الحصول على حالة الملفات المتعقّبة | File[] | + +#### معلمات الاستعلام لـ `/find/file` + +- `query` (مطلوب) — سلسلة البحث (مطابقة ضبابية) +- `type` (اختياري) — حصر النتائج في `"file"` أو `"directory"` +- `directory` (اختياري) — تجاوز جذر المشروع لأجل البحث +- `limit` (اختياري) — الحد الأقصى للنتائج (1–200) +- `dirs` (اختياري) — خيار قديم (إرجاع `"false"` يعيد الملفات فقط) + +--- + +### الأدوات (تجريبية) + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ------------------------------------------- | --------------------------------- | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` | سرد جميع معرّفات الأدوات | ToolIDs | +| `GET` | `/experimental/tool?provider=

&model=` | سرد الأدوات مع مخططات JSON لنموذج | ToolList | + +--- + +### LSP والمنسّقات و MCP + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ------------ | ------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | الحصول على حالة خادم LSP | LSPStatus[] | +| `GET` | `/formatter` | الحصول على حالة المنسّقات | FormatterStatus[] | +| `GET` | `/mcp` | الحصول على حالة خادم MCP | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | إضافة خادم MCP ديناميكيا | المتن: `{ name, config }`، يعيد كائن حالة MCP | + +--- + +### الوكلاء + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | -------- | ------------------------- | ------------------------------------------- | +| `GET` | `/agent` | سرد جميع الوكلاء المتاحين | Agent[] | + +--- + +### التسجيل + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ------ | ------------------------------------------------------------- | --------- | +| `POST` | `/log` | كتابة إدخال سجل. المتن: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ----------------------- | ------------------------------------------ | ------------- | +| `POST` | `/tui/append-prompt` | إلحاق نص بالموجّه | `boolean` | +| `POST` | `/tui/open-help` | فتح مربع حوار المساعدة | `boolean` | +| `POST` | `/tui/open-sessions` | فتح محدد الجلسات | `boolean` | +| `POST` | `/tui/open-themes` | فتح محدد السمات | `boolean` | +| `POST` | `/tui/open-models` | فتح محدد النماذج | `boolean` | +| `POST` | `/tui/submit-prompt` | إرسال الموجّه الحالي | `boolean` | +| `POST` | `/tui/clear-prompt` | مسح الموجّه | `boolean` | +| `POST` | `/tui/execute-command` | تنفيذ أمر (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | عرض toast (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | الانتظار لطلب التحكم التالي | كائن طلب تحكم | +| `POST` | `/tui/control/response` | الاستجابة لطلب تحكم (`{ body }`) | `boolean` | + +--- + +### المصادقة + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ----------- | ------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | تعيين بيانات اعتماد المصادقة. يجب أن يطابق المتن مخطط المزوّد | `boolean` | + +--- + +### الأحداث + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | -------- | -------------------------------------------------------------------------------- | -------------------------- | +| `GET` | `/event` | تدفق أحداث مرسلة من الخادم (SSE). أول حدث هو `server.connected` ثم أحداث الحافلة | تدفق أحداث مرسلة من الخادم | + +--- + +### التوثيق + +| الطريقة | المسار | الوصف | الاستجابة | +| ------- | ------ | ------------------ | ------------------------------ | +| `GET` | `/doc` | مواصفة OpenAPI 3.1 | صفحة HTML تتضمن مواصفة OpenAPI | diff --git a/packages/web/src/content/docs/ar/share.mdx b/packages/web/src/content/docs/ar/share.mdx new file mode 100644 index 000000000..535d44dad --- /dev/null +++ b/packages/web/src/content/docs/ar/share.mdx @@ -0,0 +1,127 @@ +--- +title: المشاركة +description: شارك محادثات OpenCode الخاصة بك. +--- + +تتيح لك ميزة المشاركة في OpenCode إنشاء روابط عامة لمحادثات OpenCode الخاصة بك، بحيث يمكنك التعاون مع زملائك أو الحصول على المساعدة من الآخرين. + +:::note +المحادثات المشتركة متاحة للعامة لأي شخص لديه الرابط. +::: + +--- + +## كيف تعمل + +عند مشاركة محادثة، يقوم OpenCode بما يلي: + +1. ينشئ عنوان URL عاما فريدا لجلستك +2. يزامن سجل محادثتك مع خوادمنا +3. يجعل المحادثة متاحة عبر رابط قابل للمشاركة — `opncd.ai/s/` + +--- + +## المشاركة + +يدعم OpenCode ثلاثة أوضاع للمشاركة تتحكم في كيفية مشاركة المحادثات: + +--- + +### يدوي (افتراضي) + +افتراضيا، يستخدم OpenCode وضع المشاركة اليدوي. لا تتم مشاركة الجلسات تلقائيا، لكن يمكنك مشاركتها يدويا باستخدام الأمر `/share`: + +``` +/share +``` + +سيُنشئ هذا عنوان URL فريدا وسيُنسخ إلى الحافظة. + +لضبط الوضع اليدوي صراحة في [ملف الإعدادات](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### المشاركة التلقائية + +يمكنك تفعيل المشاركة التلقائية لجميع المحادثات الجديدة عبر ضبط خيار `share` إلى `"auto"` في [ملف الإعدادات](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +عند تفعيل المشاركة التلقائية، ستتم مشاركة كل محادثة جديدة تلقائيا وسيتم إنشاء رابط لها. + +--- + +### معطلة + +يمكنك تعطيل المشاركة بالكامل عبر ضبط خيار `share` إلى `"disabled"` في [ملف الإعدادات](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +لفرض ذلك على مستوى فريقك لمشروع معين، أضفه إلى ملف `opencode.json` في مشروعك ثم قم بإدراجه في Git. + +--- + +## إلغاء المشاركة + +لإيقاف مشاركة محادثة وإزالتها من الوصول العام: + +``` +/unshare +``` + +سيؤدي ذلك إلى إزالة رابط المشاركة وحذف البيانات المتعلقة بالمحادثة. + +--- + +## الخصوصية + +هناك بعض الأمور التي ينبغي وضعها في الاعتبار عند مشاركة محادثة. + +--- + +### الاحتفاظ بالبيانات + +تظل المحادثات المشتركة متاحة حتى تقوم بإلغاء مشاركتها صراحة. يشمل ذلك: + +- سجل المحادثة كاملا +- جميع الرسائل والردود +- بيانات تعريف الجلسة + +--- + +### توصيات + +- شارك فقط المحادثات التي لا تتضمن معلومات حساسة. +- راجع محتوى المحادثة قبل مشاركتها. +- ألغِ مشاركة المحادثات عند اكتمال التعاون. +- تجنب مشاركة المحادثات التي تتضمن شيفرة مملوكة أو بيانات سرية. +- للمشاريع الحساسة، عطّل المشاركة بالكامل. + +--- + +## للمؤسسات + +في عمليات النشر الخاصة بالمؤسسات، يمكن أن تكون ميزة المشاركة: + +- **معطلة** بالكامل للامتثال الأمني +- **مقيدة** على المستخدمين الموثقين عبر SSO فقط +- **مستضافة ذاتيا** على بنيتك التحتية الخاصة + +[تعرّف على المزيد](/docs/enterprise) حول استخدام OpenCode في مؤسستك. diff --git a/packages/web/src/content/docs/ar/skills.mdx b/packages/web/src/content/docs/ar/skills.mdx new file mode 100644 index 000000000..b658e7d94 --- /dev/null +++ b/packages/web/src/content/docs/ar/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "مهارات الوكيل" +description: "عرّف سلوكاً قابلاً لإعادة الاستخدام عبر تعريفات SKILL.md" +--- + +تتيح مهارات الوكيل لـ OpenCode اكتشاف تعليمات قابلة لإعادة الاستخدام من مستودعك أو من دليل المنزل. +تُحمَّل المهارات عند الطلب عبر أداة `skill` المدمجة — يرى الوكلاء المهارات المتاحة ويمكنهم تحميل المحتوى الكامل عند الحاجة. + +--- + +## وضع الملفات + +أنشئ مجلداً واحداً لكل اسم مهارة وضع بداخله ملف `SKILL.md`. +يبحث OpenCode في هذه المواقع: + +- إعدادات المشروع: `.opencode/skills//SKILL.md` +- إعدادات عامة: `~/.config/opencode/skills//SKILL.md` +- مشروع متوافق مع Claude: `.claude/skills//SKILL.md` +- عام متوافق مع Claude: `~/.claude/skills//SKILL.md` +- مشروع متوافق مع الوكلاء: `.agents/skills//SKILL.md` +- عام متوافق مع الوكلاء: `~/.agents/skills//SKILL.md` + +--- + +## فهم الاكتشاف + +بالنسبة لمسارات المشروع المحلية، يتدرج OpenCode صعوداً من دليل العمل الحالي حتى يصل إلى `git worktree`. +ويحمّل أي ملفات مطابقة لـ `skills/*/SKILL.md` داخل `.opencode/` وأي ملفات مطابقة لـ `.claude/skills/*/SKILL.md` أو `.agents/skills/*/SKILL.md` على طول الطريق. + +كما تُحمَّل التعريفات العامة أيضاً من `~/.config/opencode/skills/*/SKILL.md` و `~/.claude/skills/*/SKILL.md` و `~/.agents/skills/*/SKILL.md`. + +--- + +## كتابة بيانات `frontmatter` + +يجب أن يبدأ كل ملف `SKILL.md` بـ `frontmatter` بتنسيق YAML. +لا يتم التعرف إلا على الحقول التالية: + +- `name` (مطلوب) +- `description` (مطلوب) +- `license` (اختياري) +- `compatibility` (اختياري) +- `metadata` (اختياري، خريطة من سلسلة إلى سلسلة) + +يتم تجاهل أي حقول `frontmatter` غير معروفة. + +--- + +## التحقق من الأسماء + +يجب أن يكون `name`: + +- بطول 1–64 حرفاً +- أحرفاً وأرقاماً بحروف صغيرة مع فواصل شرطة مفردة +- لا يبدأ ولا ينتهي بـ `-` +- لا يحتوي على `--` متتالية +- يطابق اسم الدليل الذي يحتوي على `SKILL.md` + +التعبير النمطي المكافئ: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## اتباع قواعد الطول + +يجب أن يكون `description` بطول 1-1024 حرفاً. +اجعله محدداً بما يكفي كي يختار الوكيل بشكل صحيح. + +--- + +## استخدم مثالاً + +أنشئ `.opencode/skills/git-release/SKILL.md` بهذا الشكل: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## التعرّف على وصف الأداة + +يعرض OpenCode المهارات المتاحة في وصف أداة `skill`. +يتضمن كل إدخال اسم المهارة ووصفها: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +يقوم الوكيل بتحميل مهارة عبر استدعاء الأداة: + +``` +skill({ name: "git-release" }) +``` + +--- + +## تهيئة الصلاحيات + +تحكم في المهارات التي يمكن للوكلاء الوصول إليها باستخدام صلاحيات مبنية على أنماط داخل `opencode.json`: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| الصلاحية | السلوك | +| -------- | -------------------------------------- | +| `allow` | تُحمَّل المهارة فوراً | +| `deny` | تُخفى المهارة عن الوكيل ويُرفض الوصول | +| `ask` | يُطلب من المستخدم الموافقة قبل التحميل | + +تدعم الأنماط أحرف البدل: يطابق `internal-*` كلاً من `internal-docs` و `internal-tools` وغير ذلك. + +--- + +## تجاوز الإعدادات لكل وكيل + +امنح وكلاء محددين صلاحيات مختلفة عن الإعدادات الافتراضية العامة. + +**للوكلاء المخصصين** (في `frontmatter` الخاص بالوكيل): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**للوكلاء المدمجين** (في `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## تعطيل أداة skill + +عطّل المهارات بالكامل للوكلاء الذين لا ينبغي أن يستخدموها: + +**للوكلاء المخصصين**: + +```yaml +--- +tools: + skill: false +--- +``` + +**للوكلاء المدمجين**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +عند تعطيلها، يتم حذف قسم `` بالكامل. + +--- + +## استكشاف أخطاء التحميل + +إذا لم تظهر مهارة: + +1. تحقّق من أن `SKILL.md` مكتوب بأحرف كبيرة بالكامل +2. تحقّق من أن `frontmatter` تتضمن `name` و `description` +3. تأكد من أن أسماء المهارات فريدة عبر جميع المواقع +4. تحقّق من الصلاحيات — المهارات ذات `deny` تكون مخفية عن الوكلاء diff --git a/packages/web/src/content/docs/ar/themes.mdx b/packages/web/src/content/docs/ar/themes.mdx new file mode 100644 index 000000000..ffd4126ce --- /dev/null +++ b/packages/web/src/content/docs/ar/themes.mdx @@ -0,0 +1,369 @@ +--- +title: السمات +description: اختر سمة مدمجة أو عرّف سمة خاصة بك. +--- + +مع OpenCode يمكنك الاختيار من بين عدة سمات مدمجة، أو استخدام سمة تتكيّف مع سمة طرفيتك، أو تعريف سمة مخصصة خاصة بك. + +افتراضيًا، يستخدم OpenCode سمتنا `opencode`. + +--- + +## متطلبات الطرفية + +لكي تُعرض السمات بشكل صحيح مع لوحة ألوانها الكاملة، يجب أن تدعم طرفيتك **truecolor** (ألوان 24-بت). تدعم معظم الطرفيات الحديثة ذلك افتراضيًا، لكن قد تحتاج إلى تفعيله: + +- **التحقق من الدعم**: شغّل `echo $COLORTERM` - يجب أن يطبع `truecolor` أو `24bit` +- **تفعيل truecolor**: اضبط متغير البيئة `COLORTERM=truecolor` في ملف إعدادات الصدفة +- **توافق الطرفية**: تأكد من أن محاكي الطرفية يدعم ألوان 24-بت (معظم الطرفيات الحديثة مثل iTerm2 وAlacritty وKitty وWindows Terminal والإصدارات الحديثة من GNOME Terminal تدعم ذلك) + +بدون دعم truecolor، قد تظهر السمات بدقة ألوان أقل أو تعود إلى أقرب تقريب ضمن 256 لونًا. + +--- + +## السمات المدمجة + +يأتي OpenCode مع عدة سمات مدمجة. + +| الاسم | الوصف | +| ---------------------- | --------------------------------------------------------------------------- | +| `system` | يتكيّف مع لون خلفية طرفيتك | +| `tokyonight` | مبني على سمة [Tokyonight](https://github.com/folke/tokyonight.nvim) | +| `everforest` | مبني على سمة [Everforest](https://github.com/sainnhe/everforest) | +| `ayu` | مبني على السمة الداكنة [Ayu](https://github.com/ayu-theme) | +| `catppuccin` | مبني على سمة [Catppuccin](https://github.com/catppuccin) | +| `catppuccin-macchiato` | مبني على سمة [Catppuccin](https://github.com/catppuccin) | +| `gruvbox` | مبني على سمة [Gruvbox](https://github.com/morhetz/gruvbox) | +| `kanagawa` | مبني على سمة [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | +| `nord` | مبني على سمة [Nord](https://github.com/nordtheme/nord) | +| `matrix` | سمة خضراء على أسود بأسلوب الهاكر | +| `one-dark` | مبني على السمة الداكنة [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) | + +وغير ذلك؛ نضيف سمات جديدة باستمرار. + +--- + +## سمة النظام + +صُممت سمة `system` لتتكيّف تلقائيًا مع مخطط ألوان طرفيتك. وعلى عكس السمات التقليدية التي تستخدم ألوانًا ثابتة، فإن سمة _system_: + +- **توليد تدرج رمادي**: تنشئ تدرجًا رماديًا مخصصًا اعتمادًا على لون خلفية طرفيتك، بما يضمن أفضل تباين. +- **استخدام ألوان ANSI**: تستفيد من ألوان ANSI القياسية (0-15) لإبراز الصياغة وعناصر الواجهة، والتي تحترم لوحة ألوان طرفيتك. +- **الحفاظ على افتراضيات الطرفية**: تستخدم `none` لألوان النص والخلفية للحفاظ على مظهر طرفيتك الأصلي. + +سمة النظام مناسبة للمستخدمين الذين: + +- يريدون أن يطابق OpenCode مظهر طرفيتهم +- يستخدمون مخططات ألوان مخصصة للطرفية +- يفضلون مظهرًا متسقًا عبر جميع تطبيقات الطرفية + +--- + +## استخدام سمة + +يمكنك اختيار سمة بفتح منتقي السمات باستخدام الأمر `/theme`. أو يمكنك تحديدها في [الضبط](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## سمات مخصصة + +يدعم OpenCode نظام سمات مرنًا قائمًا على JSON يتيح للمستخدمين إنشاء السمات وتخصيصها بسهولة. + +--- + +### التسلسل الهرمي + +تُحمَّل السمات من عدة مجلدات بالترتيب التالي، حيث تتجاوز المجلدات اللاحقة المجلدات السابقة: + +1. **السمات المدمجة** - تكون مضمنة داخل الملف التنفيذي +2. **مجلد ضبط المستخدم** - معرّف في `~/.config/opencode/themes/*.json` أو `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **مجلد جذر المشروع** - معرّف في `/.opencode/themes/*.json` +4. **مجلد العمل الحالي** - معرّف في `./.opencode/themes/*.json` + +إذا احتوت عدة مجلدات على سمة بالاسم نفسه، فستُستخدم السمة من المجلد ذي الأولوية الأعلى. + +--- + +### إنشاء سمة + +لإنشاء سمة مخصصة، أنشئ ملف JSON في أحد مجلدات السمات. + +للسمات على مستوى المستخدم: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +وللسمات الخاصة بالمشروع: + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### تنسيق JSON + +تستخدم السمات تنسيق JSON مرنًا مع دعم لـ: + +- **ألوان سداسية عشرية**: `"#ffffff"` +- **ألوان ANSI**: `3` (0-255) +- **مراجع الألوان**: `"primary"` أو تعريفات مخصصة +- **متغيرات داكن/فاتح**: `{"dark": "#000", "light": "#fff"}` +- **بدون لون**: `"none"` - يستخدم اللون الافتراضي للطرفية أو يكون شفافًا + +--- + +### تعريفات الألوان + +قسم `defs` اختياري، ويتيح لك تعريف ألوان قابلة لإعادة الاستخدام يمكن الإشارة إليها داخل السمة. + +--- + +### افتراضيات الطرفية + +يمكن استخدام القيمة الخاصة `"none"` لأي لون لوراثة اللون الافتراضي للطرفية. هذا مفيد خصوصًا لإنشاء سمات تمتزج بسلاسة مع مخطط ألوان طرفيتك: + +- `"text": "none"` - يستخدم لون المقدمة الافتراضي للطرفية +- `"background": "none"` - يستخدم لون الخلفية الافتراضي للطرفية + +--- + +### مثال + +إليك مثالًا على سمة مخصصة: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/ar/tools.mdx b/packages/web/src/content/docs/ar/tools.mdx new file mode 100644 index 000000000..beab5bffb --- /dev/null +++ b/packages/web/src/content/docs/ar/tools.mdx @@ -0,0 +1,379 @@ +--- +title: الأدوات +description: إدارة الأدوات التي يمكن لـ LLM استخدامها. +--- + +تتيح الأدوات لـ LLM تنفيذ إجراءات داخل قاعدة الشفرة الخاصة بك. يأتي OpenCode مع مجموعة من الأدوات المدمجة، لكن يمكنك توسيعه عبر [أدوات مخصصة](/docs/custom-tools) أو [خوادم MCP](/docs/mcp-servers). + +افتراضيا، تكون جميع الأدوات **مفعلة** ولا تحتاج إلى إذن للتشغيل. يمكنك التحكم في سلوك الأدوات عبر [الأذونات](/docs/permissions). + +--- + +## التهيئة + +استخدم الحقل `permission` للتحكم في سلوك الأدوات. يمكنك السماح أو الرفض أو طلب الموافقة لكل أداة. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +يمكنك أيضا استخدام أحرف البدل للتحكم في عدة أدوات دفعة واحدة. على سبيل المثال، لطلب الموافقة على جميع الأدوات القادمة من خادم MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[اعرف المزيد](/docs/permissions) حول تهيئة الأذونات. + +--- + +## المدمجة + +فيما يلي جميع الأدوات المدمجة المتاحة في OpenCode. + +--- + +### bash + +نفذ أوامر الصدفة (Shell) في بيئة مشروعك. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +تتيح هذه الأداة لـ LLM تشغيل أوامر الطرفية مثل `npm install` و`git status` أو أي أمر صدفة آخر. + +--- + +### edit + +عدّل الملفات الموجودة باستخدام استبدال نصي مطابق تماما. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +تجري هذه الأداة تعديلات دقيقة على الملفات عبر استبدال مقاطع نصية متطابقة. وهي الطريقة الأساسية التي يعدّل بها LLM الشفرة. + +--- + +### write + +أنشئ ملفات جديدة أو اكتب فوق الملفات الموجودة. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +استخدم هذا للسماح لـ LLM بإنشاء ملفات جديدة. سيكتب فوق الملفات الموجودة إذا كانت موجودة بالفعل. + +:::note +تُدار أداة `write` عبر إذن `edit`، والذي يشمل جميع تعديلات الملفات (`edit` و`write` و`patch` و`multiedit`). +::: + +--- + +### read + +اقرأ محتويات الملفات من قاعدة الشفرة الخاصة بك. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +تقرأ هذه الأداة الملفات وتعيد محتوياتها. وتدعم قراءة نطاقات محددة من الأسطر للملفات الكبيرة. + +--- + +### grep + +ابحث في محتوى الملفات باستخدام التعابير النمطية (Regex). + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +بحث سريع في المحتوى عبر قاعدة الشفرة الخاصة بك. يدعم صياغة Regex الكاملة وتصفية الملفات عبر أنماط المسارات. + +--- + +### glob + +اعثر على الملفات عبر مطابقة الأنماط. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +ابحث عن الملفات باستخدام أنماط glob مثل `**/*.js` أو `src/**/*.ts`. يعيد مسارات الملفات المطابقة مرتبة حسب وقت التعديل. + +--- + +### list + +اعرض قائمة بالملفات والمجلدات في مسار محدد. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +تعرض هذه الأداة محتويات المجلد. وتقبل أنماط glob لتصفية النتائج. + +--- + +### lsp (experimental) + +تفاعل مع خوادم LSP التي قمت بتهيئتها للحصول على ميزات ذكاء الشفرة مثل التعاريف والمراجع ومعلومات التحويم وتسلسل الاستدعاءات. + +:::note +هذه الأداة متاحة فقط عند ضبط `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (أو `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +تتضمن العمليات المدعومة: `goToDefinition` و`findReferences` و`hover` و`documentSymbol` و`workspaceSymbol` و`goToImplementation` و`prepareCallHierarchy` و`incomingCalls` و`outgoingCalls`. + +لتهيئة خوادم LSP المتاحة لمشروعك، راجع [خوادم LSP](/docs/lsp). + +--- + +### patch + +طبّق الرقع (Patches) على الملفات. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +تطبق هذه الأداة ملفات الرقع على قاعدة الشفرة الخاصة بك. وهي مفيدة لتطبيق الفروقات (Diffs) والرقع من مصادر متعددة. + +:::note +تُدار أداة `patch` عبر إذن `edit`، والذي يشمل جميع تعديلات الملفات (`edit` و`write` و`patch` و`multiedit`). +::: + +--- + +### skill + +حمّل [مهارة](/docs/skills) (ملف `SKILL.md`) وأعد محتواها ضمن المحادثة. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todowrite + +أدِر قوائم المهام أثناء جلسات البرمجة. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +تنشئ هذه الأداة قوائم المهام وتحدّثها لتتبع التقدم أثناء العمليات المعقدة. يستخدمها LLM لتنظيم المهام متعددة الخطوات. + +:::note +هذه الأداة معطلة للوكلاء الفرعيين افتراضيا، لكن يمكنك تفعيلها يدويا. [اعرف المزيد](/docs/agents/#permissions) +::: + +--- + +### todoread + +اقرأ قوائم المهام الموجودة. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +تقرأ هذه الأداة الحالة الحالية لقائمة المهام. يستخدمها LLM لتتبع المهام المعلقة أو المكتملة. + +:::note +هذه الأداة معطلة للوكلاء الفرعيين افتراضيا، لكن يمكنك تفعيلها يدويا. [اعرف المزيد](/docs/agents/#permissions) +::: + +--- + +### webfetch + +اجلب محتوى الويب. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +تتيح هذه الأداة لـ LLM جلب صفحات الويب وقراءتها. وهي مفيدة للبحث عن التوثيق أو لاستكشاف موارد عبر الإنترنت. + +--- + +### websearch + +ابحث في الويب عن معلومات. + +:::note +هذه الأداة متاحة فقط عند استخدام مزود OpenCode أو عند ضبط متغير البيئة `OPENCODE_ENABLE_EXA` على أي قيمة منطقية صحيحة (مثل `true` أو `1`). + +للتفعيل عند تشغيل OpenCode: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +تجري عمليات بحث على الويب باستخدام Exa AI للعثور على معلومات ذات صلة عبر الإنترنت. وهي مفيدة للبحث في المواضيع، والعثور على أحداث جارية، أو جمع معلومات تتجاوز حد بيانات التدريب. + +لا يلزم مفتاح API - إذ تتصل الأداة مباشرة بخدمة MCP المستضافة لدى Exa AI دون مصادقة. + +:::tip +استخدم `websearch` عندما تحتاج إلى العثور على معلومات (Discovery)، واستخدم `webfetch` عندما تحتاج إلى جلب محتوى من رابط محدد (Retrieval). +::: + +--- + +### question + +اطرح على المستخدم أسئلة أثناء التنفيذ. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +تتيح هذه الأداة لـ LLM طرح أسئلة على المستخدم أثناء المهمة. وهي مفيدة من أجل: + +- جمع تفضيلات المستخدم أو متطلباته +- توضيح التعليمات غير الواضحة +- الحصول على قرارات حول خيارات التنفيذ +- تقديم خيارات حول الاتجاه الذي يجب اتباعه + +يتضمن كل سؤال عنوانا ونص السؤال وقائمة بالخيارات. يمكن للمستخدمين الاختيار من الخيارات المتاحة أو كتابة إجابة مخصصة. وعند وجود عدة أسئلة، يمكن للمستخدمين التنقل بينها قبل إرسال جميع الإجابات. + +--- + +## أدوات مخصصة + +تتيح لك الأدوات المخصصة تعريف دوالك الخاصة التي يمكن لـ LLM استدعاؤها. تُعرّف هذه الأدوات في ملف التهيئة ويمكنها تنفيذ شفرة عشوائية. + +[اعرف المزيد](/docs/custom-tools) حول إنشاء أدوات مخصصة. + +--- + +## خوادم MCP + +تتيح لك خوادم MCP (Model Context Protocol) دمج أدوات وخدمات خارجية. يشمل ذلك الوصول إلى قواعد البيانات وتكاملات API وخدمات الجهات الخارجية. + +[اعرف المزيد](/docs/mcp-servers) حول تهيئة خوادم MCP. + +--- + +## التفاصيل الداخلية + +داخليا، تستخدم أدوات مثل `grep` و`glob` و`list` أداة [ripgrep](https://github.com/BurntSushi/ripgrep) في الخلفية. افتراضيا، يحترم ripgrep أنماط `.gitignore`، ما يعني أن الملفات والمجلدات المدرجة في `.gitignore` ستُستبعد من عمليات البحث وعرض القوائم. + +--- + +### Ignore patterns + +لتضمين ملفات يتم تجاهلها عادة، أنشئ ملف `.ignore` في جذر المشروع. يمكن لهذا الملف السماح صراحة بمسارات محددة. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +على سبيل المثال، يسمح ملف `.ignore` هذا لـ ripgrep بالبحث داخل مجلدات `node_modules/` و`dist/` و`build/` حتى لو كانت مدرجة في `.gitignore`. diff --git a/packages/web/src/content/docs/ar/troubleshooting.mdx b/packages/web/src/content/docs/ar/troubleshooting.mdx new file mode 100644 index 000000000..1ee7cbfbd --- /dev/null +++ b/packages/web/src/content/docs/ar/troubleshooting.mdx @@ -0,0 +1,299 @@ +--- +title: استكشاف الأخطاء وإصلاحها +description: المشكلات الشائعة وكيفية حلها. +--- + +لاستكشاف المشكلات في OpenCode وإصلاحها، ابدأ بالتحقق من السجلات والبيانات المحلية التي يخزنها على القرص. + +--- + +## السجلات + +يتم حفظ ملفات السجل في: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: اضغط `WIN+R` والصق `%USERPROFILE%\.local\share\opencode\log` + +تتم تسمية ملفات السجل بطوابع زمنية (مثل `2025-01-09T123456.log`) ويتم الاحتفاظ بأحدث 10 ملفات سجل. + +يمكنك ضبط مستوى السجل باستخدام خيار سطر الأوامر `--log-level` للحصول على معلومات تصحيح أكثر تفصيلا. على سبيل المثال: `opencode --log-level DEBUG`. + +--- + +## التخزين + +يخزن opencode بيانات الجلسات وبيانات التطبيق الأخرى على القرص في: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: اضغط `WIN+R` والصق `%USERPROFILE%\.local\share\opencode` + +يحتوي هذا الدليل على: + +- `auth.json` - بيانات المصادقة مثل مفاتيح API ورموز OAuth +- `log/` - سجلات التطبيق +- `project/` - بيانات خاصة بالمشروع مثل بيانات الجلسة والرسائل + - إذا كان المشروع داخل مستودع Git، فسيتم تخزينه في `.//storage/` + - إذا لم يكن داخل مستودع Git، فسيتم تخزينه في `./global/storage/` + +--- + +## تطبيق سطح المكتب + +يشغل OpenCode Desktop خادما محليا لـ OpenCode (العملية الجانبية `opencode-cli`) في الخلفية. معظم المشكلات سببها إضافة لا تعمل بشكل صحيح، أو ذاكرة تخزين مؤقت تالفة، أو إعداد خادم غير صحيح. + +### فحوصات سريعة + +- أغلق التطبيق تماما ثم أعد تشغيله. +- إذا عرض التطبيق شاشة خطأ، انقر **Restart** وانسخ تفاصيل الخطأ. +- على macOS فقط: قائمة `OpenCode` -> **Reload Webview** (يفيد إذا كانت الواجهة فارغة/متجمدة). + +--- + +### تعطيل الإضافات + +إذا كان تطبيق سطح المكتب يتعطل عند التشغيل، أو يتوقف عن الاستجابة، أو يتصرف بشكل غريب، فابدأ بتعطيل الإضافات. + +#### تحقق من الإعدادات العامة + +افتح ملف الإعدادات العام وابحث عن المفتاح `plugin`. + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (أو `~/.config/opencode/opencode.json`) +- **macOS/Linux** (عمليات تثبيت أقدم): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: اضغط `WIN+R` والصق `%USERPROFILE%\.config\opencode\opencode.jsonc` + +إذا كانت لديك إضافات مضبوطة، فقم بتعطيلها مؤقتا بإزالة المفتاح أو ضبطه على مصفوفة فارغة: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### تحقق من أدلة الإضافات + +يمكن لـ OpenCode أيضا تحميل إضافات محلية من القرص. انقلها مؤقتا إلى مكان آخر (أو أعد تسمية المجلد) ثم أعد تشغيل تطبيق سطح المكتب: + +- **إضافات عامة** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: اضغط `WIN+R` والصق `%USERPROFILE%\.config\opencode\plugins` +- **إضافات المشروع** (فقط إذا كنت تستخدم إعدادات لكل مشروع) + - `/.opencode/plugins/` + +إذا عاد التطبيق للعمل، فأعد تفعيل الإضافات واحدة تلو الأخرى لمعرفة أيها يسبب المشكلة. + +--- + +### مسح ذاكرة التخزين المؤقت + +إذا لم يساعد تعطيل الإضافات (أو كانت عملية تثبيت إضافة عالقة)، فامسح ذاكرة التخزين المؤقت حتى يتمكن OpenCode من إعادة بنائها. + +1. أغلق OpenCode Desktop تماما. +2. احذف دليل ذاكرة التخزين المؤقت: + +- **macOS**: Finder -> `Cmd+Shift+G` -> الصق `~/.cache/opencode` +- **Linux**: احذف `~/.cache/opencode` (أو شغّل `rm -rf ~/.cache/opencode`) +- **Windows**: اضغط `WIN+R` والصق `%USERPROFILE%\.cache\opencode` + +3. أعد تشغيل OpenCode Desktop. + +--- + +### إصلاح مشكلات اتصال الخادم + +يمكن لـ OpenCode Desktop إما تشغيل خادمه المحلي (افتراضيا) أو الاتصال بعنوان URL لخادم قمت بتهيئته. + +إذا ظهرت نافذة **"Connection Failed"** (أو لم يتجاوز التطبيق شاشة البداية)، فتحقق مما إذا كان هناك عنوان URL مخصص للخادم. + +#### مسح عنوان URL الافتراضي لخادم سطح المكتب + +من شاشة Home، انقر اسم الخادم (مع نقطة الحالة) لفتح محدد الخوادم. في قسم **Default server**، انقر **Clear**. + +#### إزالة `server.port` / `server.hostname` من الإعدادات + +إذا كان `opencode.json(c)` يحتوي على قسم `server`، فأزله مؤقتا ثم أعد تشغيل تطبيق سطح المكتب. + +#### تحقق من متغيرات البيئة + +إذا كان `OPENCODE_PORT` مضبوطا في بيئتك، فسيحاول تطبيق سطح المكتب استخدام ذلك المنفذ للخادم المحلي. + +- أزل ضبط `OPENCODE_PORT` (أو اختر منفذا متاحا) ثم أعد التشغيل. + +--- + +### Linux: مشكلات Wayland / X11 + +على Linux، قد تتسبب بعض إعدادات Wayland في نوافذ فارغة أو أخطاء في مدير التركيب (compositor). + +- إذا كنت تستخدم Wayland وكانت نافذة التطبيق فارغة/يتعطل، فجرّب التشغيل مع `OC_ALLOW_WAYLAND=1`. +- إذا جعل ذلك الأمور أسوأ، فأزل هذا المتغير وجرّب التشغيل ضمن جلسة X11 بدلا من ذلك. + +--- + +### Windows: بيئة تشغيل WebView2 + +على Windows، يتطلب OpenCode Desktop وجود **WebView2 Runtime** الخاصة بـ Microsoft Edge. إذا فتح التطبيق نافذة فارغة أو لم يبدأ، فقم بتثبيت/تحديث WebView2 ثم جرّب مجددا. + +--- + +### Windows: مشكلات الأداء العامة + +إذا كنت تواجه بطءا في الأداء، أو مشكلات في الوصول إلى الملفات، أو مشكلات في الطرفية على Windows، فجرّب استخدام [WSL (نظام Windows الفرعي لـ Linux)](/docs/windows-wsl). يوفر WSL بيئة Linux تعمل بسلاسة أكبر مع ميزات OpenCode. + +--- + +### الإشعارات لا تظهر + +لا يعرض OpenCode Desktop إشعارات النظام إلا عندما: + +- تكون الإشعارات مفعلة لـ OpenCode في إعدادات نظام التشغيل، و +- تكون نافذة التطبيق غير نشطة. + +--- + +### إعادة تعيين تخزين تطبيق سطح المكتب (كحل أخير) + +إذا لم يبدأ التطبيق ولم تتمكن من مسح الإعدادات من داخل الواجهة، فأعد تعيين الحالة المحفوظة لتطبيق سطح المكتب. + +1. أغلق OpenCode Desktop. +2. اعثر على هذه الملفات واحذفها (توجد في دليل بيانات تطبيق OpenCode Desktop): + +- `opencode.settings.dat` (عنوان URL الافتراضي لخادم سطح المكتب) +- `opencode.global.dat` و `opencode.workspace.*.dat` (حالة الواجهة مثل الخوادم/المشاريع الأخيرة) + +للعثور على الدليل بسرعة: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (ثم ابحث عن أسماء الملفات أعلاه) +- **Linux**: ابحث ضمن `~/.local/share` عن أسماء الملفات أعلاه +- **Windows**: اضغط `WIN+R` -> `%APPDATA%` (ثم ابحث عن أسماء الملفات أعلاه) + +--- + +## الحصول على المساعدة + +إذا كنت تواجه مشكلات مع OpenCode: + +1. **الإبلاغ عن المشكلات على GitHub** + + أفضل طريقة للإبلاغ عن الأخطاء أو طلب الميزات هي عبر مستودعنا على GitHub: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + قبل إنشاء مشكلة جديدة، ابحث في المشكلات الموجودة لمعرفة ما إذا كانت مشكلتك قد تم الإبلاغ عنها بالفعل. + +2. **انضم إلى Discord** + + للحصول على مساعدة فورية ونقاشات المجتمع، انضم إلى خادم Discord الخاص بنا: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## مشكلات شائعة + +فيما يلي بعض المشكلات الشائعة وكيفية حلها. + +--- + +### OpenCode لا يبدأ + +1. تحقق من السجلات بحثا عن رسائل الخطأ +2. جرّب التشغيل مع `--print-logs` لرؤية المخرجات في الطرفية +3. تأكد من أنك تستخدم أحدث إصدار عبر `opencode upgrade` + +--- + +### مشكلات المصادقة + +1. جرّب إعادة المصادقة باستخدام الأمر `/connect` في واجهة TUI +2. تحقق من أن مفاتيح API الخاصة بك صالحة +3. تأكد من أن شبكتك تسمح بالاتصال بواجهة API الخاصة بالمزوّد + +--- + +### النموذج غير متاح + +1. تحقق من أنك قمت بالمصادقة مع المزوّد +2. تأكد من أن اسم النموذج في الإعدادات صحيح +3. قد تتطلب بعض النماذج صلاحيات وصول محددة أو اشتراكات + +إذا واجهت `ProviderModelNotFoundError` فمن المرجح أنك تشير إلى نموذج بشكل غير صحيح في مكان ما. +يجب الإشارة إلى النماذج بهذه الصيغة: `/` + +أمثلة: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +لمعرفة النماذج التي لديك صلاحية الوصول إليها، شغّل `opencode models` + +--- + +### ProviderInitError + +إذا واجهت ProviderInitError، فمن المحتمل أن إعداداتك غير صالحة أو تالفة. + +لحل ذلك: + +1. أولا، تحقق من أن المزوّد مضبوط بشكل صحيح باتباع [دليل المزوّدين](/docs/providers) +2. إذا استمرت المشكلة، فجرّب مسح الإعدادات المخزنة لديك: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + على Windows، اضغط `WIN+R` واحذف: `%USERPROFILE%\.local\share\opencode` + +3. أعد المصادقة مع المزوّد باستخدام الأمر `/connect` في واجهة TUI. + +--- + +### AI_APICallError ومشكلات حزم المزوّد + +إذا واجهت أخطاء في استدعاءات API، فقد يكون السبب حزم مزوّد قديمة. يقوم opencode بتثبيت حزم المزوّد (OpenAI و Anthropic و Google وغير ذلك) ديناميكيا عند الحاجة ويقوم بتخزينها مؤقتا محليا. + +لحل مشكلات حزم المزوّد: + +1. امسح ذاكرة التخزين المؤقت لحزم المزوّد: + + ```bash + rm -rf ~/.cache/opencode + ``` + + على Windows، اضغط `WIN+R` واحذف: `%USERPROFILE%\.cache\opencode` + +2. أعد تشغيل opencode لإعادة تثبيت أحدث حزم المزوّد + +سيجبر ذلك opencode على تنزيل أحدث إصدارات حزم المزوّد، وهو ما يحل غالبا مشكلات التوافق مع معاملات النماذج وتغييرات API. + +--- + +### النسخ/اللصق لا يعمل على Linux + +يحتاج مستخدمو Linux إلى تثبيت إحدى أدوات الحافظة التالية حتى تعمل ميزة النسخ/اللصق: + +**لأنظمة X11:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**لأنظمة Wayland:** + +```bash +apt install -y wl-clipboard +``` + +**للبيئات بدون واجهة رسومية (Headless):** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +سيكتشف opencode ما إذا كنت تستخدم Wayland ويفضل `wl-clipboard`، وإلا فسيحاول العثور على أدوات الحافظة بالترتيب التالي: `xclip` ثم `xsel`. diff --git a/packages/web/src/content/docs/ar/tui.mdx b/packages/web/src/content/docs/ar/tui.mdx new file mode 100644 index 000000000..8ea206db5 --- /dev/null +++ b/packages/web/src/content/docs/ar/tui.mdx @@ -0,0 +1,386 @@ +--- +title: TUI +description: استخدام واجهة المستخدم الطرفية (TUI) في OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +يوفّر OpenCode واجهة طرفية تفاعلية (TUI) للعمل على مشاريعك باستخدام نموذج لغوي كبير. + +يؤدي تشغيل OpenCode إلى بدء واجهة TUI للدليل الحالي. + +```bash +opencode +``` + +أو يمكنك تشغيلها لدليل عمل محدد. + +```bash +opencode /path/to/project +``` + +بعد الدخول إلى واجهة TUI، يمكنك إرسال رسالة كطلب. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## مراجع الملفات + +يمكنك الإشارة إلى الملفات في رسائلك باستخدام `@`. يُجري ذلك بحثا ضبابيا عن الملفات ضمن دليل العمل الحالي. + +:::tip +يمكنك أيضا استخدام `@` للإشارة إلى الملفات في رسائلك. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +تُضاف محتويات الملف إلى المحادثة تلقائيا. + +--- + +## أوامر Bash + +ابدأ الرسالة بـ `!` لتشغيل أمر في الصدفة. + +```bash frame="none" +!ls -la +``` + +يُضاف خرج الأمر إلى المحادثة كنتيجة أداة. + +--- + +## الأوامر + +عند استخدام واجهة OpenCode الطرفية، يمكنك كتابة `/` متبوعة باسم أمر لتنفيذ الإجراءات بسرعة. مثلا: + +```bash frame="none" +/help +``` + +تملك معظم الأوامر أيضا اختصارا باستخدام `ctrl+x` كمفتاح قائد، حيث إن `ctrl+x` هو المفتاح القائد الافتراضي. [اعرف المزيد](/docs/keybinds). + +فيما يلي جميع أوامر الشرطة المائلة المتاحة: + +--- + +### connect + +أضف موفّرا إلى OpenCode. يتيح لك اختيار أحد الموفّرين المتاحين وإضافة مفاتيح API الخاصة بهم. + +```bash frame="none" +/connect +``` + +--- + +### compact + +قم بضغط الجلسة الحالية. _الاسم المستعار_: `/summarize` + +```bash frame="none" +/compact +``` + +**اختصار لوحة المفاتيح:** `ctrl+x c` + +--- + +### details + +بدّل عرض تفاصيل تنفيذ الأدوات. + +```bash frame="none" +/details +``` + +**اختصار لوحة المفاتيح:** `ctrl+x d` + +--- + +### editor + +افتح محررا خارجيا لكتابة الرسائل. يستخدم المحرر المحدد في متغير البيئة `EDITOR`. [اعرف المزيد](#editor-setup). + +```bash frame="none" +/editor +``` + +**اختصار لوحة المفاتيح:** `ctrl+x e` + +--- + +### exit + +اخرج من OpenCode. _الأسماء المستعارة_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**اختصار لوحة المفاتيح:** `ctrl+x q` + +--- + +### export + +صدّر المحادثة الحالية إلى Markdown وافتحها في المحرر الافتراضي لديك. يستخدم المحرر المحدد في متغير البيئة `EDITOR`. [اعرف المزيد](#editor-setup). + +```bash frame="none" +/export +``` + +**اختصار لوحة المفاتيح:** `ctrl+x x` + +--- + +### help + +اعرض مربع حوار المساعدة. + +```bash frame="none" +/help +``` + +**اختصار لوحة المفاتيح:** `ctrl+x h` + +--- + +### init + +أنشئ ملف `AGENTS.md` أو حدّثه. [اعرف المزيد](/docs/rules). + +```bash frame="none" +/init +``` + +**اختصار لوحة المفاتيح:** `ctrl+x i` + +--- + +### models + +اعرض النماذج المتاحة. + +```bash frame="none" +/models +``` + +**اختصار لوحة المفاتيح:** `ctrl+x m` + +--- + +### new + +ابدأ جلسة جديدة. _الاسم المستعار_: `/clear` + +```bash frame="none" +/new +``` + +**اختصار لوحة المفاتيح:** `ctrl+x n` + +--- + +### redo + +أعِد تنفيذ رسالة تم التراجع عنها سابقا. متاح فقط بعد استخدام `/undo`. + +:::tip +ستتم أيضا استعادة أي تغييرات على الملفات. +::: + +داخليا، يستخدم هذا Git لإدارة تغييرات الملفات. لذلك يجب أن يكون مشروعك **مستودع Git**. + +```bash frame="none" +/redo +``` + +**اختصار لوحة المفاتيح:** `ctrl+x r` + +--- + +### sessions + +اعرض الجلسات وبدّل بينها. _الأسماء المستعارة_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**اختصار لوحة المفاتيح:** `ctrl+x l` + +--- + +### share + +شارك الجلسة الحالية. [اعرف المزيد](/docs/share). + +```bash frame="none" +/share +``` + +**اختصار لوحة المفاتيح:** `ctrl+x s` + +--- + +### themes + +اعرض السمات المتاحة. + +```bash frame="none" +/theme +``` + +**اختصار لوحة المفاتيح:** `ctrl+x t` + +--- + +### thinking + +بدّل إظهار كتل التفكير/الاستدلال في المحادثة. عند تفعيله، يمكنك رؤية عملية استدلال النموذج للنماذج التي تدعم التفكير الموسّع. + +:::note +يتحكم هذا الأمر فقط فيما إذا كانت كتل التفكير **تُعرض**؛ ولا يفعّل أو يعطّل قدرات الاستدلال في النموذج. لتبديل قدرات الاستدلال فعليا، استخدم `ctrl+t` للتنقّل بين إصدارات النموذج. +::: + +```bash frame="none" +/thinking +``` + +--- + +### undo + +تراجع عن آخر رسالة في المحادثة. يزيل أحدث رسالة للمستخدم، وكل الردود اللاحقة، وأي تغييرات على الملفات. + +:::tip +سيتم أيضا التراجع عن أي تغييرات على الملفات. +::: + +داخليا، يستخدم هذا Git لإدارة تغييرات الملفات. لذلك يجب أن يكون مشروعك **مستودع Git**. + +```bash frame="none" +/undo +``` + +**اختصار لوحة المفاتيح:** `ctrl+x u` + +--- + +### unshare + +ألغِ مشاركة الجلسة الحالية. [اعرف المزيد](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## إعداد المحرر +يستخدم الأمران `/editor` و`/export` المحرر المحدد في متغير البيئة `EDITOR`. + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + + لجعل ذلك دائما، أضف هذا إلى ملف تهيئة الصدفة لديك؛ + `~/.bashrc`، `~/.zshrc`، إلخ. + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + + لجعل ذلك دائما، استخدم **System Properties** > **Environment Variables**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + + لجعل ذلك دائما، أضف هذا إلى ملف تهيئة PowerShell لديك. + + + + +تتضمن خيارات المحررات الشائعة ما يلي: + +- `code` - Visual Studio Code +- `cursor` - Cursor +- `windsurf` - Windsurf +- `nvim` - محرر Neovim +- `vim` - محرر Vim +- `nano` - محرر Nano +- `notepad` - Windows Notepad +- `subl` - Sublime Text + +:::note +تحتاج بعض المحررات مثل VS Code إلى التشغيل مع الخيار `--wait`. +::: + +تحتاج بعض المحررات إلى وسائط سطر الأوامر لتعمل بوضع الحجب. يجعل الخيار `--wait` عملية المحرر تنتظر حتى يتم إغلاقها. + +--- + +## الإعداد + +يمكنك تخصيص سلوك واجهة TUI عبر ملف إعدادات OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### الخيارات + +- `scroll_acceleration` - فعّل تسارع التمرير على نمط macOS لتمرير سلس وطبيعي. عند تفعيله، تزداد سرعة التمرير مع إيماءات التمرير السريعة وتبقى دقيقة للحركات الأبطأ. **يتقدّم هذا الإعداد على `scroll_speed` ويستبدله عند تفعيله.** +- `scroll_speed` - يتحكم في سرعة تمرير واجهة TUI عند استخدام أوامر التمرير (الحد الأدنى: `1`). القيمة الافتراضية هي `3`. **ملاحظة: يتم تجاهل هذا إذا تم ضبط `scroll_acceleration.enabled` على `true`.** + +--- + +## التخصيص + +يمكنك تخصيص جوانب مختلفة من عرض واجهة TUI باستخدام لوحة الأوامر (`ctrl+x h` أو `/help`). تبقى هذه الإعدادات محفوظة عبر عمليات إعادة التشغيل. + +--- + +#### عرض اسم المستخدم + +بدّل ما إذا كان اسم المستخدم يظهر في رسائل الدردشة. يمكنك الوصول إلى هذا عبر: + +- لوحة الأوامر: ابحث عن "username" أو "hide username" +- يُحفظ الإعداد تلقائيا وسيتم تذكره عبر جلسات واجهة TUI diff --git a/packages/web/src/content/docs/ar/web.mdx b/packages/web/src/content/docs/ar/web.mdx new file mode 100644 index 000000000..d7f887e04 --- /dev/null +++ b/packages/web/src/content/docs/ar/web.mdx @@ -0,0 +1,142 @@ +--- +title: الويب +description: استخدام OpenCode في متصفحك. +--- + +يمكن تشغيل OpenCode كتطبيق ويب داخل متصفحك، ليمنحك تجربة البرمجة القوية بالذكاء الاصطناعي نفسها دون الحاجة إلى الطرفية. + +![OpenCode Web - جلسة جديدة](../../../assets/web/web-homepage-new-session.png) + +## البدء + +ابدأ تشغيل واجهة الويب عبر تنفيذ: + +```bash +opencode web +``` + +يؤدي ذلك إلى تشغيل خادم محلي على `127.0.0.1` بمنفذ عشوائي متاح، ويفتح OpenCode تلقائيا في المتصفح الافتراضي لديك. + +:::caution +إذا لم يتم تعيين `OPENCODE_SERVER_PASSWORD` فسيكون الخادم دون حماية. هذا مناسب للاستخدام المحلي، لكنه يجب أن يكون مُعينا عند إتاحة الوصول عبر الشبكة. +::: + +:::tip[مستخدمو Windows] +لأفضل تجربة، شغّل `opencode web` من [WSL](/docs/windows-wsl) بدلا من PowerShell. يضمن ذلك وصولا صحيحا إلى نظام الملفات وتكاملا أفضل مع الطرفية. +::: + +--- + +## الإعدادات + +يمكنك ضبط خادم الويب باستخدام خيارات سطر الأوامر أو عبر [ملف الإعدادات](/docs/config). + +### المنفذ + +افتراضيا، يختار OpenCode منفذا متاحا. يمكنك تحديد منفذ: + +```bash +opencode web --port 4096 +``` + +### اسم المضيف + +افتراضيا، يرتبط الخادم بـ `127.0.0.1` (للاستخدام المحلي فقط). لجعل OpenCode متاحا على شبكتك: + +```bash +opencode web --hostname 0.0.0.0 +``` + +عند استخدام `0.0.0.0` سيعرض OpenCode كلا من عناوين الوصول المحلي وعناوين الشبكة: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### اكتشاف mDNS + +فعّل mDNS لجعل خادمك قابلا للاكتشاف على الشبكة المحلية: + +```bash +opencode web --mdns +``` + +يضبط ذلك تلقائيا اسم المضيف إلى `0.0.0.0` ويعلن عن الخادم باسم `opencode.local`. + +يمكنك تخصيص اسم نطاق mDNS لتشغيل عدة نسخ على الشبكة نفسها: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +للسماح بنطاقات إضافية عبر CORS (مفيد للواجهات الأمامية المخصصة): + +```bash +opencode web --cors https://example.com +``` + +### المصادقة + +لحماية الوصول، عيّن كلمة مرور عبر متغير البيئة `OPENCODE_SERVER_PASSWORD`: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +اسم المستخدم الافتراضي هو `opencode`، ويمكن تغييره عبر `OPENCODE_SERVER_USERNAME`. + +--- + +## استخدام واجهة الويب + +بعد التشغيل، تتيح لك واجهة الويب الوصول إلى جلسات OpenCode الخاصة بك. + +### الجلسات + +اعرض جلساتك وأدرها من الصفحة الرئيسية. يمكنك رؤية الجلسات النشطة وبدء جلسات جديدة. + +![OpenCode Web - جلسة نشطة](../../../assets/web/web-homepage-active-session.png) + +### حالة الخادم + +انقر على "See Servers" لعرض الخوادم المتصلة وحالتها. + +![OpenCode Web - See Servers (عرض الخوادم)](../../../assets/web/web-homepage-see-servers.png) + +--- + +## إرفاق طرفية + +يمكنك إرفاق واجهة طرفية (TUI) بخادم ويب قيد التشغيل: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +يتيح لك ذلك استخدام واجهة الويب والطرفية في الوقت نفسه، مع مشاركة الجلسات والحالة نفسها. + +--- + +## ملف الإعدادات + +يمكنك أيضا ضبط إعدادات الخادم داخل ملف الإعدادات `opencode.json`: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +تكون خيارات سطر الأوامر ذات أولوية أعلى من إعدادات ملف الإعدادات. diff --git a/packages/web/src/content/docs/ar/windows-wsl.mdx b/packages/web/src/content/docs/ar/windows-wsl.mdx new file mode 100644 index 000000000..171319bb2 --- /dev/null +++ b/packages/web/src/content/docs/ar/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: شغّل OpenCode على Windows باستخدام WSL لأفضل تجربة. +--- + +import { Steps } from "@astrojs/starlight/components" + +رغم أن OpenCode يمكن تشغيله مباشرة على Windows، نوصي باستخدام [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) للحصول على أفضل تجربة. يوفر WSL بيئة Linux تعمل بسلاسة مع ميزات OpenCode. + +:::tip[لماذا WSL؟] +يوفر WSL أداء أفضل لنظام الملفات، ودعمًا كاملًا للطرفية، وتوافقًا مع أدوات التطوير التي يعتمد عليها OpenCode. +::: + +--- + +## الإعداد + + + +1. **ثبّت WSL** + + إذا لم تقم بذلك بعد، [ثبّت WSL](https://learn.microsoft.com/en-us/windows/wsl/install) باستخدام دليل Microsoft الرسمي. + +2. **ثبّت OpenCode داخل WSL** + + بعد إعداد WSL، افتح طرفية WSL وثبّت OpenCode باستخدام إحدى [طرق التثبيت](/docs/). + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **استخدم OpenCode من WSL** + + انتقل إلى مجلد مشروعك (يمكنك الوصول لملفات Windows عبر `/mnt/c/` و`/mnt/d/` وغيرها) ثم شغّل OpenCode. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## تطبيق سطح المكتب + خادم WSL + +إذا كنت تفضّل تطبيق OpenCode لسطح المكتب لكن تريد تشغيل الخادم داخل WSL: + +1. **ابدأ الخادم داخل WSL** مع `--hostname 0.0.0.0` للسماح بالاتصالات الخارجية: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **اربط تطبيق سطح المكتب** على `http://localhost:4096` + +:::note +إذا لم يعمل `localhost` في إعدادك، اتصل باستخدام عنوان IP الخاص بـ WSL بدلًا منه (من داخل WSL: `hostname -I`) واستخدم `http://:4096`. +::: + +:::caution +عند استخدام `--hostname 0.0.0.0`، اضبط `OPENCODE_SERVER_PASSWORD` لحماية الخادم. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## عميل الويب + WSL + +لأفضل تجربة ويب على Windows: + +1. **شغّل `opencode web` من طرفية WSL** بدلًا من PowerShell: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **افتحه من متصفح Windows** عبر `http://localhost:` (يعرض OpenCode الرابط) + +تشغيل `opencode web` من WSL يضمن وصولًا صحيحًا لنظام الملفات وتكاملًا أفضل مع الطرفية، مع بقائه متاحًا من متصفح Windows. + +--- + +## الوصول إلى ملفات Windows + +يمكن لـ WSL الوصول إلى جميع ملفات Windows عبر مجلد `/mnt/`: + +- قرص `C:` → `/mnt/c/` +- قرص `D:` → `/mnt/d/` +- وهكذا... + +مثال: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +لأفضل سلاسة، يمكنك استنساخ/نسخ المستودع إلى نظام ملفات WSL (مثل `~/code/`) وتشغيل OpenCode من هناك. +::: + +--- + +## نصائح + +- شغّل OpenCode داخل WSL للمشاريع المخزنة على أقراص Windows حتى يكون الوصول للملفات سلسًا +- استخدم [إضافة WSL في VS Code](https://code.visualstudio.com/docs/remote/wsl) مع OpenCode لسير عمل تطوير متكامل +- إعدادات OpenCode وجلساته تُخزَّن داخل بيئة WSL في `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/ar/zen.mdx b/packages/web/src/content/docs/ar/zen.mdx new file mode 100644 index 000000000..f25b321a9 --- /dev/null +++ b/packages/web/src/content/docs/ar/zen.mdx @@ -0,0 +1,243 @@ +--- +title: Zen +description: قائمة منتقاة من النماذج يوفّرها OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen هي قائمة بالنماذج التي اختبرها فريق OpenCode وتحقّق منها. + +:::note +OpenCode Zen متاح حاليا بنسخة تجريبية. +::: + +يعمل Zen مثل أي مزوّد آخر في OpenCode. تسجّل الدخول إلى OpenCode Zen وتحصل على +مفتاح API. استخدامه **اختياري بالكامل** ولا تحتاج إليه لاستخدام OpenCode. + +--- + +## الخلفية + +توجد نماذج كثيرة جدا، لكن عددا قليلا فقط منها يعمل بشكل جيد كعوامل للبرمجة. +بالإضافة إلى ذلك، فإن معظم المزوّدين يختلفون كثيرا في طريقة الإعداد؛ لذلك قد +تحصل على أداء وجودة مختلفين بشكل كبير. + +:::tip +اختبرنا مجموعة منتقاة من النماذج والمزوّدين الذين يعملون جيدا مع OpenCode. +::: + +لذلك إذا كنت تستخدم نموذجا عبر خدمة مثل OpenRouter، فلن تكون واثقا أبدا من أنك +تحصل على أفضل نسخة من النموذج الذي تريده. + +لمعالجة ذلك، قمنا بعدة أمور: + +1. اختبرنا مجموعة منتقاة من النماذج وتحدثنا مع فرقها حول افضل طريقة لتشغيلها. +2. ثم عملنا مع عدد من المزوّدين للتأكد من تقديمها بشكل صحيح. +3. أخيرا، قمنا بقياس أداء توليفة النموذج/المزوّد وخرجنا بقائمة نوصي بها بثقة. + +OpenCode Zen هو بوابة للذكاء الاصطناعي تتيح لك الوصول إلى هذه النماذج. + +--- + +## كيف يعمل + +يعمل OpenCode Zen مثل أي مزوّد آخر في OpenCode. + +1. تسجّل الدخول إلى **OpenCode Zen**، وتضيف تفاصيل الفوترة، ثم تنسخ مفتاح API. +2. تشغّل الأمر `/connect` في واجهة TUI، وتختار OpenCode Zen، ثم تلصق مفتاح API. +3. شغّل `/models` في واجهة TUI لعرض قائمة النماذج التي نوصي بها. + +يتم احتساب الرسوم لكل طلب، ويمكنك إضافة رصيد إلى حسابك. + +--- + +## نقاط النهاية + +يمكنك أيضا الوصول إلى نماذجنا عبر نقاط نهاية API التالية. + +| النموذج | معرّف النموذج | نقطة النهاية | حزمة AI SDK | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Free | minimax-m2.1-free | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Free | glm-4.7-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Free | kimi-k2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +يستخدم [معرّف النموذج](/docs/config/#models) في إعدادات OpenCode الصيغة `opencode/`. +على سبيل المثال، بالنسبة إلى GPT 5.2 Codex ستستخدم `opencode/gpt-5.2-codex` في إعداداتك. + +--- + +### النماذج + +يمكنك جلب القائمة الكاملة بالنماذج المتاحة وبياناتها الوصفية من: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## التسعير + +ندعم نموذج الدفع حسب الاستخدام. فيما يلي الأسعار **لكل 1M tokens**. + +| النموذج | الإدخال | الإخراج | قراءة مخزنة | كتابة مخزنة | +| --------------------------------- | ------- | ------- | ----------- | ----------- | +| Big Pickle | Free | Free | Free | - | +| MiniMax M2.1 Free | Free | Free | Free | - | +| MiniMax M2.1 | $0.30 | $1.20 | $0.10 | - | +| GLM 4.7 Free | Free | Free | Free | - | +| GLM 4.7 | $0.60 | $2.20 | $0.10 | - | +| GLM 4.6 | $0.60 | $2.20 | $0.10 | - | +| Kimi K2.5 Free | Free | Free | Free | - | +| Kimi K2.5 | $0.60 | $3.00 | $0.08 | - | +| Kimi K2 Thinking | $0.40 | $2.50 | - | - | +| Kimi K2 | $0.40 | $2.50 | - | - | +| Qwen3 Coder 480B | $0.45 | $1.50 | - | - | +| Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | +| Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | +| Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | +| Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | +| Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | - | +| Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | - | +| Gemini 3 Flash | $0.50 | $3.00 | $0.05 | - | +| GPT 5.2 | $1.75 | $14.00 | $0.175 | - | +| GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | - | +| GPT 5.1 | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | - | +| GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | - | +| GPT 5 | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Nano | Free | Free | Free | - | + +قد تلاحظ _Claude Haiku 3.5_ في سجل الاستخدام. هذا [نموذج منخفض التكلفة](/docs/config/#models) يُستخدم لتوليد عناوين جلساتك. + +:::note +يتم تمرير رسوم بطاقات الائتمان بالتكلفة الفعلية (4.4% + $0.30 لكل معاملة)؛ ولا نفرض أي رسوم إضافية غير ذلك. +::: + +النماذج المجانية: + +- GLM 4.7 Free متاح على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج. +- Kimi K2.5 Free متاح على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج. +- MiniMax M2.1 Free متاح على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج. +- Big Pickle نموذج خفي ومتاح مجانا على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج. + +تواصل معنا إذا كانت لديك أي أسئلة. + +--- + +### إعادة الشحن التلقائي + +إذا انخفض رصيدك عن $5، فسيقوم Zen تلقائيا بإعادة شحن $20. + +يمكنك تغيير مبلغ إعادة الشحن التلقائي. ويمكنك أيضا تعطيل إعادة الشحن التلقائي بالكامل. + +--- + +### الحدود الشهرية + +يمكنك أيضا تعيين حد شهري للاستخدام لمساحة العمل بالكامل ولكل عضو في فريقك. + +على سبيل المثال، لنفترض أنك ضبطت حد الاستخدام الشهري على $20، فلن يتجاوز Zen مبلغ $20 خلال شهر. +لكن إذا كانت إعادة الشحن التلقائي مفعّلة، فقد ينتهي الأمر بخصم أكثر من $20 إذا انخفض رصيدك عن $5. + +--- + +## الخصوصية + +تتم استضافة جميع نماذجنا في الولايات المتحدة. يلتزم مزوّدونا بسياسة عدم الاحتفاظ بالبيانات (zero-retention) ولا يستخدمون بياناتك لتدريب النماذج، مع الاستثناءات التالية: + +- Big Pickle: خلال فترة إتاحته المجانية، قد تُستخدم البيانات المجمعة لتحسين النموذج. +- GLM 4.7 Free: خلال فترة إتاحته المجانية، قد تُستخدم البيانات المجمعة لتحسين النموذج. +- Kimi K2.5 Free: خلال فترة إتاحته المجانية، قد تُستخدم البيانات المجمعة لتحسين النموذج. +- MiniMax M2.1 Free: خلال فترة إتاحته المجانية، قد تُستخدم البيانات المجمعة لتحسين النموذج. +- OpenAI APIs: يتم الاحتفاظ بالطلبات لمدة 30 يوما وفقا لـ [سياسات بيانات OpenAI](https://platform.openai.com/docs/guides/your-data). +- Anthropic APIs: يتم الاحتفاظ بالطلبات لمدة 30 يوما وفقا لـ [سياسات بيانات Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## للفرق + +يعمل Zen بشكل ممتاز للفرق أيضا. يمكنك دعوة زملاء الفريق، وتعيين الأدوار، وتنظيم +النماذج التي يستخدمها فريقك، والمزيد. + +:::note +مساحات العمل مجانية حاليا للفرق كجزء من النسخة التجريبية. +::: + +إدارة مساحة العمل مجانية حاليا للفرق كجزء من النسخة التجريبية. سنشارك المزيد من التفاصيل حول التسعير قريبا. + +--- + +### الأدوار + +يمكنك دعوة زملاء الفريق إلى مساحة عملك وتعيين الأدوار: + +- **Admin**: إدارة النماذج والأعضاء ومفاتيح API والفوترة +- **Member**: إدارة مفاتيح API الخاصة به فقط + +يمكن للمسؤولين أيضا تعيين حدود إنفاق شهرية لكل عضو للسيطرة على التكاليف. + +--- + +### صلاحيات الوصول للنماذج + +يمكن للمسؤولين تفعيل نماذج محددة لمساحة العمل أو تعطيلها. ستعيد الطلبات المرسلة إلى نموذج معطّل خطأ. + +يفيد ذلك في الحالات التي تريد فيها تعطيل استخدام نموذج يقوم بجمع البيانات. + +--- + +### استخدم مفتاحك الخاص + +يمكنك استخدام مفاتيح API الخاصة بك لدى OpenAI أو Anthropic مع الاستمرار في الوصول إلى نماذج أخرى ضمن Zen. + +عند استخدام مفاتيحك الخاصة، تتم فوترة tokens مباشرة من المزوّد وليس من Zen. + +على سبيل المثال، قد تكون لدى مؤسستك بالفعل مفاتيح لـ OpenAI أو Anthropic وتريد استخدامها بدلا من المفتاح الذي يوفّره Zen. + +--- + +## الأهداف + +أنشأنا OpenCode Zen من أجل: + +1. **قياس الأداء** لأفضل النماذج/المزوّدين لعوامل البرمجة. +2. إتاحة خيارات **عالية الجودة** دون خفض الأداء أو توجيه الطلبات إلى مزوّدين أرخص. +3. تمرير أي **انخفاض في الأسعار** عبر البيع بالتكلفة؛ بحيث تكون الزيادة الوحيدة لتغطية رسوم المعالجة. +4. عدم فرض **أي ارتباط حصري (lock-in)** عبر تمكينك من استخدامه مع أي عامل برمجة آخر، مع إتاحة استخدام أي مزوّد آخر مع OpenCode أيضا. diff --git a/packages/web/src/content/docs/bs/1-0.mdx b/packages/web/src/content/docs/bs/1-0.mdx new file mode 100644 index 000000000..d1edef004 --- /dev/null +++ b/packages/web/src/content/docs/bs/1-0.mdx @@ -0,0 +1,54 @@ +--- +title: Migracija na 1.0 +description: Šta je novo u OpenCode 1.0. +--- + +OpenCode 1.0 je potpuna revizija TUI-ja. +Prešli smo sa TUI zasnovanog na go+bubbletea koji je imao problema sa performansama i mogućnostima na interni okvir (OpenTUI) napisan u zig+solidjs. +Novi TUI radi kao stari jer se povezuje na isti opencode server. + +--- +## Upgrade +Ne biste trebali biti automatski nadograđeni na 1.0 ako trenutno koristite prethodnu +verzija. Međutim, neke starije verzije OpenCode-a uvijek uzimaju najnoviju verziju. +Za ručnu nadogradnju, pokrenite + +```bash +$ opencode upgrade 1.0.0 + +``` + +Za vraćanje na 0.x, pokrenite + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## UX promjene +Historija sesije je komprimovanija i prikazuje samo sve detalje alata za uređivanje i bash. +Dodali smo komandnu traku kroz koju prolazi skoro sve. Pritisnite ctrl+p da prikažete u bilo kom kontekstu i vidite sve što možete učiniti. +Dodatna bočna traka sesije (može se prebaciti) sa korisnim informacijama. +Uklonili smo neke funkcije za koje nismo bili sigurni da ih neko koristi. Ako nešto važno nedostaje, otvorite problem i brzo ćemo ga dodati. + +--- +## Revolucionarne promjene +### Tastature su preimenovane +- povratne_poruke -> poništite_poruke +- switch_agent -> agent_cycle +- switch_agent_reverse -> agent_cycle_reverse +- switch_mode -> agent_cycle +- switch_mode_reverse -> agent_cycle_reverse +### Linkovi za degustatore su uklonjeni +- messages_layout_toggle +- poruke_sljedeće +- messages_previous +- file_diff_toggle +- file_search +- file_close +- lista_datoteka +- app_help +- project_init +- detalji alata +- razmišljanje_blokovi \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/acp.mdx b/packages/web/src/content/docs/bs/acp.mdx new file mode 100644 index 000000000..44145a900 --- /dev/null +++ b/packages/web/src/content/docs/bs/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACP podrška +description: Koristite OpenCode u bilo kojem uređivaču kompatibilnom sa ACP. +--- + +OpenCode podržava [Agent Client Protocol](https://agentclientprotocol.com) (ACP), što vam omogućava da ga koristite direktno u kompatibilnim uređivačima i IDE-ovima. + +:::tip +Za listu uređivača i alata koji podržavaju ACP, pogledajte [ACP izvještaj o napretku](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP je otvoreni protokol koji standardizira komunikaciju između uređivača koda i AI coding agenata. + +--- + +## Konfiguriši + +Da biste koristili OpenCode putem ACP-a, konfigurirajte svoj uređivač da pokrene naredbu `opencode acp`. + +Naredba pokreće OpenCode kao ACP-kompatibilan podproces koji komunicira sa vašim uređivačem preko JSON-RPC-a kroz stdio. + +Ispod su primjeri za popularne uređivače koji podržavaju ACP. + +--- + +### Zed + +Dodajte u svoju [Zed](https://zed.dev) konfiguraciju (`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +Da biste ga otvorili, koristite akciju `agent: new thread` u **Command Palette**. + +Također možete vezati prečicu na tastaturi uređivanjem vašeg `keymap.json`: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### JetBrains IDE-ovi + +Dodajte u svoj [JetBrains IDE](https://www.jetbrains.com/) `acp.json` prema [dokumentaciji](https://www.jetbrains.com/help/ai-assistant/acp.html): + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +Da biste ga otvorili, koristite novog "OpenCode" agenta u AI Chat agent selektoru. + +--- + +### Avante.nvim + +Dodajte u svoju [Avante.nvim](https://github.com/yetone/avante.nvim) konfiguraciju: + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +Ako trebate proslijediti varijable okruženja: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +Da koristite OpenCode kao ACP agenta u [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim), dodajte sljedeće u svoju Neovim konfiguraciju: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +Ova konfiguracija postavlja CodeCompanion da koristi OpenCode kao ACP chat agenta. + +Ako trebate proslijediti varijable okruženja (kao što je `OPENCODE_API_KEY`), pogledajte [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) u dokumentaciji CodeCompanion.nvim. + +## Podrška + +OpenCode radi isto kroz ACP kao i u terminalu. Podržane su sve funkcije: + +:::note +Neke ugrađene komande kao što su `/undo` i `/redo` trenutno nisu podržane. +::: + +- Ugrađeni alati (operacije sa datotekama, naredbe terminala, itd.) +- Prilagođeni alati i komande kosih crta +- MCP serveri konfigurisani u vašoj OpenCode konfiguraciji +- Pravila specifična za projekat `AGENTS.md` +- Prilagođeni formateri i linteri +- Agenti i sistem dozvola diff --git a/packages/web/src/content/docs/bs/agents.mdx b/packages/web/src/content/docs/bs/agents.mdx new file mode 100644 index 000000000..ea5d5621b --- /dev/null +++ b/packages/web/src/content/docs/bs/agents.mdx @@ -0,0 +1,651 @@ +--- +title: Agenti +description: Konfigurirajte i koristite specijalizirane agente. +--- + +Agenti su specijalizirani AI asistenti koji se mogu konfigurirati za specifične zadatke i tokove posla. Oni vam omogućavaju da kreirate fokusirane alate sa prilagođenim upitima, modelima i pristupom alatima. +:::tip +Koristite agenta plana za analizu koda i pregled prijedloga bez ikakvih promjena koda. +::: +Možete se prebacivati ​​između agenata tokom sesije ili ih pozvati spominjanjem `@`. + +--- +## Vrsta +Postoje dvije vrste agenata u OpenCode-u; primarni agensi i subagensi. + +--- +### Primarni agenti +Primarni agenti su glavni pomoćnici s kojima direktno komunicirate. Možete se kretati kroz njih pomoću tipke **Tab** ili vašeg konfigurisanog povezivanja tipki `switch_agent`. Ovi agenti vode vaš glavni razgovor. Pristup alatima se konfiguriše putem dozvola — na primjer, Build ima omogućene sve alate dok je Plan ograničen. +::: tip +Možete koristiti tipku **Tab** za prebacivanje između primarnih agenata tokom sesije. +::: +OpenCode dolazi sa dva ugrađena primarna agenta, **Build** i **Plan**. Hoćemo +pogledajte ove u nastavku. + +--- +### Subagent +Subagenti su specijalizovani pomoćnici koje primarni agenti mogu pozvati za određene zadatke. Možete ih i ručno pozvati **@ spominjanjem** u svojim porukama. +OpenCode dolazi sa dva ugrađena subagenta, **General** i **Explore**. Ovo ćemo pogledati u nastavku. + +--- +## Embedded +OpenCode dolazi sa dva ugrađena primarna agenta i dva ugrađena subagenta. + +--- +### Koristi build +_Način_: `primary` +Build je **podrazumevani** primarni agent sa svim omogućenim alatima. Ovo je standardni agent za razvojni rad gdje vam je potreban pun pristup operacijama datoteka i sistemskim komandama. + +--- +### Koristite plan +_Način_: `primary` +Konačan agent dizajniran za planiranje i analizu. Koristimo sistem dozvola kako bismo vam pružili veću kontrolu i spriječili neželjene promjene. +Prema zadanim postavkama, sve sljedeće je postavljeno na `ask`: +- `file edits`: Sva upisivanja, zakrpe i uređivanja +- `bash`: Sve bash komande +Ovaj agent je koristan kada želite da LLM analizira kod, predloži promjene ili kreira planove bez stvarnih modifikacija vaše baze koda. + +--- +### Upotreba općenito +_Način_: `subagent` +Agent opće namjene za istraživanje složenih pitanja i izvršavanje zadataka u više koraka. Ima potpuni pristup alatima (osim zadataka), tako da može mijenjati fajl kada je to potrebno. Koristite ovo za paralelno pokretanje više jedinica rada. + +--- +### Koristite explore +_Način_: `subagent` +Brzi agent samo za čitanje za istraživanje kodnih baza. Nije moguće mijenjati fajlove. Koristite ovo kada trebate brzo pronaći datoteke po uzorku, pretražiti kod za ključne riječi ili odgovoriti na pitanja o bazi kodova. + +--- +### Koristite zbijanje +_Način_: `primary` +Skriveni sistemski agent koji sažima dugi kontekst u manji sažetak. Pokreće se automatski kada je potrebno i ne može se odabrati u korisničkom interfejsu. + +--- +### Koristite naslov +_Način_: `primary` +Skriveni sistemski agent koji generiše kratke naslove sesija. Pokreće se automatski i ne može se odabrati u korisničkom interfejsu. + +--- +### Koristi sažetak +_Način_: `primary` +Skriveni sistemski agent koji kreira sažetke sesije. Pokreće se automatski i ne može se odabrati u korisničkom interfejsu. + +--- +## Upotreba +1. Za primarne agente, koristite taster **Tab** za kretanje kroz njih tokom sesije. Također možete koristiti svoju konfiguriranu vezu tipke `switch_agent`. +2. Subagenti se mogu pozvati: +- **Automatski** od strane primarnih agenata za specijalizovane zadatke na osnovu njihovih opisa. +- Ručno **@ spominjanjem** subagenta u vašoj poruci. Na primjer. + +```txt frame="none" + @general help me search for this function + +``` + +3. **Navigacija između sesija**: Kada subagenti kreiraju vlastite podređene sesije, možete se kretati između roditeljske sesije i svih podređenih sesija koristeći: +- **\+Desno** (ili vaša konfigurirana `session_child_cycle` veza) za petlju naprijed kroz roditelj → dijete1 → dijete2 → ... → roditelj +- **\+Levo** (ili vaše konfigurirano povezivanje tipki `session_child_cycle_reverse`) za kretanje unazad kroz roditelj ← dijete1 ← dijete2 ← ... ← roditelj +Ovo vam omogućava neprimetno prebacivanje između glavnog razgovora i rada specijalizovanog podagenta. + +--- + +## Konfiguriši +Možete prilagoditi ugrađene agente ili kreirati vlastite kroz konfiguraciju. Agenti se mogu konfigurisati na dva načina: + +--- + +### JSON +Konfigurirajte agente u svom konfiguracijskom fajlu `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Markdown +Također možete definirati agente koristeći mardown datoteke. Stavite ih u: +- Globalno: `~/.config/opencode/agents/` +- Po projektu: `.opencode/agents/ + +````markdown title="~/.config/opencode/agents/review.md" + +--- +opis: Recenzira kod za kvalitet i najbolje prakse +način rada: subagent +model: anthropic/claude-sonnet-4-20250514 +temperatura: 0.1 +alati: + napisati: netačno + edit: false + bash: lažno + +--- + +Nalazite se u načinu pregleda koda. Fokusirajte se na: +- Kvalitet koda i najbolje prakse +- Potencijalne greške i rubni slučajevi +- Implikacije na performanse +- Sigurnosna pitanja +Dajte konstruktivne povratne informacije bez direktnih promjena. + +``` + +Ime marginalne datoteke postaje ime agenta. Na primjer, `review.md` kreira `review` agenta. + +--- + +## Opcije +Pogledajmo ove opcije konfiguracije detaljno. + +--- + +### Opis +Koristite opciju `description` da pružite kratak opis onoga što agent radi i kada ga koristiti. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +Ovo je **obavezna** opcija konfiguracije. + +--- +### Temperatura +Kontrolišite slučajnost i kreativnost odgovora LLM-a pomoću `temperature` konfiguracije. +Niže vrijednosti čine odgovore fokusiranijim i determinističkim, dok više vrijednosti povećavaju kreativnost i varijabilnost. + +```json title="opencode.json" +{ +"agent": { + "plan": { + "temperatura": 0,1 }, +"kreativno": { + "temperatura": 0,8 } + } +} +``` + +Vrijednosti temperature se obično kreću od 0,0 do 1,0: +- **0,0-0,2**: Vrlo fokusirani i deterministički odgovori, idealni za analizu i planiranje koda +- **0,3-0,5**: Uravnoteženi odgovori sa malo kreativnosti, dobro za opšte razvojne zadatke +- **0,6-1,0**: kreativniji i raznovrsniji odgovori, korisni za razmišljanje i istraživanje + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Ako temperatura nije navedena, OpenCode koristi standardne postavke specifične za model; obično 0 za većinu modela, 0,55 za Qwen modele. + +--- +### Maks. stepenice +Kontrolirajte maksimalni broj iteracija agenta koje agent može izvesti prije nego što bude prisiljen da odgovori samo tekstom. Ovo omogućava korisnicima koji žele kontrolirati troškove da postave ograničenje na akcije agenta. +Ako ovo nije postavljeno, agent će nastaviti iterirati sve dok model ne odluči da se zaustavi ili korisnik ne prekine sesiju. + +```json title="opencode.json" +{ +"agent": { + "brzo mislilac": { + "opis": "Brzo razmišljanje s ograničenim iteracijama", + "prompt": "Vi brzo mislite. Riješite probleme minimalnim koracima.", + "koraci": 5 } + } +} +``` + +Kada se dostigne ograničenje, agent prima poseban sistemski prompt koji ga upućuje da odgovori sa rezimeom svog rada i preporučenim preostalim zadacima. +:::oprez +Naslijeđeno polje `maxSteps` je zastarjelo. Umjesto toga koristite `steps`. +::: + +--- + +### Onemogući +Postavite na `true` da onemogućite agenta. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Prompt +Navedite prilagođenu sistemsku prompt datoteku za ovog agenta sa `prompt` konfiguracijom. Datoteka s promptom treba da sadrži upute specifične za svrhu agenta. + +```json title="opencode.json" +{ +"agent": { + "recenzija": { + "prompt": "{file:./prompts/code-review.txt}" } + } +} +``` + +Ova putanja je relativna u odnosu na mjesto gdje se nalazi konfiguracijski fajl. Dakle, ovo radi i za globalnu OpenCode konfiguraciju i za konfiguraciju specifične za projekat. + +--- + +### Model +Koristite `model` konfiguraciju da nadjačate model za ovog agenta. Korisno za korištenje različitih modela optimiziranih za različite zadatke. Na primjer, brži model za planiranje, sposobniji model za implementaciju. +:::tip +Ako ne navedete model, primarni agenti koriste [model globalno konfiguriran](/docs/config#models) dok će podagenti koristiti model primarnog agenta koji je pozvao subagenta. +::: +```json title="opencode.json" +{ +"agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" } + } +} +``` + +ID modela u vašoj OpenCode konfiguraciji koristi format `provider/model-id`. Na primjer, ako koristite [OpenCode Zen](/docs/zen), koristili biste `opencode/gpt-5.1-codex` za GPT 5.1 Codex. + +--- + +### Uvijek +Kontrolirajte koji su alati dostupni u ovom agentu koristeći konfiguraciju `tools`. Možete omogućiti ili onemogućiti određene alate tako što ćete ih postaviti na `true` ili `false`. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::napomena +Konfiguracija specifična za agenta poništava globalnu konfiguraciju. +::: +Također možete koristiti zamjenske znakove za kontrolu više alata odjednom. Na primjer, da onemogućite sve alate sa MCP servera: + +```json title="opencode.json" +{ +"$schema": "https://opencode.ai/config.json", + "agent": { + "samo za čitanje": { + "alati": { + "mymcp_*": lažno, + "pisati": lažno, + "uredi": netačno } + } + } +} +``` + +[Saznajte više o alatima](/docs/tools). + +--- + +### Dozvole +Možete konfigurirati dozvole za upravljanje radnjama koje agent može poduzeti. Trenutno se dozvole za alate `edit`, `bash` i `webfetch` mogu konfigurirati na: +- `"ask"` — Zatražite odobrenje prije pokretanja alata +- `"allow"` — Dozvoli sve operacije bez odobrenja +- `"deny"` — Onemogućite alat + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +Možete nadjačati ove dozvole po agentu. + +```json title="opencode.json" {3-5,8-10} +{ +"$schema": "https://opencode.ai/config.json", + "dozvola": { + "edit": "odbiti" }, +"agent": { + "build": { + "dozvola": { + "uredi": "pitaj" } + } + } +} +``` + +Također možete postaviti dozvole u Markdown agentima. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +Možete postaviti dozvole za određene bash komande. + +```json title="opencode.json" {7} +{ +"$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "dozvola": { + "bash": { + "git push": "pitaj", + "grep *": "dozvoli" } + } + } + } +} +``` + +Ovo može poprimiti oblik lopte. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +Također možete koristiti zamjenski znak `*` za kontrolu dozvola za sve komande. +Budući da posljednje podudarno pravilo ima prednost, prvo postavite zamjenski znak `*`, a zatim navedena pravila. + +```json title="opencode.json" {8} +{ +"$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "dozvola": { + "bash": { + "*": "pitaj", + "git status *": "dozvoli" } + } + } + } +} +``` + +[Saznajte više o dozvolama](/docs/permissions). + +--- + +### Mode +Kontrolirajte način rada agenta koristeći konfiguraciju `mode`. Opcija `mode` se koristi da specificira kako se agent može koristiti. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +Opcija `mode` se može postaviti na `primary`, `subagent` ili `all`. Ako `mode` nije specificirano, podrazumevano je `all`. + +--- +### Skriveno +Sakrij podagenta iz `@` menija za automatsko dovršavanje sa `hidden: true`. Korisno za interne podagente koje bi drugi agenti trebali programski pozvati samo preko Task alata. + +```json title="opencode.json" +{ +"agent": { + "interni-pomoćnik": { + "mode": "subagent", + "skriveno": istina } + } +} +``` + +Ovo utiče samo na vidljivost korisnika u meniju za automatsko dovršavanje. Model i dalje može pozvati skrivene agente putem alata Zadatak ako dozvole dozvoljavaju. +:::napomena +Odnosi se samo na `mode: subagent` agente. +::: + +--- + +### Dozvole za zadatak +Kontrolirajte koje podagente agent može pozvati preko Task alata sa `permission.task`. Koristi glob uzorke za fleksibilno uparivanje. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +Kada se postavi na `deny`, subagent se u potpunosti uklanja iz opisa alata za zadatak, tako da ga model neće pokušati pozvati. +:::tip +Pravila se procjenjuju po redoslijedu i **pobjeđuje **poslednje odgovarajuće pravilo**. U gornjem primjeru, `orchestrator-planner` odgovara i `*` (odbije) i `orchestrator-*` (dozvoli), ali pošto `orchestrator-*` dolazi nakon `*`, rezultat je `allow`. +::: +:::tip +Korisnici uvijek mogu pozvati bilo kojeg subagenta direktno preko `@` menija za autodovršavanje, čak i ako bi dozvole za zadatak agenta to uskratile. +::: + +--- + +### Boja +Prilagodite vizualni izgled agenta u korisničkom sučelju s opcijom `color`. Ovo utiče na to kako se agent pojavljuje u interfejsu. +Koristite važeću heksadecimalnu boju (npr. `#FF5733`) ili boju teme: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ +"agent": { + "kreativno": { + "boja": "#ff6b6b" }, +"code-reviewer": { + "boja": "akcent" } + } +} +``` + +--- + +### Leglo P +Kontrolirajte raznolikost odgovora s opcijom `top_p`. Alternativa temperaturi za kontrolu nasumice. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +Vrijednosti se kreću od 0,0 do 1,0. Niže vrijednosti su više fokusirane, više vrijednosti raznovrsnije. + +--- +### Dodatni +Sve druge opcije koje navedete u konfiguraciji agenta će biti **direktno proslijeđene** dobavljaču kao opcije modela. Ovo vam omogućava da koristite karakteristike i parametre specifične za provajdera. +Na primjer, sa OpenAI-jevim modelima rezonovanja, možete kontrolisati napor rasuđivanja: + +```json title="opencode.json" {6,7} +{ +"agent": { + "duboki mislilac": { + "opis": "Agent koji koristi veliki napor u razmišljanju za složene probleme", + "model": "openai/gpt-5", + "reasoningEffort": "visoko", + "textVerbosity": "niska" } + } +} +``` + +Ove dodatne opcije su specifične za model i dobavljača. U dokumentaciji vašeg provajdera provjerite dostupne parametre. +:::tip +Pokrenite `opencode models` da vidite listu dostupnih modela. +::: + +--- + +## Kreirajte agente +Možete kreirati nove agente koristeći sljedeću naredbu: + +```bash +opencode agent create +``` + +Ova interaktivna komanda će: +1. Pitajte gdje da sačuvate agenta; globalno ili specifično za projekat. +2. Opis onoga što agent treba da uradi. +3. Generirajte odgovarajući sistemski prompt i identifikator. +4. Omogućite vam da odaberete kojim alatima agent može pristupiti. +5. Konačno, kreirajte markdown datoteku s konfiguracijom agenta. + +--- +## Slučajevi upotrebe +Evo nekoliko uobičajenih slučajeva upotrebe različitih agenata. +- **Build agent**: Potpuni razvojni rad sa svim omogućenim alatima +- **Agent za plan**: Analiza i planiranje bez unošenja promjena +- **Agent za pregled**: Pregled koda sa pristupom samo za čitanje plus alati za dokumentaciju +- **Agent za otklanjanje grešaka**: Fokusiran na istragu sa omogućenim bash i alatima za čitanje +- **Docs agent**: Pisanje dokumentacije sa operacijama datoteka, ali bez sistemskih naredbi + +--- +## Primjeri +Evo nekoliko primjera agenata koji bi vam mogli biti korisni. +::: momak +Imate li agenta kojeg biste željeli podijeliti? [Pošalji PR](https://github.com/anomalyco/opencode). +::: + +--- + +### Agent za dokumentaciju + +```markdown title="~/.config/opencode/agents/docs-writer.md" + +--- +opis: Piše i vodi projektnu dokumentaciju +način rada: subagent +alati: + bash: lažno + +--- + +Vi ste tehnički pisac. Kreirajte jasnu, sveobuhvatnu dokumentaciju. +Fokusirajte se na: +- Jasna objašnjenja +- Pravilna struktura +- Primjeri kodova +- Jezik prilagođen korisniku + +``` + +--- + +### Sigurnosni revizor + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/bs/cli.mdx b/packages/web/src/content/docs/bs/cli.mdx new file mode 100644 index 000000000..f151024b3 --- /dev/null +++ b/packages/web/src/content/docs/bs/cli.mdx @@ -0,0 +1,540 @@ +--- +title: CLI +description: OpenCode CLI opcije i naredbe. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode CLI po defaultu pokreće [TUI](/docs/tui) kada se pokrene bez ikakvih argumenata. + +```bash +opencode + +``` + +Ali takođe prihvata komande kao što je dokumentovano na ovoj stranici. Ovo vam omogućava programsku interakciju sa OpenCodeom. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui +Pokrenite korisnički interfejs OpenCode terminala. + +```bash +opencode [project] + +``` + +#### Zastave +| Zastava | Kratko | Opis || ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | Nastavite posljednju sesiju | +| `--session` | `-s` | ID sesije za nastavak | +| `--prompt` | | Uputstvo za upotrebu | +| `--model` | `-m` | Model za korištenje u obliku dobavljača/modela | +| `--agent` | | Agent za korištenje | +| `--port` | | Port za slušanje na | +| `--hostname` | | Slušajte ime hosta | + +--- + +## komandante +OpenCode CLI takođe ima sledeće komande. + +--- + +### agent +Upravljajte agentima za OpenCode. + +```bash +opencode agent [command] +``` + +--- + +### prilog +Priključite terminal na već pokrenut OpenCode backend server pokrenut putem `serve` ili `web` komandi. + +```bash +opencode attach [url] + +``` + +Ovo omogućava korištenje TUI-ja sa udaljenim OpenCode backend-om. na primjer: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### Zastave +| Zastava | Kratko | Opis || ----------- | ----- | --------------------------------- | +| `--dir` | | Radni direktorij za pokretanje TUI u | +| `--session` | `-s` | ID sesije za nastavak | + +--- +#### kreiraj +Kreirajte novog agenta s prilagođenom konfiguracijom. + +```bash +opencode agent create + +``` + +Ova komanda će vas voditi kroz kreiranje novog agenta sa prilagođenim sistemskim promptom i konfiguracijom alata. + +--- + +#### lista +Navedite sve dostupne agente. + +```bash +opencode agent list +``` + +--- + +### auth +Naredba za upravljanje vjerodajnicama i prijavom za provajdere. + +```bash +opencode auth [command] + +``` + +--- + +#### aplikacija +OpenCode pokreće lista provajdera na [Models.dev](https://models.dev), tako da možete koristiti `opencode auth login` da konfigurirate API ključeve za bilo kojeg provajdera kojeg želite koristiti. Ovo je pohranjeno u `~/.local/share/opencode/auth.json`. + +```bash +opencode auth login +``` + +Kada se OpenCode pokrene, učitava dobavljače iz datoteke vjerodajnica. I ako postoje neki ključevi definirani u vašim okruženjima ili `.env` fajl u vašem projektu. + +--- +#### lista +Navodi sve autentifikovane dobavljače pohranjene u datoteci akreditiva. + +```bash +opencode auth lista + +``` + +Ili kratka verzija. + +```bash +opencode auth ls +``` + +--- + +#### odjava +Odjavljuje vas s provajdera tako što ga briše iz datoteke vjerodajnica. + +```bash +opencode auth logout + +``` + +--- + +### github +Upravljajte GitHub agentom za automatizaciju spremišta. + +```bash +opencode github [command] +``` + +--- + +#### instaliraj +Instalirajte GitHub agenta u svoje spremište. + +```bash +opencode github instalacija + +``` + +Ovo postavlja neophodni tok rada GitHub Actions i vodi vas kroz proces konfiguracije. [Saznajte više](/docs/github). + +--- + +#### trči +Pokrenite GitHub agent. Ovo se obično koristi u GitHub akcijama. + +```bash +opencode github run +``` + +##### Zastave +| Zastava | Opis || --------- | -------------------------------------- | +| `--event` | GitHub lažni događaj za pokretanje agenta za | +| `--token` | GitHub token ličnog pristupa | + +--- +### mcp +Upravljajte serverima protokola konteksta modela. + +```bash +opencode mcp [command] + +``` + +--- + +#### dodaj +Dodajte MCP server svojoj konfiguraciji. + +```bash +opencode mcp add +``` + +Ova komanda će vas voditi kroz dodavanje lokalnog ili udaljenog MCP servera. + +--- +#### lista +Navedite sve konfigurirane MCP servere i njihov status veze. + +```bash +opencode mcp lista + +``` + +Ili koristite kratku verziju. + +```bash +opencode mcp ls +``` + +--- + +#### auth +Autentifikujte se sa MCP serverom koji je omogućen za OAuth. + +```bash +opencode mcp auth [name] + +``` + +Ako ne navedete ime servera, od vas će biti zatraženo da izaberete neki od dostupnih servera koji podržavaju OAuth. +Također možete navesti servere koji podržavaju OAuth i njihov status provjere autentičnosti. + +```bash +opencode mcp auth list +``` + +Ili koristite kratku verziju. + +```bash +opencode mcp auth ls + +``` + +--- + +#### odjava +Uklonite OAuth vjerodajnice za MCP server. + +```bash +opencode mcp logout [name] +``` + +--- + +#### otklanjanje grešaka +Otklanjanje grešaka OAuth veze sa MCP serverom. + +```bash +opencode mcp debug + +``` + +--- + +### model +Navedite sve dostupne modele konfiguriranih provajdera. + +```bash +opencode models [provider] +``` + +Ova naredba prikazuje sve modele dostupne kod vaših konfiguriranih provajdera u formatu `provider/model`. +Ovo je korisno za pronalaženje tačnog naziva modela za korištenje u [vašoj konfiguraciji](/docs/config/). +Opciono možete proslijediti ID provajdera za filtriranje modela po tom dobavljaču. + +```bash +opencode models anthropic + +``` + +#### Zastave +| Zastava | Opis || ----------- | ------------------------------------------------------------ | +| `--refresh` | Osvježite predmemoriju modela sa models.dev | +| `--verbose` | Koristite detaljniji izlaz modela (uključuje metapodatke poput troškova) | +Koristite `--refresh` zastavicu da ažurirate keširanu listu modela. Ovo je korisno kada su novi modeli dodani provajderu i želite da ih vidite u OpenCode-u. + +```bash +opencode models --refresh +``` + +--- + +### trči +Pokrenite opencode u neinteraktivnom modu tako što ćete direktno proslijediti prompt. + +```bash +opencode run [message..] + +``` + +Ovo je korisno za skriptiranje, automatizaciju ili kada želite brz odgovor bez pokretanja punog TUI-ja. Na primjer. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +Također možete priključiti pokrenutu `opencode serve` instancu kako biste izbjegli vrijeme hladnog pokretanja MCP servera pri svakom pokretanju: + +```bash +# Start a headless server in one terminal +opencode serve +# U drugom terminalu, pokrenite komande koje se vezuju za njega +opencode run --attach http://localhost:4096 "Objasni async/await u JavaScriptu" + +``` + +#### Zastave +| Zastava | Kratko | Opis || ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | | Naredba za pokretanje, koristite poruku za args | +| `--continue` | `-c` | Nastavite posljednju sesiju | +| `--session` | `-s` | ID sesije za nastavak | +| `--share` | | Podijelite sesiju | +| `--model` | `-m` | Model za korištenje u obliku provider/model | +| `--agent` | | Agent za korištenje | +| `--file` | `-f` | Fajlovi koje treba priložiti poruci | +| `--format` | | Format: default (formatiran) ili json (sirovi JSON događaji) | +| `--title` | | Naslov sesije (koristi skraćeni prompt ako nije navedena vrijednost) | +| `--attach` | | Priključite na pokrenuti opencode server (npr. http://localhost:4096) | +| `--port` | | Port za lokalni server (zadano na nasumični port) | + +--- + +### poslužiti +Pokrenite OpenCode server bez glave za pristup API-ju. Pogledajte [server docs](/docs/server) za kompletan HTTP interfejs. + +```bash +opencode serve +``` + +Ovo pokreće HTTP server koji pruža API pristup funkcionalnosti otvorenog koda bez TUI interfejsa. Postavite `OPENCODE_SERVER_PASSWORD` da omogućite HTTP osnovnu auth (korisničko ime je zadano na `opencode`). +#### Zastave +| Zastava | Opis || ------------ | ------------------------------------------ | +| `--port` | Port za slušanje na | +| `--hostname` | Ime hosta za slušanje | +| `--mdns` | Omogući mDNS otkrivanje | +| `--cors` | Dodatni izvor(a) pretraživača koji dozvoljavaju CORS | + +--- +### sesija +Upravljajte OpenCode sesijama. + +```bash +opencode sesija [naredba] + +``` + +--- + +#### lista +Navedite sve OpenCode sesije. + +```bash +opencode session list +``` + +##### Zastave +| Zastava | Kratko | Opis || ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` | Ograničenje na N najnovijih sesija | +| `--format` | | Izlazni format: tablica ili json (tabela) | + +--- +### statistika +Prikaži statistiku upotrebe tokena i troškova za vaše OpenCode sesije. + +```bash +opencode stats + +``` + +#### Zastave +| Zastava | Opis || ----------- | ------------------------------------------------------------------------------------- | +| `--days` | Prikaži statistiku za zadnjih N dana (sva vremena) | +| `--tools` | Broj alata za prikaz (svi) | +| `--models` | Prikaži raščlambu korištenja modela (skriveno prema zadanim postavkama). Proslijedite broj za prikaz vrha N | +| `--project` | Filtriraj po projektu (svi projekti, prazan niz: trenutni projekt) | + +--- + +### izvoz +Izvezite podatke sesije kao JSON. + +```bash +opencode export [sessionID] +``` + +Ako ne unesete ID sesije, od vas će biti zatraženo da odaberete neku od dostupnih sesija. + +--- +### uvoz +Uvezite podatke sesije iz JSON datoteke ili OpenCode dijeljenog URL-a. + +```bash +opencode import + +``` + +Možete uvesti iz lokalne datoteke ili OpenCode dijeljenog URL-a. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### web +Pokrenite OpenCode server bez glave sa web interfejsom. + +```bash +opencode web + +``` + +Ovo pokreće HTTP server i otvara web pretraživač za pristup OpenCodeu preko web interfejsa. Postavite `OPENCODE_SERVER_PASSWORD` da omogućite HTTP osnovnu auth (korisničko ime je zadano na `opencode`). +#### Zastave +| Zastava | Opis || ------------ | ------------------------------------------ | +| `--port` | Port za slušanje na | +| `--hostname` | Ime hosta za slušanje | +| `--mdns` | Omogući mDNS otkrivanje | +| `--cors` | Dodatni izvor(a) pretraživača koji dozvoljavaju CORS | + +--- + +### acp +Pokrenite ACP (Agent Client Protocol) server. + +```bash +opencode acp +``` + +Ova komanda pokreće ACP server koji komunicira preko stdin/stdout koristeći nd-JSON. +#### Zastave +| Zastava | Opis || ------------ | --------------------- | +| `--cwd` | Radni imenik | +| `--port` | Port za slušanje na | +| `--hostname` | Slušajte ime hosta | + +--- +### deinstaliraj +Deinstalirajte OpenCode i uklonite sve povezane datoteke. + +```bash +opencode uninstall + +``` + +#### Zastave +| Zastava | Kratko | Opis || --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` | Čuvajte konfiguracijske datoteke | +| `--keep-data` | `-d` | Čuvajte podatke i snimke sesije | +| `--dry-run` | | Pokažite šta bi bilo uklonjeno bez uklanjanja | +| `--force` | `-f` | Preskoči upite za potvrdu | + +--- + +### upgrade +Ažurira opencode na najnoviju verziju ili određenu verziju. + +```bash +opencode upgrade [target] +``` + +Za nadogradnju na najnoviju verziju. + +```bash +opencode upgrade + +``` + +Za nadogradnju na određenu verziju. + +```bash +opencode upgrade v0.1.48 +``` + +#### Zastave +| Zastava | Kratko | Opis || ---------- | ----- | ------------------------------------------------------------------ | +| `--method` | `-m` | Korišteni način instalacije; curl, npm, pnpm, bun, brew | + +--- +## Globalne zastave +CLI otvorenog koda uzima sljedeće globalne zastavice. +| Zastava | Kratko | Opis || -------------- | ----- | ------------------------------------ | +| `--help` | `-h` | Prikaži pomoć | +| `--version` | `-v` | Odštampaj broj verzije | +| `--print-logs` | | Ispis zapisnika u stderr | +| `--log-level` | | Nivo dnevnika (DEBUG, INFO, WARN, ERROR) | + +--- +## Varijable okruženja +OpenCode se može konfigurirati pomoću varijabli okruženja. +| Varijabilna | Vrsta | Opis || ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | boolean | Automatski dijeli sesije | +| `OPENCODE_GIT_BASH_PATH` | string | Putanja do Git Bash izvršne datoteke na Windows | +| `OPENCODE_CONFIG` | string | Put do konfiguracionog fajla | +| `OPENCODE_CONFIG_DIR` | string | Put do konfiguracijskog direktorija | +| `OPENCODE_CONFIG_CONTENT` | string | Inline json konfiguracijski sadržaj | +| `OPENCODE_DISABLE_AUTOUPDATE` | boolean | Onemogući automatske provjere ažuriranja | +| `OPENCODE_DISABLE_PRUNE` | boolean | Onemogući orezivanje starih podataka | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | boolean | Onemogući automatsko ažuriranje naslova terminala | +| `OPENCODE_PERMISSION` | string | Umetnuta json konfiguracija dozvola | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | boolean | Onemogući podrazumevane dodatke | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | boolean | Onemogući automatsko preuzimanje LSP servera | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | boolean | Omogući eksperimentalne modele | +| `OPENCODE_DISABLE_AUTOCOMPACT` | boolean | Onemogući automatsko sažimanje konteksta | +| `OPENCODE_DISABLE_CLAUDE_CODE` | boolean | Onemogući čitanje sa `.claude` (prompt + vještine) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | boolean | Onemogući čitanje `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | boolean | Onemogući učitavanje `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | boolean | Onemogući dohvaćanje modela iz udaljenih izvora | +| `OPENCODE_FAKE_VCS` | string | Lažni VCS provajder za potrebe testiranja | +| `OPENCODE_DISABLE_FILETIME_CHECK` | boolean | Onemogući provjeru vremena datoteke radi optimizacije | +| `OPENCODE_CLIENT` | string | Identifikator klijenta (zadano na `cli`) | +| `OPENCODE_ENABLE_EXA` | boolean | Omogući Exa alate za web pretraživanje | +| `OPENCODE_SERVER_PASSWORD` | string | Omogući osnovnu autorizaciju za `OPENCODE_GIT_BASH_PATH`/`OPENCODE_CONFIG` | +| `OPENCODE_SERVER_USERNAME` | string | Poništi osnovno korisničko ime autentifikacije (zadano `opencode`) | +| `OPENCODE_MODELS_URL` | string | Prilagođeni URL za dohvaćanje konfiguracije modela | + +--- +### Eksperimentalno +Ove varijable okruženja omogućavaju eksperimentalne karakteristike koje se mogu promijeniti ili ukloniti. +| Varijabilna | Vrsta | Opis || ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | boolean | Omogući sve eksperimentalne funkcije | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | boolean | Omogući otkrivanje ikona | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | boolean | Onemogući kopiranje pri odabiru u TUI | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | broj | Zadano vremensko ograničenje za bash komande u ms | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | broj | Maksimalni izlazni tokeni za LLM odgovore | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | boolean | Omogući praćenje datoteka za cijeli dir | +| `OPENCODE_EXPERIMENTAL_OXFMT` | boolean | Omogući oxfmt formatter | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | boolean | Omogući eksperimentalni LSP alat | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | boolean | Onemogući praćenje datoteka | +| `OPENCODE_EXPERIMENTAL_EXA` | boolean | Omogući eksperimentalne Exa funkcije | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | boolean | Omogući eksperimentalnu provjeru tipa LSP | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | boolean | Omogući eksperimentalne funkcije smanjenja | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | boolean | Omogući režim plana | \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/commands.mdx b/packages/web/src/content/docs/bs/commands.mdx new file mode 100644 index 000000000..8a49979f7 --- /dev/null +++ b/packages/web/src/content/docs/bs/commands.mdx @@ -0,0 +1,299 @@ +--- +title: komandant +description: Kreirajte prilagođene komande za zadatke koji se ponavljaju. +--- + +Prilagođene komande vam omogućavaju da odredite prompt koji želite da pokrenete kada se ta naredba izvrši u TUI-ju. + +```bash frame="none" +/my-command + +``` + +Prilagođene komande su dodatak ugrađenim komandama kao što su `/init`, `/undo`, `/redo`, `/share`, `/help`. [Saznajte više](/docs/tui#commands). + +--- + +## Kreirajte komandne fajlove +Kreirajte mardown fajlove u direktorijumu `commands/` da definišete prilagođene komande. +Kreiraj `.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Frontmatter definira svojstva komande. Sadržaj postaje predložak. +Koristite komandu tako što ćete upisati `/` nakon čega slijedi naziv komande. + +```bash frame="none" +"/test" + +``` + +--- + +## Konfiguriši +Možete dodati prilagođene komande kroz OpenCode konfiguraciju ili kreiranjem markdown datoteka u direktoriju `commands/`. + +--- + +### JSON +Koristite opciju `command` u svom OpenCode [config](/docs/config): + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Sada možete pokrenuti ovu naredbu u TUI: + +```bash frame="none" +/test + +``` + +--- + +### Markdown +Također možete definirati komande koristeći mardown datoteke. Stavite ih u: +- Globalno: `~/.config/opencode/commands/` +- Po projektu: `.opencode/commands/ + +````markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Ime datoteke za označavanje postaje ime naredbe. Na primjer, `test.md` dozvoljava +pokrećeš: + +```bash frame="none" +/test + +``` + +--- + +## Prompt config +Promptovi za prilagođene komande podržavaju nekoliko posebnih čuvara mjesta i sintakse. + +--- + +### Argumenti +Proslijedite argumente naredbama koristeći čuvar mjesta `$ARGUMENTS`. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +Pokrenite naredbu s argumentima: + +```bash frame="none" +/componentButton + +``` + +I `$ARGUMENTS` će biti zamijenjen sa `Button`. +Također možete pristupiti pojedinačnim argumentima koristeći pozicione parametre: +- `$1` - Prvi argument +- `$2` - Drugi argument +- `$3` - Treći argument +- I tako dalje... +na primjer: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +Pokrenite naredbu: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" + +``` + +Ovo zamjenjuje: +- `$1` do `config.json` +- `$2` do `src` +- `$3` do `{ "key": "value" }` + +--- + +### Izlaz ljuske +Koristite _!`command`_ da ubacite [bash command](/docs/tui#bash-commands) izlaz u svoj prompt. +Na primjer, da kreirate prilagođenu naredbu koja analizira pokrivenost testom: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +Ili da vidite nedavne promjene: + +```md title=".opencode/commands/review-changes.md" + +--- +opis: Pregledajte nedavne promjene + +--- + +Nedavna git urezivanja: +!`git log --oneline -10` +Pregledajte ove promjene i predložite bilo kakva poboljšanja. + +``` + +Naredbe se pokreću u korijenskom direktoriju vašeg projekta i njihov izlaz postaje dio prompta. + +--- + +### Reference fajlova +Uključite datoteke u svoju naredbu koristeći `@` nakon čega slijedi naziv datoteke. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +Sadržaj datoteke se automatski uključuje u prompt. + +--- +## Opcije +Pogledajmo detaljno opcije konfiguracije. + +--- +### Template +Opcija `template` definira prompt koji će biti poslan LLM-u kada se naredba izvrši. + +```json title="opencode.json" +{ +"komanda": { + "test": { + "template": "Pokrenite kompletan testni paket sa izvještajem o pokrivenosti i pokažite sve greške.\nFokusirajte se na neuspjele testove i predložite popravke." } + } +} +``` + +Ovo je **obavezna** opcija konfiguracije. + +--- + +### Opis +Koristite opciju `description` da pružite kratak opis onoga što naredba radi. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +Ovo se prikazuje kao opis u TUI-u kada unesete naredbu. + +--- +### Agent +Koristite `agent` konfiguraciju da opciono odredite koji [agent](/docs/agents) treba da izvrši ovu naredbu. +Ako je ovo [subagent](/docs/agents/#subagents) naredba će po defaultu pokrenuti pozivanje subagenta. +Da onemogućite ovo ponašanje, postavite `subtask` na `false`. + +```json title="opencode.json" +{ +"komanda": { + "recenzija": { + "agent": "plan" } + } +} +``` + +Ovo je **opciona** opcija konfiguracije. Ako nije navedeno, podrazumevano je vaš trenutni agent. + +--- + +### Subdatatak +Koristite `subtask` boolean da prisilite naredbu da pokrene [subagent](/docs/agents/#subagents) pozivanje. +Ovo je korisno ako želite da naredba ne zagađuje vaš primarni kontekst i da će **primorati** agenta da djeluje kao subagent, +čak i ako je `mode` postavljeno na `primary` u konfiguraciji [agent](/docs/agents). + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +Ovo je **opciona** opcija konfiguracije. + +--- +### Model +Koristite `model` konfiguraciju da nadjačate zadani model za ovu naredbu. + +```json title="opencode.json" +{ +"komanda": { + "analizirati": { + "model": "antropski/claude-3-5-sonnet-20241022" } + } +} +``` + +Ovo je **opciona** opcija konfiguracije. + +--- + +## Embedded +opencode uključuje nekoliko ugrađenih naredbi kao što su `/init`, `/undo`, `/redo`, `/share`, `/help`; [saznaj više](/docs/tui#commands). +:::napomena +Prilagođene komande mogu nadjačati ugrađene komande. +::: +Ako definirate prilagođenu naredbu s istim imenom, ona će nadjačati ugrađenu naredbu. \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/config.mdx b/packages/web/src/content/docs/bs/config.mdx new file mode 100644 index 000000000..e3d289b23 --- /dev/null +++ b/packages/web/src/content/docs/bs/config.mdx @@ -0,0 +1,657 @@ +--- +title: Config +description: Korištenje OpenCode JSON konfiguracije. +--- + +Možete konfigurirati OpenCode koristeći JSON konfiguracijski fajl. + +--- + +## Format + +OpenCode podržava i **JSON** i **JSONC** (JSON sa komentarima) formate. + +```jsonc title="opencode.jsonc" +{ +"$schema": "https://opencode.ai/config.json", + // Konfiguracija teme + "tema": "otvoreni kod", + "model": "antropski/claude-sonnet-4-5", + "automatsko ažuriranje": istina,} +``` + +--- + +## Lokacije + +Možete postaviti svoju konfiguraciju na nekoliko različitih lokacija i one imaju a +drugačiji redosled prioriteta. +:::napomena +Konfiguracijski fajlovi su **spojeni zajedno**, a ne zamijenjeni. +::: +Konfiguracijski fajlovi se spajaju, ne zamjenjuju. Kombiniraju se postavke sa sljedećih konfiguracijskih lokacija. Kasnije konfiguracije poništavaju prethodne samo za konfliktne ključeve. Nekonfliktne postavke iz svih konfiguracija su sačuvane. +Na primjer, ako vaša globalna konfiguracija postavlja `theme: "opencode"` i `autoupdate: true`, a vaša projektna konfiguracija postavlja `model: "anthropic/claude-sonnet-4-5"`, konačna konfiguracija će uključivati ​​sve tri postavke. + +--- + +### Redoslijed prioriteta + +Izvori konfiguracije se učitavaju ovim redoslijedom (kasniji izvori poništavaju ranije): + +1. **Udaljena konfiguracija** (od `.well-known/opencode`) - organizacione postavke +2. **Globalna konfiguracija** (`~/.config/opencode/opencode.json`) - korisničke postavke +3. **Prilagođena konfiguracija** (`OPENCODE_CONFIG` env var) - prilagođena zaobilaženja +4. **Konfiguracija projekta** (`opencode.json` u projektu) - postavke specifične za projekat +5. **`.opencode` direktoriji** - agenti, komande, dodaci +6. **Inline config** (`OPENCODE_CONFIG_CONTENT` env var) - runtime nadjačava + To znači da konfiguracije projekta mogu nadjačati globalne zadane postavke, a globalne konfiguracije mogu nadjačati postavke udaljene organizacije. + :::napomena + Direktoriji `.opencode` i `~/.config/opencode` koriste **imena u množini** za poddirektorije: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/` i `themes/`. Pojedinačna imena (npr. `agent/`) su također podržana za kompatibilnost unatrag. + ::: + +--- + +### Daljinski + +Organizacije mogu pružiti zadanu konfiguraciju preko `.well-known/opencode` krajnje točke. Ovo se automatski preuzima kada se autentifikujete kod provajdera koji to podržava. +Prvo se učitava udaljena konfiguracija koja služi kao osnovni sloj. Svi ostali izvori konfiguracije (globalni, projektni) mogu nadjačati ove zadane postavke. +Na primjer, ako vaša organizacija nudi MCP servere koji su po defaultu onemogućeni: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +Možete omogućiti određene servere u vašoj lokalnoj konfiguraciji: + +```json title="opencode.json" +{ +"mcp": { + "jira": { + "tip": "daljinski", + "url": "https://jira.example.com/mcp", + "omogućeno": istina } + } +} +``` + +--- + +### Global + +Postavite svoju globalnu OpenCode konfiguraciju u `~/.config/opencode/opencode.json`. Koristite globalnu konfiguraciju za korisničke preferencije kao što su teme, provajderi ili veze tipki. +Globalna konfiguracija poništava zadane postavke udaljene organizacije. + +--- + +### Nakon projekta + +Dodajte `opencode.json` u korijen projekta. Konfiguracija projekta ima najveći prioritet među standardnim konfiguracijskim datotekama - ona nadjačava globalne i udaljene konfiguracije. +::: tip +Postavite specifičnu konfiguraciju projekta u korijen vašeg projekta. +::: +Kada se OpenCode pokrene, traži konfiguracijsku datoteku u trenutnom direktoriju ili prelazi do najbližeg Git direktorija. +Ovo je također sigurno provjeriti u Git i koristi istu shemu kao globalna. + +--- + +### Custom track + +Navedite prilagođenu putanju konfiguracijske datoteke koristeći varijablu okruženja `OPENCODE_CONFIG`. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +Prilagođena konfiguracija se učitava između globalne i projektne konfiguracije po redoslijedu prioriteta. + +--- + +### Prilagođeni imenik + +Navedite prilagođeni konfiguracijski direktorij koristeći `OPENCODE_CONFIG_DIR` +varijabla okruženja. U ovom direktoriju će se tražiti agenti, komande, +modove i dodatke baš kao standardni `.opencode` direktorij, i trebali bi +prate istu strukturu. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" + +``` + +Prilagođeni direktorij se učitava nakon direktorija globalne konfiguracije i `.opencode`, tako da **može nadjačati** njihove postavke. + +--- + +## Shema + +Konfiguracijski fajl ima šemu koja je definirana u [**`opencode.ai/config.json`**](https://opencode.ai/config.json). +Vaš uređivač bi trebao biti u mogućnosti da potvrdi i autodovršava na osnovu šeme. + +--- + +### TUI + +Možete konfigurirati postavke specifične za TUI putem opcije `tui`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +Dostupne opcije: + +- `scroll_acceleration.enabled` - Omogući ubrzanje skrolovanja u macOS stilu. **Ima prednost nad `scroll_speed`.** +- `scroll_speed` - Prilagođeni množitelj brzine pomicanja (podrazumevano: `3`, minimalno: `1`). Zanemareno ako je `scroll_acceleration.enabled` `true`. +- `diff_style` - Kontrola prikaza razlike. `"auto"` se prilagođava širini terminala, `"stacked"` uvijek prikazuje jednu kolonu. + [Ovdje saznajte više o korištenju TUI](/docs/tui). + +--- + +### Server + +Možete konfigurirati postavke servera za komande `opencode serve` i `opencode web` putem opcije `server`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +Dostupne opcije: + +- `port` - Port za slušanje. +- `hostname` - Ime hosta za slušanje. Kada je `mdns` omogućen i nije postavljeno ime hosta, podrazumevano je `0.0.0.0`. +- `mdns` - Omogući otkrivanje mDNS usluge. Ovo omogućava drugim uređajima na mreži da otkriju vaš OpenCode server. +- `mdnsDomain` - Prilagođeno ime domene za mDNS uslugu. Zadano je `opencode.local`. Korisno za pokretanje više instanci na istoj mreži. +- `cors` - Dodatni izvori koji omogućavaju CORS kada koristite HTTP server iz klijenta baziranog na pretraživaču. Vrijednosti moraju biti punog porijekla (šema + host + opcijski port), npr. `https://app.example.com`. + [Saznajte više o serveru](/docs/server) ovdje. + +--- + +### Uvijek + +Možete upravljati alatima koje LLM može koristiti putem opcije `tools`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[Saznajte više o alatima](/docs/tools) ovdje. + +--- + +### Model + +Možete konfigurirati dobavljače i modele koje želite koristiti u svojoj OpenCode konfiguraciji kroz opcije `provider`, `model` i `small_model`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +Opcija `small_model` konfigurira poseban model za lagane zadatke poput generiranja naslova. Podrazumevano, OpenCode pokušava da koristi jeftiniji model ako je dostupan od vašeg provajdera, inače se vraća na vaš glavni model. +Opcije provajdera mogu uključivati ​​`timeout` i `setCacheKey`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - Vrijeme čekanja zahtjeva u milisekundama (podrazumevano: 300000). Postavite na `false` da onemogućite. +- `setCacheKey` - Osigurajte da je ključ keš memorije uvijek postavljen za određenog provajdera. + Također možete konfigurirati [lokalni modeli](/docs/models#local). [Saznajte više](/docs/models). + +--- + +#### Opcije specifične za provajdere + +Neki provajderi podržavaju dodatne opcije konfiguracije osim generičkih postavki `timeout` i `apiKey`. + +##### Amazon Bedrock + +Amazon Bedrock podržava konfiguraciju specifičnu za AWS: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - AWS regija za Bedrock (zadano na `AWS_REGION` env var ili `us-east-1`) +- `profile` - AWS imenovan profil od `~/.aws/credentials` (podrazumevano na `AWS_PROFILE` env var) +- `endpoint` - URL prilagođene krajnje tačke za VPC krajnje tačke. Ovo je pseudonim za generičku opciju `baseURL` koristeći terminologiju specifičnu za AWS. Ako su oba navedena, `endpoint` ima prednost. + :::napomena + Tokeni nosioca (`AWS_BEARER_TOKEN_BEDROCK` ili `/connect`) imaju prednost nad autentifikacijom zasnovanom na profilu. Pogledajte [prednost autentifikacije](/docs/providers#authentication-precedence) za detalje. + ::: + [Saznajte više o konfiguraciji Amazon Bedrock](/docs/providers#amazon-bedrock). + +--- + +### Domaći + +Možete konfigurirati temu koju želite koristiti u svojoj OpenCode konfiguraciji putem opcije `theme`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[Saznajte više ovdje](/docs/themes). + +--- + +### Agenti + +Možete konfigurirati specijalizirane agente za određene zadatke putem opcije `agent`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +Također možete definirati agente koristeći mardown datoteke u `~/.config/opencode/agents/` ili `.opencode/agents/`. [Saznajte više ovdje](/docs/agents). + +--- + +### Zadani agent + +Možete postaviti zadanog agenta koristeći opciju `default_agent`. Ovo određuje koji se agent koristi kada nijedan nije eksplicitno specificiran. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +Zadani agent mora biti primarni agent (ne podagent). Ovo može biti ugrađeni agent kao što je `"build"` ili `"plan"`, ili [prilagođeni agent](/docs/agents) koji ste definirali. Ako navedeni agent ne postoji ili je subagent, OpenCode će se vratiti na `"build"` s upozorenjem. +Ova postavka se primjenjuje na sva sučelja: TUI, CLI (`opencode run`), desktop aplikaciju i GitHub Action. + +--- + +### Dijeljenje + +Možete konfigurirati funkciju [share](/docs/share) putem opcije `share`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +Ovo traje: + +- `"manual"` - Dozvoli ručno dijeljenje putem komandi (podrazumevano) +- `"auto"` - Automatski dijelite nove razgovore +- `"disabled"` - Onemogući dijeljenje u potpunosti + Podrazumevano, dijeljenje je postavljeno na ručni način rada gdje trebate eksplicitno dijeliti razgovore pomoću naredbe `/share`. + +--- + +### komandante + +Možete konfigurirati prilagođene komande za ponavljanje zadataka putem opcije `command`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +Također možete definirati komande koristeći mardown fajlove u `~/.config/opencode/commands/` ili `.opencode/commands/`. [Saznajte više ovdje](/docs/commands). + +--- + +### Keybinds + +Možete prilagoditi svoje veze ključeva putem opcije `keybinds`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[Saznajte više ovdje](/docs/keybinds). + +--- + +### Automatsko ažuriranje + +OpenCode će automatski preuzeti sva nova ažuriranja kada se pokrene. Ovo možete onemogućiti opcijom `autoupdate`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +Ako ne želite ažuriranja, ali želite biti obaviješteni kada nova verzija bude dostupna, postavite `autoupdate` na `"notify"`. +Imajte na umu da ovo funkcionira samo ako nije instalirano pomoću upravitelja paketa kao što je Homebrew. + +--- + +### Trenerke + +Možete konfigurirati formatere koda putem opcije `formatter`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[Saznajte više o formatterima](/docs/formatters) ovdje. + +--- + +### Dozvole + +Prema zadanim postavkama, opencode **dopušta sve operacije** bez potrebe za eksplicitnim dopuštenjem. Ovo možete promijeniti koristeći opciju `permission`. +Na primjer, da osigurate da alati `edit` i `bash` zahtijevaju odobrenje korisnika: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[Ovdje saznajte više o ](/docs/permissions) dozvolama. + +--- + +### Compaction + +Možete kontrolirati ponašanje sažimanja konteksta putem opcije `compaction`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - Automatski sažimanje sesije kada je kontekst pun (podrazumevano: `true`). +- `prune` - Uklonite stare izlaze alata da sačuvate tokene (podrazumevano: `true`). + +--- + +### Watcher + +Možete konfigurirati obrasce ignoriranja promatrača datoteka putem opcije `watcher`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +Obrasci prate glob sintaksu. Koristite ovo da isključite bučne direktorije iz pregleda datoteka. + +--- + +### MCP serveri + +Možete konfigurirati MCP servere koje želite koristiti putem opcije `mcp`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[Saznajte više ovdje](/docs/mcp-servers). + +--- + +### Extras + +[Plugins](/docs/plugins) proširuju OpenCode sa prilagođenim alatima, kukicama i integracijama. +Postavite datoteke dodataka u `.opencode/plugins/` ili `~/.config/opencode/plugins/`. Također možete učitati dodatke iz npm-a preko opcije `plugin`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[Saznajte više ovdje](/docs/plugins). + +--- + +### Uputstva + +Možete konfigurirati upute za model koji koristite putem opcije `instructions`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Ovo uzima niz putanja i uzoraka globusa do datoteka instrukcija. [Saznajte više +o pravilima ovdje](/docs/rules). + +--- + +### Onemogućeni provajderi + +Možete onemogućiti dobavljače koji se automatski učitavaju preko opcije `disabled_providers`. Ovo je korisno kada želite spriječiti učitavanje određenih provajdera čak i ako su njihovi vjerodajnici dostupni. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::napomena +`disabled_providers` ima prioritet nad `enabled_providers`. +::: +Opcija `disabled_providers` prihvata niz ID-ova provajdera. Kada je provajder onemogućen: + +- Neće se učitati čak i ako su varijable okruženja postavljene. +- Neće se učitati čak i ako su API ključevi konfigurirani putem `/connect` komande. +- Modeli dobavljača se neće pojaviti na listi za odabir modela. + +--- + +### Omogućeni provajderi + +Možete odrediti listu dozvoljenih dobavljača putem opcije `enabled_providers`. Kada se podesi, samo navedeni provajderi će biti omogućeni, a svi ostali će biti zanemareni. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +Ovo je korisno kada želite da ograničite OpenCode da koristi samo određene provajdere umesto da ih onemogućavate jednog po jednog. +:::napomena +`disabled_providers` ima prioritet nad `enabled_providers`. +::: +Ako se provajder pojavljuje i u `enabled_providers` i `disabled_providers`, `disabled_providers` ima prioritet za kompatibilnost unatrag. + +--- + +### Eksperimentalno + +Ključ `experimental` sadrži opcije koje su u aktivnom razvoju. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::oprez +Eksperimentalne opcije nisu stabilne. Mogu se promijeniti ili ukloniti bez prethodne najave. +::: + +--- + +## Varijable + +Možete koristiti zamjenu varijabli u vašim konfiguracijskim datotekama da biste referencirali varijable okruženja i sadržaj datoteke. + +--- + +### Env vars + +Koristite `{env:VARIABLE_NAME}` za zamjenu varijabli okruženja: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +Ako varijabla okruženja nije postavljena, bit će zamijenjena praznim nizom. + +--- + +### Fajlovi + +Koristite `{file:path/to/file}` da zamijenite sadržaj fajla: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +Putanja fajla mogu biti: + +- U odnosu na direktorij konfiguracijskih datoteka +- Ili apsolutne staze koje počinju sa `/` ili `~` + Ovo je korisno za: +- Pohranjivanje osjetljivih podataka poput API ključeva u odvojenim datotekama. +- Uključujući velike datoteke instrukcija bez zatrpavanja vaše konfiguracije. +- Dijeljenje zajedničkih isječaka konfiguracije u više konfiguracijskih datoteka. diff --git a/packages/web/src/content/docs/bs/custom-tools.mdx b/packages/web/src/content/docs/bs/custom-tools.mdx new file mode 100644 index 000000000..9a13ab185 --- /dev/null +++ b/packages/web/src/content/docs/bs/custom-tools.mdx @@ -0,0 +1,160 @@ +--- +title: Custom Tools +description: Kreirajte alate koje LLM može pozvati u otvorenom kodu. +--- + +Prilagođeni alati su funkcije koje kreirate i koje LLM može pozvati tokom razgovora. Oni rade zajedno sa [ugrađenim opencode](/docs/tools) alatima kao što su `read`, `write` i `bash`. + +--- + +## Kreiranje alata +Alati su definisani kao **TypeScript** ili **JavaScript** datoteke. Međutim, definicija alata može pozvati skripte napisane na **bilo kom jeziku** — TypeScript ili JavaScript se koriste samo za samu definiciju alata. + +--- + +### Lokacija +Mogu se definisati: +- Lokalno postavljanjem u `.opencode/tools/` direktorij vašeg projekta. +- Ili globalno, postavljanjem u `~/.config/opencode/tools/`. + +--- + +### Struktura +Najlakši način za kreiranje alata je korištenje pomoćnika `tool()` koji pruža sigurnost tipa i validaciju. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +**ime datoteke** postaje **naziv alata**. Gore navedeno je kreirano pomoću `database` alata. + +--- + +#### Više alata po datoteci +Također možete izvesti više alata iz jedne datoteke. Svaki izvoz postaje **poseban alat** pod nazivom **`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +Ovo stvara dva alata: `math_add` i `math_multiply`. + +--- + +### Argumenti +Možete koristiti `tool.schema`, što je samo [Zod](https://zod.dev), da definirate tipove argumenata. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +Također možete direktno uvesti [Zod](https://zod.dev) i vratiti običan objekt: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### Kontekst +Alati primaju kontekst o trenutnoj sesiji: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +Koristite `context.directory` za radni direktorij sesije. +Koristite `context.worktree` za korijen git radnog stabla. + +--- + +## Primjeri +### Napišite alat u Python-u +Možete pisati svoje alate na bilo kom jeziku koji želite. Evo primjera koji zbraja dva broja koristeći Python. +Prvo kreirajte alat kao Python skriptu: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +Zatim kreirajte definiciju alata koja ga poziva: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +Ovdje koristimo [`Bun.$`_](https://bun.com/docs/runtime/shell) uslužni program za pokretanje Python skripte. \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/ecosystem.mdx b/packages/web/src/content/docs/bs/ecosystem.mdx new file mode 100644 index 000000000..9cc861177 --- /dev/null +++ b/packages/web/src/content/docs/bs/ecosystem.mdx @@ -0,0 +1,66 @@ +--- +title: Ekosistem +description: Projekti i integracije izgrađeni uz OpenCode. +--- + +Kolekcija projekata zajednice izgrađenih na OpenCode-u. +:::napomena +Želite li na ovu listu dodati svoj OpenCode projekat? Pošaljite PR. +::: +Također možete pogledati [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) i [opencode.cafe](https://opencode.cafe), zajednicu koja spaja ekosistem i zajednicu. + +--- + +## Dodaci +| Ime | Opis || --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | Automatski pokrenite OpenCode sesije u izoliranim Daytona sandboxovima uz git sinhronizaciju i preglede uživo | +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Automatski ubacite Helicone zaglavlja sesije za grupisanje zahtjeva | +| [opencode-type-iject](https://github.com/nick-vi/opencode-type-inject) | Automatski ubaci TypeScript/Svelte tipove u čitanje datoteka pomoću alata za pretraživanje | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Koristite svoju ChatGPT Plus/Pro pretplatu umjesto API kredita | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Koristite svoj postojeći Gemini plan umjesto API naplate | +| [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Koristite besplatne modele Antigravity umjesto API naplate | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Izolacija devcontainer-a s više grana s plitkim klonovima i automatski dodijeljenim portovima | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Antigravity OAuth dodatak, s podrškom za Google pretraživanje i robusnijim API rukovanjem | +| [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Optimizirajte korištenje tokena smanjenjem izlaza zastarjelih alata | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Dodajte podršku za izvorno web pretraživanje za podržane provajdere sa stilom utemeljenim na Googleu | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Omogućuje AI agentima da pokreću pozadinske procese u PTY-u, šalju im interaktivni ulaz. | +| [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Upute za neinteraktivne naredbe ljuske - sprječava visi od TTY ovisnih operacija || [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Pratite upotrebu OpenCodea sa Wakatime | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Očistite tabele umanjenja vrijednosti koje su izradili LLM | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | 10x brže uređivanje koda s Morph Fast Apply API-jem i markerima za lijeno uređivanje | +| [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Pozadinski agenti, unapred izgrađeni LSP/AST/MCP alati, kurirani agenti, kompatibilni sa Claude Code | +| [opencode-notificator](https://github.com/panta82/opencode-notificator) | Obavještenja na radnoj površini i zvučna upozorenja za OpenCode sesije | +| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Obavještenja na radnoj površini i zvučna upozorenja za dozvole, završetak i događaje greške | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | Automatsko imenovanje Zellij sesije na bazi OpenCode konteksta | +| [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Dozvolite OpenCode agentima da lijeno učitavaju upite na zahtjev uz otkrivanje vještina i ubrizgavanje | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Trajna memorija kroz sesije koristeći Supermemory | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Interaktivni pregled plana s vizualnim napomenama i privatnim/offline dijeljenjem | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Proširite opencode /komande u moćan sistem orkestracije sa granularnom kontrolom toka | +| [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Planirajte ponavljajuće poslove koristeći launchd (Mac) ili systemd (Linux) sa cron sintaksom || [micode](https://github.com/vtemian/micode) | Strukturirana Brainstorm → Plan → Implementacija toka rada uz kontinuitet sesije | +| [oktobar](https://github.com/vtemian/octto) | Interaktivno korisničko sučelje pretraživača za AI brainstorming sa obrascima za više pitanja | +| [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Pozadinski agenti u stilu Claudea s asinhroniziranim delegiranjem i postojanošću konteksta | +| [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Notifikacije izvornog OS-a za OpenCode – znajte kada se zadaci dovrše | +| [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Uvezeni višeagentni orkestracijski pojas – 16 komponenti, jedna instalacija | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Git radna stabla bez trenja za OpenCode | + +--- + +## Projekti +| Ime | Opis || ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | Discord bot za kontrolu OpenCode sesija, izgrađen na SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Neovim dodatak za upite svjestan uređivača, izgrađen na API | +| [portal](https://github.com/hosenur/portal) | Mobilni korisnički interfejs za OpenCode preko Tailscale/VPN | +| [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | Predložak za izgradnju OpenCode dodataka | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Neovim frontend za opencode - terminal baziran AI agent za kodiranje | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Vercel AI SDK dobavljač za korištenje OpenCodea putem @opencode-ai/sdk | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | Web / Desktop App i VS Code Extension za OpenCode | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Obsidian dodatak koji ugrađuje OpenCode u Obsidian-ov UI | +| [OpenWork](https://github.com/different-ai/openwork) | Alternativa otvorenog koda Claudeu Coworku, pokretana pomoću OpenCode | +| [ocx](https://github.com/kdcokenny/ocx) | OpenCode menadžer ekstenzija sa prenosivim, izolovanim profilima. | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Desktop, Web, Mobile i Remote Client aplikacija za OpenCode | + +--- + +## Agenti +| Ime | Opis || ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [Agentic](https://github.com/Cluster444/agentic) | Modularni AI agenti i komande za strukturirani razvoj | +| [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Konfiguracije, upiti, agenti i dodaci za poboljšane tokove rada | \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/enterprise.mdx b/packages/web/src/content/docs/bs/enterprise.mdx new file mode 100644 index 000000000..8064fe3e0 --- /dev/null +++ b/packages/web/src/content/docs/bs/enterprise.mdx @@ -0,0 +1,165 @@ +--- +title: Enterprise +description: Sigurno korištenje OpenCodea u vašoj organizaciji. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise je za organizacije koje žele osigurati da njihov kod i podaci nikada ne napuštaju njihovu infrastrukturu. To omogućava centralizovana konfiguracija koja se integriše s vašim SSO-om i internim AI gateway-om. + +:::note +OpenCode ne pohranjuje nijedan vaš kod ili kontekstualne podatke. +::: + +Da započnete s OpenCode Enterprise: + +1. Uradite interni probni period sa svojim timom. +2. **Kontaktirajte nas** da razgovaramo o cijenama i opcijama implementacije. + +--- + +## Trial + +OpenCode je otvorenog koda i ne pohranjuje vaš kod niti kontekstualne podatke, tako da vaši developeri mogu jednostavno [započeti](/docs/) i provesti probu. + +--- + +### Rukovanje podacima + +**OpenCode ne pohranjuje vaš kod ni kontekstualne podatke.** Sva obrada se odvija lokalno ili putem direktnih API poziva vašem AI provajderu. + +To znači da, sve dok koristite provajdera kojem vjerujete ili interni AI gateway, OpenCode možete koristiti sigurno. + +Jedina iznimka je opcionalna funkcija `/share`. + +--- + +#### Dijeljenje razgovora + +Ako korisnik uključi funkciju `/share`, razgovor i povezani podaci šalju se servisu koji koristimo za hosting ovih share stranica na opencode.ai. + +Podaci se trenutno serviraju kroz edge mrežu našeg CDN-a i keširaju se blizu korisnika. + +Preporučujemo da ovo onemogućite tokom probe. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[Saznajte više o dijeljenju](/docs/share). + +--- + +### Vlasništvo koda + +**Vi posjedujete sav kod koji OpenCode proizvede.** Nema ograničenja licenciranja niti zahtjeva za vlasništvo. + +--- + +## Pricing + +Koristimo model naplate po sjedištu za OpenCode Enterprise. Ako imate vlastiti LLM gateway, ne naplaćujemo korištene tokene. Za više detalja o cijenama i opcijama implementacije, **kontaktirajte nas**. + +--- + +## Deployment + +Nakon što završite probni period i spremni ste koristiti OpenCode u svojoj organizaciji, možete **kontaktirati nas** da razgovaramo o cijenama i opcijama implementacije. + +--- + +### Central Config + +Možemo postaviti OpenCode da koristi jednu centralnu konfiguraciju za cijelu organizaciju. + +Ta centralizovana konfiguracija može se integrisati s vašim SSO provajderom i osigurava da svi korisnici pristupaju samo vašem internom AI gateway-u. + +--- + +### SSO integracija + +Kroz centralnu konfiguraciju, OpenCode se može integrisati sa SSO provajderom vaše organizacije za autentifikaciju. + +To omogućava OpenCodeu da dobije vjerodajnice za interni AI gateway kroz vaš postojeći sistem upravljanja identitetom. + +--- + +### Interni AI gateway + +Uz centralnu konfiguraciju, OpenCode se može podesiti da koristi samo vaš interni AI gateway. + +Također možete onemogućiti sve druge AI provajdere, čime osiguravate da svi zahtjevi prolaze kroz odobrenu infrastrukturu vaše organizacije. + +--- + +### Self-hosting + +Iako preporučujemo onemogućavanje share stranica kako biste osigurali da podaci nikada ne napuštaju vašu organizaciju, možemo vam pomoći i da ih samostalno hostujete na vlastitoj infrastrukturi. + +Ovo je trenutno na našoj mapi puta. Ako ste zainteresovani, **javite nam**. + +--- + +## FAQ + +

+What is OpenCode Enterprise? + +OpenCode Enterprise je za organizacije koje žele osigurati da njihov kod i podaci nikada ne napuštaju njihovu infrastrukturu. To omogućava centralizovana konfiguracija koja se integriše s vašim SSO-om i internim AI gateway-om. + +
+ +
+How do I get started with OpenCode Enterprise? + +Jednostavno započnite internu probu sa svojim timom. OpenCode po defaultu ne pohranjuje vaš kod ni kontekstualne podatke, što olakšava početak. + +Zatim **kontaktirajte nas** da razgovaramo o cijenama i opcijama implementacije. + +
+ +
+How does enterprise pricing work? + +Nudimo enterprise cijene po sjedištu. Ako imate vlastiti LLM gateway, ne naplaćujemo korištene tokene. Za više detalja, **kontaktirajte nas** za prilagođenu ponudu prema potrebama vaše organizacije. + +
+ +
+Is my data secure with OpenCode Enterprise? + +Da. OpenCode ne pohranjuje vaš kod niti kontekstualne podatke. Sva obrada se odvija lokalno ili putem direktnih API poziva vašem AI provajderu. Uz centralnu konfiguraciju i SSO integraciju, vaši podaci ostaju sigurni unutar infrastrukture vaše organizacije. + +
+ +
+Can we use our own private NPM registry? + +OpenCode podržava privatne npm registre kroz Bunovu izvornu podršku za `.npmrc` datoteku. Ako vaša organizacija koristi privatni registar, kao što je JFrog Artifactory, Nexus ili slično, osigurajte da su developeri autentifikovani prije pokretanja OpenCodea. + +Da postavite autentifikaciju s privatnim registrom: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +Ovo kreira `~/.npmrc` s detaljima za autentifikaciju. OpenCode će to automatski prepoznati. + +:::caution +Morate biti prijavljeni na privatni registar prije pokretanja OpenCodea. +::: + +Alternativno, možete ručno konfigurisati `.npmrc` datoteku: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Developeri moraju biti prijavljeni na privatni registar prije pokretanja OpenCodea kako bi se paketi mogli instalirati iz vašeg enterprise registra. + +
diff --git a/packages/web/src/content/docs/bs/formatters.mdx b/packages/web/src/content/docs/bs/formatters.mdx new file mode 100644 index 000000000..bb0816d70 --- /dev/null +++ b/packages/web/src/content/docs/bs/formatters.mdx @@ -0,0 +1,115 @@ +--- +title: Trenerke +description: OpenCode koristi formatere specifične za jezik. +--- + +OpenCode automatski formatira datoteke nakon što su napisane ili uređene pomoću formatera specifičnih za jezik. Ovo osigurava da kod koji se generira prati stilove koda vašeg projekta. + +--- + +## Ugrađeno +OpenCode dolazi sa nekoliko ugrađenih formatera za popularne jezike i okvire. Ispod je lista formatera, podržanih ekstenzija datoteka i naredbi ili opcija konfiguracije koje su mu potrebne. +| Formatter | Ekstenzije | Zahtjevi || -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| gofmt | .go | `gofmt` komanda dostupna | +| mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` komanda dostupna | +| ljepše | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml i [više](https://prettier.io/docs/en/index.html) | `prettier` zavisnost u `package.json` | +| biom | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml i [više](https://biomejs.dev/) | `biome.json(c)` konfiguracijski fajl | +| zig | .zig, .zon | `zig` komanda dostupna | +| clang-format | .c, .cpp, .h, .hpp, .ino i [više](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` konfiguracijski fajl | +| ktlint | .kt, .kts | `ktlint` komanda dostupna | +| ruff | .py, .pyi | `ruff` komanda dostupna sa konfiguracijom | +| rustfmt | .rs | `rustfmt` komanda dostupna | +| cargofmt | .rs | `cargo fmt` komanda dostupna | +| uv | .py, .pyi | `uv` komanda dostupna || rubocop | .rb, .rake, .gemspec, .ru | `rubocop` komanda dostupna | +| standardrb | .rb, .rake, .gemspec, .ru | `standardrb` komanda dostupna | +| htmlbeautifier | .erb, .html.erb | `htmlbeautifier` komanda dostupna | +| zrak | .R | `air` komanda dostupna | +| dart | .dart | `dart` komanda dostupna | +| ocamlformat | .ml, .mli | `ocamlformat` komanda dostupna i `.ocamlformat` konfiguracioni fajl | +| terraform | .tf, .tfvars | `terraform` komanda dostupna | +| sjaj | .bleam | `gleam` komanda dostupna | +| nixfmt | .nix | `nixfmt` komanda dostupna | +| shfmt | .sh, .bash | `shfmt` komanda dostupna | +| pint | .php | `laravel/pint` zavisnost u `composer.json` || oxfmt (Eksperimentalno) | .js, .jsx, .ts, .tsx | `oxfmt` zavisnost u `package.json` i [eksperimentalna env varijabla flag](/docs/cli/#experimental) | +| ormolu | .hs | `ormolu` komanda dostupna | +Dakle, ako vaš projekat ima `prettier` u vašem `package.json`, OpenCode će ga automatski koristiti. + +--- + +## Kako radi +Kada OpenCode piše ili uređuje datoteku, on: +1. Provjerava ekstenziju datoteke prema svim omogućenim formaterima. +2. Pokreće odgovarajuću naredbu za formatiranje na datoteci. +3. Automatski primjenjuje promjene formatiranja. +Ovaj proces se događa u pozadini, osiguravajući da se vaši stilovi koda održavaju bez ikakvih ručnih koraka. + +--- + +## Konfiguriši +Možete prilagoditi formatere kroz `formatter` odjeljak u vašoj OpenCode konfiguraciji. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +Svaka konfiguracija formatera podržava sljedeće: +| Nekretnine | Vrsta | Opis || ------------- | -------- | ------------------------------------------------------- | +| `disabled` | boolean | Postavite ovo na `true` da onemogućite formater | +| `command` | string[] | Naredba za pokretanje za formatiranje | +| `environment` | objekt | Varijable okruženja koje treba postaviti prilikom pokretanja formatera | +| `extensions` | string[] | Ekstenzije datoteka koje ovaj formater treba da obrađuje | +Pogledajmo neke primjere. + +--- + +### Onemogućavanje formatera +Da onemogućite **sve** formatere globalno, postavite `formatter` na `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +Da onemogućite **specifični** formater, postavite `disabled` na `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Prilagođeni formateri +Možete nadjačati ugrađene formatere ili dodati nove navođenjem naredbe, varijabli okruženja i ekstenzija datoteke: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +**`$FILE` čuvar mjesta** u naredbi će biti zamijenjen putanjom do datoteke koja se formatira. \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/github.mdx b/packages/web/src/content/docs/bs/github.mdx new file mode 100644 index 000000000..499d26bc7 --- /dev/null +++ b/packages/web/src/content/docs/bs/github.mdx @@ -0,0 +1,305 @@ +--- +title: GitHub +description: Koristite OpenCode u GitHub problemima i zahtjevima za povlačenjem. +--- + +OpenCode se integriše sa vašim GitHub tokovom rada. Spomenite `/opencode` ili `/oc` u svom komentaru i OpenCode će izvršiti zadatke unutar vašeg GitHub Actions runnera. + +--- + +## Karakteristike +- **Problemi trijaže**: Zamolite OpenCode da ispita problem i objasni vam ga. +- **Popravi i implementiraj**: Zamolite OpenCode da popravi problem ili implementira funkciju. I radit će u novoj poslovnici i dostavljati PR sa svim promjenama. +- **Secure**: OpenCode se pokreće unutar pokretača vašeg GitHub-a. + +--- + +## Instalacija +Pokrenite sljedeću naredbu u projektu koji se nalazi u GitHub repo: + +```bash +opencode github install +``` + +Ovo će vas provesti kroz instalaciju GitHub aplikacije, kreiranje toka posla i postavljanje tajni. + +--- + +### Ručno podešavanje +Ili ga možete postaviti ručno. +1. **Instalirajte GitHub aplikaciju** +Idite na [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). Uvjerite se da je instaliran na ciljnom spremištu. +2. **Dodajte radni tok** +Dodajte sljedeći fajl toka posla u `.github/workflows/opencode.yml` u svoj repo. Obavezno postavite odgovarajuće `model` i potrebne API ključeve u `env`. + +```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + + +``` + +3. **Sačuvaj API ključeve u tajne** +U **postavkama** organizacije ili projekta proširite **Tajne i varijable** na lijevoj strani i odaberite **Radnje**. I dodajte potrebne API ključeve. + +--- + +## Konfiguracija +- `model`: Model za korištenje s OpenCodeom. Uzima format `provider/model`. Ovo je **obavezno**. +- `agent`: Agent za korištenje. Mora biti primarni agent. Vraća se na `default_agent` iz konfiguracije ili `"build"` ako nije pronađen. +- `share`: Da li dijeliti OpenCode sesiju. Podrazumevano je **true** za javna spremišta. +- `prompt`: Opcioni prilagođeni upit za nadjačavanje zadanog ponašanja. Koristite ovo da prilagodite kako OpenCode obrađuje zahtjeve. +- `token`: Opcionalni GitHub pristupni token za izvođenje operacija kao što su kreiranje komentara, upisivanje promjena i otvaranje zahtjeva za povlačenjem. OpenCode prema zadanim postavkama koristi token za pristup instalaciji iz aplikacije OpenCode GitHub, tako da se urezivanje, komentari i zahtjevi za povlačenjem pojavljuju kao da dolaze iz aplikacije. +Alternativno, možete koristiti GitHub Action runner [ugrađeni `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) bez instaliranja OpenCode GitHub aplikacije. Samo se pobrinite da date potrebna odobrenja u svom toku rada: + +```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + + +``` + +Također možete koristiti [Personal Access Tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) ako želite. + +--- + +## Podržani događaji +OpenCode se može pokrenuti sljedećim GitHub događajima: +| Vrsta događaja | Pokrenuo | Detalji || ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | Komentirajte problem ili PR | Navedite `/opencode` ili `/oc` u svom komentaru. OpenCode čita kontekst i može kreirati grane, otvarati PR-ove ili odgovarati. | +| `pull_request_review_comment` | Komentirajte određene linije koda u PR-u | Navedite `/opencode` ili `/oc` dok pregledavate kod. OpenCode prima putanju datoteke, brojeve redova i kontekst razlike. | +| `issues` | Broj otvoren ili uređen | Automatski pokrenite OpenCode kada se problemi kreiraju ili modificiraju. Zahtijeva `prompt` unos. | +| `pull_request` | PR otvoren ili ažuriran | Automatski pokrenite OpenCode kada se PR-ovi otvore, sinkroniziraju ili ponovo otvore. Korisno za automatske recenzije. | +| `schedule` | Cron baziran raspored | Pokrenite OpenCode prema rasporedu. Zahtijeva `prompt` unos. Izlaz ide u dnevnike i PR-ove (nema problema za komentarisanje). | +| `workflow_dispatch` | Ručni okidač iz GitHub korisničkog sučelja | Aktivirajte OpenCode na zahtjev preko kartice Akcije. Zahtijeva `prompt` unos. Izlaz ide u dnevnike i PR-ove. | +### Primjer rasporeda +Pokrenite OpenCode po rasporedu za obavljanje automatiziranih zadataka: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +Za zakazane događaje, unos `prompt` je **potreban** jer nema komentara za izvlačenje instrukcija. Planirani tokovi posla se pokreću bez korisničkog konteksta za provjeru dozvola, tako da tok posla mora odobriti `contents: write` i `pull-requests: write` ako očekujete da će OpenCode kreirati grane ili PR-ove. + +--- + +### Primjer zahtjeva za povlačenjem +Automatski pregledajte PR-ove kada se otvore ili ažuriraju: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Za `pull_request` događaje, ako nije naveden `prompt`, OpenCode podrazumevano pregledava zahtjev za povlačenjem. + +--- + +### Primjer trijaže problema +Automatski triažirajte nove probleme. Ovaj primjer filtrira na račune starije od 30 dana radi smanjenja neželjene pošte: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +Za `issues` događaje, `prompt` unos je **potreban** jer nema komentara za izvlačenje instrukcija. + +--- + +## Prilagođene upite +Zaobiđite zadani prompt da biste prilagodili ponašanje OpenCodea za vaš tok posla. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Ovo je korisno za provođenje specifičnih kriterija pregleda, standarda kodiranja ili fokusnih područja relevantnih za vaš projekt. + +--- + +## Primjeri +Evo nekoliko primjera kako možete koristiti OpenCode u GitHubu. +- **Objasnite problem** +Dodajte ovaj komentar u GitHub izdanje. + +``` + /opencode explain this issue + + +``` + +OpenCode će pročitati cijelu temu, uključujući sve komentare, i odgovoriti s jasnim objašnjenjem. +- **Popravi problem** +U izdanju na GitHub-u recite: + +``` + /opencode fix this + + +``` + +I OpenCode će kreirati novu granu, implementirati promjene i otvoriti PR sa promjenama. +- **Pregledajte PR-ove i izvršite izmjene** +Ostavite sljedeći komentar na GitHub PR-u. + +``` + Delete the attachment from S3 when the note is removed /oc + + +``` + +OpenCode će implementirati traženu promjenu i posvetiti je istom PR-u. +- **Pregledajte određene linije koda** +Ostavite komentar direktno na linije koda u PR kartici "Files". OpenCode automatski detektuje datoteku, brojeve redova i kontekst razlike kako bi pružio precizne odgovore. + +``` + [Comment on specific lines in Files tab] + /oc add error handling here + + +``` + +Kada komentarišete određene linije, OpenCode prima: + - Tačan fajl se pregleda + - Specifične linije koda + - Okolni diff kontekst + - Informacije o broju linije +Ovo omogućava više ciljanih zahtjeva bez potrebe za ručno specificiranjem putanja datoteka ili brojeva linija. \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/gitlab.mdx b/packages/web/src/content/docs/bs/gitlab.mdx new file mode 100644 index 000000000..2aee159fc --- /dev/null +++ b/packages/web/src/content/docs/bs/gitlab.mdx @@ -0,0 +1,194 @@ +--- +title: GitLab +description: Koristite OpenCode u GitLab problemima i zahtjevima za spajanje. +--- + +OpenCode se integriše sa vašim GitLab radnim tokom kroz vaš GitLab CI/CD cevovod ili sa GitLab Duo. +U oba slučaja, OpenCode će se pokrenuti na vašim GitLab pokretačima. + +--- + +## GitLab CI + +OpenCode radi u redovnom GitLab cevovodu. Možete ga ugraditi u cjevovod kao [CI komponenta](https://docs.gitlab.com/ee/ci/components/) +Ovdje koristimo CI/CD komponentu kreiranu u zajednici za OpenCode — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### Karakteristike + +- **Koristite prilagođenu konfiguraciju po poslu**: Konfigurirajte OpenCode s prilagođenim konfiguracijskim direktorijem, na primjer `./config/#custom-directory` da omogućite ili onemogućite funkcionalnost po OpenCode pozivanju. +- **Minimalno podešavanje**: CI komponenta postavlja OpenCode u pozadini, samo trebate kreirati OpenCode konfiguraciju i početnu prompt. +- **Fleksibilno**: CI komponenta podržava nekoliko ulaza za prilagođavanje njenog ponašanja + +--- + +### Podešavanje + +1. Sačuvajte JSON za autentifikaciju OpenCode-a kao CI varijable okruženja tipa datoteke pod **Postavke** > **CI/CD** > **Varijable**. Obavezno ih označite kao "Maskirane i skrivene". +2. Dodajte sljedeće u svoju `.gitlab-ci.yml` datoteku. + +```yaml title=".gitlab-ci.yml" +include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" +``` + +Za više unosa i slučajeva upotrebe [pogledajte dokumente docs](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) za ovu komponentu. + +--- + +## GitLab Duo + +OpenCode se integriše sa vašim GitLab tokovom rada. +Spomenite `@opencode` u komentaru i OpenCode će izvršiti zadatke unutar vašeg GitLab CI cevovoda. + +--- + +### Karakteristike + +- **Problemi trijaže**: Zamolite OpenCode da ispita problem i objasni vam ga. +- **Popravi i implementiraj**: Zamolite OpenCode da popravi problem ili implementira funkciju. + To će kreirati novu granu i pokrenuti zahtjev za spajanje s promjenama. +- **Secure**: OpenCode radi na vašim GitLab pokretačima. + +--- + +### Podešavanje + +OpenCode radi u vašem GitLab CI/CD cevovodu, evo šta će vam trebati da ga postavite: +:::tip +Pogledajte [**GitLab dokumente**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) za ažurirane upute. +::: + +1. Konfigurirajte svoje GitLab okruženje +2. Postavite CI/CD +3. Nabavite API ključ dobavljača AI modela +4. Kreirajte nalog usluge +5. Konfigurirajte CI/CD varijable +6. Kreirajte konfiguracijski fajl toka, evo primjera: + +
+ + Flow configuration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +Možete vidjeti [GitLab CLI agenti docs](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) za detaljna uputstva. + +--- + +### Primjeri + +Evo nekoliko primjera kako možete koristiti OpenCode u GitLabu. +:::tip +Možete konfigurirati da koristite drugu frazu okidača od `@opencode`. +::: + +- **Objasnite problem** + Dodajte ovaj komentar u izdanje GitLaba. + +``` + @opencode explain this issue + + +``` + +OpenCode će pročitati problem i odgovoriti jasnim objašnjenjem. + +- **Reši problem** + U izdanju GitLaba recite: + +``` + @opencode fix this + + +``` + +OpenCode će kreirati novu granu, implementirati promjene i otvoriti zahtjev za spajanje s promjenama. + +- **Pregledajte zahtjeve za pridruživanje** + Ostavite sljedeći komentar na zahtjev za spajanje GitLab-a. + +``` + @opencode review this merge request + + +``` + +OpenCode će pregledati zahtjev za spajanje i dati povratne informacije. diff --git a/packages/web/src/content/docs/bs/ide.mdx b/packages/web/src/content/docs/bs/ide.mdx new file mode 100644 index 000000000..f8829ba0e --- /dev/null +++ b/packages/web/src/content/docs/bs/ide.mdx @@ -0,0 +1,41 @@ +--- +title: IDE +description: Ekstenzija OpenCode za VS Code, Cursor i druge IDE +--- + +OpenCode se integriše sa VS kodom, kursorom ili bilo kojim IDE-om koji podržava terminal. Samo pokrenite `opencode` u terminalu da započnete. + +--- + +## Upotreba +- **Brzo pokretanje**: Koristite `Cmd+Esc` (Mac) ili `Ctrl+Esc` (Windows/Linux) da otvorite OpenCode u prikazu podijeljenog terminala ili fokusirajte postojeću terminalsku sesiju ako je već pokrenuta. +- **Nova sesija**: Koristite `Cmd+Shift+Esc` (Mac) ili `Ctrl+Shift+Esc` (Windows/Linux) da započnete novu OpenCode terminalsku sesiju, čak i ako je ona već otvorena. Takođe možete kliknuti na dugme OpenCode u korisničkom sučelju. +- **Svijest o kontekstu**: Automatski dijelite svoj trenutni odabir ili karticu s OpenCodeom. +- **Prečice za referencu datoteka**: Koristite `Cmd+Option+K` (Mac) ili `Alt+Ctrl+K` (Linux/Windows) za umetanje referenci datoteka. Na primjer, `@File#L37-42`. + +--- + +## Instalacija +Da biste instalirali OpenCode na VS Code i popularne viljuške kao što su Cursor, Windsurf, VSCodium: +1. Otvorite VS Code +2. Otvorite integrirani terminal +3. Pokrenite `opencode` - ekstenzija se automatski instalira +Ako s druge strane želite da koristite svoj vlastiti IDE kada pokrenete `/editor` ili `/export` iz TUI-ja, morat ćete postaviti `export EDITOR="code --wait"`. [Saznajte više](/docs/tui/#editor-setup). + +--- + +### Ručna instalacija +Potražite **OpenCode** na Extension Marketplaceu i kliknite na **Instaliraj**. + +--- + +### Rješavanje problema +Ako se ekstenzija ne uspije automatski instalirati: +- Uvjerite se da koristite `opencode` u integriranom terminalu. +- Potvrdite da je CLI za vaš IDE instaliran: + - Za VS kod: `code` naredbu + - Za kursor: `cursor` naredba + - Za jedrenje na dasci: `windsurf` komanda + - Za VSCodium: `codium` komanda + - Ako ne, pokrenite `Cmd+Shift+P` (Mac) ili `Ctrl+Shift+P` (Windows/Linux) i potražite "Shell Command: Install 'code' command in PATH" (ili ekvivalent za vaš IDE) +- Osigurajte da VS Code ima dozvolu za instaliranje ekstenzija \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/index.mdx b/packages/web/src/content/docs/bs/index.mdx new file mode 100644 index 000000000..b3ab917c9 --- /dev/null +++ b/packages/web/src/content/docs/bs/index.mdx @@ -0,0 +1,360 @@ +--- +title: Intro +description: Započnite s OpenCodeom. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) je agent za AI kodiranje otvorenog koda. Dostupan je kao interfejs baziran na terminalu, desktop aplikacija ili IDE ekstenzija. +![OpenCode TUI sa temom otvorenog koda](../../../assets/lander/screenshot.png) +Hajde da počnemo. + +--- + +#### Preduvjeti + +Da biste koristili OpenCode u svom terminalu, trebat će vam: + +1. Moderan emulator terminala kao što su: + - [WezTerm](https://wezterm.org), multi-platforma + - [Alacritty](https://alacritty.org), više platforma + - [Ghostty](https://ghostty.org), Linux i macOS + - [Kitty](https://sw.kovidgoyal.net/kitty/), Linux i macOS +2. API ključevi za LLM provajdere koje želite koristiti. + +--- + +## Instaliraj + +Najlakši način za instaliranje OpenCode-a je putem instalacione skripte. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +Također ga možete instalirati pomoću sljedećih naredbi: + +- **Korišćenje Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **Korišćenje Homebrew-a na macOS-u i Linux-u** + +```bash + brew install anomalyco/tap/opencode + + +``` + +> Preporučujemo korištenje OpenCode tap za najnovija izdanja. Službenu formulu `brew install opencode` održava Homebrew tim i ažurira se rjeđe. + +- **Korišćenje Parua na Arch Linuxu** + +```bash + paru -S opencode-bin + + +``` + +#### Windows + +:::tip[Preporučeno: Koristite WSL] +Za najbolje iskustvo na Windows-u preporučujemo korištenje [Windows Subsystem for Linux (WSL)](/docs/windows-wsl). Pruža bolje performanse i potpunu kompatibilnost sa OpenCode karakteristikama. +::: + +- **Upotreba čokolade** + +```bash + choco install opencode + + +``` + +- **Upotreba Scoop-a** + +```bash + scoop install opencode + + +``` + +- **Upotreba NPM-a** + +```bash + npm install -g opencode-ai + + +``` + +- **Korišćenje Mise** + +```bash + mise use -g github:anomalyco/opencode + + +``` + +- **Korišćenje Dockera** + +```bash + docker run -it --rm ghcr.io/anomalyco/opencode + + +``` + +Podrška za instaliranje OpenCode-a na Windows koristeći Bun je trenutno u toku. +Također možete preuzeti binarnu datoteku iz [Releases](https://github.com/anomalyco/opencode/releases). + +--- + +## Konfiguriši + +Uz OpenCode možete koristiti bilo kojeg LLM provajdera tako što ćete konfigurirati njihove API ključeve. +Ako ste tek počeli koristiti LLM provajdere, preporučujemo korištenje [OpenCode Zen](/docs/zen). +To je kurirana lista modela koji su testirani i verifikovani od strane OpenCode-a +tim. + +1. Pokrenite naredbu `/connect` u TUI-u, odaberite opencode i idite na [opencode.ai/auth](https://opencode.ai/auth). + +```txt + /connect + + +``` + +2. Prijavite se, dodajte svoje detalje naplate i kopirajte svoj API ključ. +3. Zalijepite svoj API ključ. + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +Alternativno, možete odabrati jednog od drugih provajdera. [Saznajte više](/docs/providers#directory). + +--- + +## Inicijaliziraj + +Sada kada ste konfigurisali provajdera, možete se kretati do projekta koji +na čemu želite da radite. + +```bash +cd /path/to/project +``` + +I pokrenite OpenCode. + +```bash +opencode +``` + +Zatim inicijalizirajte OpenCode za projekat pokretanjem sljedeće naredbe. + +```bash frame="none" +/init +``` + +Ovo će omogućiti OpenCode da analizira vaš projekat i kreira `AGENTS.md` fajl u njemu +korijen projekta. +:::tip +Trebali biste urezati datoteku `AGENTS.md` vašeg projekta u Git. +::: +Ovo pomaže OpenCodeu da razumije strukturu projekta i obrasce kodiranja +korišteno. + +--- + +## Upotreba + +Sada ste spremni da koristite OpenCode za rad na svom projektu. Slobodno pitajte +bilo šta! +Ako ste novi u korištenju agenta za AI kodiranje, evo nekoliko primjera koji bi mogli +pomoć. + +--- + +### Postavljajte pitanja + +Možete zamoliti OpenCode da vam objasni kodnu bazu. +:::tip +Koristite tipku `@` za nejasnu pretragu datoteka u projektu. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +Ovo je korisno ako postoji dio kodne baze na kojem niste radili. + +--- + +### Dodajte karakteristike + +Možete zamoliti OpenCode da vašem projektu doda nove funkcije. Iako preporučujemo da ga prvo zamolite da napravi plan. + +1. **Kreirajte plan** + OpenCode ima _Plan mod_ koji onemogućuje njegovu sposobnost da pravi promjene i + umjesto toga predložite _kako_ će implementirati ovu funkciju. + Prebacite se na njega pomoću tipke **Tab**. Vidjet ćete indikator za ovo u donjem desnom uglu. + +```bash frame="none" title="Switch to Plan mode" + + + +``` + +Hajde sada da opišemo šta želimo da uradi. + +```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + + +``` + +Želite da date OpenCode-u dovoljno detalja da razumete šta želite. Pomaže +da razgovarate s njim kao da razgovarate sa mlađim programerom u svom timu. +:::tip +Dajte OpenCodeu dosta konteksta i primjera koji će mu pomoći da razumije šta vi +želim. ::: 2. **Ponovite plan** +Kada vam da plan, možete mu dati povratne informacije ili dodati više detalja. + +```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + + +``` + +:::tip +Prevucite i ispustite slike u terminal da biste ih dodali u prompt. ::: +OpenCode može skenirati sve slike koje mu date i dodati ih u prompt. Možeš +učinite to povlačenjem i ispuštanjem slike u terminal. 3. **Izgradite funkciju** +Kada se osjećate ugodno s planom, vratite se na _Build mode_ do +ponovnim pritiskom na taster **Tab**. + +```bash frame="none" + + + +``` + +I tražeći od njega da napravi promjene. + +```bash frame="none" + Sounds good! Go ahead and make the changes. + + +``` + +--- + +### Napravite promjene + +Za jednostavnije promjene, možete zamoliti OpenCode da ga direktno izgradi +bez potrebe da prvo pregledate plan. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +Želite da budete sigurni da ste pružili dobru količinu detalja kako bi OpenCode bio ispravan +promjene. + +--- + +### Poništi promjene + +Recimo da tražite od OpenCodea da izvrši neke promjene. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Ali shvatate da to nije ono što ste želeli. Možete **poništiti** promjene +koristeći naredbu `/undo`. + +```bash frame="none" +/undo +``` + +OpenCode će sada poništiti promjene koje ste napravili i prikazati vašu originalnu poruku +opet. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Odavde možete podesiti prompt i zamoliti OpenCode da pokuša ponovo. +:::tip +Možete pokrenuti `/undo` više puta da poništite više promjena. +::: +Ili **možete ponoviti** promjene koristeći naredbu `/redo`. + +```bash frame="none" +/redo +``` + +--- + +## Dijeli + +Razgovore koje imate sa OpenCodeom možete [dijeliti sa vašim +tim](/docs/share). + +```bash frame="none" +/share +``` + +Ovo će kreirati vezu do trenutnog razgovora i kopirati je u međuspremnik. +:::note +Razgovori se ne dijele prema zadanim postavkama. +::: +Evo [primjer razgovora](https://opencode.ai/s/4XP1fce5) sa OpenCodeom. + +--- + +## Prilagodi + +I to je to! Sada ste profesionalac u korištenju OpenCodea. +Da biste to učinili svojim, preporučujemo [odabir teme](/docs/themes), [prilagođavanje povezivanja tipki](/docs/keybinds), [konfiguriranje formatera koda](/docs/formatters), [kreiranje prilagođenih komandi](/docs/commands), ili igranje sa [OpenCode config](/docs/config). diff --git a/packages/web/src/content/docs/bs/keybinds.mdx b/packages/web/src/content/docs/bs/keybinds.mdx new file mode 100644 index 000000000..d586d56d3 --- /dev/null +++ b/packages/web/src/content/docs/bs/keybinds.mdx @@ -0,0 +1,182 @@ +--- +title: Keybinds +description: Prilagodite svoje veze dugmadi. +--- + +OpenCode ima listu veza ključeva koje možete prilagoditi preko OpenCode konfiguracije. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## Leader key +OpenCode koristi `leader` ključ za većinu povezivanja tipki. Ovo izbjegava sukobe u vašem terminalu. +Prema zadanim postavkama, `ctrl+x` je vodeći taster i većina radnji zahtijeva da prvo pritisnete vodeći taster, a zatim i prečicu. Na primjer, da biste započeli novu sesiju, prvo pritisnite `ctrl+x`, a zatim pritisnite `n`. +Ne morate koristiti vodeći ključ za svoje veze tipki, ali preporučujemo da to učinite. + +--- + +## Onemogući povezivanje tastera +Možete onemogućiti spajanje tipki dodavanjem ključa u svoju konfiguraciju s vrijednošću "none". + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## Prečice za radnu površinu +Unos prompta aplikacije OpenCode za desktop podržava uobičajene prečice u stilu Readline/Emacs za uređivanje teksta. Oni su ugrađeni i trenutno se ne mogu konfigurirati putem `opencode.json`. +| Prečica | Akcija || -------- | ---------------------------------------- | +| `ctrl+a` | Prelazak na početak tekućeg reda | +| `ctrl+e` | Prelazak na kraj trenutnog reda | +| `ctrl+b` | Pomeri kursor za jedan znak unazad | +| `ctrl+f` | Pomicanje kursora naprijed za jedan znak | +| `alt+b` | Pomeri kursor za jednu reč unazad | +| `alt+f` | Pomeri kursor za jednu reč unapred | +| `ctrl+d` | Izbriši znak ispod kursora | +| `ctrl+k` | Ubiti do kraja reda | +| `ctrl+u` | Kill do početka reda | +| `ctrl+w` | Ubiti prethodnu riječ | +| `alt+d` | Ubiti sljedeću riječ | +| `ctrl+t` | Transponirajte znakove | +| `ctrl+g` | Otkaži iskakanje / poništi odgovor na pokretanje | + +--- + +## Shift+Enter +Neki terminali ne šalju modifikatorske tipke sa Enter prema zadanim postavkama. Možda ćete trebati konfigurirati svoj terminal da pošalje `Shift+Enter` kao escape sekvencu. +### Windows terminal +Otvorite svoj `settings.json` na: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +Dodajte ovo u niz korijenskog nivoa `actions`: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Dodajte ovo u niz korijenskog nivoa `keybindings`: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Sačuvajte datoteku i ponovo pokrenite Windows Terminal ili otvorite novu karticu. \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/lsp.mdx b/packages/web/src/content/docs/bs/lsp.mdx new file mode 100644 index 000000000..caf7ddaf5 --- /dev/null +++ b/packages/web/src/content/docs/bs/lsp.mdx @@ -0,0 +1,160 @@ +--- +title: LSP serveri +description: OpenCode se integriše sa vašim LSP serverima. +--- + +OpenCode se integriše sa vašim jezičkim serverskim protokolom (LSP) kako bi pomogao LLM-u u interakciji s vašom bazom koda. Koristi dijagnostiku za pružanje povratnih informacija LLM-u. +--- + +## Ugrađeno +OpenCode dolazi sa nekoliko ugrađenih LSP servera za popularne jezike: +| LSP server | Ekstenzije | Zahtjevi || ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +| astro | .astro | Automatske instalacije za Astro projekte | +| bash | .sh, .bash, .zsh, .ksh | Automatski instalira bash-language-server | +| clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Automatske instalacije za C/C++ projekte | +| csharp | .cs | `.NET SDK` instaliran | +| clojure-lsp | .clj, .cljs, .cljc, .edn | `clojure-lsp` komanda dostupna | +| dart | .dart | `dart` komanda dostupna | +| deno | .ts, .tsx, .js, .jsx, .mjs | `deno` komanda dostupna (automatski detektuje deno.json/deno.jsonc) | +| elixir-ls | .ex, .exs | `elixir` komanda dostupna | +| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` ovisnost u projektu | +| fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` instaliran | +| sjaj | .bleam | `gleam` komanda dostupna | +| gopls | .go | `go` komanda dostupna | +| hls | .hs, .lhs | `haskell-language-server-wrapper` komanda dostupna | +| jdtls | .java | `Java SDK (version 21+)` instaliran | +| kotlin-ls | .kt, .kts | Automatske instalacije za Kotlin projekte | +| lua-ls | .lua | Automatske instalacije za Lua projekte | +| nixd | .nix | `nixd` komanda dostupna | +| ocaml-lsp | .ml, .mli | `ocamllsp` komanda dostupna | +| oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | `oxlint` zavisnost u projektu | +| php intelephense | .php | Automatske instalacije za PHP projekte | +| prisma | .prisma | `prisma` komanda dostupna | +| pyright | .py, .pyi | `pyright` ovisnost instalirana | +| ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | `ruby` i `gem` komande dostupne | +| hrđa | .rs | `rust-analyzer` komanda dostupna | +| sourcekit-lsp | .swift, .objc, .objcpp | `swift` instaliran (`xcode` na macOS-u) | +| vitka | .svelte | Automatske instalacije za Svelte projekte | +| terraform | .tf, .tfvars | Automatske instalacije iz GitHub izdanja | +| tinymist | .typ, .typc | Automatske instalacije iz GitHub izdanja | +| strojopis | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` zavisnost u projektu | +| vue | .vue | Automatske instalacije za Vue projekte | +| yaml-ls | .yaml, .yml | Automatski instalira Red Hat yaml-language-server | +| zls | .zig, .zon | `zig` komanda dostupna | +LSP serveri su automatski omogućeni kada se otkrije jedna od gore navedenih ekstenzija datoteke i zahtjevi su ispunjeni. +:::napomena +Možete onemogućiti automatska preuzimanja LSP servera tako što ćete postaviti varijablu okruženja `OPENCODE_DISABLE_LSP_DOWNLOAD` na `true`. +::: + +--- + +## Kako radi +Kada opencode otvori fajl, on: +1. Provjerava ekstenziju datoteke u odnosu na sve omogućene LSP servere. +2. Pokreće odgovarajući LSP server ako već nije pokrenut. +--- + +## Konfiguriši +Možete prilagoditi LSP servere kroz `lsp` odjeljak u vašoj opencode konfiguraciji. +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Svaki LSP server podržava sljedeće: +| Nekretnine | Vrsta | Opis || ---------------- | -------- | ------------------------------------------------- | +| `disabled` | boolean | Postavite ovo na `true` da onemogućite LSP server | +| `command` | string[] | Naredba za pokretanje LSP servera | +| `extensions` | string[] | Ekstenzije datoteka koje ovaj LSP server treba da rukuje | +| `env` | objekt | Varijable okruženja koje treba postaviti prilikom pokretanja servera | +| `initialization` | objekt | Opcije inicijalizacije za slanje na LSP server | +Pogledajmo neke primjere. +--- + +### Varijable okruženja +Koristite svojstvo `env` za postavljanje varijabli okruženja prilikom pokretanja LSP servera: +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### Opcije inicijalizacije +Koristite svojstvo `initialization` da prosledite opcije inicijalizacije na LSP server. Ovo su postavke specifične za server poslane tokom LSP `initialize` zahtjeva: +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::napomena +Opcije inicijalizacije razlikuju se od LSP servera. Provjerite dokumentaciju vašeg LSP servera za dostupne opcije. +::: + +--- + +### Onemogućavanje LSP servera +Da biste onemogućili **sve** LSP servere globalno, postavite `lsp` na `false`: +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +Da onemogućite **specifičan** LSP server, postavite `disabled` na `true`: +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Prilagođeni LSP serveri +Možete dodati prilagođene LSP servere navodeći ekstenzije naredbe i datoteke: +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## Dodatne informacije +### PHP Intelephense +PHP Intelephense nudi vrhunske funkcije putem licencnog ključa. Možete dati licencni ključ postavljanjem (samo) ključa u tekstualnu datoteku na: +- Na macOS/Linuxu: `$HOME/intelephense/licence.txt` +- Na Windowsima: `%USERPROFILE%/intelephense/licence.txt` +Datoteka treba da sadrži samo licencni ključ bez dodatnog sadržaja. \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/mcp-servers.mdx b/packages/web/src/content/docs/bs/mcp-servers.mdx new file mode 100644 index 000000000..90b5f03d8 --- /dev/null +++ b/packages/web/src/content/docs/bs/mcp-servers.mdx @@ -0,0 +1,432 @@ +--- +title: MCP serveri +description: Dodajte lokalne i udaljene MCP alate. +--- + +Možete dodati vanjske alate u OpenCode koristeći _Model Context Protocol_, ili MCP. OpenCode podržava i lokalne i udaljene servere. +Jednom dodani, MCP alati su automatski dostupni LLM-u zajedno sa ugrađenim alatima. +--- + +#### Upozorenja +Kada koristite MCP server, on dodaje u kontekst. Ovo se može brzo zbrojiti ako imate puno alata. Stoga preporučujemo da pazite koje MCP servere koristite. +:::tip +MCP serveri dodaju vaš kontekst, tako da želite da budete pažljivi s tim koje ćete omogućiti. +::: + +Određeni MCP serveri, poput GitHub MCP servera, imaju tendenciju da dodaju mnogo tokena i lako mogu premašiti ograničenje konteksta. +--- + +## Omogući +Možete definirati MCP servere u vašoj [OpenCode Config](https://opencode.ai/docs/config/) pod `mcp`. Dodajte svaki MCP sa jedinstvenim imenom. Možete se pozvati na taj MCP po imenu kada tražite LLM. +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +Također možete onemogućiti server postavljanjem `enabled` na `false`. Ovo je korisno ako želite privremeno onemogućiti server bez uklanjanja iz vaše konfiguracije. +--- + +### Poništavanje daljinskih zadanih postavki +Organizacije mogu obezbijediti zadane MCP servere preko svoje krajnje tačke `.well-known/opencode`. Ovi serveri mogu biti onemogućeni prema zadanim postavkama, omogućavajući korisnicima da se odluče za one koji su im potrebni. +Da omogućite određeni server iz udaljene konfiguracije vaše organizacije, dodajte ga u svoju lokalnu konfiguraciju sa `enabled: true`: +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +Vrijednosti vaše lokalne konfiguracije nadjačavaju udaljene zadane postavke. Pogledajte [config precedence](/docs/config#precedence-order) za više detalja. +--- + +## Lokalno +Dodajte lokalne MCP servere koristeći `type` u `"local"` unutar MCP objekta. +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +Naredba je način na koji se pokreće lokalni MCP server. Također možete proslijediti listu varijabli okruženja. +Na primjer, evo kako možete dodati testni [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP server. +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +I da ga koristim mogu dodati `use the mcp_everything tool` u svoje upite. +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### Opcije +Ovdje su sve opcije za konfiguriranje lokalnog MCP servera. +| Opcija | Vrsta | Obavezno | Opis || ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | String | Y | Tip veze sa MCP serverom, mora biti `"local"`. | +| `command` | Niz | Y | Naredba i argumenti za pokretanje MCP servera. | +| `environment` | Objekt | | Varijable okruženja koje treba postaviti prilikom pokretanja servera. | +| `enabled` | Boolean | | Omogućite ili onemogućite MCP server pri pokretanju. | +| `timeout` | Broj | | Vremensko ograničenje u ms za dohvaćanje alata sa MCP servera. Podrazumevano je 5000 (5 sekundi). | +--- + +## Daljinski +Dodajte udaljene MCP servere postavljanjem `type` na `"remote"`. +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` je URL udaljenog MCP servera i sa opcijom `headers` možete proslijediti listu zaglavlja. +--- + +#### Opcije +| Opcija | Vrsta | Obavezno | Opis || --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | String | Y | Tip veze sa MCP serverom, mora biti `"remote"`. | +| `url` | String | Y | URL udaljenog MCP servera. | +| `enabled` | Boolean | | Omogućite ili onemogućite MCP server pri pokretanju. | +| `headers` | Objekt | | Zaglavlja za slanje uz zahtjev. | +| `oauth` | Objekt | | Konfiguracija OAuth provjere autentičnosti. Pogledajte odjeljak [OAuth](#oauth) ispod. | +| `timeout` | Broj | | Vremensko ograničenje u ms za preuzimanje alata sa MCP servera. Podrazumevano je 5000 (5 sekundi). | +--- + +## OAuth +OpenCode automatski rukuje OAuth autentifikacijom za udaljene MCP servere. Kada server zahtijeva autentifikaciju, OpenCode će: +1. Otkrijte 401 odgovor i pokrenite OAuth tok +2. Koristite **Dynamic Client Registration (RFC 7591)** ako podržava server +3. Sigurno čuvajte tokene za buduće zahtjeve +--- + +### Automatski +Za većinu MCP servera sa omogućenim OAuthom nije potrebna posebna konfiguracija. Samo konfigurirajte udaljeni server: +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +Ako server zahtijeva autentifikaciju, OpenCode će od vas zatražiti autentifikaciju kada prvi put pokušate da ga koristite. Ako ne, možete [ručno pokrenuti tok](#authenticating) sa `opencode mcp auth `. +--- + +### Prethodno registrovano +Ako imate klijentske vjerodajnice od dobavljača MCP servera, možete ih konfigurirati: +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### Autentifikacija +Možete ručno pokrenuti autentifikaciju ili upravljati vjerodajnicama. +Autentifikacija sa određenim MCP serverom: +```bash +opencode mcp auth my-oauth-server +``` + +Navedite sve MCP servere i njihov status autentifikacije: +```bash +opencode mcp list +``` + +Uklonite pohranjene vjerodajnice: +```bash +opencode mcp logout my-oauth-server +``` + +Komanda `mcp auth` će otvoriti vaš pretraživač za autorizaciju. Nakon što odobrite, OpenCode će sigurno pohraniti tokene u `~/.local/share/opencode/mcp-auth.json`. +--- + +#### Onemogućavanje OAuth-a +Ako želite onemogućiti automatski OAuth za server (npr. za servere koji umjesto toga koriste API ključeve), postavite `oauth` na `false`: +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### OAuth opcije +| Opcija | Vrsta | Opis || -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` | Objekt \| false | OAuth konfiguracijski objekt, ili `false` da onemogućite automatsko otkrivanje OAuth. | +| `clientId` | String | ID OAuth klijenta. Ako nije navedeno, pokušat će se izvršiti dinamička registracija klijenta. | +| `clientSecret` | String | Tajna OAuth klijenta, ako to zahtijeva autorizacijski server. | +| `scope` | String | OAuth opseg zahtjeva za vrijeme autorizacije. | +#### Otklanjanje grešaka +Ako udaljeni MCP server ne uspije u autentifikaciji, možete dijagnosticirati probleme pomoću: +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +Komanda `mcp debug` pokazuje trenutni status auth, testira HTTP povezanost i pokušava tok otkrivanja OAuth. +--- + +## Upravljaj +Vaši MCP-ovi su dostupni kao alati u OpenCode-u, zajedno sa ugrađenim alatima. Tako da možete upravljati njima kroz OpenCode konfiguraciju kao i svaki drugi alat. +--- + +### Global +To znači da ih možete omogućiti ili onemogućiti globalno. +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +Također možemo koristiti glob obrazac da onemogućimo sve odgovarajuće MCP-ove. +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +Ovdje koristimo glob obrazac `my-mcp*` da onemogućimo sve MCP-ove. +--- + +### Po agentu +Ako imate veliki broj MCP servera, možda ćete želeti da ih omogućite samo po agentu i da ih onemogućite globalno. Da biste to učinili: +1. Onemogućite ga kao alat globalno. +2. U vašem [agent config](/docs/agents#tools), omogućite MCP server kao alat. +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### Glob uzorci +Uzorak glob koristi jednostavne šablone globbiranja regularnih izraza: +- `*` odgovara nuli ili više bilo kojeg znaka (npr. `"my-mcp*"` odgovara `my-mcp_search`, `my-mcp_list`, itd.) +- `?` odgovara tačno jednom znaku +- Svi ostali likovi se bukvalno podudaraju +:::napomena +MCP serverski alati se registruju sa imenom servera kao prefiksom, tako da onemogućite sve alate za server jednostavno koristite: +``` +"mymcpservername_*": false +``` + +::: + +--- + +## Primjeri +Ispod su primjeri nekih uobičajenih MCP servera. Možete poslati PR ako želite dokumentirati druge servere. +--- + +### Stražar +Dodajte [Sentry MCP server](https://mcp.sentry.dev) za interakciju sa vašim Sentry projektima i problemima. +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +Nakon dodavanja konfiguracije, autentifikujte se sa Sentry: +```bash +opencode mcp auth sentry +``` + +Ovo će otvoriti prozor pretraživača da završite OAuth tok i povežete OpenCode sa vašim Sentry nalogom. +Nakon provjere autentičnosti, možete koristiti Sentry alate u svojim upitima za upite o problemima, projektima i podacima o greškama. +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Kontekst7 +Dodajte [Context7 MCP server](https://github.com/upstash/context7) za pretraživanje dokumenata. +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +Ako ste se prijavili za besplatni račun, možete koristiti svoj API ključ i dobiti viša ograničenja stope. +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +Ovdje pretpostavljamo da imate postavljenu varijablu okruženja `CONTEXT7_API_KEY`. +Dodajte `use context7` vašim upitima za korištenje Context7 MCP servera. +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +Alternativno, možete dodati nešto poput ovoga na svoj [AGENTS.md](/docs/rules/). +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep od Vercela +Dodajte [Grep by Vercel](https://grep.app) MCP server za pretraživanje isječaka koda na GitHubu. +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +Pošto smo naš MCP server nazvali `gh_grep`, možete dodati `use the gh_grep tool` u svoje upite da natjerate agenta da ga koristi. +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +Alternativno, možete dodati nešto poput ovoga na svoj [AGENTS.md](/docs/rules/). +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/bs/models.mdx b/packages/web/src/content/docs/bs/models.mdx new file mode 100644 index 000000000..3e755e4a1 --- /dev/null +++ b/packages/web/src/content/docs/bs/models.mdx @@ -0,0 +1,186 @@ +--- +title: Modeli +description: Konfiguriranje LLM provajdera i modela. +--- + +OpenCode koristi [AI SDK](https://ai-sdk.dev/) i [Models.dev](https://models.dev) za podršku **75+ LLM provajdera** i podržava pokretanje lokalnih modela. +--- + +## Provajderi +Većina popularnih provajdera su unaprijed učitani prema zadanim postavkama. Ako ste dodali vjerodajnice za provajdera putem naredbe `/connect`, oni će biti dostupni kada pokrenete OpenCode. +Saznajte više o [providers](/docs/providers). +--- + +## Odaberite model +Nakon što konfigurirate svog provajdera, možete odabrati model koji želite upisivanjem: +```bash frame="none" +/models +``` + +--- + +## Preporučeni modeli +Postoji mnogo modela vani, a novi modeli izlaze svake sedmice. +:::tip +Razmislite o korištenju jednog od modela koje preporučujemo. +::: + +Međutim, postoji samo nekoliko njih koji su dobri i u generiranju koda i u pozivanju alata. +Evo nekoliko modela koji dobro rade sa OpenCodeom, bez posebnog redosleda. (Ovo nije potpuna lista niti je nužno ažurirana): +- GPT 5.2 +- Kodeks GPT 5.1 +- Claude Opus 4.5 +- Claude Sonet 4.5 +- Minimax M2.1 +- Gemini 3 Pro +--- + +## Postavite zadano +Da postavite jedan od ovih kao zadani model, možete postaviti ključ `model` u svom +OpenCode config. +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Ovdje je puni ID `provider_id/model_id`. Na primjer, ako koristite [OpenCode Zen](/docs/zen), koristili biste `opencode/gpt-5.1-codex` za GPT 5.1 Codex. +Ako ste konfigurirali [prilagođenog provajdera](/docs/providers#custom), `provider_id` je ključ iz `provider` dijela vaše konfiguracije, a `model_id` je ključ iz `provider.models`. +--- + +## Konfigurišite modele +Možete globalno konfigurirati opcije modela kroz config. +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Ovdje konfiguriramo globalne postavke za dva ugrađena modela: `gpt-5` kada se pristupa preko `openai` provajdera i `claude-sonnet-4-20250514` kada se pristupa preko `anthropic` provajdera. +Ugrađeni dobavljač i nazivi modela mogu se naći na [Models.dev](https://models.dev). +Također možete konfigurirati ove opcije za sve agente koje koristite. Konfiguracija agenta poništava sve globalne opcije ovdje. [Saznajte više](/docs/agents/#additional). +Također možete definirati prilagođene varijante koje proširuju ugrađene. Varijante vam omogućavaju da konfigurirate različite postavke za isti model bez stvaranja duplih unosa: +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## Varijante +Mnogi modeli podržavaju više varijanti sa različitim konfiguracijama. OpenCode se isporučuje sa ugrađenim podrazumevanim varijantama za popularne provajdere. +### Ugrađene varijante +OpenCode se isporučuje sa zadanim varijantama za mnoge provajdere: +**Antropski**: +- `high` - Visok budžet za razmišljanje (zadano) +- `max` - Maksimalni budžet za razmišljanje +**OpenAI**: +Zavisi od modela, ali otprilike: +- `none` - Bez obrazloženja +- `minimal` - Minimalni napor za rasuđivanje +- `low` - Nizak napor u rasuđivanju +- `medium` - Srednji napor u zaključivanju +- `high` - Veliki napor u rasuđivanju +- `xhigh` - Ekstra visok napor u rasuđivanju +**Google**: +- `low` - Manji trud/budžet tokena +- `high` - Veći budžet za trud/token +:::tip +Ova lista nije sveobuhvatna. Mnogi drugi provajderi također imaju ugrađene zadane postavke. +::: + +### Prilagođene varijante +Možete nadjačati postojeće varijante ili dodati svoje: +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### Varijante ciklusa +Koristite vezu `variant_cycle` za brzo prebacivanje između varijanti. [Saznajte više](/docs/keybinds). +--- + +## Učitavanje modela +Kada se OpenCode pokrene, on provjerava modele u sljedećem prioritetnom redoslijedu: +1. Oznaka komandne linije `--model` ili `-m`. Format je isti kao u konfiguracijskoj datoteci: `provider_id/model_id`. +2. Lista modela u OpenCode konfiguraciji. + + +```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + + +``` + +Format ovdje je `provider/model`. +3. Posljednji korišteni model. +4. Prvi model koji koristi interni prioritet. \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/modes.mdx b/packages/web/src/content/docs/bs/modes.mdx new file mode 100644 index 000000000..9731600cb --- /dev/null +++ b/packages/web/src/content/docs/bs/modes.mdx @@ -0,0 +1,283 @@ +--- +title: Načini rada +description: Različiti načini za različite slučajeve upotrebe. +--- + +:::oprez +Načini se sada konfiguriraju preko opcije `agent` u konfiguraciji otvorenog koda. The +`mode` opcija je sada zastarjela. [Saznajte više](/docs/agents). +::: + +Režimi u otvorenom kodu omogućavaju vam da prilagodite ponašanje, alate i upite za različite slučajeve upotrebe. +Dolazi sa dva ugrađena načina rada: **gradite** i **planirajte**. Možete prilagoditi +ove ili konfigurirajte svoje putem opencode config. +Možete se prebacivati ​​između režima tokom sesije ili ih konfigurisati u svom konfiguracionom fajlu. +--- + +## Ugrađeno +opencode dolazi sa dva ugrađena načina rada. +--- + +### Build +Izrada je **podrazumevani** režim sa svim omogućenim alatima. Ovo je standardni način rada na razvoju gdje vam je potreban pun pristup operacijama datoteka i sistemskim komandama. +--- + +### Plan +Ograničeni način rada dizajniran za planiranje i analizu. U načinu plana, sljedeći alati su onemogućeni prema zadanim postavkama: +- `write` - Ne mogu kreirati nove fajlove +- `edit` - Ne mogu modificirati postojeće fajlove, osim fajlova koji se nalaze na `.opencode/plans/*.md` radi detaljiziranja samog plana +- `patch` - Ne mogu primijeniti zakrpe +- `bash` - Ne mogu izvršiti naredbe ljuske +Ovaj način rada je koristan kada želite da AI analizira kod, predlaže promjene ili kreira planove bez ikakvih stvarnih modifikacija u vašoj bazi kodova. +--- + +## Prebacivanje +Možete se prebacivati ​​između načina rada tokom sesije pomoću tipke _Tab_. Ili vaše konfigurirano `switch_mode` spajanje tipki. +Vidi također: [Formatters](/docs/formatters) za informacije o konfiguraciji formatiranja koda. +--- + +## Konfiguriši +Možete prilagoditi ugrađene načine rada ili kreirati vlastite kroz konfiguraciju. Modovi se mogu konfigurirati na dva načina: +### JSON konfiguracija +Konfigurirajte načine rada u svom `opencode.json` konfiguracijskom fajlu: +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Markdown konfiguracija +Također možete definirati načine rada koristeći mardown datoteke. Postavite ih u: +- Globalno: `~/.config/opencode/modes/` +- Projekat: `.opencode/modes/` +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Naziv datoteke s uštedom postaje naziv načina (npr. `review.md` kreira `review` način rada). +Pogledajmo ove opcije konfiguracije detaljno. +--- + +### Model +Koristite `model` konfiguraciju da nadjačate zadani model za ovaj način rada. Korisno za korištenje različitih modela optimiziranih za različite zadatke. Na primjer, brži model za planiranje, sposobniji model za implementaciju. +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Temperatura +Kontrolišite slučajnost i kreativnost odgovora AI pomoću `temperature` konfiguracije. Niže vrijednosti čine odgovore fokusiranijim i determinističkim, dok veće vrijednosti povećavaju kreativnost i varijabilnost. +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Vrijednosti temperature obično se kreću od 0,0 do 1,0: +- **0,0-0,2**: Vrlo fokusirani i deterministički odgovori, idealni za analizu i planiranje koda +- **0,3-0,5**: Uravnoteženi odgovori sa malo kreativnosti, dobro za opšte razvojne zadatke +- **0,6-1,0**: kreativniji i raznovrsniji odgovori, korisni za razmišljanje i istraživanje +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Ako temperatura nije navedena, opencode koristi zadane postavke specifične za model (obično 0 za većinu modela, 0,55 za Qwen modele). +--- + +### Prompt +Navedite prilagođenu sistemsku datoteku prompta za ovaj način rada s konfiguracijom `prompt`. Datoteka s promptom treba da sadrži upute specifične za svrhu načina rada. +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Ova putanja je relativna u odnosu na mjesto gdje se nalazi konfiguracijski fajl. Dakle, ovo radi za +i globalnu konfiguraciju otvorenog koda i konfiguraciju specifične za projekat. +--- + +### Alati +Kontrolirajte koji su alati dostupni u ovom načinu rada pomoću `tools` konfiguracije. Možete omogućiti ili onemogućiti određene alate tako što ćete ih postaviti na `true` ili `false`. +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +Ako nijedan alat nije specificiran, svi alati su omogućeni prema zadanim postavkama. +--- + +#### Dostupni alati +Ovdje su svi alati koji se mogu kontrolirati kroz konfiguraciju načina rada. +| Alat | Opis || ----------- | ----------------------- | +| `bash` | Izvrši naredbe ljuske | +| `edit` | Izmijenite postojeće datoteke | +| `write` | Kreirajte nove fajlove | +| `read` | Pročitajte sadržaj datoteke | +| `grep` | Pretraži sadržaj datoteke | +| `glob` | Pronađite datoteke po uzorku | +| `list` | Lista sadržaja direktorija | +| `patch` | Primijenite zakrpe na datoteke | +| `todowrite` | Upravljanje listama zadataka | +| `todoread` | Pročitajte liste obaveza | +| `webfetch` | Dohvati web sadržaj | +--- + +## Prilagođeni načini rada +Možete kreirati vlastite prilagođene modove tako što ćete ih dodati u konfiguraciju. Evo primjera koji koriste oba pristupa: +### Korištenje JSON konfiguracije +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Korištenje mardown fajlova +Kreirajte fajlove načina u `.opencode/modes/` za specifične načine rada ili `~/.config/opencode/modes/` za globalne načine: +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### Slučajevi upotrebe +Evo nekoliko uobičajenih slučajeva upotrebe za različite načine rada. +- **Način izgradnje**: Potpuni razvojni rad sa svim omogućenim alatima +- **Način planiranja**: Analiza i planiranje bez izmjena +- **Review mode**: Pregled koda sa pristupom samo za čitanje plus alati za dokumentaciju +- **Režim za otklanjanje grešaka**: Fokusiran na istragu sa omogućenim bash i alatima za čitanje +- **Režim dokumenata**: Pisanje dokumentacije sa operacijama datoteka, ali bez sistemskih naredbi +Možda ćete također otkriti da su različiti modeli dobri za različite slučajeve upotrebe. \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/network.mdx b/packages/web/src/content/docs/bs/network.mdx new file mode 100644 index 000000000..31d8d3d85 --- /dev/null +++ b/packages/web/src/content/docs/bs/network.mdx @@ -0,0 +1,48 @@ +--- +title: Mreža +description: Konfigurirajte proksije i prilagođene certifikate. +--- + +OpenCode podržava standardne varijable proxy okruženja i prilagođene sertifikate za mrežna okruženja preduzeća. +--- + +## Proxy +OpenCode poštuje standardne varijable proxy okruženja. +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::oprez +TUI komunicira sa lokalnim HTTP serverom. Morate zaobići proxy za ovu vezu kako biste spriječili petlje usmjeravanja. +::: + +Možete konfigurirati port servera i ime hosta koristeći [CLI flags](/docs/cli#run). +--- + +### Autentikacija +Ako vaš proxy zahtijeva osnovnu autentifikaciju, uključite vjerodajnice u URL. +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::oprez +Izbjegavajte tvrdo kodiranje lozinki. Koristite varijable okruženja ili sigurno skladište vjerodajnica. +::: + +Za proxy servere koji zahtijevaju naprednu autentifikaciju kao što je NTLM ili Kerberos, razmislite o korištenju LLM Gatewaya koji podržava vašu metodu provjere autentičnosti. +--- + +## Prilagođeni certifikati +Ako vaše preduzeće koristi prilagođene CA-ove za HTTPS veze, konfigurirajte OpenCode da im vjeruje. +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +Ovo radi i za proxy veze i za direktan pristup API-ju. \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/permissions.mdx b/packages/web/src/content/docs/bs/permissions.mdx new file mode 100644 index 000000000..79e4a9b63 --- /dev/null +++ b/packages/web/src/content/docs/bs/permissions.mdx @@ -0,0 +1,201 @@ +--- +title: Dozvole +description: Kontrolirajte koje radnje zahtijevaju odobrenje za pokretanje. +--- + +OpenCode koristi `permission` konfiguraciju da odluči da li će se određena radnja pokrenuti automatski, zatražiti od vas ili biti blokirana. +Od `v1.1.1`, naslijeđena `tools` logička konfiguracija je zastarjela i spojena je u `permission`. Stara `tools` konfiguracija je još uvijek podržana za kompatibilnost unatrag. +--- + +## Akcije +Svako pravilo dozvole rješava jedno od: +- `"allow"` — pokrenuti bez odobrenja +- `"ask"` — upit za odobrenje +- `"deny"` — blokiraj akciju +--- + +## Konfiguracija +Dozvole možete postaviti globalno (sa `*`) i nadjačati određene alate. +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +Također možete postaviti sve dozvole odjednom: +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## Granularna pravila (sintaksa objekta) +Za većinu dozvola, možete koristiti objekt za primjenu različitih radnji na osnovu unosa alata. +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +Pravila se procjenjuju na osnovu podudaranja uzorka, pri čemu **pobjeđuje **poslednje odgovarajuće pravilo**. Uobičajeni obrazac je da se prvo pravilo `"*"` stavi sveobuhvatno, a poslije njega konkretnija pravila. +### Zamjenski znakovi +Uzorci dozvola koriste jednostavno podudaranje zamjenskih znakova: +- `*` odgovara nula ili više bilo kojeg znaka +- `?` odgovara tačno jednom znaku +- Svi ostali likovi se bukvalno podudaraju +### Proširenje kućnog imenika +Možete koristiti `~` ili `$HOME` na početku obrasca da referencirate svoj početni direktorij. Ovo je posebno korisno za [`external_directory`](#external-directories) pravila. +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` +### Vanjski imenici +Koristite `external_directory` da dozvolite pozive alata koji dodiruju putanje izvan radnog direktorija gdje je OpenCode pokrenut. Ovo se odnosi na bilo koji alat koji uzima putanju kao ulaz (na primjer `read`, `edit`, `list`, `glob`, `grep` i mnoge `bash` komande). +Proširenje kuće (poput `~/...`) utiče samo na način na koji je obrazac napisan. Ne čini vanjsku stazu dijelom trenutnog radnog prostora, tako da staze izvan radnog direktorija i dalje moraju biti dozvoljene preko `external_directory`. +Na primjer, ovo omogućava pristup svemu pod `~/projects/personal/`: +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +Svaki direktorij koji je ovdje dozvoljen nasljeđuje iste zadane postavke kao trenutni radni prostor. Pošto je [`read` zadano na `allow`](#defaults), čitanje je također dozvoljeno za unose pod `external_directory` osim ako se ne poništi. Dodajte eksplicitna pravila kada bi alat trebao biti ograničen na ovim stazama, kao što je blokiranje uređivanja uz zadržavanje čitanja: +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +Neka lista bude fokusirana na pouzdane staze, a dodatni sloj dozvoljava ili odbija pravila prema potrebi za druge alate (na primjer `bash`). +--- + +## Dostupne dozvole +Dozvole OpenCode-a su označene imenom alata, plus nekoliko sigurnosnih mjera: +- `read` — čitanje datoteke (odgovara putanji datoteke) +- `edit` — sve izmjene fajlova (pokriva `edit`, `write`, `patch`, `multiedit`) +- `glob` — globbiranje fajla (odgovara glob uzorku) +- `grep` — pretraga sadržaja (podudara se sa regularnim izrazom) +- `list` — lista fajlova u direktorijumu (podudara se sa putanjom direktorijuma) +- `bash` — izvođenje komandi ljuske (podudara se s raščlanjenim komandama kao što je `git status --porcelain`) +- `task` — pokretanje subagenta (odgovara tipu podagenta) +- `skill` — učitavanje vještine (odgovara nazivu vještine) +- `lsp` — pokretanje LSP upita (trenutno negranularno) +- `todoread`, `todowrite` — čitanje/ažuriranje liste obaveza +- `webfetch` — dohvaćanje URL-a (odgovara URL-u) +- `websearch`, `codesearch` — pretraživanje weba/koda (odgovara upitu) +- `external_directory` — pokreće se kada alat dodirne staze izvan radnog direktorija projekta +- `doom_loop` — aktivira se kada se isti poziv alata ponovi 3 puta sa identičnim unosom +--- + +## Defaults +Ako ništa ne navedete, OpenCode počinje od dozvoljenih zadanih vrijednosti: +- Većina dozvola je zadana na `"allow"`. +- `doom_loop` i `external_directory` zadano na `"ask"`. +- `read` je `"allow"`, ali `.env` fajlovi su po defaultu odbijeni: +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## Šta radi “Ask”. +Kada OpenCode zatraži odobrenje, korisničko sučelje nudi tri ishoda: +- `once` — odobri samo ovaj zahtjev +- `always` — odobri buduće zahtjeve koji odgovaraju predloženim obrascima (za ostatak trenutne OpenCode sesije) +- `reject` — odbiti zahtjev +Skup obrazaca koje bi `always` odobrio pruža alat (na primjer, bash odobrenja obično stavljaju na bijelu listu sigurni prefiks komande kao što je `git status*`). +--- + +## Agenti +Možete nadjačati dozvole po agentu. Dozvole agenta su spojene sa globalnom konfiguracijom, a pravila agenta imaju prednost. [Saznajte više](/docs/agents#permissions) o dozvolama agenta. +:::napomena +Pogledajte gornji odjeljak [Granularna pravila (sintaksa objekata)](#granular-rules-object-syntax) za detaljnije primjere podudaranja uzoraka. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +Također možete konfigurirati dozvole agenta u Markdownu: +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tip +Koristite podudaranje uzoraka za naredbe s argumentima. `"grep *"` dozvoljava `grep pattern file.txt`, dok bi ga samo `"grep"` blokirao. Naredbe poput `git status` rade za zadano ponašanje, ali zahtijevaju eksplicitnu dozvolu (kao `"git status *"`) kada se prosljeđuju argumenti. +::: diff --git a/packages/web/src/content/docs/bs/plugins.mdx b/packages/web/src/content/docs/bs/plugins.mdx new file mode 100644 index 000000000..99346fe2e --- /dev/null +++ b/packages/web/src/content/docs/bs/plugins.mdx @@ -0,0 +1,309 @@ +--- +title: Plugins +description: Napišite vlastite dodatke za proširenje OpenCode-a. +--- + +Dodaci vam omogućavaju da proširite OpenCode spajanjem na različite događaje i prilagođavanjem ponašanja. Možete kreirati dodatke za dodavanje novih funkcija, integraciju sa eksternim uslugama ili izmenu zadanog ponašanja OpenCode-a. +Za primjere, pogledajte [plugins](/docs/ecosystem#plugins) kreirane od strane zajednice. +--- + +## Koristite dodatak +Postoje dva načina za učitavanje dodataka. +--- + +### Iz lokalnih datoteka +Postavite JavaScript ili TypeScript datoteke u direktorij dodataka. +- `.opencode/plugins/` - Dodaci na nivou projekta +- `~/.config/opencode/plugins/` - Globalni dodaci +Datoteke u ovim direktorijumima se automatski učitavaju pri pokretanju. +--- + +### Od npm +Navedite npm pakete u vašoj konfiguracijskoj datoteci. +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +Podržani su i regularni i npm paketi sa opsegom. +Pregledajte dostupne dodatke u [ecosystem](/docs/ecosystem#plugins). +--- + +### Kako se instaliraju dodaci +**npm dodaci** se instaliraju automatski pomoću Bun pri pokretanju. Paketi i njihove zavisnosti su keširani u `~/.cache/opencode/node_modules/`. +**Lokalni dodaci** se učitavaju direktno iz direktorija dodataka. Da biste koristili vanjske pakete, morate kreirati `package.json` unutar svog konfiguracijskog direktorija (pogledajte [Zavisnosti](#dependencies)) ili objaviti dodatak na npm i [dodati ga u svoju konfiguraciju](/docs/config#plugins). +--- + +### Učitaj redoslijed +Dodaci se učitavaju iz svih izvora i svi zakačnjaci rade u nizu. Redoslijed učitavanja je: +1. Globalna konfiguracija (`~/.config/opencode/opencode.json`) +2. Konfiguracija projekta (`opencode.json`) +3. Globalni direktorij dodataka (`~/.config/opencode/plugins/`) +4. Direktorij dodataka projekta (`.opencode/plugins/`) +Duplicirani npm paketi sa istim imenom i verzijom se učitavaju jednom. Međutim, lokalni dodatak i npm dodatak sa sličnim nazivima se učitavaju odvojeno. +--- + +## Kreirajte dodatak +Dodatak je **JavaScript/TypeScript modul** koji izvozi jedan ili više dodataka +funkcije. Svaka funkcija prima objekt konteksta i vraća hooks objekt. +--- + +### Zavisnosti +Lokalni dodaci i prilagođeni alati mogu koristiti vanjske npm pakete. Dodajte `package.json` u svoj konfiguracijski direktorij sa zavisnostima koje su vam potrebne. +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode pokreće `bun install` pri pokretanju da ih instalira. Vaši dodaci i alati ih zatim mogu uvesti. +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### Osnovna struktura +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +Funkcija dodatka prima: +- `project`: Trenutne informacije o projektu. +- `directory`: Trenutni radni direktorij. +- `worktree`: Putanja git radnog stabla. +- `client`: Opencode SDK klijent za interakciju sa AI. +- `$`: Bun's [shell API](https://bun.com/docs/runtime/shell) za izvršavanje naredbi. +--- + +### Podrška za TypeScript +Za TypeScript dodatke, možete uvesti tipove iz paketa dodataka: +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### Događaji +Dodaci se mogu pretplatiti na događaje kao što je prikazano ispod u odjeljku Primjeri. Evo liste različitih dostupnih događaja. +#### Komandni događaji +- `command.executed` +#### Događaji datoteka +- `file.edited` +- `file.watcher.updated` +#### Instalacijski događaji +- `installation.updated` +#### LSP događaji +- `lsp.client.diagnostics` +- `lsp.updated` +#### Poruka Događaji +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` +#### Događaji dozvole +- `permission.asked` +- `permission.replied` +#### Serverski događaji +- `server.connected` +#### Događaji sesije +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` +#### Todo događaji +- `todo.updated` +#### Shell događaji +- `shell.env` +#### Alat Događaji +- `tool.execute.after` +- `tool.execute.before` +#### TUI događaji +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` +--- + +## Primjeri +Evo nekoliko primjera dodataka koje možete koristiti za proširenje otvorenog koda. +--- + +### Šalji obavještenja +Pošaljite obavještenja kada se dogode određeni događaji: +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +Koristimo `osascript` za pokretanje AppleScript-a na macOS-u. Ovdje ga koristimo za slanje obavještenja. +:::napomena +Ako koristite desktop aplikaciju OpenCode, ona može automatski slati sistemske obavijesti kada je odgovor spreman ili kada dođe do greške u sesiji. +::: + +--- + +### .env zaštita +Spriječite opencode da čita `.env` fajlove: +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### Ubacite varijable okruženja +Ubacite varijable okruženja u sva izvršavanja ljuske (AI alati i korisnički terminali): +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### Prilagođeni alati +Dodaci također mogu dodati prilagođene alate u opencode: +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +Pomoćnik `tool` kreira prilagođeni alat koji opencode može pozvati. Uzima funkciju Zod sheme i vraća definiciju alata sa: +- `description`: Šta alat radi +- `args`: Zod šema za argumente alata +- `execute`: Funkcija koja se pokreće kada se pozove alat +Vaši prilagođeni alati će biti dostupni za opencode zajedno sa ugrađenim alatima. +--- + +### Logging +Koristite `client.app.log()` umjesto `console.log` za strukturirano bilježenje: +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +Nivoi: `debug`, `info`, `warn`, `error`. Pogledajte [SDK dokumentaciju](https://opencode.ai/docs/sdk) za detalje. +--- + +### Kuke za sabijanje +Prilagodite kontekst uključen kada se sesija zbije: +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +`experimental.session.compacting` kuka se aktivira prije nego što LLM generira sažetak nastavka. Koristite ga za ubacivanje konteksta specifičnog za domenu koji bi zadani prompt za sažimanje propustio. +Također možete u potpunosti zamijeniti prompt za sabijanje postavljanjem `output.prompt`: +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +Kada je `output.prompt` postavljen, on u potpunosti zamjenjuje zadani prompt za sažimanje. Niz `output.context` se zanemaruje u ovom slučaju. \ No newline at end of file diff --git a/packages/web/src/content/docs/bs/providers.mdx b/packages/web/src/content/docs/bs/providers.mdx new file mode 100644 index 000000000..d88115713 --- /dev/null +++ b/packages/web/src/content/docs/bs/providers.mdx @@ -0,0 +1,2413 @@ +--- +title: Provajderi +description: Korištenje bilo kojeg LLM provajdera u OpenCodeu. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode koristi [AI SDK](https://ai-sdk.dev/) i [Models.dev](https://models.dev) za podršku **75+ LLM provajdera** i podržava pokretanje lokalnih modela. + +Za dodavanje provajdera potrebno je: + +1. Dodajte API ključeve za provajdera koristeći naredbu `/connect`. +2. Konfigurirajte dobavljača u vašoj OpenCode konfiguraciji. + +--- + +### Akreditacije + +Kada dodate API ključeve dobavljača sa naredbom `/connect`, oni se pohranjuju +u `~/.local/share/opencode/auth.json`. + +--- + +### Config + +Možete prilagoditi dobavljače putem odjeljka `provider` u vašem OpenCode-u +config. + +--- + +#### Osnovni URL + +Možete prilagoditi osnovni URL za bilo kojeg provajdera postavljanjem opcije `baseURL`. Ovo je korisno kada koristite proxy usluge ili prilagođene krajnje tačke. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen je lista modela koje je obezbedio OpenCode tim koji su bili +testirano i potvrđeno da dobro radi sa OpenCodeom. [Saznajte više](/docs/zen). + +:::tip +Ako ste novi, preporučujemo da počnete sa OpenCode Zen. +::: + +1. Pokrenite naredbu `/connect` u TUI-u, odaberite opencode i idite na [opencode.ai/auth](https://opencode.ai/auth). + + + +```txt + /connect + + +``` + +2. Prijavite se, dodajte svoje detalje naplate i kopirajte svoj API ključ. + +3. Zalijepite svoj API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite `/models` u TUI da vidite listu modela koje preporučujemo. + + + +```txt + /models + + +``` + +Radi kao i svaki drugi provajder u OpenCode-u i potpuno je opcionalan za korištenje. + +--- + +## Imenik + +Pogledajmo neke od provajdera detaljno. Ako želite dodati provajdera na +listu, slobodno otvori PR. + +:::note +Ne vidite provajdera ovdje? Pošaljite PR. +::: + +--- + +### 302.AI + +1. Idite na [302.AI konzolu](https://302.ai/), kreirajte račun i generirajte API ključ. + +2. Pokrenite naredbu `/connect` i potražite **302.AI**. + + + +```txt + /connect + + +``` + +3. Unesite svoj 302.AI API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model. + + + +```txt + /models + + +``` + +--- + +### Amazon Bedrock + +Da biste koristili Amazon Bedrock s OpenCodeom: + +1. Idite na **Katalog modela** na Amazon Bedrock konzoli i zatražite + pristup modelima koje želite. + + :::tip + Morate imati pristup modelu koji želite u Amazon Bedrock. + ::: + +2. **Konfigurirajte autentifikaciju** koristeći jedan od sljedećih metoda: + + #### Varijable okruženja (brzi početak) + + Postavite jednu od ovih varijabli okruženja dok pokrećete opencode: + + + +```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + + +``` + + Ili ih dodajte na svoj bash profil: + + + +```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + + +``` + + #### Konfiguracijski fajl (preporučeno) + + Za konfiguraciju specifičnu za projekat ili trajnu konfiguraciju, koristite `opencode.json`: + + + +```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + + +``` + + **Dostupne opcije:** + - `region` - ​​AWS regija (npr. `us-east-1`, `eu-west-1`) + - `profile` - ​​AWS je imenovao profil od `~/.aws/credentials` + - `endpoint` - ​​URL prilagođene krajnje tačke za VPC krajnje tačke (pseudonim za generičku opciju `baseURL`) + + :::tip + Opcije konfiguracijske datoteke imaju prednost nad varijablama okruženja. + ::: + + #### Napredno: VPC krajnje tačke + + Ako koristite VPC krajnje tačke za Bedrock: + + + +```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + + +``` + + :::note + Opcija `endpoint` je pseudonim za generičku opciju `baseURL`, koristeći terminologiju specifičnu za AWS. Ako su specificirani i `endpoint` i `baseURL`, `endpoint` ima prednost. + ::: + + #### Metode provjere autentičnosti + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: Kreirajte IAM korisnika i generirajte pristupne ključeve u AWS konzoli + - **`AWS_PROFILE`**: Koristite imenovane profile od `~/.aws/credentials`. Prvo konfigurirajte sa `aws configure --profile my-profile` ili `aws sso login` + - **`AWS_BEARER_TOKEN_BEDROCK`**: Generirajte dugoročne API ključeve sa Amazon Bedrock konzole + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: Za EKS IRSA (IAM uloge za servisne naloge) ili druga Kubernetes okruženja sa OIDC federacijom. Kubernetes automatski ubacuje ove varijable okruženja kada se koriste napomene naloga usluge. + + #### Prioritet autentifikacije + + Amazon Bedrock koristi sljedeći prioritet autentifikacije: + 1. **Token nosioca** - `AWS_BEARER_TOKEN_BEDROCK` varijabla okruženja ili token iz naredbe `/connect` + 2. **AWS lanac vjerodajnica** - profil, pristupni ključevi, dijeljeni vjerodajnici, IAM uloge, tokeni web identiteta (EKS IRSA), metapodaci instance + + :::note + Kada se postavi token nosioca (putem `/connect` ili `AWS_BEARER_TOKEN_BEDROCK`), on ima prednost nad svim AWS metodama akreditiva uključujući konfigurirane profile. + ::: + +3. Pokrenite naredbu `/models` da odaberete model koji želite. + + + +```txt + /models + + +``` + +:::note +Za prilagođene profile zaključivanja, koristite ime modela i dobavljača u ključu i postavite svojstvo `id` na arn. Ovo osigurava ispravno keširanje: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### Antropic + +1. Nakon što ste se prijavili, pokrenite naredbu `/connect` i odaberite Anthropic. + + + +```txt + /connect + + +``` + +2. Ovdje možete odabrati opciju **Claude Pro/Max** i ona će otvoriti vaš pretraživač + i traži od vas da se autentifikujete. + + + +```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + + +``` + +3. Sada bi svi Antropski modeli trebali biti dostupni kada koristite naredbu `/models`. + + + +```txt + /models + + +``` + +:::info +[Anthropic] (https://anthropic.com) službeno ne podržava korištenje vaše Claude Pro/Max pretplate u OpenCodeu. +::: + +##### Korištenje API ključeva + +Također možete odabrati **Kreiraj API ključ** ako nemate Pro/Max pretplatu. Također će otvoriti vaš pretraživač i zatražiti od vas da se prijavite na Anthropic i dati vam kod koji možete zalijepiti u svoj terminal. + +Ili ako već imate API ključ, možete odabrati **Ručno unesite API ključ** i zalijepite ga u svoj terminal. + +--- + +### Azure OpenAI + +:::note +Ako naiđete na greške "Žao mi je, ali ne mogu pomoći s tim zahtjevom", pokušajte promijeniti filter sadržaja iz **DefaultV2** u **Default** u vašem Azure resursu. +::: + +1. Idite na [Azure portal](https://portal.azure.com/) i kreirajte **Azure OpenAI** resurs. trebat će vam: + - **Naziv resursa**: Ovo postaje dio vaše krajnje tačke API-ja (`https://RESOURCE_NAME.openai.azure.com/`) + - **API ključ**: Ili `KEY 1` ili `KEY 2` sa vašeg izvora + +2. Idite na [Azure AI Foundry](https://ai.azure.com/) i implementirajte model. + + :::note + Ime implementacije mora odgovarati imenu modela da bi opencode ispravno radio. + ::: + +3. Pokrenite naredbu `/connect` i potražite **Azure**. + + + +```txt + /connect + + +``` + +4. Unesite svoj API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +5. Postavite ime vašeg resursa kao varijablu okruženja: + + + +```bash + AZURE_RESOURCE_NAME=XXX opencode + + +``` + + Ili ga dodajte na svoj bash profil: + + + +```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + + +``` + +6. Pokrenite naredbu `/models` da odaberete svoj raspoređeni model. + + + +```txt + /models + + +``` + +--- + +### Azure Cognitive Services + +1. Idite na [Azure portal](https://portal.azure.com/) i kreirajte **Azure OpenAI** resurs. trebat će vam: + - **Naziv resursa**: Ovo postaje dio vaše krajnje tačke API-ja (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) + - **API ključ**: Ili `KEY 1` ili `KEY 2` sa vašeg izvora + +2. Idite na [Azure AI Foundry](https://ai.azure.com/) i implementirajte model. + + :::note + Ime implementacije mora odgovarati imenu modela da bi opencode ispravno radio. + ::: + +3. Pokrenite naredbu `/connect` i potražite **Azure kognitivne usluge**. + + + +```txt + /connect + + +``` + +4. Unesite svoj API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +5. Postavite ime vašeg resursa kao varijablu okruženja: + + + +```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + + +``` + + Ili ga dodajte na svoj bash profil: + + + +```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + + +``` + +6. Pokrenite naredbu `/models` da odaberete svoj raspoređeni model. + + + +```txt + /models + + +``` + +--- + +### Baseten + +1. Idite na [Baseten](https://app.baseten.co/), kreirajte račun i generirajte API ključ. + +2. Pokrenite naredbu `/connect` i potražite **Baseten**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Baseten API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model. + + + +```txt + /models + + +``` + +--- + +### Cerebras + +1. Idite na [Cerebras konzolu](https://inference.cerebras.ai/), kreirajte račun i generirajte API ključ. + +2. Pokrenite naredbu `/connect` i potražite **Cerebras**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Cerebras API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _Qwen 3 Coder 480B_. + + + +```txt + /models + + +``` + +--- + +### Cloudflare AI Gateway + +Cloudflare AI Gateway vam omogućava da pristupite modelima iz OpenAI, Anthropic, Workers AI i više preko objedinjene krajnje tačke. Sa [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) nisu vam potrebni posebni API ključevi za svakog provajdera. + +1. Idite na [Cloudflare kontrolnu tablu](https://dash.cloudflare.com/), idite na **AI** > **AI Gateway** i kreirajte novi pristupnik. + +2. Postavite svoj ID naloga i ID pristupnika kao varijable okruženja. + + + +```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + + +``` + +3. Pokrenite naredbu `/connect` i potražite **Cloudflare AI Gateway**. + + + +```txt + /connect + + +``` + +4. Unesite svoj Cloudflare API token. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + + Ili ga postavite kao varijablu okruženja. + + + +```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + + +``` + +5. Pokrenite naredbu `/models` da odaberete model. + + + +```txt + /models + + +``` + + Također možete dodati modele kroz svoju opencode konfiguraciju. + + + +```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + + +``` + +--- + +### Cortecs + +1. Idite na [Cortecs konzolu](https://cortecs.ai/), kreirajte račun i generirajte API ključ. + +2. Pokrenite naredbu `/connect` i potražite **Cortecs**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Cortecs API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _Kimi K2 Instruct_. + + + +```txt + /models + + +``` + +--- + +### DeepSeek + +1. Idite na [DeepSeek konzolu](https://platform.deepseek.com/), kreirajte nalog i kliknite na **Kreiraj novi API ključ**. + +2. Pokrenite naredbu `/connect` i potražite **DeepSeek**. + + + +```txt + /connect + + +``` + +3. Unesite svoj DeepSeek API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete DeepSeek model kao što je _DeepSeek Reasoner_. + + + +```txt + /models + + +``` + +--- + +### Duboka infra + +1. Idite na [Deep Infra kontrolnu tablu](https://deepinfra.com/dash), kreirajte nalog i generišite API ključ. + +2. Pokrenite naredbu `/connect` i potražite **Deep Infra**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Deep Infra API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model. + + + +```txt + /models + + +``` + +--- + +### Firmware + +1. Idite na [kontrolnu tablu firmvera](https://app.firmware.ai/signup), kreirajte nalog i generišite API ključ. + +2. Pokrenite naredbu `/connect` i potražite **Firmware**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Firmware API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model. + + + +```txt + /models + + +``` + +--- + +### Vatromet AI + +1. Idite na [Fireworks AI konzolu](https://app.fireworks.ai/), kreirajte račun i kliknite na **Kreiraj API ključ**. + +2. Pokrenite naredbu `/connect` i potražite **Fireworks AI**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Fireworks AI API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _Kimi K2 Instruct_. + + + +```txt + /models + + +``` + +--- + +### GitLab Duo + +GitLab Duo pruža agentsko ćaskanje sa AI-om sa izvornim mogućnostima pozivanja alata preko GitLab-ovog Anthropic proxyja. + +1. Pokrenite naredbu `/connect` i odaberite GitLab. + + + +```txt + /connect + + +``` + +2. Odaberite svoj način autentifikacije: + + + +```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + + +``` + + #### Korištenje OAuth-a (preporučeno) + + Odaberite **OAuth** i vaš pretraživač će se otvoriti za autorizaciju. + + #### Korištenje tokena ličnog pristupa + 1. Idite na [GitLab korisničke postavke > Pristupni tokeni](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. Kliknite **Dodaj novi token** + 3. Naziv: `OpenCode`, opseg: `api` + 4. Kopirajte token (počinje sa `glpat-`) + 5. Unesite ga u terminal + +3. Pokrenite naredbu `/models` da vidite dostupne modele. + + + +```txt + /models + + +``` + + Dostupna su tri modela bazirana na Claudeu: + - **duo-chat-haiku-4-5** (zadano) - Brzi odgovori za brze zadatke + - **duo-chat-sonnet-4-5** - Uravnotežene performanse za većinu tokova posla + - **duo-chat-opus-4-5** - Najsposobniji za kompleksnu analizu + +:::note +Također možete odrediti 'GITLAB_TOKEN' varijablu okruženja ako ne želite +da pohrani token u opencode auth memoriju. +::: + +##### Samostalni GitLab + +:::note[compliance note] +OpenCode koristi mali model za neke AI zadatke kao što je generiranje naslova sesije. +Podrazumevano je konfigurisan da koristi gpt-5-nano, a hostuje ga Zen. Da zaključate OpenCode +da biste koristili samo svoju vlastitu instancu koju hostuje GitLab, dodajte sljedeće u svoju +`opencode.json` fajl. Također se preporučuje da onemogućite dijeljenje sesije. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +Za GitLab instance koje hostuju sami: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +Ako vaša instanca pokreće prilagođeni AI Gateway: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +Ili dodajte na svoj bash profil: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +Vaš GitLab administrator mora omogućiti sljedeće: + +1. [Duo Agent Platforma](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) za korisnika, grupu ili instancu +2. Zastavice funkcija (preko Rails konzole): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### OAuth za self-hosted instance + +Da bi Oauth radio za vašu instancu koju sami hostujete, morate kreirati +novu aplikaciju (Podešavanja → Aplikacije) sa +URL povratnog poziva `http://127.0.0.1:8080/callback` i sljedeći opseg: + +- api (pristupite API-ju u svoje ime) +- read_user (Pročitajte svoje lične podatke) +- read_repository (omogućava pristup spremištu samo za čitanje) + +Zatim izložite ID aplikacije kao varijablu okruženja: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +Više dokumentacije na početnoj stranici [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth). + +##### Konfiguracija + +Prilagodite putem `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API alati (opciono, ali se preporučuje) + +Za pristup GitLab alatima (zahtjevi za spajanje, problemi, cjevovodi, CI/CD, itd.): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +Ovaj dodatak pruža sveobuhvatne mogućnosti upravljanja GitLab repozitorijumom, uključujući MR preglede, praćenje problema, praćenje procesa i još mnogo toga. + +--- + +### GitHub Copilot + +Da biste koristili svoju GitHub Copilot pretplatu s opencodeom: + +:::note +Neki modeli će možda trebati [Pro+ +pretplata](https://github.com/features/copilot/plans) za korištenje. + +Neki modeli moraju biti ručno omogućeni u vašim [postavkama GitHub Copilot](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. Pokrenite naredbu `/connect` i potražite GitHub Copilot. + + + +```txt + /connect + + +``` + +2. Idite na [github.com/login/device](https://github.com/login/device) i unesite kod. + + + +```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + + +``` + +3. Sada pokrenite naredbu `/models` da odaberete model koji želite. + + + +```txt + /models + + +``` + +--- + +### Google Vertex AI + +Za korištenje Google Vertex AI s OpenCodeom: + +1. Idite do **Model Garden** u Google Cloud Console i provjerite + modeli dostupni u vašoj regiji. + + :::note + Morate imati Google Cloud projekat sa omogućenim Vertex AI API. + ::: + +2. Postavite potrebne varijable okruženja: + - `GOOGLE_CLOUD_PROJECT`: ID vašeg Google Cloud projekta + - `VERTEX_LOCATION` (opciono): Region za Vertex AI (podrazumevano na `global`) + - Autentifikacija (odaberite jednu): + - `GOOGLE_APPLICATION_CREDENTIALS`: Put do JSON ključnog fajla vašeg naloga usluge + - Autentifikacija koristeći gcloud CLI: `gcloud auth application-default login` + + Postavite ih dok se pokreće opencode. + + + +```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + + +``` + + Ili ih dodajte svom bash profilu. + + + +```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + + +``` + +:::tip +Regija `global` poboljšava dostupnost i smanjuje greške bez dodatnih troškova. Koristite regionalne krajnje tačke (npr. `us-central1`) za zahtjeve rezidentnosti podataka. [Saznajte više](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. Pokrenite naredbu `/models` da odaberete model koji želite. + + + +```txt + /models + + +``` + +--- + +### Groq + +1. Idite na [Groq konzolu](https://console.groq.com/), kliknite **Kreiraj API ključ** i kopirajte ključ. + +2. Pokrenite naredbu `/connect` i potražite Groq. + + + +```txt + /connect + + +``` + +3. Unesite API ključ za provajdera. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete onu koju želite. + + + +```txt + /models + + +``` + +--- + +### Hugging Face + +[Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers) omogućava pristup otvorenim modelima koje podržava 17+ provajdera. + +1. Idite na [Postavke zagrljaja](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) da kreirate token s dozvolom za upućivanje poziva dobavljačima inference. + +2. Pokrenite naredbu `/connect` i potražite **Hugging Face**. + + + +```txt + /connect + + +``` + +3. Unesite svoj token Hugging Face. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _Kimi-K2-Instruct_ ili _GLM-4.6_. + + + +```txt + /models + + +``` + +--- + +### Helicone + +[Helicone](https://helicone.ai) je platforma za praćenje LLM koja pruža evidenciju, praćenje i analitiku za vaše AI aplikacije. Helicone AI Gateway automatski usmjerava vaše zahtjeve do odgovarajućeg provajdera na osnovu modela. + +1. Idite na [Helicone](https://helicone.ai), kreirajte račun i generirajte API ključ sa svoje kontrolne table. + +2. Pokrenite naredbu `/connect` i potražite **Helicone**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Helicone API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model. + + + +```txt + /models + + +``` + +Za više provajdera i napredne funkcije kao što su keširanje i ograničavanje brzine, provjerite [Helicone dokumentaciju](https://docs.helicone.ai). + +#### Opcione konfiguracije + +U slučaju da vidite funkciju ili model iz Helicone-a koji nije automatski konfiguriran putem opencodea, uvijek ga možete sami konfigurirati. + +Evo [Heliconeov katalog modela](https://helicone.ai/models), ovo će vam trebati da preuzmete ID-ove modela koje želite dodati. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### Prilagođena zaglavlja + +Helicone podržava prilagođena zaglavlja za funkcije kao što su keširanje, praćenje korisnika i upravljanje sesijom. Dodajte ih u konfiguraciju svog provajdera koristeći `options.headers`: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### Praćenje sesije + +Heliconeova funkcija [Sessions](https://docs.helicone.ai/features/sessions) vam omogućava da grupišete povezane LLM zahtjeve zajedno. Koristite dodatak [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) da automatski prijavite svaki OpenCode razgovor kao sesiju u Helicone-u. + +```bash +npm install -g opencode-helicone-session +``` + +Dodajte ga u svoju konfiguraciju. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +Dodatak ubacuje zaglavlja `Helicone-Session-Id` i `Helicone-Session-Name` u vaše zahtjeve. Na stranici Helicone Sessions, vidjet ćete svaki OpenCode razgovor naveden kao zasebna sesija. + +##### Uobičajena Helicone zaglavlja + +| Header | Opis | +| -------------------------- | ------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | Omogući keširanje odgovora (`true`/`false`) | +| `Helicone-User-Id` | Pratite metriku po korisniku | +| `Helicone-Property-[Name]` | Dodajte prilagođena svojstva (npr. `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | Povezivanje zahtjeva sa brzim verzijama | + +Pogledajte [Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory) za sva dostupna zaglavlja. + +--- + +### llama.cpp + +Možete konfigurirati opencode za korištenje lokalnih modela putem [llama.cpp's](https://github.com/ggml-org/llama.cpp) uslužnog programa llama-server + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +U ovom primjeru: + +- `llama.cpp` je ID prilagođenog provajdera. Ovo može biti bilo koji niz koji želite. +- `npm` specificira paket koji će se koristiti za ovog provajdera. Ovdje se `@ai-sdk/openai-compatible` koristi za bilo koji OpenAI kompatibilan API. +- `name` je ime za prikaz za provajdera u korisničkom sučelju. +- `options.baseURL` je krajnja tačka za lokalni server. +- `models` je mapa ID-ova modela prema njihovim konfiguracijama. Naziv modela će biti prikazan na listi za odabir modela. + +--- + +### IO.NET + +IO.NET nudi 17 modela optimiziranih za različite slučajeve upotrebe: + +1. Idite na [IO.NET konzolu](https://ai.io.net/), kreirajte račun i generirajte API ključ. + +2. Pokrenite naredbu `/connect` i potražite **IO.NET**. + + + +```txt + /connect + + +``` + +3. Unesite svoj IO.NET API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model. + + + +```txt + /models + + +``` + +--- + +### LM Studio + +Možete konfigurirati opencode za korištenje lokalnih modela preko LM Studio. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +U ovom primjeru: + +- `lmstudio` je ID prilagođenog provajdera. Ovo može biti bilo koji niz koji želite. +- `npm` specificira paket koji će se koristiti za ovog provajdera. Ovdje se `@ai-sdk/openai-compatible` koristi za bilo koji OpenAI kompatibilan API. +- `name` je ime za prikaz za provajdera u korisničkom sučelju. +- `options.baseURL` je krajnja tačka za lokalni server. +- `models` je mapa ID-ova modela prema njihovim konfiguracijama. Naziv modela će biti prikazan na listi za odabir modela. + +--- + +### Moonshot AI + +Da biste koristili Kimi K2 iz Moonshot AI: + +1. Idite na [Moonshot AI konzolu](https://platform.moonshot.ai/console), kreirajte nalog i kliknite na **Kreiraj API ključ**. + +2. Pokrenite naredbu `/connect` i potražite **Moonshot AI**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Moonshot API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete _Kimi K2_. + + + +```txt + /models + + +``` + +--- + +### MiniMax + +1. Prijeđite na [MiniMax API konzolu](https://platform.minimax.io/login), kreirajte račun i generirajte API ključ. + +2. Pokrenite naredbu `/connect` i potražite **MiniMax**. + + + +```txt + /connect + + +``` + +3. Unesite svoj MiniMax API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _M2.1_. + + + +```txt + /models + + +``` + +--- + +### Nebius Token Factory + +1. Idite na [Nebius Token Factory konzolu](https://tokenfactory.nebius.com/), kreirajte nalog i kliknite na **Dodaj ključ**. + +2. Pokrenite naredbu `/connect` i potražite **Nebius Token Factory**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Nebius Token Factory API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _Kimi K2 Instruct_. + + + +```txt + /models + + +``` + +--- + +### Ollama + +Možete konfigurirati opencode za korištenje lokalnih modela putem Ollame. + +:::tip +Ollama se može automatski konfigurirati za OpenCode. Pogledajte [Ollama integracijske dokumente](https://docs.ollama.com/integrations/opencode) za detalje. +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +U ovom primjeru: + +- `ollama` je ID prilagođenog provajdera. Ovo može biti bilo koji niz koji želite. +- `npm` specificira paket koji će se koristiti za ovog provajdera. Ovdje se `@ai-sdk/openai-compatible` koristi za bilo koji OpenAI kompatibilan API. +- `name` je ime za prikaz za provajdera u korisničkom sučelju. +- `options.baseURL` je krajnja tačka za lokalni server. +- `models` je mapa ID-ova modela prema njihovim konfiguracijama. Naziv modela će biti prikazan na listi za odabir modela. + +:::tip +Ako pozivi alata ne rade, pokušajte povećati `num_ctx` u Ollama. Počnite oko 16k - 32k. +::: + +--- + +### Ollama Cloud + +Da biste koristili Ollama Cloud s OpenCodeom: + +1. Idite na [https://ollama.com/](https://ollama.com/) i prijavite se ili kreirajte račun. + +2. Idite na **Postavke** > **Ključevi** i kliknite na **Dodaj API ključ** da generišete novi API ključ. + +3. Kopirajte API ključ za korištenje u OpenCodeu. + +4. Pokrenite naredbu `/connect` i potražite **Ollama Cloud**. + + + +```txt + /connect + + +``` + +5. Unesite svoj Ollama Cloud API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +6. **Važno**: Prije upotrebe modela oblaka u OpenCodeu, morate lokalno povući informacije o modelu: + + + +```bash + ollama pull gpt-oss:20b-cloud + + +``` + +7. Pokrenite naredbu `/models` da odaberete svoj model Ollama Cloud. + + + +```txt + /models + + +``` + +--- + +### OpenAI + +Preporučujemo da se prijavite za [ChatGPT Plus ili Pro](https://chatgpt.com/pricing). + +1. Nakon što ste se prijavili, pokrenite naredbu `/connect` i odaberite OpenAI. + + + +```txt + /connect + + +``` + +2. Ovdje možete odabrati opciju **ChatGPT Plus/Pro** i ona će otvoriti vaš pretraživač + i traži od vas da se autentifikujete. + + + +```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + + +``` + +3. Sada bi svi OpenAI modeli trebali biti dostupni kada koristite naredbu `/models`. + + + +```txt + /models + + +``` + +##### Korištenje API ključeva + +Ako već imate API ključ, možete odabrati **Ručno unesite API ključ** i zalijepite ga u svoj terminal. + +--- + +### OpenCode Zen + +OpenCode Zen je lista testiranih i verifikovanih modela koju je obezbedio OpenCode tim. [Saznajte više](/docs/zen). + +1. Prijavite se na **OpenCode Zen** i kliknite na **Kreiraj API ključ**. + +2. Pokrenite naredbu `/connect` i potražite **OpenCode Zen**. + + + +```txt + /connect + + +``` + +3. Unesite svoj OpenCode API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _Qwen 3 Coder 480B_. + + + +```txt + /models + + +``` + +--- + +### OpenRouter + +1. Idite na [OpenRouter nadzornu ploču](https://openrouter.ai/settings/keys), kliknite na **Kreiraj API ključ** i kopirajte ključ. + +2. Pokrenite naredbu `/connect` i potražite OpenRouter. + + + +```txt + /connect + + +``` + +3. Unesite API ključ za provajdera. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Mnogi OpenRouter modeli su unapred učitani po defaultu, pokrenite naredbu `/models` da odaberete onaj koji želite. + + + +```txt + /models + + +``` + + Također možete dodati dodatne modele putem vaše opencode konfiguracije. + + + +```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + + +``` + +5. Također ih možete prilagoditi putem vaše opencode konfiguracije. Evo primjera navođenja provajdera + + + +```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + + +``` + +--- + +### SAP AI Core + +SAP AI Core omogućava pristup preko 40+ modela iz OpenAI, Anthropic, Google, Amazon, Meta, Mistral i AI21 putem objedinjene platforme. + +1. Idite na vaš [SAP BTP Cockpit](https://account.hana.ondemand.com/), idite na instancu usluge SAP AI Core i kreirajte servisni ključ. + + :::tip + Servisni ključ je JSON objekat koji sadrži `clientid`, `clientsecret`, `url` i `serviceurls.AI_API_URL`. Svoju AI Core instancu možete pronaći pod **Usluge** > **Instance i pretplate** u BTP kokpitu. + ::: + +2. Pokrenite naredbu `/connect` i potražite **SAP AI Core**. + + + +```txt + /connect + + +``` + +3. Unesite JSON svoj servisni ključ. + + + +```txt + ┌ Service key + │ + │ + └ enter + + +``` + + Ili postavite varijablu okruženja `AICORE_SERVICE_KEY`: + + + +```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + + +``` + + Ili ga dodajte na svoj bash profil: + + + +```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + + +``` + +4. Opciono postavite ID implementacije i grupu resursa: + + + +```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + + +``` + + :::note + Ove postavke su opcione i treba ih konfigurirati u skladu s vašim SAP AI Core postavkama. + ::: + +5. Pokrenite naredbu `/models` da odaberete između 40+ dostupnih modela. + + + +```txt + /models + + +``` + +--- + +### OVHcloud AI krajnje tačke + +1. Idite na [OVHcloud panel](https://ovh.com/manager). Idite do odjeljka `Public Cloud`, `AI & Machine Learning` > `AI Endpoints` i na kartici `API Keys` kliknite na **Kreiraj novi API ključ**. + +2. Pokrenite naredbu `/connect` i potražite **OVHcloud AI krajnje točke**. + + + +```txt + /connect + + +``` + +3. Unesite svoj OVHcloud AI Endpoints API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _gpt-oss-120b_. + + + +```txt + /models + + +``` + +--- + +### Scaleway + +Da biste koristili [Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/) sa Opencodeom: + +1. Prijeđite na [Scaleway Console IAM postavke](https://console.scaleway.com/iam/api-keys) da generišete novi API ključ. + +2. Pokrenite naredbu `/connect` i potražite **Scaleway**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Scaleway API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _devstral-2-123b-instruct-2512_ ili _gpt-oss-120b_. + + + +```txt + /models + + +``` + +--- + +### Zajedno AI + +1. Idite na [Together AI console](https://api.together.ai), kreirajte nalog i kliknite na **Dodaj ključ**. + +2. Pokrenite naredbu `/connect` i potražite **Zajedno AI**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Together AI API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _Kimi K2 Instruct_. + + + +```txt + /models + + +``` + +--- + +### Venice AI + +1. Idite na [Venice AI konzolu](https://venice.ai), kreirajte račun i generirajte API ključ. + +2. Pokrenite naredbu `/connect` i potražite **Venice AI**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Venice AI API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _Llama 3.3 70B_. + + + +```txt + /models + + +``` + +--- + +### Vercel AI Gateway + +Vercel AI Gateway vam omogućava da pristupite modelima iz OpenAI, Anthropic, Google, xAI i drugih putem objedinjene krajnje tačke. Modeli se nude po kataloškim cijenama bez maraka. + +1. Idite na [Vercel kontrolnu tablu](https://vercel.com/), idite na karticu **AI Gateway** i kliknite na **API ključevi** da kreirate novi API ključ. + +2. Pokrenite naredbu `/connect` i potražite **Vercel AI Gateway**. + + + +```txt + /connect + + +``` + +3. Unesite svoj Vercel AI Gateway API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model. + + + +```txt + /models + + +``` + +Također možete prilagoditi modele kroz svoju opencode konfiguraciju. Evo primjera specificiranja redoslijeda usmjeravanja dobavljača. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +Neke korisne opcije rutiranja: + +| Opcija | Opis | +| ------------------- | ---------------------------------------------------- | +| `order` | Redoslijed dobavljača za pokušaj | +| `only` | Ograničiti na određene provajdere | +| `zeroDataRetention` | Koristite samo provajdere sa nultom politikom zadržavanja podataka | + +--- + +### xAI + +1. Prijeđite na [xAI konzolu](https://console.x.ai/), kreirajte račun i generirajte API ključ. + +2. Pokrenite naredbu `/connect` i potražite **xAI**. + + + +```txt + /connect + + +``` + +3. Unesite svoj xAI API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _Grok Beta_. + + + +```txt + /models + + +``` + +--- + +### Z.AI + +1. Idite na [Z.AI API konzolu](https://z.ai/manage-apikey/apikey-list), kreirajte nalog i kliknite na **Kreiraj novi API ključ**. + +2. Pokrenite naredbu `/connect` i potražite **Z.AI**. + + + +```txt + /connect + + +``` + + Ako ste pretplaćeni na **GLM plan kodiranja**, odaberite **Z.AI plan kodiranja**. + +3. Unesite svoj Z.AI API ključ. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Pokrenite naredbu `/models` da odaberete model kao što je _GLM-4.7_. + + + +```txt + /models + + +``` + +--- + +### ZenMux + +1. Idite na [ZenMux kontrolnu tablu](https://zenmux.ai/settings/keys), kliknite na **Kreiraj API ključ** i kopirajte ključ. + +2. Pokrenite naredbu `/connect` i potražite ZenMux. + + + +```txt + /connect + + +``` + +3. Unesite API ključ za provajdera. + + + +```txt + ┌ API key + │ + │ + └ enter + + +``` + +4. Mnogi ZenMux modeli su unaprijed učitani po defaultu, pokrenite naredbu `/models` da odaberete onaj koji želite. + + + +```txt + /models + + +``` + + Također možete dodati dodatne modele putem vaše opencode konfiguracije. + + + +```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + + +``` + +--- + +## Prilagođeni provajder + +Da biste dodali bilo kojeg **OpenAI-kompatibilnog** provajdera koji nije naveden u naredbi `/connect`: + +:::tip +Možete koristiti bilo kojeg OpenAI kompatibilnog provajdera s opencode-om. Većina modernih AI provajdera nudi API-je kompatibilne sa OpenAI. +::: + +1. Pokrenite naredbu `/connect` i pomaknite se prema dolje do **Ostalo**. + + + +```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + + +``` + +2. Unesite jedinstveni ID za provajdera. + + + +```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + + +``` + + :::note + Odaberite ID koji se pamti, to ćete koristiti u svom konfiguracijskom fajlu. + ::: + +3. Unesite svoj API ključ za provajdera. + + + +```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + + +``` + +4. Kreirajte ili ažurirajte svoju `opencode.json` datoteku u direktoriju projekta: + + + +```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + + +``` + + Evo opcija konfiguracije: + - **npm**: AI SDK paket za korištenje, `@ai-sdk/openai-compatible` za OpenAI-kompatibilne provajdere + - **name**: Ime za prikaz u korisničkom sučelju. + - **modeli**: Dostupni modeli. + - **options.baseURL**: URL krajnje tačke API-ja. + - **options.apiKey**: Opciono postavite API ključ, ako ne koristite auth. + - **options.headers**: Opciono postavite prilagođena zaglavlja. + + Više o naprednim opcijama u primjeru ispod. + +5. Pokrenite naredbu `/models` i vaš prilagođeni provajder i modeli će se pojaviti na listi izbora. + +--- + +##### Primjer + +Evo primjera postavljanja opcija `apiKey`, `headers` i modela `limit`. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +Detalji konfiguracije: + +- **apiKey**: Postavite pomoću sintakse varijable `env`, [saznajte više](/docs/config#env-vars). +- **zaglavlja**: Prilagođena zaglavlja se šalju sa svakim zahtjevom. +- **limit.context**: Maksimalni ulazni tokeni koje model prihvata. +- **limit.output**: Maksimalni tokeni koje model može generirati. + +Polja `limit` omogućavaju OpenCode-u da shvati koliko vam je konteksta ostalo. Standardni dobavljači ih automatski preuzimaju sa models.dev. + +--- + +## Rješavanje problema + +Ako imate problema s konfiguracijom provajdera, provjerite sljedeće: + +1. **Provjerite postavke autentifikacije**: Pokrenite `opencode auth list` da vidite da li su vjerodajnice + za provajdera se dodaju u vašu konfiguraciju. + + Ovo se ne odnosi na dobavljače kao što je Amazon Bedrock, koji se oslanjaju na varijable okruženja za svoju autentifikaciju. + +2. Za prilagođene provajdere, provjerite konfiguraciju otvorenog koda i: + - Uvjerite se da ID provajdera korišten u naredbi `/connect` odgovara ID-u u vašoj opencode konfiguraciji. + - Za provajdera se koristi pravi npm paket. Na primjer, koristite `@ai-sdk/cerebras` za Cerebras. A za sve ostale OpenAI kompatibilne provajdere, koristite `@ai-sdk/openai-compatible`. + - Provjerite da li se ispravna krajnja tačka API-ja koristi u polju `options.baseURL`. diff --git a/packages/web/src/content/docs/bs/rules.mdx b/packages/web/src/content/docs/bs/rules.mdx new file mode 100644 index 000000000..620e489a7 --- /dev/null +++ b/packages/web/src/content/docs/bs/rules.mdx @@ -0,0 +1,180 @@ +--- +title: Pravila +description: Postavite prilagodena uputstva za opencode. +--- + +Mozete dodati prilagodena uputstva za opencode tako sto kreirate `AGENTS.md` datoteku. Ovo je slicno pravilima u Cursoru. Sadrzi uputstva koja se ubacuju u LLM kontekst da prilagode ponasanje za vas projekat. + +--- + +## Inicijalizacija + +Da kreirate novu `AGENTS.md` datoteku, pokrenite `/init` komandu u opencode. + +:::tip +Preporuceno je da `AGENTS.md` iz projekta commitujete u Git. +::: + +Ovo skenira projekat i njegov sadrzaj, razumije cemu projekat sluzi i generise `AGENTS.md`. Tako opencode bolje navigira kroz kod. + +Ako vec imate `AGENTS.md`, komanda ce pokusati da ga dopuni. + +--- + +## Primjer + +Datoteku mozete napraviti i rucno. Evo primjera sta mozete staviti u `AGENTS.md`. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +Ovdje dodajete uputstva specificna za projekat koja se dijele sa timom. + +--- + +## Tipovi + +opencode podrzava citanje `AGENTS.md` datoteke sa vise lokacija. Svaka lokacija ima drugu svrhu. + +### Projekat + +Stavite `AGENTS.md` u korijen projekta za pravila specificna za taj projekat. Primjenjuju se samo kada radite u tom direktoriju ili poddirektorijima. + +### Globalno + +Mozete imati i globalna pravila u `~/.config/opencode/AGENTS.md`. Ona se primjenjuju u svim opencode sesijama. + +Posto se ovo ne commituje u Git niti dijeli s timom, najbolje je da ovdje cuvate licna pravila koja LLM treba pratiti. + +### Kompatibilnost s Claude Code + +Za korisnike koji prelaze sa Claude Code, OpenCode podrzava i Claude konvencije datoteka kao rezervu: + +- **Pravila projekta**: `CLAUDE.md` u direktoriju projekta (koristi se ako ne postoji `AGENTS.md`) +- **Globalna pravila**: `~/.claude/CLAUDE.md` (koristi se ako ne postoji `~/.config/opencode/AGENTS.md`) +- **Skills**: `~/.claude/skills/` — pogledajte [Agent Skills](/docs/skills/) za detalje + +Da iskljucite kompatibilnost sa Claude Code, postavite jednu od ovih varijabli okruzenja: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## Prioritet + +Kada se opencode pokrene, trazi datoteke pravila ovim redoslijedom: + +1. **Lokalne datoteke** pretrazivanjem prema gore od trenutnog direktorija (`AGENTS.md`, `CLAUDE.md`) +2. **Globalna datoteka** na `~/.config/opencode/AGENTS.md` +3. **Claude Code datoteka** na `~/.claude/CLAUDE.md` (osim ako je iskljucena) + +Prva pronadena datoteka pobjeduje u svakoj kategoriji. Na primjer, ako imate i `AGENTS.md` i `CLAUDE.md`, koristi se samo `AGENTS.md`. Isto tako, `~/.config/opencode/AGENTS.md` ima prednost nad `~/.claude/CLAUDE.md`. + +--- + +## Prilagodena uputstva + +Mozete navesti prilagodene datoteke uputstava u `opencode.json` ili globalnom `~/.config/opencode/opencode.json`. Tako vi i tim ponovo koristite postojeca pravila bez dupliranja u AGENTS.md. + +Primjer: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Mozete koristiti i udaljene URL-ove za ucitavanje uputstava sa weba. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +Udaljena uputstva se preuzimaju uz timeout od 5 sekundi. + +Sve datoteke uputstava se kombinuju sa vasim `AGENTS.md` datotekama. + +--- + +## Referenciranje eksternih datoteka + +Iako opencode ne parsira automatski reference datoteka u `AGENTS.md`, slicno ponasanje mozete dobiti na dva nacina: + +### Koristenje opencode.json + +Preporuceni pristup je da koristite `instructions` polje u `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Rucna uputstva u AGENTS.md + +Mozete nauciti opencode da cita eksterne datoteke tako sto cete dati eksplicitna uputstva u `AGENTS.md`. Evo prakticnog primjera: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +Ovaj pristup vam omogucava da: + +- Kreirate modularne datoteke pravila koje se mogu ponovo koristiti +- Dijelite pravila izmedu projekata kroz symlinkove ili git submodule +- Drzite AGENTS.md kratkim dok upucujete na detaljne smjernice +- Osigurate da opencode ucitava datoteke samo kad su potrebne za konkretan zadatak + +:::tip +Za monorepo projekte ili projekte sa zajednickim standardima, odrzivije je koristiti `opencode.json` sa glob obrascima (npr. `packages/*/AGENTS.md`) nego rucna uputstva. +::: diff --git a/packages/web/src/content/docs/bs/sdk.mdx b/packages/web/src/content/docs/bs/sdk.mdx new file mode 100644 index 000000000..a73978b4a --- /dev/null +++ b/packages/web/src/content/docs/bs/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: Type-safe JS klijent za opencode server. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +opencode JS/TS SDK pruza type-safe klijent za interakciju sa serverom. +Koristite ga za izradu integracija i programsko upravljanje opencode-om. + +[Saznajte vise](/docs/server) kako server radi. Za primjere pogledajte [projects](/docs/ecosystem#projects) koje je napravila zajednica. + +--- + +## Install + +Instalirajte SDK sa npm-a: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## Create client + +Kreirajte instancu opencode-a: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +Ovo pokrece i server i klijent + +#### Options + +| Opcija | Tip | Opis | Default | +| ---------- | ------------- | ----------------------------- | ----------- | +| `hostname` | `string` | Hostname servera | `127.0.0.1` | +| `port` | `number` | Port servera | `4096` | +| `signal` | `AbortSignal` | Abort signal za otkazivanje | `undefined` | +| `timeout` | `number` | Timeout u ms za start servera | `5000` | +| `config` | `Config` | Konfiguracijski objekat | `{}` | + +--- + +## Config + +Mozete proslijediti konfiguracijski objekat za prilagodavanje ponasanja. Instanca i dalje ucitava `opencode.json`, ali konfiguraciju mozete nadjacati ili dodati inline: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## Client only + +Ako vec imate pokrenutu opencode instancu, mozete napraviti klijentsku instancu i povezati se na nju: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### Options + +| Opcija | Tip | Opis | Default | +| --------------- | ---------- | --------------------------------- | ----------------------- | +| `baseUrl` | `string` | URL servera | `http://localhost:4096` | +| `fetch` | `function` | Prilagodena fetch implementacija | `globalThis.fetch` | +| `parseAs` | `string` | Metoda parsiranja odgovora | `auto` | +| `responseStyle` | `string` | Stil povrata: `data` ili `fields` | `fields` | +| `throwOnError` | `boolean` | Baci greske umjesto povrata | `false` | + +--- + +## Types + +SDK ukljucuje TypeScript definicije za sve API tipove. Uvezite ih direktno: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +Svi tipovi su generisani iz OpenAPI specifikacije servera i dostupni u types datoteci. + +--- + +## Errors + +SDK moze baciti greske koje mozete uhvatiti i obraditi: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## APIs + +SDK izlaže sve server API-je kroz type-safe klijent. + +--- + +### Global + +| Metoda | Opis | Odgovor | +| ----------------- | --------------------------- | ------------------------------------ | +| `global.health()` | Provjera zdravlja i verzije | `{ healthy: true, version: string }` | + +--- + +#### Examples + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### App + +| Metoda | Opis | Odgovor | +| -------------- | ----------------------- | ------------------------------------------- | +| `app.log()` | Upis log zapisa | `boolean` | +| `app.agents()` | Lista dostupnih agenata | Agent[] | + +--- + +#### Examples + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### Project + +| Metoda | Opis | Odgovor | +| ------------------- | -------------------- | --------------------------------------------- | +| `project.list()` | Lista svih projekata | Project[] | +| `project.current()` | Trenutni projekat | Project | + +--- + +#### Examples + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### Path + +| Metoda | Opis | Odgovor | +| ------------ | ---------------- | ---------------------------------------- | +| `path.get()` | Trenutna putanja | Path | + +--- + +#### Examples + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### Config + +| Metoda | Opis | Odgovor | +| -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` | Info o konfiguraciji | Config | +| `config.providers()` | Lista provajdera i default modela | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +#### Examples + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### Sessions + +| Method | Description | Notes | +| ---------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` | List sessions | Returns Session[] | +| `session.get({ path })` | Get session | Returns Session | +| `session.children({ path })` | List child sessions | Returns Session[] | +| `session.create({ body })` | Create session | Returns Session | +| `session.delete({ path })` | Delete session | Returns `boolean` | +| `session.update({ path, body })` | Update session properties | Returns Session | +| `session.init({ path, body })` | Analyze app and create `AGENTS.md` | Returns `boolean` | +| `session.abort({ path })` | Abort a running session | Returns `boolean` | +| `session.share({ path })` | Share session | Returns Session | +| `session.unshare({ path })` | Unshare session | Returns Session | +| `session.summarize({ path, body })` | Summarize session | Returns `boolean` | +| `session.messages({ path })` | List messages in a session | Returns `{ info: `Message`, parts: `Part[]`}[]` | +| `session.message({ path })` | Get message details | Returns `{ info: `Message`, parts: `Part[]`}` | +| `session.prompt({ path, body })` | Send prompt message | `body.noReply: true` returns UserMessage (context only). Default returns AssistantMessage with AI response | +| `session.command({ path, body })` | Send command to session | Returns `{ info: `AssistantMessage`, parts: `Part[]`}` | +| `session.shell({ path, body })` | Run a shell command | Returns AssistantMessage | +| `session.revert({ path, body })` | Revert a message | Returns Session | +| `session.unrevert({ path })` | Restore reverted messages | Returns Session | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | Respond to a permission request | Returns `boolean` | + +--- + +#### Examples + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### Files + +| Method | Description | Response | +| ------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `find.text({ query })` | Search for text in files | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `find.files({ query })` | Find files and directories by name | `string[]` (paths) | +| `find.symbols({ query })` | Find workspace symbols | Symbol[] | +| `file.read({ query })` | Read a file | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | Get status for tracked files | File[] | + +`find.files` supports a few optional query fields: + +- `type`: `"file"` or `"directory"` +- `directory`: override the project root for the search +- `limit`: max results (1–200) + +--- + +#### Examples + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +| Method | Description | Response | +| ------------------------------ | ------------------------- | --------- | +| `tui.appendPrompt({ body })` | Append text to the prompt | `boolean` | +| `tui.openHelp()` | Open the help dialog | `boolean` | +| `tui.openSessions()` | Open the session selector | `boolean` | +| `tui.openThemes()` | Open the theme selector | `boolean` | +| `tui.openModels()` | Open the model selector | `boolean` | +| `tui.submitPrompt()` | Submit the current prompt | `boolean` | +| `tui.clearPrompt()` | Clear the prompt | `boolean` | +| `tui.executeCommand({ body })` | Execute a command | `boolean` | +| `tui.showToast({ body })` | Show toast notification | `boolean` | + +--- + +#### Examples + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### Auth + +| Method | Description | Response | +| ------------------- | ------------------------------ | --------- | +| `auth.set({ ... })` | Set authentication credentials | `boolean` | + +--- + +#### Examples + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### Events + +| Method | Description | Response | +| ------------------- | ------------------------- | ------------------------- | +| `event.subscribe()` | Server-sent events stream | Server-sent events stream | + +--- + +#### Examples + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/bs/server.mdx b/packages/web/src/content/docs/bs/server.mdx new file mode 100644 index 000000000..c2a106de9 --- /dev/null +++ b/packages/web/src/content/docs/bs/server.mdx @@ -0,0 +1,284 @@ +--- +title: Server +description: Komunicirajte s opencode serverom preko HTTP-a. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Komanda `opencode serve` pokrece headless HTTP server koji izlaže OpenAPI endpoint koji opencode klijent moze koristiti. + +--- + +### Usage + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### Options + +| Zastava | Opis | Default | +| --------------- | ----------------------------------- | ---------------- | +| `--port` | Port na kojem slusa | `4096` | +| `--hostname` | Hostname na kojem slusa | `127.0.0.1` | +| `--mdns` | Ukljuci mDNS otkrivanje | `false` | +| `--mdns-domain` | Prilagodeni domen za mDNS servis | `opencode.local` | +| `--cors` | Dodatni browser origin-i koje dozv. | `[]` | + +`--cors` mozete navesti vise puta: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### Authentication + +Postavite `OPENCODE_SERVER_PASSWORD` da zastitite server HTTP basic auth mehanizmom. Korisnicko ime je po defaultu `opencode`, ili postavite `OPENCODE_SERVER_USERNAME` za nadjacavanje. Ovo vazi i za `opencode serve` i za `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### How it works + +Kada pokrenete `opencode`, pokrecu se TUI i server. TUI je klijent koji komunicira sa serverom. Server izlaže OpenAPI 3.1 spec endpoint koji se koristi i za generisanje [SDK-a](/docs/sdk). + +:::tip +Koristite opencode server za programsku interakciju sa opencode-om. +::: + +Ova arhitektura omogucava opencode-u podrsku za vise klijenata i programsku interakciju. + +Mozete pokrenuti `opencode serve` da startate standalone server. Ako je opencode TUI vec pokrenut, `opencode serve` ce pokrenuti novi server. + +--- + +#### Connect to an existing server + +Kada pokrenete TUI, port i hostname se nasumicno dodijele. Umjesto toga, mozete zadati `--hostname` i `--port` [zastave](/docs/cli), pa se povezati na taj server. + +Endpoint [`/tui`](#tui) mozete koristiti za upravljanje TUI-jem kroz server. Na primjer, mozete unaprijed popuniti ili pokrenuti prompt. Ovaj setup koriste OpenCode [IDE](/docs/ide) pluginovi. + +--- + +## Spec + +Server objavljuje OpenAPI 3.1 specifikaciju koju mozete vidjeti na: + +``` +http://:/doc +``` + +Na primjer, `http://localhost:4096/doc`. Koristite specifikaciju da generisete klijente ili pregledate tipove zahtjeva i odgovora. Mozete je otvoriti i u Swagger exploreru. + +--- + +## APIs + +opencode server izlaže sljedece API-je. + +--- + +### Global + +| Method | Path | Description | Response | +| ------ | ---------------- | ------------------------------ | ------------------------------------ | +| `GET` | `/global/health` | Get server health and version | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | Get global events (SSE stream) | Event stream | + +--- + +### Project + +| Method | Path | Description | Response | +| ------ | ------------------ | ----------------------- | --------------------------------------------- | +| `GET` | `/project` | List all projects | Project[] | +| `GET` | `/project/current` | Get the current project | Project | + +--- + +### Path & VCS + +| Method | Path | Description | Response | +| ------ | ------- | ------------------------------------ | ------------------------------------------- | +| `GET` | `/path` | Get the current path | Path | +| `GET` | `/vcs` | Get VCS info for the current project | VcsInfo | + +--- + +### Instance + +| Method | Path | Description | Response | +| ------ | ------------------- | ---------------------------- | --------- | +| `POST` | `/instance/dispose` | Dispose the current instance | `boolean` | + +--- + +### Config + +| Method | Path | Description | Response | +| ------- | ------------------- | --------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` | Get config info | Config | +| `PATCH` | `/config` | Update config | Config | +| `GET` | `/config/providers` | List providers and default models | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +### Provider + +| Method | Path | Description | Response | +| ------ | -------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` | List all providers | `{ all: `Provider[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | Get provider authentication methods | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | Authorize a provider using OAuth | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | Handle OAuth callback for a provider | `boolean` | + +--- + +### Sessions + +| Method | Path | Description | Notes | +| -------- | ---------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------- | +| `GET` | `/session` | List all sessions | Returns Session[] | +| `POST` | `/session` | Create a new session | body: `{ parentID?, title? }`, returns Session | +| `GET` | `/session/status` | Get session status for all sessions | Returns `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | Get session details | Returns Session | +| `DELETE` | `/session/:id` | Delete a session and all its data | Returns `boolean` | +| `PATCH` | `/session/:id` | Update session properties | body: `{ title? }`, returns Session | +| `GET` | `/session/:id/children` | Get a session's child sessions | Returns Session[] | +| `GET` | `/session/:id/todo` | Get the todo list for a session | Returns Todo[] | +| `POST` | `/session/:id/init` | Analyze app and create `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returns `boolean` | +| `POST` | `/session/:id/fork` | Fork an existing session at a message | body: `{ messageID? }`, returns Session | +| `POST` | `/session/:id/abort` | Abort a running session | Returns `boolean` | +| `POST` | `/session/:id/share` | Share a session | Returns Session | +| `DELETE` | `/session/:id/share` | Unshare a session | Returns Session | +| `GET` | `/session/:id/diff` | Get the diff for this session | query: `messageID?`, returns FileDiff[] | +| `POST` | `/session/:id/summarize` | Summarize the session | body: `{ providerID, modelID }`, returns `boolean` | +| `POST` | `/session/:id/revert` | Revert a message | body: `{ messageID, partID? }`, returns `boolean` | +| `POST` | `/session/:id/unrevert` | Restore all reverted messages | Returns `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | Respond to a permission request | body: `{ response, remember? }`, returns `boolean` | + +--- + +### Messages + +| Method | Path | Description | Notes | +| ------ | --------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` | List messages in a session | query: `limit?`, returns `{ info: `Message`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` | Send a message and wait for response | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, returns `{ info: `Message`, parts: `Part[]`}` | +| `GET` | `/session/:id/message/:messageID` | Get message details | Returns `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/prompt_async` | Send a message asynchronously (no wait) | body: same as `/session/:id/message`, returns `204 No Content` | +| `POST` | `/session/:id/command` | Execute a slash command | body: `{ messageID?, agent?, model?, command, arguments }`, returns `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/shell` | Run a shell command | body: `{ agent, model?, command }`, returns `{ info: `Message`, parts: `Part[]`}` | + +--- + +### Commands + +| Method | Path | Description | Response | +| ------ | ---------- | ----------------- | --------------------------------------------- | +| `GET` | `/command` | List all commands | Command[] | + +--- + +### Files + +| Method | Path | Description | Response | +| ------ | ------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | Search for text in files | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | Find files and directories by name | `string[]` (paths) | +| `GET` | `/find/symbol?query=` | Find workspace symbols | Symbol[] | +| `GET` | `/file?path=` | List files and directories | FileNode[] | +| `GET` | `/file/content?path=

` | Read a file | FileContent | +| `GET` | `/file/status` | Get status for tracked files | File[] | + +#### `/find/file` query parameters + +- `query` (required) — search string (fuzzy match) +- `type` (optional) — limit results to `"file"` or `"directory"` +- `directory` (optional) — override the project root for the search +- `limit` (optional) — max results (1–200) +- `dirs` (optional) — legacy flag (`"false"` returns only files) + +--- + +### Tools (Experimental) + +| Method | Path | Description | Response | +| ------ | ------------------------------------------- | ---------------------------------------- | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` | List all tool IDs | ToolIDs | +| `GET` | `/experimental/tool?provider=

&model=` | List tools with JSON schemas for a model | ToolList | + +--- + +### LSP, Formatters & MCP + +| Method | Path | Description | Response | +| ------ | ------------ | -------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | Get LSP server status | LSPStatus[] | +| `GET` | `/formatter` | Get formatter status | FormatterStatus[] | +| `GET` | `/mcp` | Get MCP server status | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | Add MCP server dynamically | body: `{ name, config }`, returns MCP status object | + +--- + +### Agents + +| Method | Path | Description | Response | +| ------ | -------- | ------------------------- | ------------------------------------------- | +| `GET` | `/agent` | List all available agents | Agent[] | + +--- + +### Logging + +| Method | Path | Description | Response | +| ------ | ------ | ------------------------------------------------------------ | --------- | +| `POST` | `/log` | Write log entry. Body: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| Method | Path | Description | Response | +| ------ | ----------------------- | ------------------------------------------- | ---------------------- | +| `POST` | `/tui/append-prompt` | Append text to the prompt | `boolean` | +| `POST` | `/tui/open-help` | Open the help dialog | `boolean` | +| `POST` | `/tui/open-sessions` | Open the session selector | `boolean` | +| `POST` | `/tui/open-themes` | Open the theme selector | `boolean` | +| `POST` | `/tui/open-models` | Open the model selector | `boolean` | +| `POST` | `/tui/submit-prompt` | Submit the current prompt | `boolean` | +| `POST` | `/tui/clear-prompt` | Clear the prompt | `boolean` | +| `POST` | `/tui/execute-command` | Execute a command (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | Show toast (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | Wait for the next control request | Control request object | +| `POST` | `/tui/control/response` | Respond to a control request (`{ body }`) | `boolean` | + +--- + +### Auth + +| Method | Path | Description | Response | +| ------ | ----------- | --------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | Set authentication credentials. Body must match provider schema | `boolean` | + +--- + +### Events + +| Method | Path | Description | Response | +| ------ | -------- | ----------------------------------------------------------------------------- | ------------------------- | +| `GET` | `/event` | Server-sent events stream. First event is `server.connected`, then bus events | Server-sent events stream | + +--- + +### Docs + +| Method | Path | Description | Response | +| ------ | ------ | ------------------------- | --------------------------- | +| `GET` | `/doc` | OpenAPI 3.1 specification | HTML page with OpenAPI spec | diff --git a/packages/web/src/content/docs/bs/share.mdx b/packages/web/src/content/docs/bs/share.mdx new file mode 100644 index 000000000..43959d16b --- /dev/null +++ b/packages/web/src/content/docs/bs/share.mdx @@ -0,0 +1,127 @@ +--- +title: Dijeljenje +description: Dijelite OpenCode razgovore javnim linkovima. +--- + +OpenCode opcija dijeljenja vam omogucava da kreirate javne linkove za razgovore. Tako lakse saradujete s timom ili trazite pomoc od drugih. + +:::note +Dijeljeni razgovori su javno dostupni svakome ko ima link. +::: + +--- + +## Kako radi + +Kada podijelite razgovor, OpenCode: + +1. Kreira jedinstveni javni URL za vasu sesiju +2. Sinhronizuje historiju razgovora na nase servere +3. Cini razgovor dostupnim preko linka za dijeljenje — `opncd.ai/s/` + +--- + +## Sharing + +OpenCode podrzava tri nacina dijeljenja koji odreduju kako se razgovori dijele: + +--- + +### Manual (default) + +Po defaultu, OpenCode koristi rucni nacin dijeljenja. Sesije se ne dijele automatski, ali ih mozete rucno podijeliti komandom `/share`: + +``` +/share +``` + +Ovo ce generisati jedinstveni URL i kopirati ga u clipboard. + +Da eksplicitno postavite rucni nacin u [config datoteci](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### Auto-share + +Mozete ukljuciti automatsko dijeljenje za sve nove razgovore tako sto `share` postavite na `"auto"` u [config datoteci](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +Kada je auto-share ukljucen, svaki novi razgovor se automatski dijeli i kreira se link. + +--- + +### Disabled + +Dijeljenje mozete potpuno iskljuciti tako sto `share` postavite na `"disabled"` u [config datoteci](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +Da ovo vazi za cijeli tim u odredenom projektu, dodajte postavku u projektni `opencode.json` i commitujte u Git. + +--- + +## Uklanjanje dijeljenja + +Da prestanete dijeliti razgovor i uklonite javni pristup: + +``` +/unshare +``` + +Ovo uklanja link za dijeljenje i brise podatke povezane s razgovorom. + +--- + +## Privatnost + +Imajte na umu nekoliko stvari prije dijeljenja razgovora. + +--- + +### Cuvanje podataka + +Dijeljeni razgovori ostaju dostupni dok ih eksplicitno ne uklonite iz dijeljenja. Ovo ukljucuje: + +- Kompletnu historiju razgovora +- Sve poruke i odgovore +- Metapodatke sesije + +--- + +### Preporuke + +- Dijelite samo razgovore koji ne sadrze osjetljive informacije. +- Pregledajte sadrzaj razgovora prije dijeljenja. +- Uklonite dijeljenje kad saradnja zavrsi. +- Izbjegavajte dijeljenje razgovora s vlasnickim kodom ili povjerljivim podacima. +- Za osjetljive projekte potpuno iskljucite dijeljenje. + +--- + +## Za enterprise + +Za enterprise okruzenja, opcija dijeljenja moze biti: + +- **Iskljucena** u potpunosti radi sigurnosne uskladenosti +- **Ogranicena** samo na korisnike autentifikovane kroz SSO +- **Self-hosted** na vasoj infrastrukturi + +[Saznajte vise](/docs/enterprise) o koristenju opencode u organizaciji. diff --git a/packages/web/src/content/docs/bs/skills.mdx b/packages/web/src/content/docs/bs/skills.mdx new file mode 100644 index 000000000..ec144af74 --- /dev/null +++ b/packages/web/src/content/docs/bs/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "Skills agenata" +description: "Definisite ponasanje koje se moze ponovo koristiti" +--- + +Agent skills omogucavaju OpenCode-u da pronade uputstva koja se mogu ponovo koristiti iz repozitorija ili home direktorija. +Skills se ucitavaju po potrebi kroz ugradeni `skill` alat - agenti vide dostupne skills i ucitavaju puni sadrzaj kad zatreba. + +--- + +## Postavite datoteke + +Kreirajte jedan folder po nazivu skill-a i stavite `SKILL.md` unutar njega. +OpenCode pretrazuje ove lokacije: + +- Konfiguracija projekta: `.opencode/skills//SKILL.md` +- Globalna konfiguracija: `~/.config/opencode/skills//SKILL.md` +- Claude kompatibilno u projektu: `.claude/skills//SKILL.md` +- Globalno Claude kompatibilno: `~/.claude/skills//SKILL.md` +- Agent kompatibilno u projektu: `.agents/skills//SKILL.md` +- Globalno agent kompatibilno: `~/.agents/skills//SKILL.md` + +--- + +## Razumijte otkrivanje + +Za projektne lokalne putanje, OpenCode ide prema gore od trenutnog radnog direktorija dok ne dode do git worktree-ja. +Usput ucitava sve odgovarajuce `skills/*/SKILL.md` u `.opencode/` i odgovarajuce `.claude/skills/*/SKILL.md` ili `.agents/skills/*/SKILL.md`. + +Globalne definicije se takoder ucitavaju iz `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` i `~/.agents/skills/*/SKILL.md`. + +--- + +## Napisite frontmatter + +Svaki `SKILL.md` mora poceti YAML frontmatter-om. +Prepoznaju se samo ova polja: + +- `name` (obavezno) +- `description` (obavezno) +- `license` (opcionalno) +- `compatibility` (opcionalno) +- `metadata` (opcionalno, mapa string->string) + +Nepoznata frontmatter polja se ignorisu. + +--- + +## Validirajte nazive + +`name` mora: + +- Imati 1-64 karaktera +- Biti malim slovima i brojevima sa jednim crticama kao razdvajacima +- Ne pocinjati ni zavrsavati sa `-` +- Ne sadrzavati uzastopno `--` +- Odgovarati nazivu direktorija koji sadrzi `SKILL.md` + +Ekvivalentni regex: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## Pratite pravila duzine + +`description` mora imati 1-1024 karaktera. +Neka bude dovoljno precizan da agent moze pravilno odabrati. + +--- + +## Koristite primjer + +Kreirajte `.opencode/skills/git-release/SKILL.md` ovako: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## Prepoznajte opis alata + +OpenCode navodi dostupne skills u opisu `skill` alata. +Svaki unos sadrzi naziv i opis skill-a: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +Agent ucitava skill pozivom alata: + +``` +skill({ name: "git-release" }) +``` + +--- + +## Konfigurisite dozvole + +Kontrolisite kojim skills agenti mogu pristupiti pomocu dozvola baziranih na obrascima u `opencode.json`: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Dozvola | Ponasanje | +| ------- | ------------------------------------------- | +| `allow` | Skill se ucitava odmah | +| `deny` | Skill je skriven od agenta, pristup odbijen | +| `ask` | Korisnik mora odobriti prije ucitavanja | + +Obrasci podrzavaju wildcard znakove: `internal-*` poklapa `internal-docs`, `internal-tools` itd. + +--- + +## Nadjacajte po agentu + +Dajte odredenim agentima drugacije dozvole od globalnih defaulta. + +**Za prilagodene agente** (u frontmatter-u agenta): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**Za ugradene agente** (u `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## Iskljucite skill alat + +Potpuno iskljucite skills za agente koji ih ne bi trebali koristiti: + +**Za prilagodene agente**: + +```yaml +--- +tools: + skill: false +--- +``` + +**Za ugradene agente**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +Kada je iskljuceno, sekcija `` se potpuno izostavlja. + +--- + +## Rjesavanje problema s ucitavanjem + +Ako se skill ne pojavi: + +1. Provjerite da je naziv `SKILL.md` napisan velikim slovima +2. Provjerite da frontmatter sadrzi `name` i `description` +3. Potvrdite da su nazivi skill-ova jedinstveni na svim lokacijama +4. Provjerite dozvole - skills sa `deny` su skriveni od agenata diff --git a/packages/web/src/content/docs/bs/themes.mdx b/packages/web/src/content/docs/bs/themes.mdx new file mode 100644 index 000000000..4508075bd --- /dev/null +++ b/packages/web/src/content/docs/bs/themes.mdx @@ -0,0 +1,369 @@ +--- +title: Teme +description: Izaberite ugradenu temu ili napravite svoju. +--- + +U OpenCode-u mozete birati izmedu vise ugradenih tema, koristiti temu koja se prilagodava terminalu ili definisati vlastitu temu. + +Po defaultu, OpenCode koristi nasu `opencode` temu. + +--- + +## Zahtjevi terminala + +Da bi teme bile prikazane ispravno sa punom paletom boja, terminal mora podrzavati **truecolor** (24-bitne boje). Vecina modernih terminala to podrzava, ali nekad ga treba ukljuciti: + +- **Provjerite podrsku**: Pokrenite `echo $COLORTERM` - trebalo bi vratiti `truecolor` ili `24bit` +- **Ukljucite truecolor**: Postavite varijablu okruzenja `COLORTERM=truecolor` u shell profilu +- **Kompatibilnost terminala**: Potvrdite da emulator terminala podrzava 24-bitne boje (vecina modernih terminala kao iTerm2, Alacritty, Kitty, Windows Terminal i novije verzije GNOME Terminala) + +Bez truecolor podrske, teme mogu imati slabiju preciznost boja ili pasti na najblizu 256-color aproksimaciju. + +--- + +## Ugradene teme + +OpenCode dolazi sa vise ugradenih tema. + +| Naziv | Opis | +| ---------------------- | -------------------------------------------------------------------------- | +| `system` | Prilagodava se boji pozadine vaseg terminala | +| `tokyonight` | Bazirana na [Tokyonight](https://github.com/folke/tokyonight.nvim) temi | +| `everforest` | Bazirana na [Everforest](https://github.com/sainnhe/everforest) temi | +| `ayu` | Bazirana na [Ayu](https://github.com/ayu-theme) dark temi | +| `catppuccin` | Bazirana na [Catppuccin](https://github.com/catppuccin) temi | +| `catppuccin-macchiato` | Bazirana na [Catppuccin](https://github.com/catppuccin) temi | +| `gruvbox` | Bazirana na [Gruvbox](https://github.com/morhetz/gruvbox) temi | +| `kanagawa` | Bazirana na [Kanagawa](https://github.com/rebelot/kanagawa.nvim) temi | +| `nord` | Bazirana na [Nord](https://github.com/nordtheme/nord) temi | +| `matrix` | Hacker stil zelena-na-crnom tema | +| `one-dark` | Bazirana na [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) Dark temi | + +I jos mnogo njih, stalno dodajemo nove teme. + +--- + +## System tema + +`system` tema je napravljena da se automatski prilagodi sem i boja vaseg terminala. Za razliku od tradicionalnih tema sa fiksnim bojama, _system_ tema: + +- **Generise sivu skalu**: Pravi prilagodenu sivu skalu na osnovu boje pozadine terminala za optimalan kontrast. +- **Koristi ANSI boje**: Koristi standardne ANSI boje (0-15) za sintaksno isticanje i UI elemente, uz postovanje palete terminala. +- **Cuva terminalske defaulte**: Koristi `none` za boju teksta i pozadine da zadrzi izvorni izgled terminala. + +System tema je za korisnike koji: + +- Zele da OpenCode odgovara izgledu njihovog terminala +- Koriste prilagodene seme boja terminala +- Preferiraju konzistentan izgled kroz sve terminalske aplikacije + +--- + +## Koristenje teme + +Temu mozete izabrati preko selektora tema komandom `/theme`. Mozete je navesti i u [configu](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Prilagodene teme + +OpenCode podrzava fleksibilan sistem tema baziran na JSON-u koji olaksava kreiranje i prilagodavanje tema. + +--- + +### Hijerarhija + +Teme se ucitavaju iz vise direktorija ovim redoslijedom, gdje kasniji direktoriji prepisuju ranije: + +1. **Ugradene teme** - Ugradene su u binarni fajl +2. **Korisnicki config direktorij** - `~/.config/opencode/themes/*.json` ili `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Korijenski direktorij projekta** - `/.opencode/themes/*.json` +4. **Trenutni radni direktorij** - `./.opencode/themes/*.json` + +Ako vise direktorija sadrzi temu istog naziva, koristit ce se tema iz direktorija s vecim prioritetom. + +--- + +### Kreiranje teme + +Da kreirate prilagodenu temu, napravite JSON datoteku u jednom od direktorija za teme. + +Za korisnicke teme na nivou sistema: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +I za teme specificne za projekat. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON format + +Teme koriste fleksibilan JSON format koji podrzava: + +- **Hex boje**: `"#ffffff"` +- **ANSI boje**: `3` (0-255) +- **Reference boja**: `"primary"` ili prilagodene definicije +- **Dark/light varijante**: `{"dark": "#000", "light": "#fff"}` +- **Bez boje**: `"none"` - koristi defaultnu boju terminala ili transparentno + +--- + +### Definicije boja + +Sekcija `defs` je opcionalna i omogucava da definisete boje koje se mogu ponovo koristiti kroz temu. + +--- + +### Terminalski defaulti + +Specijalna vrijednost `"none"` moze se koristiti za bilo koju boju da naslijedi defaultnu boju terminala. Ovo je korisno za teme koje se prirodno uklapaju u semu boja terminala: + +- `"text": "none"` - koristi defaultnu boju teksta terminala +- `"background": "none"` - koristi defaultnu boju pozadine terminala + +--- + +### Example + +Evo primjera prilagodene teme: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/bs/tools.mdx b/packages/web/src/content/docs/bs/tools.mdx new file mode 100644 index 000000000..26a3fee97 --- /dev/null +++ b/packages/web/src/content/docs/bs/tools.mdx @@ -0,0 +1,379 @@ +--- +title: Alati +description: Upravljajte alatima koje LLM moze koristiti. +--- + +Alati omogucavaju LLM-u da izvrsava akcije u vasem kodu. OpenCode dolazi sa skupom ugradenih alata, a mozete ga prosiriti kroz [custom tools](/docs/custom-tools) ili [MCP servers](/docs/mcp-servers). + +Po defaultu su svi alati **ukljuceni** i ne traze dozvolu za pokretanje. Ponasanje alata kontrolisete kroz [permissions](/docs/permissions). + +--- + +## Configure + +Koristite polje `permission` za kontrolu ponasanja alata. Za svaki alat mozete postaviti allow, deny ili ask. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +Mozete koristiti i wildcard obrasce da kontrolisete vise alata odjednom. Na primjer, da trazite odobrenje za sve alate jednog MCP servera: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[Saznajte vise](/docs/permissions) o konfigurisanju dozvola. + +--- + +## Built-in + +Ovo su svi ugradeni alati dostupni u OpenCode-u. + +--- + +### bash + +Izvrsava shell komande u okruzenju projekta. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +Ovaj alat omogucava LLM-u da pokrece terminalske komande kao `npm install`, `git status` i druge shell komande. + +--- + +### edit + +Mijenja postojece datoteke tacnim zamjenama stringova. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Ovaj alat radi precizne izmjene datoteka zamjenom tacnih poklapanja teksta. To je glavni nacin na koji LLM mijenja kod. + +--- + +### write + +Kreira nove datoteke ili prepisuje postojece. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Koristite ovo da dozvolite LLM-u kreiranje novih datoteka. Ako datoteka vec postoji, bit ce prepisana. + +:::note +`write` alat kontrolise `edit` dozvola, koja pokriva sve izmjene datoteka (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### read + +Cita sadrzaj datoteka iz vaseg koda. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +Ovaj alat cita datoteke i vraca njihov sadrzaj. Podrzava citanje odredenih raspona linija kod velikih fajlova. + +--- + +### grep + +Pretrazuje sadrzaj datoteka pomocu regularnih izraza. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Brza pretraga sadrzaja kroz cijeli kod. Podrzava puni regex i filtriranje po obrascima datoteka. + +--- + +### glob + +Pronalazi datoteke po obrascima. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +Trazi datoteke koristeci glob obrasce kao `**/*.js` ili `src/**/*.ts`. Vraca putanje sortirane po vremenu izmjene. + +--- + +### list + +Ispisuje datoteke i direktorije na zadanoj putanji. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +Ovaj alat ispisuje sadrzaj direktorija. Prihvata glob obrasce za filtriranje rezultata. + +--- + +### lsp (experimental) + +Komunicira sa konfigurisanim LSP serverima za funkcije inteligencije koda kao definicije, reference, hover info i hijerarhija poziva. + +:::note +Ovaj alat je dostupan samo kada je `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (ili `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +Podrzane operacije ukljucuju `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` i `outgoingCalls`. + +Za konfiguraciju dostupnih LSP servera u projektu, pogledajte [LSP Servers](/docs/lsp). + +--- + +### patch + +Primjenjuje zakrpe na datoteke. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Ovaj alat primjenjuje patch datoteke na kod. Koristan je za diffs i patch-eve iz razlicitih izvora. + +:::note +`patch` alat kontrolise `edit` dozvola, koja pokriva sve izmjene datoteka (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### skill + +Ucitajte [skill](/docs/skills) (`SKILL.md` datoteku) i vratite njegov sadrzaj u razgovor. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todowrite + +Upravlja todo listama tokom coding sesija. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +Kreira i azurira liste zadataka za pracenje napretka tokom slozenih operacija. LLM ovo koristi za organizaciju zadataka u vise koraka. + +:::note +Ovaj alat je po defaultu iskljucen za subagente, ali ga mozete rucno ukljuciti. [Saznajte vise](/docs/agents/#permissions) +::: + +--- + +### todoread + +Cita postojece todo liste. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +Cita trenutno stanje todo liste. LLM ga koristi da prati sta je na cekanju i sta je zavrseno. + +:::note +Ovaj alat je po defaultu iskljucen za subagente, ali ga mozete rucno ukljuciti. [Saznajte vise](/docs/agents/#permissions) +::: + +--- + +### webfetch + +Preuzima web sadrzaj. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +Omogucava LLM-u da preuzima i cita web stranice. Korisno za dokumentaciju i online istrazivanje. + +--- + +### websearch + +Pretrazuje web za informacije. + +:::note +Ovaj alat je dostupan samo uz OpenCode provajdera ili kada je varijabla `OPENCODE_ENABLE_EXA` postavljena na truthy vrijednost (npr. `true` ili `1`). + +Da ukljucite pri pokretanju OpenCode-a: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Vrsi web pretrage preko Exa AI da pronade relevantne informacije online. Korisno za istrazivanje tema, aktuelnosti i podataka van granice trening skupa. + +API kljuc nije potreban - alat se direktno povezuje na Exa AI hosted MCP servis bez autentifikacije. + +:::tip +Koristite `websearch` kada trebate pronaci informacije (discovery), a `webfetch` kada trebate preuzeti sadrzaj sa konkretnog URL-a (retrieval). +::: + +--- + +### question + +Postavlja korisniku pitanja tokom izvrsavanja. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +Ovaj alat omogucava LLM-u da postavlja pitanja korisniku tokom zadatka. Koristan je za: + +- Prikupljanje korisnickih preferencija i zahtjeva +- Razjasnjavanje nejasnih uputstava +- Donosenje odluka oko implementacije +- Nudjenje izbora o smjeru rada + +Svako pitanje ukljucuje naslov, tekst pitanja i listu opcija. Korisnici mogu izabrati ponudenu opciju ili upisati vlastiti odgovor. Kada ima vise pitanja, mogu se kretati izmedu njih prije slanja svih odgovora. + +--- + +## Custom tools + +Custom tools vam omogucavaju da definisete vlastite funkcije koje LLM moze pozivati. Definisu se u config datoteci i mogu izvrsavati proizvoljan kod. + +[Saznajte vise](/docs/custom-tools) o kreiranju custom tools. + +--- + +## MCP servers + +MCP (Model Context Protocol) serveri omogucavaju integraciju eksternih alata i servisa. Ovo ukljucuje pristup bazama, API integracije i third-party servise. + +[Saznajte vise](/docs/mcp-servers) o konfigurisanju MCP servera. + +--- + +## Internals + +Interno, alati kao `grep`, `glob` i `list` koriste [ripgrep](https://github.com/BurntSushi/ripgrep). Po defaultu, ripgrep postuje `.gitignore` obrasce, pa se fajlovi i direktoriji iz `.gitignore` izostavljaju iz pretraga i listinga. + +--- + +### Ignore patterns + +Da ukljucite fajlove koji bi inace bili ignorisani, kreirajte `.ignore` datoteku u korijenu projekta. Ova datoteka moze eksplicitno dozvoliti odredene putanje. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +Na primjer, ova `.ignore` datoteka dozvoljava ripgrep-u da pretrazuje `node_modules/`, `dist/` i `build/` direktorije i kada su navedeni u `.gitignore`. diff --git a/packages/web/src/content/docs/bs/troubleshooting.mdx b/packages/web/src/content/docs/bs/troubleshooting.mdx new file mode 100644 index 000000000..69ae66368 --- /dev/null +++ b/packages/web/src/content/docs/bs/troubleshooting.mdx @@ -0,0 +1,308 @@ +--- +title: Rješavanje problema +description: Uobičajeni problemi i kako ih riješiti. +--- + +Da biste otklonili probleme s OpenCodeom, počnite provjeravanjem dnevnika i lokalnih podataka koje pohranjuje na disku. + +--- + +## Dnevnici + +Log fajlovi se pišu na: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: Pritisnite `WIN+R` i zalijepite `%USERPROFILE%\.local\share\opencode\log` + +Datoteke evidencije se imenuju vremenskim oznakama (npr. `2025-01-09T123456.log`) i čuvaju se najnovijih 10 datoteka dnevnika. + +Možete postaviti nivo dnevnika pomoću opcije komandne linije `--log-level` da biste dobili detaljnije informacije o otklanjanju grešaka. Na primjer, `opencode --log-level DEBUG`. + +--- + +## Skladištenje + +opencode pohranjuje podatke o sesiji i druge podatke aplikacije na disku na: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: Pritisnite `WIN+R` i zalijepite `%USERPROFILE%\.local\share\opencode` + +Ovaj direktorij sadrži: + +- `auth.json` - ​​Podaci o autentifikaciji kao što su API ključevi, OAuth tokeni +- `log/` - ​​Dnevnici aplikacije +- `project/` - ​​Podaci specifični za projekat kao što su podaci o sesiji i poruci + - Ako je projekat unutar Git repo-a, on je pohranjen u `.//storage/` + - Ako nije Git repo, pohranjuje se u `./global/storage/` + +--- + +## Desktop aplikacija + +OpenCode Desktop pokreće lokalni OpenCode server (`opencode-cli` sidecar) u pozadini. Većina problema je uzrokovana nedostatkom dodatka, oštećenom keš memorijom ili lošim postavkama servera. + +### Brze provjere + +- Potpuno zatvorite i ponovo pokrenite aplikaciju. +- Ako aplikacija prikaže ekran s greškom, kliknite na **Restart** i kopirajte detalje o grešci. +- samo za macOS: `OpenCode` meni -> **Ponovo učitaj Webview** (pomaže ako je korisnički interfejs prazan/zamrznut). + +--- + +### Onemogući dodatke + +Ako se desktop aplikacija ruši pri pokretanju, visi ili se čudno ponaša, počnite s onemogućavanjem dodataka. + +#### Provjerite globalnu konfiguraciju + +Otvorite svoju globalnu konfiguracijsku datoteku i potražite ključ `plugin`. + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (ili `~/.config/opencode/opencode.json`) +- **macOS/Linux** (starije instalacije): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: Pritisnite `WIN+R` i zalijepite `%USERPROFILE%\.config\opencode\opencode.jsonc` + +Ako imate konfigurirane dodatke, privremeno ih onemogućite uklanjanjem ključa ili postavljanjem na prazan niz: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### Provjerite imenike dodataka + +OpenCode također može učitati lokalne dodatke s diska. Privremeno ih maknite s puta (ili preimenujte folder) i ponovo pokrenite desktop aplikaciju: + +- **Globalni dodaci** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: Pritisnite `WIN+R` i zalijepite `%USERPROFILE%\.config\opencode\plugins` +- **Projektni dodaci** (samo ako koristite konfiguraciju po projektu) + - `/.opencode/plugins/` + +Ako aplikacija ponovo počne raditi, ponovo omogućite dodatke jedan po jedan kako biste otkrili koji od njih uzrokuje problem. + +--- + +### Očisti keš memoriju + +Ako onemogućavanje dodataka ne pomogne (ili se instalacija dodatka zaglavila), obrišite keš memoriju kako bi ga OpenCode mogao ponovo izgraditi. + +1. Potpuno zatvorite OpenCode Desktop. +2. Izbrišite keš direktorij: + +- **macOS**: Finder -> `Cmd+Shift+G` -> zalijepi `~/.cache/opencode` +- **Linux**: obrišite `~/.cache/opencode` (ili pokrenite `rm -rf ~/.cache/opencode`) +- **Windows**: Pritisnite `WIN+R` i zalijepite `%USERPROFILE%\.cache\opencode` + +3. Ponovo pokrenite OpenCode Desktop. + +--- + +### Popravite probleme sa vezom na serveru + +OpenCode Desktop može ili pokrenuti svoj lokalni server (podrazumevano) ili se povezati na URL servera koji ste konfigurisali. + +Ako vidite dijaloški okvir **"Povezivanje nije uspjelo"** (ili aplikacija nikada ne prođe kroz početni ekran), provjerite da li postoji prilagođeni URL servera. + +#### Obrišite zadani URL servera radne površine + +Na početnom ekranu kliknite na ime servera (sa tačkom statusa) da otvorite birač servera. U odjeljku **Podrazumevani server** kliknite na **Obriši**. + +#### Uklonite `server.port` / `server.hostname` iz vaše konfiguracije + +Ako vaš `opencode.json(c)` sadrži odjeljak `server`, privremeno ga uklonite i ponovo pokrenite desktop aplikaciju. + +#### Provjerite varijable okruženja + +Ako ste postavili `OPENCODE_PORT` u svom okruženju, desktop aplikacija će pokušati da koristi taj port za lokalni server. + +- Poništite `OPENCODE_PORT` (ili odaberite slobodan port) i ponovo pokrenite. + +--- + +### Linux: Wayland / X11 problemi + +Na Linuxu, neka podešavanja Waylanda mogu uzrokovati prazne prozore ili greške sastavljača. + +- Ako ste na Waylandu, a aplikacija je prazna/ispada, pokušajte pokrenuti sa `OC_ALLOW_WAYLAND=1`. +- Ako to pogorša stvari, uklonite ga i pokušajte pokrenuti pod X11 sesijom umjesto toga. + +--- + +### Windows: WebView2 runtime + +Na Windows-u, OpenCode Desktop zahtijeva Microsoft Edge **WebView2 Runtime**. Ako se aplikacija otvori u praznom prozoru ili se ne pokrene, instalirajte/ažurirajte WebView2 i pokušajte ponovo. + +--- + +### Windows: Opšti problemi sa performansama + +Ako imate spore performanse, probleme s pristupom datotekama ili probleme s terminalom na Windows-u, pokušajte koristiti [WSL (Windows podsistem za Linux)](/docs/windows-wsl). WSL pruža Linux okruženje koje radi neprimetnije sa OpenCode-ovim karakteristikama. + +--- + +### Obavještenja se ne prikazuju + +OpenCode Desktop prikazuje sistemska obavještenja samo kada: + +- obavještenja su omogućena za OpenCode u postavkama vašeg OS-a, i +- prozor aplikacije nije fokusiran. + +--- + +### Poništi pohranu desktop aplikacija (posljednje rješenje) + +Ako se aplikacija ne pokrene i ne možete izbrisati postavke unutar korisničkog sučelja, resetirajte spremljeno stanje desktop aplikacije. + +1. Zatvorite OpenCode Desktop. +2. Pronađite i izbrišite ove datoteke (oni žive u direktoriju podataka OpenCode Desktop aplikacije): + +- `opencode.settings.dat` (URL zadanog servera za desktop) +- `opencode.global.dat` i `opencode.workspace.*.dat` (stanje korisničkog interfejsa poput nedavnih servera/projekata) + +Da brzo pronađete direktorij: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (onda potražite nazive fajlova iznad) +- **Linux**: potražite nazive fajlova iznad pod `~/.local/share` +- **Windows**: Pritisnite `WIN+R` -> `%APPDATA%` (zatim potražite nazive fajlova iznad) + +--- + +## Dobivanje pomoći + +Ako imate problema s OpenCodeom: + +1. **Prijavite probleme na GitHub** + + Najbolji način da prijavite greške ili zatražite funkcije je putem našeg GitHub spremišta: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + Prije kreiranja novog problema, pretražite postojeće probleme da vidite je li vaš problem već prijavljen. + +2. **Pridružite se našem Discordu** + + Za pomoć u stvarnom vremenu i diskusiju u zajednici, pridružite se našem Discord serveru: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Uobičajeni problemi + +Evo nekih uobičajenih problema i kako ih riješiti. + +--- + +### OpenCode se neće pokrenuti + +1. Provjerite dnevnike za poruke o greškama +2. Pokušajte pokrenuti sa `--print-logs` da vidite izlaz u terminalu +3. Uvjerite se da imate najnoviju verziju sa `opencode upgrade` + +--- + +### Problemi s autentifikacijom + +1. Pokušajte ponovo autentifikovati sa naredbom `/connect` u TUI +2. Provjerite da li su vaši API ključevi važeći +3. Uvjerite se da vaša mreža dozvoljava veze s API-jem provajdera + +--- + +### Model nije dostupan + +1. Provjerite jeste li se autentifikovali kod provajdera +2. Provjerite je li naziv modela u vašoj konfiguraciji tačan +3. Neki modeli mogu zahtijevati poseban pristup ili pretplate + +Ako naiđete na `ProviderModelNotFoundError` najvjerovatnije niste u pravu +referenciranje modela negdje. +Modele treba referencirati ovako: `/` + +primjeri: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +Da saznate kojim modelima imate pristup, pokrenite `opencode models` + +--- + +### ProviderInitError + +Ako naiđete na grešku ProviderInitError, vjerovatno imate nevažeću ili oštećenu konfiguraciju. + +Da biste ovo riješili: + +1. Prvo provjerite da li je vaš provajder ispravno postavljen slijedeći [vodič za pružatelje](/docs/providers) +2. Ako se problem nastavi, pokušajte obrisati pohranjenu konfiguraciju: + + + +```bash + rm -rf ~/.local/share/opencode + + +``` + + Na Windows-u pritisnite `WIN+R` i izbrišite: `%USERPROFILE%\.local\share\opencode` + +3. Ponovo izvršite autentifikaciju kod svog provajdera koristeći naredbu `/connect` u TUI. + +--- + +### AI_APICallError i problemi sa paketom dobavljača + +Ako naiđete na greške API poziva, to može biti zbog zastarjelih paketa dobavljača. opencode dinamički instalira pakete dobavljača (OpenAI, Anthropic, Google, itd.) po potrebi i kešira ih lokalno. + +Da biste riješili probleme s paketom dobavljača: + +1. Obrišite keš paketa provajdera: + + + +```bash + rm -rf ~/.cache/opencode + + +``` + + Na Windows-u pritisnite `WIN+R` i izbrišite: `%USERPROFILE%\.cache\opencode` + +2. Ponovo pokrenite opencode da ponovo instalirate najnovije pakete dobavljača + +Ovo će prisiliti opencode da preuzme najnovije verzije paketa dobavljača, što često rješava probleme kompatibilnosti s parametrima modela i promjenama API-ja. + +--- + +### Copy/paste ne radi na Linuxu + +Korisnici Linuxa moraju imati instaliran jedan od sljedećih uslužnih programa međuspremnika da bi funkcionirala funkcionalnost kopiranja/lijepljenja: + +**Za X11 sisteme:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**Za Wayland sisteme:** + +```bash +apt install -y wl-clipboard +``` + +**Za okruženja bez glave:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode će otkriti da li koristite Wayland i preferirate `wl-clipboard`, u suprotnom će pokušati pronaći alate međuspremnika po redoslijedu: `xclip` i `xsel`. diff --git a/packages/web/src/content/docs/bs/tui.mdx b/packages/web/src/content/docs/bs/tui.mdx new file mode 100644 index 000000000..2d6c2926b --- /dev/null +++ b/packages/web/src/content/docs/bs/tui.mdx @@ -0,0 +1,402 @@ +--- +title: TUI +description: Korištenje korisničkog interfejsa OpenCode terminala. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode pruža interaktivni terminalski interfejs ili TUI za rad na vašim projektima sa LLM. + +Pokretanje OpenCode-a pokreće TUI za trenutni direktorij. + +```bash +opencode +``` + +Ili ga možete pokrenuti za određeni radni direktorij. + +```bash +opencode /path/to/project +``` + +Kada uđete u TUI, možete to zatražiti porukom. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## Reference fajlova + +Možete referencirati datoteke u svojim porukama koristeći `@`. Ovo vrši nejasnu pretragu datoteka u trenutnom radnom direktoriju. + +:::tip +Također možete koristiti `@` da referencirate datoteke u svojim porukama. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +Sadržaj datoteke se automatski dodaje u razgovor. + +--- + +## Bash komande + +Započnite poruku sa `!` da pokrenete komandu ljuske. + +```bash frame="none" +!ls -la +``` + +Izlaz naredbe se dodaje u razgovor kao rezultat alata. + +--- + +## Komande + +Kada koristite OpenCode TUI, možete upisati `/` nakon čega slijedi ime komande da biste brzo izvršili radnje. na primjer: + +```bash frame="none" +/help +``` + +Većina naredbi također ima vezu pomoću `ctrl+x` kao vodeće tipke, gdje je `ctrl+x` zadani vodeći ključ. [Saznajte više](/docs/keybinds). + +Ovdje su sve dostupne komande kose crte: + +--- + +### connect + +Dodajte provajdera u OpenCode. Omogućava vam da odaberete između dostupnih provajdera i dodate njihove API ključeve. + +```bash frame="none" +/connect +``` + +--- + +### compact + +Sažimanje trenutne sesije. _Alias_: `/summarize` + +```bash frame="none" +/compact +``` + +**Tastatura:** `ctrl+x c` + +--- + +### details + +Prebacite detalje o izvršavanju alata. + +```bash frame="none" +/details +``` + +**Tastatura:** `ctrl+x d` + +--- + +### editor + +Otvorite vanjski uređivač za sastavljanje poruka. Koristi editor postavljen u vašoj varijabli okruženja `EDITOR`. [Saznajte više](#editor-setup). + +```bash frame="none" +/editor +``` + +**Tastatura:** `ctrl+x e` + +--- + +### exit + +Izađite iz OpenCode-a. _Aliases_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Tastatura:** `ctrl+x q` + +--- + +### export + +Izvezite trenutni razgovor u Markdown i otvorite ga u zadanom uređivaču. Koristi editor postavljen u vašoj varijabli okruženja `EDITOR`. [Saznajte više](#editor-setup). + +```bash frame="none" +/export +``` + +**Tastatura:** `ctrl+x x` + +--- + +### help + +Prikaži dijalog pomoći. + +```bash frame="none" +/help +``` + +**Tastatura:** `ctrl+x h` + +--- + +### init + +Kreirajte ili ažurirajte datoteku `AGENTS.md`. [Saznajte više](/docs/rules). + +```bash frame="none" +/init +``` + +**Tastatura:** `ctrl+x i` + +--- + +### models + +Navedite dostupne modele. + +```bash frame="none" +/models +``` + +**Tastatura:** `ctrl+x m` + +--- + +### new + +Započnite novu sesiju. _Alias_: `/clear` + +```bash frame="none" +/new +``` + +**Tastatura:** `ctrl+x n` + +--- + +### redo + +Ponovite prethodno poništenu poruku. Dostupno samo nakon korištenja `/undo`. + +:::tip +Sve promjene fajla će također biti vraćene. +::: + +Interno, ovo koristi Git za upravljanje promjenama datoteke. Dakle, vaš projekat **treba +biti Git spremište**. + +```bash frame="none" +/redo +``` + +**Tastatura:** `ctrl+x r` + +--- + +### sessions + +Listanje i prebacivanje između sesija. _Aliases_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Tastatura:** `ctrl+x l` + +--- + +### share + +Podijelite trenutnu sesiju. [Saznajte više](/docs/share). + +```bash frame="none" +/share +``` + +**Tastatura:** `ctrl+x s` + +--- + +### themes + +Navedite dostupne teme. + +```bash frame="none" +/theme +``` + +**Tastatura:** `ctrl+x t` + +--- + +### thinking + +Uključite/isključite vidljivost blokova razmišljanja/rezoniranja u razgovoru. Kada je omogućeno, možete vidjeti proces rezonovanja modela za modele koji podržavaju prošireno razmišljanje. + +:::note +Ova naredba samo kontrolira da li se blokovi razmišljanja **prikažu** - ne omogućava niti onemogućuje mogućnosti razmišljanja modela. Da biste uključili stvarne mogućnosti zaključivanja, koristite `ctrl+t` za kretanje kroz varijante modela. +::: + +```bash frame="none" +/thinking +``` + +--- + +### undo + +Poništi posljednju poruku u razgovoru. Uklanja najnoviju korisničku poruku, sve naknadne odgovore i sve promjene datoteke. + +:::tip +Sve promjene u fajlu će također biti poništene. +::: + +Interno, ovo koristi Git za upravljanje promjenama datoteke. Dakle, vaš projekat **treba +biti Git spremište**. + +```bash frame="none" +/undo +``` + +**Tastatura:** `ctrl+x u` + +--- + +### unshare + +Poništi dijeljenje trenutne sesije. [Saznajte više](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## Podešavanje uređivača + +Obje naredbe `/editor` i `/export` koriste editor specificiran u vašoj varijabli okruženja `EDITOR`. + + + + + +```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + + +``` + + Da biste ga učinili trajnim, dodajte ovo u svoj shell profil; + `~/.bashrc`, `~/.zshrc`, itd. + + + + + + +```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + + +``` + + Da biste ga učinili trajnim, koristite **Svojstva sistema** > **Okruženje + Varijable**. + + + + + + +```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + + +``` + + Da biste ga učinili trajnim, dodajte ovo u svoj PowerShell profil. + + + + +Popularne opcije uređivača uključuju: + +- `code` - ​​Visual Studio Code +- `cursor` - ​​Kursor +- `windsurf` - ​​jedrenje na dasci +- `nvim` - ​​Neovim editorom +- `vim` - ​​Vim editor +- `nano` - ​​Nano editor +- `notepad` - ​​Windows Notepad +- `subl` - ​​Uzvišeni tekst + +:::note +Neki uređivači kao što je VS Code moraju biti pokrenuti sa `--wait` zastavicom. +::: + +Nekim uređivačima su potrebni argumenti komandne linije da bi se pokrenuli u načinu blokiranja. Oznaka `--wait` blokira proces uređivača dok se ne zatvori. + +--- + +## Konfiguriši + +Možete prilagoditi TUI ponašanje putem vašeg OpenCode konfiguracionog fajla. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### Opcije + +- `scroll_acceleration` - ​​Omogućite ubrzanje pomicanja u macOS stilu za glatko, prirodno pomicanje. Kada je omogućeno, brzina pomicanja se povećava brzim pokretima pomicanja i ostaje precizna za sporije pokrete. **Ova postavka ima prednost nad `scroll_speed` i nadjačava je kada je omogućena.** +- `scroll_speed` - ​​Kontrolira koliko brzo TUI skroluje kada se koriste komande za pomeranje (minimalno: `1`). Podrazumevano je `3`. **Napomena: Ovo se zanemaruje ako je `scroll_acceleration.enabled` postavljeno na `true`.** + +--- + +## Prilagođavanje + +Možete prilagoditi različite aspekte TUI prikaza koristeći paletu komandi (`ctrl+x h` ili `/help`). Ove postavke traju i nakon ponovnog pokretanja. + +--- + +#### Prikaz korisničkog imena + +Uključite da li se vaše korisničko ime pojavljuje u porukama za ćaskanje. Pristupite ovome putem: + +- Paleta naredbi: Potražite "korisničko ime" ili "sakrij korisničko ime" +- Postavka se automatski nastavlja i pamtit će se tijekom TUI sesija diff --git a/packages/web/src/content/docs/bs/web.mdx b/packages/web/src/content/docs/bs/web.mdx new file mode 100644 index 000000000..6da5da4f3 --- /dev/null +++ b/packages/web/src/content/docs/bs/web.mdx @@ -0,0 +1,142 @@ +--- +title: Web +description: Korišćenje OpenCode-a u vašem pretraživaču. +--- + +OpenCode može raditi kao web aplikacija u vašem pretraživaču, pružajući isto moćno iskustvo AI kodiranja bez potrebe za terminalom. + +![OpenCode Web - Nova sesija](../../../assets/web/web-homepage-new-session.png) + +## Početak rada + +Pokrenite web interfejs tako što ćete pokrenuti: + +```bash +opencode web +``` + +Ovo pokreće lokalni server na `127.0.0.1` sa nasumičnim dostupnim portom i automatski otvara OpenCode u vašem podrazumevanom pretraživaču. + +:::caution +Ako `OPENCODE_SERVER_PASSWORD` nije postavljen, server će biti nezaštićen. Ovo je u redu za lokalnu upotrebu, ali bi trebalo biti postavljeno za pristup mreži. +::: + +:::tip[Windows Users] +Za najbolje iskustvo, pokrenite `opencode web` iz [WSL](/docs/windows-wsl) umjesto PowerShell-a. Ovo osigurava pravilan pristup sistemu datoteka i integraciju terminala. +::: + +--- + +## Konfiguracija + +Možete konfigurirati web server koristeći oznake komandne linije ili u vašoj [config file](/docs/config). + +### Port + +OpenCode podrazumevano bira dostupni port. Možete odrediti port: + +```bash +opencode web --port 4096 +``` + +### Ime hosta + +Podrazumevano, server se vezuje za `127.0.0.1` (samo lokalni host). Da biste OpenCode učinili dostupnim na vašoj mreži: + +```bash +opencode web --hostname 0.0.0.0 +``` + +Kada koristite `0.0.0.0`, OpenCode će prikazati i lokalne i mrežne adrese: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### mDNS Discovery + +Omogućite mDNS kako bi vaš server bio vidljiv na lokalnoj mreži: + +```bash +opencode web --mdns +``` + +Ovo automatski postavlja ime hosta na `0.0.0.0` i oglašava server kao `opencode.local`. + +Možete prilagoditi ime mDNS domene za pokretanje više instanci na istoj mreži: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +Da biste omogućili dodatne domene za CORS (korisno za prilagođene frontendove): + +```bash +opencode web --cors https://example.com +``` + +### Autentifikacija + +Da biste zaštitili pristup, postavite lozinku koristeći varijablu okruženja `OPENCODE_SERVER_PASSWORD`: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +Korisničko ime podrazumevano je `opencode`, ali se može promeniti sa `OPENCODE_SERVER_USERNAME`. + +--- + +## Korištenje web sučelja + +Jednom pokrenut, web sučelje pruža pristup vašim OpenCode sesijama. + +### Sesije + +Pregledajte i upravljajte svojim sesijama sa početne stranice. Možete vidjeti aktivne sesije i započeti nove. + +![OpenCode Web - aktivna sesija](../../../assets/web/web-homepage-active-session.png) + +### Status servera + +Kliknite "Pogledajte servere" da vidite povezane servere i njihov status. + +![OpenCode Web - Vidi servere](../../../assets/web/web-homepage-see-servers.png) + +--- + +## Povezivanje terminala + +Možete priključiti TUI terminala na aktivni web server: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +Ovo vam omogućava da istovremeno koristite i web sučelje i terminal, dijeleći iste sesije i stanje. + +--- + +## Konfiguracioni fajl + +Također možete konfigurirati postavke servera u svom `opencode.json` konfiguracijskom fajlu: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +Oznake komandne linije imaju prednost nad postavkama konfiguracione datoteke. diff --git a/packages/web/src/content/docs/bs/windows-wsl.mdx b/packages/web/src/content/docs/bs/windows-wsl.mdx new file mode 100644 index 000000000..cace9c182 --- /dev/null +++ b/packages/web/src/content/docs/bs/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: Pokrenite OpenCode na Windowsu preko WSL-a. +--- + +import { Steps } from "@astrojs/starlight/components" + +Iako OpenCode moze raditi direktno na Windowsu, preporucujemo [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) za najbolje iskustvo. WSL daje Linux okruzenje koje glatko radi sa OpenCode funkcijama. + +:::tip[Why WSL?] +WSL nudi bolje performanse fajl sistema, punu terminalsku podrsku i kompatibilnost s razvojnim alatima na koje se OpenCode oslanja. +::: + +--- + +## Setup + + + +1. **Instalirajte WSL** + + Ako vec niste, [instalirajte WSL](https://learn.microsoft.com/en-us/windows/wsl/install) prema zvanicnom Microsoft vodicu. + +2. **Instalirajte OpenCode u WSL-u** + + Kad je WSL spreman, otvorite WSL terminal i instalirajte OpenCode jednom od [metoda instalacije](/docs/). + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **Koristite OpenCode iz WSL-a** + + Idite u direktorij projekta (Windows fajlovima pristupate preko `/mnt/c/`, `/mnt/d/` itd.) i pokrenite OpenCode. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## Desktop App + WSL Server + +Ako preferirate OpenCode Desktop aplikaciju, ali zelite da server radi u WSL-u: + +1. **Pokrenite server u WSL-u** sa `--hostname 0.0.0.0` da dozvolite vanjske konekcije: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Povezite Desktop aplikaciju** na `http://localhost:4096` + +:::note +Ako `localhost` ne radi u vasem setupu, povezte se preko WSL IP adrese (u WSL-u: `hostname -I`) i koristite `http://:4096`. +::: + +:::caution +Kada koristite `--hostname 0.0.0.0`, postavite `OPENCODE_SERVER_PASSWORD` da zastitite server. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Web Client + WSL + +Za najbolje web iskustvo na Windowsu: + +1. **Pokrenite `opencode web` u WSL terminalu** umjesto u PowerShell-u: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Otvorite iz Windows browsera** na `http://localhost:` (OpenCode ispisuje URL) + +Pokretanje `opencode web` iz WSL-a osigurava ispravan pristup fajl sistemu i terminalsku integraciju, a i dalje je dostupno iz Windows browsera. + +--- + +## Pristup Windows fajlovima + +WSL moze pristupiti svim Windows fajlovima kroz `/mnt/` direktorij: + +- Disk `C:` → `/mnt/c/` +- Disk `D:` → `/mnt/d/` +- I tako dalje... + +Primjer: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +Za najgladje iskustvo, razmislite da klonirate/kopirate repo u WSL fajl sistem (npr. pod `~/code/`) i tu pokrenete OpenCode. +::: + +--- + +## Tips + +- Drzite OpenCode u WSL-u za projekte na Windows diskovima - pristup fajlovima je jednostavan +- Koristite VS Code [WSL ekstenziju](https://code.visualstudio.com/docs/remote/wsl) uz OpenCode za integrisan tok rada +- Vase OpenCode konfiguracije i sesije cuvaju se u WSL okruzenju na `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/bs/zen.mdx b/packages/web/src/content/docs/bs/zen.mdx new file mode 100644 index 000000000..6ae22551a --- /dev/null +++ b/packages/web/src/content/docs/bs/zen.mdx @@ -0,0 +1,236 @@ +--- +title: Zen +description: Kurirana lista modela koje nudi OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen je lista testiranih i provjerenih modela koje obezbjeduje OpenCode tim. + +:::note +OpenCode Zen je trenutno u beta fazi. +::: + +Zen radi kao i svaki drugi provajder u OpenCode-u. Prijavite se u OpenCode Zen i uzmete API kljuc. Ovo je **potpuno opcionalno** i ne morate ga koristiti da biste koristili OpenCode. + +--- + +## Background + +Postoji veliki broj modela, ali samo mali dio radi dobro kao coding agent. Dodatno, vecina provajdera je drugacije konfigurisana, pa su performanse i kvalitet cesto neujednaceni. + +:::tip +Testirali smo odabranu grupu modela i provajdera koji dobro rade s OpenCode-om. +::: + +Ako model koristite preko servisa poput OpenRouter-a, cesto ne mozete biti sigurni da dobijate najbolju verziju zeljenog modela. + +Da to rijesimo, uradili smo nekoliko stvari: + +1. Testirali smo odabrane modele i razgovarali sa njihovim timovima kako ih najbolje pokretati. +2. Zatim smo saradjivali s nekoliko provajdera da potvrdimo da se modeli isporucuju ispravno. +3. Na kraju smo benchmarkirali kombinacije model/provajder i sastavili listu koju preporucujemo. + +OpenCode Zen je AI gateway koji vam daje pristup tim modelima. + +--- + +## Kako radi + +OpenCode Zen radi kao i svaki drugi provajder u OpenCode-u. + +1. Prijavite se na **OpenCode Zen**, dodajte billing podatke i kopirajte API kljuc. +2. U TUI-ju pokrenite `/connect`, izaberite OpenCode Zen i zalijepite API kljuc. +3. Pokrenite `/models` u TUI-ju da vidite listu preporucenih modela. + +Naplata je po zahtjevu i mozete dodavati kredit na racun. + +--- + +## Endpoints + +Nasim modelima mozete pristupiti i preko sljedecih API endpointa. + +| Model | Model ID | Endpoint | AI SDK Package | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Free | minimax-m2.1-free | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Free | glm-4.7-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Free | kimi-k2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +[model id](/docs/config/#models) u OpenCode konfiguraciji koristi format `opencode/`. Na primjer, za GPT 5.2 Codex u konfiguraciji koristite `opencode/gpt-5.2-codex`. + +--- + +### Models + +Pun spisak dostupnih modela i metapodataka mozete preuzeti na: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## Pricing + +Podrzavamo pay-as-you-go model. Ispod su cijene **po 1M tokena**. + +| Model | Input | Output | Cached Read | Cached Write | +| --------------------------------- | ------ | ------ | ----------- | ------------ | +| Big Pickle | Free | Free | Free | - | +| MiniMax M2.1 Free | Free | Free | Free | - | +| MiniMax M2.1 | $0.30 | $1.20 | $0.10 | - | +| GLM 4.7 Free | Free | Free | Free | - | +| GLM 4.7 | $0.60 | $2.20 | $0.10 | - | +| GLM 4.6 | $0.60 | $2.20 | $0.10 | - | +| Kimi K2.5 Free | Free | Free | Free | - | +| Kimi K2.5 | $0.60 | $3.00 | $0.08 | - | +| Kimi K2 Thinking | $0.40 | $2.50 | - | - | +| Kimi K2 | $0.40 | $2.50 | - | - | +| Qwen3 Coder 480B | $0.45 | $1.50 | - | - | +| Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | +| Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | +| Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | +| Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | +| Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | - | +| Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | - | +| Gemini 3 Flash | $0.50 | $3.00 | $0.05 | - | +| GPT 5.2 | $1.75 | $14.00 | $0.175 | - | +| GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | - | +| GPT 5.1 | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | - | +| GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | - | +| GPT 5 | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Nano | Free | Free | Free | - | + +U historiji koristenja mozete primijetiti _Claude Haiku 3.5_. To je [low cost model](/docs/config/#models) koji se koristi za generisanje naslova sesija. + +:::note +Naknade kartica se prenose po stvarnom trosku (4.4% + $0.30 po transakciji) i ne naplacujemo nista preko toga. +::: + +Besplatni modeli: + +- GLM 4.7 Free je dostupan na OpenCode-u ograniceno vrijeme. Tim koristi taj period za prikupljanje feedbacka i unapredenje modela. +- Kimi K2.5 Free je dostupan na OpenCode-u ograniceno vrijeme. Tim koristi taj period za prikupljanje feedbacka i unapredenje modela. +- MiniMax M2.1 Free je dostupan na OpenCode-u ograniceno vrijeme. Tim koristi taj period za prikupljanje feedbacka i unapredenje modela. +- Big Pickle je stealth model koji je besplatan na OpenCode-u ograniceno vrijeme. Tim koristi taj period za prikupljanje feedbacka i unapredenje modela. + +Ako imate pitanja, kontaktirajte nas. + +--- + +### Auto-reload + +Ako vam stanje padne ispod $5, Zen ce automatski dopuniti $20. + +Iznos auto-reloada mozete promijeniti. Auto-reload mozete i potpuno iskljuciti. + +--- + +### Monthly limits + +Mozete postaviti mjesecni limit potrosnje za cijeli workspace i za svakog clana tima. + +Na primjer, ako postavite mjesecni limit na $20, Zen nece potrositi vise od $20 u mjesecu. Ali ako je auto-reload ukljucen, ukupna naplata moze preci $20 ako stanje padne ispod $5. + +--- + +## Privacy + +Svi nasi modeli su hostovani u SAD-u. Provajderi prate zero-retention politiku i ne koriste vase podatke za treniranje modela, uz sljedece izuzetke: + +- Big Pickle: Tokom besplatnog perioda, prikupljeni podaci mogu se koristiti za poboljsanje modela. +- GLM 4.7 Free: Tokom besplatnog perioda, prikupljeni podaci mogu se koristiti za poboljsanje modela. +- Kimi K2.5 Free: Tokom besplatnog perioda, prikupljeni podaci mogu se koristiti za poboljsanje modela. +- MiniMax M2.1 Free: Tokom besplatnog perioda, prikupljeni podaci mogu se koristiti za poboljsanje modela. +- OpenAI API-ji: Zahtjevi se cuvaju 30 dana prema [OpenAI Data Policies](https://platform.openai.com/docs/guides/your-data). +- Anthropic API-ji: Zahtjevi se cuvaju 30 dana prema [Anthropic Data Policies](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## For Teams + +Zen odlicno radi i za timove. Mozete pozvati clanove tima, dodijeliti uloge, birati modele koje tim koristi i jos mnogo toga. + +:::note +Workspaces su trenutno besplatni za timove kao dio beta faze. +::: + +Upravljanje workspace-om je trenutno besplatno za timove tokom beta faze. Vise detalja o cijenama podijelit cemo uskoro. + +--- + +### Roles + +Mozete pozvati clanove tima u workspace i dodijeliti uloge: + +- **Admin**: upravlja modelima, clanovima, API kljucevima i billingom +- **Member**: upravlja samo svojim API kljucevima + +Admini mogu postaviti i mjesecne limite potrosnje po clanu da drze troskove pod kontrolom. + +--- + +### Model access + +Admini mogu ukljuciti ili iskljuciti odredene modele za workspace. Zahtjevi prema iskljucenom modelu vracaju gresku. + +Ovo je korisno kada zelite zabraniti model koji prikuplja podatke. + +--- + +### Bring your own key + +Mozete koristiti vlastite OpenAI ili Anthropic API kljuceve i dalje koristiti ostale modele u Zen-u. + +Kada koristite vlastite kljuceve, tokene direktno naplacuje provajder, ne Zen. + +Na primjer, vasa organizacija mozda vec ima OpenAI ili Anthropic kljuc i zelite koristiti njega umjesto onog koji daje Zen. + +--- + +## Goals + +OpenCode Zen smo napravili da: + +1. **Benchmarkiramo** najbolje kombinacije model/provajder za coding agente. +2. Omogucimo pristup opcijama **najviseg kvaliteta** bez degradacije performansi i preusmjeravanja na jeftinije provajdere. +3. Prenesemo svaka **snizenja cijena** prodajom po trosku, tako da je jedini markup pokrice processing naknada. +4. Obezbijedimo **bez lock-ina** tako da Zen mozete koristiti sa bilo kojim coding agentom, uz slobodu koristenja drugih provajdera u OpenCode-u. diff --git a/packages/web/src/content/docs/da/1-0.mdx b/packages/web/src/content/docs/da/1-0.mdx new file mode 100644 index 000000000..744c4ea87 --- /dev/null +++ b/packages/web/src/content/docs/da/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: Migrerer til 1.0 +description: Hvad er nyt i OpenCode 1.0. +--- + +OpenCode 1.0 er en komplet omskrivning af TUI. + +Vi flyttede fra den go+bubbletea-baserede TUI, som havde problemer med ydeevne og kapacitet, til en intern ramme (OpenTUI) skrevet i zig+solidjs. + +Den nye TUI fungerer som den gamle, da den opretter forbindelse til den samme opencode-server. + +--- + +##Opgradering + +Du bør ikke automatisk opgraderes til 1.0, hvis du er i øjeblikket bruger en tidligere +version. Nogle ældre versioner af OpenCode henter dog altid den nyeste. + +Kør for at opgradere manuelt + +```bash +$ opencode upgrade 1.0.0 +``` + +Kør for at nedgradere tilbage til 0.x + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## UX ændringer + +Sessionshistorikken er mere komprimeret og viser kun alle detaljer om redigerings- og bash-værktøjet. + +Vi tilføjede en kommandolinje, som næsten alt flyder igennem. Tryk på ctrl+p for at få det frem i enhver sammenhæng og se alt, hvad du kan gøre. + +Tilføjet en sessionssidebjælke (kan skiftes) med nyttige oplysninger. + +Vi fjernede nogle funktioner, som vi ikke var sikre på, at nogen rent faktisk brugte. Hvis der mangler noget vigtigt, bedes du åbne et problem, så tilføjer vi det hurtigt igen. + +--- + +## Brydende ændringer + +### Nøglebindinger omdøbt + +- messages_revert -> messages_undo +- switch_agent -> agent_cyklus +- switch_agent_reverse -> agent_cyklus_reverse +- switch_mode -> agent_cyklus +- switch_mode_reverse -> agent_cyklus_reverse + +### Nøglebindinger fjernet + +- messages_layout_toggle +- beskeder_næste +- beskeder_forrige +- file_diff_toggle +- fil_søgning +- fil_luk +- fil_liste +- app_hjælp +- projekt_init +- tool_details +- tænkeblokke diff --git a/packages/web/src/content/docs/da/acp.mdx b/packages/web/src/content/docs/da/acp.mdx new file mode 100644 index 000000000..802f126e2 --- /dev/null +++ b/packages/web/src/content/docs/da/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACP support +description: Brug OpenCode i enhver ACP-kompatibel editor. +--- + +OpenCode understøtter [Agent Client Protocol](https://agentclientprotocol.com) eller (ACP), så du kan bruge det direkte i kompatible editorer og IDE'er. + +:::tip +For en liste over redaktører og værktøjer, der understøtter ACP, tjek [ACP progress report](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP er en åben protokol, der standardiserer kommunikation mellem kodeeditorer og AI-kodningsagenter. + +--- + +## Konfigurer + +For at bruge OpenCode via ACP, konfigurer din editor til at køre kommandoen `opencode acp`. + +Kommandoen starter OpenCode som en ACP-kompatibel underproces, der kommunikerer med din editor over JSON-RPC via stdio. + +Nedenfor er eksempler på populære redaktører, der understøtter ACP. + +--- + +### Zed + +Føj til din [Zed](https://zed.dev)-konfiguration (`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +For at åbne den skal du bruge handlingen `agent: new thread` i **Kommandopaletten**. + +Du kan også binde en tastaturgenvej ved at redigere din `keymap.json`: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### JetBrains IDE'er + +Tilføj til din [JetBrains IDE](https://www.jetbrains.com/) acp.json i henhold til [documentation](https://www.jetbrains.com/help/ai-assistant/acp.html): + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +For at åbne den skal du bruge den nye 'OpenCode'-agent i AI Chat-agentvælgeren. + +--- + +### Avante.nvim + +Føj til din [Avante.nvim](https://github.com/yetone/avante.nvim)-konfiguration: + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +Hvis du har brug for at videregive miljøvariabler: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +For at bruge OpenCode som en ACP-agent i [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim), skal du tilføje følgende til din Neovim-konfiguration: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +Denne konfiguration sætter CodeCompanion til at bruge OpenCode som ACP-agent til chat. + +Hvis du har brug for at sende miljøvariabler (som `OPENCODE_API_KEY`), henvises til [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) i CodeCompanion.nvim-dokumentationen for alle detaljer. + +## Support + +OpenCode fungerer på samme måde via ACP som i terminalen. Alle funktioner understøtter: + +:::note +Nogle indbyggede skråstreg-kommandoer som `/undo` og `/redo` er i øjeblikket ikke understøttet. +::: + +- Indbyggede værktøjer (filoperationer, terminalkommandoer osv.) +- Brugerdefinerede værktøjer og skråstreg-kommandoer +- MCP-servere konfigureret i din OpenCode-konfiguration +- Projektspecifikke regler fra `AGENTS.md` +- Brugerdefinerede formatere og linters +- Agenter og tilladelsessystem diff --git a/packages/web/src/content/docs/da/agents.mdx b/packages/web/src/content/docs/da/agents.mdx new file mode 100644 index 000000000..26c83ff52 --- /dev/null +++ b/packages/web/src/content/docs/da/agents.mdx @@ -0,0 +1,747 @@ +--- +title: Agent +description: Konfigurer og brug specialiserede agenter. +--- + +Agenter er specialiserede AI-assistenter, der kan konfigureres til specifikke opgaver og arbejdsgange. De giver dig mulighed for at oprette en central værktøj med brugerdefinerede prompter, modeller og værktøjsadgang. + +:::tip +Brug planagenten til at analysere kode og gennemgå forslag uden at foretage nogen kodeændringer. +::: + +Du kan skifte mellem agenter under en session eller kalde dem med `@`-omtalen. + +--- + +## Skriver + +Der er to typer agenter i OpenCode; primære midler og subagenter. + +--- + +### Primære agent + +Primære agenter er de vigtigste assistenter, du interagerer direkte med. Du kan bladre gennem dem ved at bruge **Tab**-tasten eller din konfigurerede `switch_agent`-tastebinding. Disse agenter håndterer din hovedsamtale. Værktøjsadgang konfigureres via tilladelser - for eksempel har Build alle aktiveret, mens Plan er begrænset. + +:::tip +Du kan bruge **Tab**-tasten til at skifte mellem primære agenter under en session. +::: + +OpenCode leveres med indbyggede primære agenter, **Build** og **Plan**. Godt +se på disse nedenfor. + +--- + +### Subagent + +Subagenter er specialiserede assistenter, som primære agenter kan påbegynde sig til specifikke opgaver. Du kan også kalde dem manuelt ved at **@ nævne** dem i dine beskeder. + +OpenCode leveres med til indbyggede underagenter, **Generelt** og **Udforsk**. Vi vil se på dette nedenfor. + +--- + +## Indbygget + +OpenCode leveres med to indbyggede primære agenter og to indbyggede subagenter. + +--- + +### Brug bygge + +_Tilstand_: `primary` + +Byg er den **standard** primære agent med alle aktiveret. Dette er standardagenten til udviklingsarbejde, hvor du har brug for fuld adgang til filhandlinger og systemkommandoer. + +--- + +### Brug plan + +_Tilstand_: `primary` + +En begrænset agent designet til planlægning og analyse. Vi bruger et tilladelsessystem til at give dig mere kontrol og forhindre utilsigtede ændringer. +Som standard er alle følgende indstillet til `ask`: + +- `file edits`: Alle skrivninger, patches og redigeringer +- `bash`: Alle bash-kommandoer + +Denne agent er nyttig, når du vil have LLM til at analysere kode, foreslå ændringer eller oprette planer uden at foretage egentlige ændringer af din kodebase. + +--- + +### Brug generelt + +_Tilstand_: `subagent` + +En agent til generelt formål at undersøge komplekse spørgsmål og udføre opgaver i flere trin. Har fuld værktøjsadgang (undtagen todo), så den kan foretage filændringer, når det er nødvendigt. Brug dette til at køre flere arbejdsenheder parallelt. + +--- + +### Brug udforsk + +_Tilstand_: `subagent` + +En hurtig, skrivebeskyttet agent til at udforske kodebaser. Kan ikke ændre filer. Brug dette, når du hurtigt skal finde filer efter mønstre, søge kode efter nøgleord eller besvare spørgsmål om kodebasen. + +--- + +### Brug komprimering + +_Tilstand_: `primary` + +Skjult systemagent, der komprimerer lang kontekst til et mindre resumé. Det kører automatisk, når det er nødvendigt og ikke kan vælges i brugergrænsefladen. + +--- + +### Brug titel + +_Tilstand_: `primary` + +Skjult systemagent, der genererer korte sessionstitler. Den kører automatisk og kan ikke vælges i brugergrænsefladen. + +--- + +### Brug CV + +_Tilstand_: `primary` + +Skjult systemagent, der opretter sessionsoversigter. Den kører automatisk og kan ikke vælges i brugergrænsefladen. + +--- + +## Brug + +1. For primære agenter skal du bruge tasten **Tab** til at bladre gennem dem under en session. Du kan også bruge din konfigurerede `switch_agent` nøglebinding. + +2. Subagenter kan påberåbes: + - **Automatisk** af primære agenter til specialiserede opgaver baseret på deres beskrivelser. + - Manuelt ved at **@ nævne** en underagent i din besked. F.eks. + + ```txt frame="none" + @general help me search for this function + ``` + +3. **Navigation mellem sessioner**: Når underagenter opretter deres egne underordnede sessioner, kan du navigere mellem den overordnede session og alle underordnede sessioner ved hjælp af: + - **\+Højre** (eller din konfigurerede `session_child_cycle`-smagsbinding) for at cykle fremad gennem forælder → barn1 → barn2 →... → forælder + - **\+Venstre** (eller din konfigurerede `session_child_cycle_reverse`-smagsbinding) for at cykle baglæns gennem forælder ← barn1 ← barn2 ←... ← forælder + + Dette giver dig mulighed for problemfrit at skifte mellem hovedsamtalen og specialiseret subagent arbejde. + +--- + +## Konfigurer + +Du kan tilpasse de indbyggede agenter eller oprette dine egne gennem konfiguration. Agenter kan konfigureres på følgende måder: + +--- + +### JSON + +Konfigurationsagent i din `opencode.json`-konfigurationsfil: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Markdown + +Du kan også definere agenter ved hjælp af markdown-filer. Placer dem i: + +- Globalt: `~/.config/opencode/agents/` +- Pr. projekt: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Markdown-filnavnet bliver agentnavnet. For eksempel opretter `review.md` og `review`-agent. + +--- + +## Indstillinger + +Lad os se nærmere på disse konfigurationsmuligheder. + +--- + +### Beskrivelse + +Brug indstillingen `description` til at give en kort beskrivelse af, hvad agenten gør, og hvornår den skal bruges. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +Dette er en **påkrævet** konfigurationsindstilling. + +--- + +### Temperatur + +Styr tilfældigheden og kreativiteten af ​​​​LLMs svar med `temperature`-konfigurationen. + +Lavere værdier gør svar mere fokuserede og deterministiske, mens højere værdier øger kreativitet og variabilitet. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Temperaturværdier typisk fra 0,0 til 1,0: + +- **0.0-0.2**: Meget fokuseret og deterministisk svar, ideel til kodeanalyse og planlægning +- **0,3-0,5**: Afbalancerede svar med en vis kreativitet, god til generelle udviklingsopgaver +- **0.6-1.0**: Mere kreative og varierede svar, nyttige til brainstorming og udforskning + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Hvis ingen temperatur er angivet, bruger OpenCode modelspecifikke standardindstillinger; typisk 0 for de fleste modeller, 0,55 for Qwen-modeller. + +--- + +### Maks. skridt + +Kontrollerer det maksimale antal agent-gentagelser, som en agent kan udføre, før han bliver tvunget til kun at svare med tekst. Dette giver brugere, der ønsker at kontrollere, mulighed for at sætte en grænse for agenthandlinger. + +Hvis dette ikke er indstillet, vil agenten fortsætte med at iterere, indtil modellen vælger at stoppe, eller brugeren afbryder sessionen. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +Når grænsen er nået, modtager agenten en speciel systemprompt, der instruerer den om at svare med en opsummering af sit arbejde og anbefalede resterende opgaver. + +:::forsigtighed +Det gamle `maxSteps` følte er forældet. Brug `steps` i stedet. +::: + +--- + +### Deaktiver + +Indstil til `true` for at deaktivere agenten. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Spørg + +Angiv en brugerdefineret systempromptfil for denne agent med `prompt`-konfigurationen. Promptfilen skal indeholde instruktioner, der er specifikke for agentens formål. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Denne sti er i forhold til, hvor konfigurationsfilen er placeret. Så dette virker både for den globale OpenCode-konfiguration og den projektspecifikke konfiguration. + +--- + +### Model + +Brug `model`-konfigurationen til at tilsidesætte modeller for denne agent. Nyttigt til brug af forskellige modeller optimeret til forskellige opgaver. For eksempel en hurtigere model til planlægning, en dygtig model til implementering. + +:::tip +Hvis du ikke angiver en model, bruger primære agenter [model globally configured](/docs/config#models), mens subagenter vil bruge modeller for den primære agent, der påkaldte subagenten. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +Model-id'et i din OpenCode-konfiguration brugerformatet `provider/model-id`. For eksempel, hvis du bruger [OpenCode Zen](/docs/zen), vil du bruge `opencode/gpt-5.1-codex` til GPT 5.1 Codex. + +--- + +### Værktøjer + +Kontroller, hvilke værktøjer der er tilgængelige i denne agent med `tools`-konfigurationen. Du kan aktivere eller deaktivere specifikke redskaber ved at indstille dem til `true` eller `false`. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +Den agentspecifikke konfiguration tilsidesætter den globale konfiguration. +::: + +Du kan også bruge jokertegn til at styre flere værktøjer på én gang. For eksempel, for at deaktivere alle værktøjer fra en MCP-server: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[Learn more about tools](/docs/tools). + +--- + +### Tilladelser + +Du kan konfigurere tilladelser til at administrere, hvilke handlinger og agenter kan udføre. I øjeblikket kan tilladelserne til værktøjerne `edit`, `bash` og `webfetch` konfigureres til: + +- `"ask"` — Bed om godkendelse, før du kører værktøjet +- `"allow"` — Tillad alle operationer uden godkendelse +- `"deny"` — Deaktiver værktøjet + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +Du kan tilsidesætte disse tilladelser pr. agent. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +Du kan også angive tilladelser i Markdown-agenter. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +Du kan indstille tilladelser til specifikke bash-kommandoer. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +Dette kan tage et globmønster. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +Og du kan også bruge jokertegnet `*` til at administrere tilladelser for alle kommandoer. +Da den sidste matchningsregel har forrang, skal du sætte jokertegnet `*` først og specifikke regler efter. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[Learn more about permissions](/docs/permissions). + +--- + +### Tilstand + +Styr agentens tilstand med `mode`-konfigurationen. Indstillingen `mode` bruges til at bestemme, hvordan agenten kan bruges. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +Indstillingen `mode` kan indstilles til `primary`, `subagent` eller `all`. Hvis der ikke er angivet nogen `mode`, er den som standard `all`. + +--- + +### Skjult + +Skjul en underagent fra `@` autofuldførelsesmenuen med `hidden: true`. Nyttigt for interne underagenter, der kun bør startes programmatisk af andre agenter via opgaveværktøjet. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +Dette påvirker kun brugerens synlighed i autofuldførelsesmenuen. Skjulte agenter kan stadig påkaldes af modellen via opgaveværktøjet, hvis tilladelser tillader det. + +:::note +Gælder kun for `mode: subagent`-agent. +::: + +--- + +### Opgavetilladelser + +Kontroller, hvilke subagenter en agent kan påkalde via opgaveværktøjet med `permission.task`. Bruger glob-mønstre til fleksibel matchning. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +Når den er indstillet til `deny`, fjernes subagenten helt fra opgaveværktøjsbeskrivelsen, så modeller vil ikke forsøge at starte den. + +:::tip +Reglerne vurderer i rækkefølge, og den **sidste matchende regel vinder**. I eksemplet ovenfor matcher `orchestrator-planner` både `*` (afvis) og `orchestrator-*` (tillad), men da `orchestrator-*` kommer efter `*`, er resultatet `allow`. +::: + +:::tip +Brugere kan altid påkalde enhver underagent direkte via `@` autofuldførelsesmenuen, nægt agentens opgavetilladelser ville det. +::: + +--- + +### Farve + +Tilpas agentens visuelle udseende i brugergrænsefladen med muligheden `color`. Dette påvirker, hvordan agenter vises i grænsefladen. + +Brug en gyldig hex-farve (f.eks. `#FF5733`) eller temafarve: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### Top P + +Styr responsdiversiteten med `top_p`-muligheden. Alternativ til temperatur for at kontrollere tilfældighed. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +Værdier spænder fra 0,0 til 1,0. Lavere værdier er mere fokuserede, højere værdier mere forskelligartede. + +--- + +### Yderligere + +Alle andre muligheder, du angiver i din agentkonfiguration, vil blive **overført direkte** til udbyderen som modelvalg. Dette giver dig mulighed for at bruge udbyderspecifikke funktioner og parametre. + +For eksempel, med OpenAIs ræsoneringsmodeller kan du styre ræsonnementindsatsen: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +Disse yderligere muligheder er model- og udbyderspecifikke. Tjek din udbyders dokumentation for tilgængelige parametre. + +:::tip +Kør `opencode models` for at se en liste over de tilgængelige modeller. +::: + +--- + +## Opret agent + +Du kan oprette nye agenter ved hjælp af følgende kommando: + +```bash +opencode agent create +``` + +Denne interaktive kommando vil: + +1. Spørg, hvor agenten skal gemmes; globalt eller projektspecifikt. +2. Beskrivelse af, hvad agenten skal gøre. +3. Generer en passende systemprompt og identifikator. +4. Lad dig vælge, hvilke værktøjer agenter har adgang til. +5. Til sidst skal du oprette en markdown-fil med agentkonfigurationen. + +--- + +## Use cases + +Her er nogle almindelige use cases for forskellige agenter. + +- **Byggeagent**: Fuldt udviklingsarbejde med alle aktiveret +- **Planagent**: Analyse og planlægning uden ændringer +- **Anmeldelsesagent**: Kodegennemgang med skrivebeskyttet adgang plus dokumentationsværktøjer +- **Debug agent**: Fokuseret på undersøgelse med bash og læseværktøjer aktiveret +- **Docs-agent**: Dokumentationsskrivning med filhandlinger, men ingen systemkommandoer + +--- + +## Eksempler + +Her er nogle eksempler på agenter, du kan finde nyttige. + +:::tip +Har du en agent, du gerne vil dele? [Submit a PR](https://github.com/anomalyco/opencode). +::: + +--- + +### Dokumentationsagent + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### Sikkerhedsrevisor + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/da/cli.mdx b/packages/web/src/content/docs/da/cli.mdx new file mode 100644 index 000000000..8ad292421 --- /dev/null +++ b/packages/web/src/content/docs/da/cli.mdx @@ -0,0 +1,601 @@ +--- +title: CLI +description: OpenCode CLI muligheder og kommandoer. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode CLI starter som standard [TUI](/docs/tui), når den kører uden nogen argumenter. + +```bash +opencode +``` + +Men den accepterer også kommandoer som dokumenteret på denne side. Dette giver dig mulighed for at interagere med OpenCode programmatisk. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui + +Start OpenCode terminalbrugergrænsefladen. + +```bash +opencode [project] +``` + +#### Flag + +| Flag | Kort | Beskrivelse | +| ------------ | ---- | --------------------------------------- | +| `--continue` | `-c` | Fortsæt sidste session | +| `--session` | `-s` | Sessions-id for at fortsætte | +| `--prompt` | | Spørg om at bruge | +| `--model` | `-m` | Model til brug i form af provider/model | +| `--agent` | | Agent hos bruge | +| `--port` | | Port at lytte på | +| `--hostname` | | Værtsnavn at lytte på | + +--- + +## Kommandoer + +OpenCode CLI har også følgende kommandoer. + +--- + +### agent + +Administratoragent for OpenCode. + +```bash +opencode agent [command] +``` + +--- + +### vedhæft + +Tilslut en terminal til en allerede kørende OpenCode backend-server startet via `serve` eller `web` kommandoer. + +```bash +opencode attach [url] +``` + +Dette gør det muligt at bruge TUI med en ekstern OpenCode backend. For eksempel: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### Flag + +| Flag | Kort | Beskrivelse | +| ----------- | ---- | -------------------------------- | +| `--dir` | | Arbejdsmappe til at starte TUI i | +| `--session` | `-s` | Sessions-id for at fortsætte | + +--- + +#### oprette + +Opret en ny agent med tilpasset konfiguration. + +```bash +opencode agent create +``` + +Denne kommando vil guide dig gennem oprettelse af en ny agent med en brugerdefineret systemprompt og værktøjskonfiguration. + +--- + +#### liste + +Liste over alle tilgængelige agenter. + +```bash +opencode agent list +``` + +--- + +### auth + +Kommando til at administrere legitimationsoplysninger og login for udbydere. + +```bash +opencode auth [command] +``` + +--- + +#### login + +OpenCode drives af udbyderlisten på [Models.dev](https://models.dev), så du kan bruge `opencode auth login` til at konfigurere API nøgler for enhver udbyder, du vil bruge. Dette er gemt i `~/.local/share/opencode/auth.json`. + +```bash +opencode auth login +``` + +Når OpenCode starter op, indlæser den udbyderne fra legitimationsfilen. Og hvis der er nogen nøgler defineret i dine miljøer eller en `.env` fil i dit projekt. + +--- + +#### liste + +Viser alle de godkendte udbydere som gemt i legitimationsfilen. + +```bash +opencode auth list +``` + +Eller den korte version. + +```bash +opencode auth ls +``` + +--- + +#### log ud + +Logger dig ud af en udbyder ved at rydde den fra legitimationsfilen. + +```bash +opencode auth logout +``` + +--- + +### github + +Administrator GitHub-agenten til lagerautomatisering. + +```bash +opencode github [command] +``` + +--- + +#### installationsprogram + +Installatør GitHub-agenten i dit lager. + +```bash +opencode github install +``` + +Dette opsætter det nødvendige GitHub Actions workflow og guider dig gennem konfigurationsprocessen. [Learn more](/docs/github). + +--- + +#### løb + +Kør GitHub-agenten. Dette bruges typisk i GitHub Actions. + +```bash +opencode github run +``` + +##### Flag + +| Flag | Beskrivelse | +| --------- | ---------------------------------------------- | +| `--event` | GitHub mock begivenhed for at køre agenten for | +| `--token` | GitHub personlig adgangstoken | + +--- + +### mcp + +Administrator Model Context Protocol-servere. + +```bash +opencode mcp [command] +``` + +--- + +#### tilføje + +Tilføj en MCP-server til din konfiguration. + +```bash +opencode mcp add +``` + +Denne kommando vil guide dig gennem tilføjelse af enten en lokal eller ekstern MCP-server. + +--- + +#### liste + +Liste over alle konfigurerede MCP-servere og deres forbindelsesstatus. + +```bash +opencode mcp list +``` + +Eller brug den korte version. + +```bash +opencode mcp ls +``` + +--- + +#### auth + +Godkendt med en OAuth-aktiveret MCP-server. + +```bash +opencode mcp auth [name] +``` + +Hvis du ikke angiver et servernavn, bliver du bedt om at vælge blandt tilgængelige OAuth-kompatible servere. + +Du kan også angive OAuth-kompatible servere og deres godkendelsesstatus. + +```bash +opencode mcp auth list +``` + +Eller brug den korte version. + +```bash +opencode mcp auth ls +``` + +--- + +#### log ud + +Fjern OAuth-legitimationsoplysninger for en MCP-server. + +```bash +opencode mcp logout [name] +``` + +--- + +#### fejlretning + +Fejlfinding af OAuth-forbindelsesproblemer for en MCP-server. + +```bash +opencode mcp debug +``` + +--- + +### modeller + +Liste over alle tilgængelige modeller fra konfigurerede udbydere. + +```bash +opencode models [provider] +``` + +Denne kommando viser alle tilgængelige modeller på tværs af dine konfigurerede udbydere i formatet `provider/model`. + +Dette er nyttigt til at finde ud af det nøjagtige modelnavn, der skal bruges i [your config](/docs/config/). + +Du kan eventuelt videregive et udbyder-id for at filtrere modeller efter den udbyder. + +```bash +opencode models anthropic +``` + +#### Flag + +| Flag | Beskrivelse | +| ----------- | ----------------------------------------------------------------------- | +| `--refresh` | Opdater modelcachen fra models.dev | +| `--verbose` | Brug mere detaljeret modeloutput (inkluderer metadata som omkostninger) | + +Brug flaget `--refresh` til at opdatere den cachelagrede modelliste. Dette er nyttigt, når nye modeller er blevet tilføjet til en udbyder, og du vil se dem i OpenCode. + +```bash +opencode models --refresh +``` + +--- + +### løb + +Kør opencode i ikke-interaktiv tilstand ved at sende en prompt direkte. + +```bash +opencode run [message..] +``` + +Dette er nyttigt til scripting, automatisering, eller når du vil have et hurtigt svar uden at starte hele TUI. F.eks. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +Du kan også vedhæfte til en kørende `opencode serve`-instans for at undgå MCP serverens kolde opstartstider ved hver kørsel: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### Flag + +| Flag | Kort | Beskrivelse | +| ------------ | ---- | ----------------------------------------------------------------------------------- | +| `--command` | | Kommandoen til at køre, brug besked til args | +| `--continue` | `-c` | Fortsæt sidste session | +| `--session` | `-s` | Sessions-id for at fortsætte | +| `--share` | | Del sessionen | +| `--model` | `-m` | Model til brug i form af provider/model | +| `--agent` | | Agent til brug | +| `--file` | `-f` | Fil(er), der skal vedhæftes til meddelelsen | +| `--format` | | Format: standard (formateret) eller json (rå JSON hændelser) | +| `--title` | | Titel for sessionen (bruger trunkeret prompt, hvis der ikke er angivet nogen værdi) | +| `--attach` | | Tilslut til en kørende opencode-server (f.eks. http://localhost:4096) | +| `--port` | | Port til den lokale server (standard til vilkårlig port) | + +--- + +### server + +Start en hovedløs OpenCode-server til API-adgang. Tjek [server docs](/docs/server) for den fulde HTTP-grænseflade. + +```bash +opencode serve +``` + +Dette starter en HTTP-server, der giver API-adgang til opencode-funktionalitet uden TUI-grænsefladen. Indstil `OPENCODE_SERVER_PASSWORD` for at aktivere HTTP grundlæggende godkendelse (brugernavn er standard til `opencode`). + +#### Flag + +| Flag | Beskrivelse | +| ------------ | ------------------------------------------------ | +| `--port` | Port at lytte på | +| `--hostname` | Værtsnavn at lytte på | +| `--mdns` | Aktiver mDNS-opdagelse | +| `--cors` | Yderligere browseroprindelse til at tillade CORS | + +--- + +### session + +Administrator OpenCode sessionsholder. + +```bash +opencode session [command] +``` + +--- + +#### liste + +Liste over alle OpenCode sessioner. + +```bash +opencode session list +``` + +##### Flag + +| Flag | Kort | Beskrivelse | +| ------------- | ---- | -------------------------------------- | +| `--max-count` | `-n` | Begræns til N seneste sessioner | +| `--format` | | Outputformat: tabel eller json (tabel) | + +--- + +### statistik + +Vis tokenbrug og omkostningsstatistikker for dine OpenCode-sessioner. + +```bash +opencode stats +``` + +#### Flag + +| Flag | Beskrivelse | +| ----------- | --------------------------------------------------------------------------- | +| `--days` | Vis statistik for de sidste N dage (hele tiden) | +| `--tools` | Antal værktøjer, der skal vises (alle) | +| `--models` | Vis modelbrugsopdeling (skjult som standard). Send et tal for at vise top N | +| `--project` | Filtre efter projekt (alle projekter, tom streng: nuværende projekt) | + +--- + +### eksport + +Eksporter sessionsdata som JSON. + +```bash +opencode export [sessionID] +``` + +Hvis du ikke angiver et sessions-id, bliver du bedt om at vælge mellem tilgængelige sessioner. + +--- + +### import + +Importer sessionsdata fra en JSON fil eller OpenCode del URL. + +```bash +opencode import +``` + +Du kan importere fra en lokal fil eller en OpenCode share URL. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### web + +Start en hovedløs OpenCode-server med en webgrænseflade. + +```bash +opencode web +``` + +Dette starter en HTTP-server og åbner en webbrowser for at få adgang til OpenCode via en webgrænseflade. Indstil `OPENCODE_SERVER_PASSWORD` for at aktivere HTTP grundlæggende godkendelse (brugernavn er standard til `opencode`). + +#### Flag + +| Flag | Beskrivelse | +| ------------ | ------------------------------------------------ | +| `--port` | Port at lytte på | +| `--hostname` | Værtsnavn at lytte på | +| `--mdns` | Aktiver mDNS-opdagelse | +| `--cors` | Yderligere browseroprindelse til at tillade CORS | + +--- + +### acp + +Start en ACP-server (Agent Client Protocol). + +```bash +opencode acp +``` + +Denne kommando starter en ACP-server, der kommunikerer via stdin/stdout ved hjælp af nd-JSON. + +#### Flag + +| Flag | Beskrivelse | +| ------------ | --------------------- | +| `--cwd` | Arbejdsmappe | +| `--port` | Port at lytte på | +| `--hostname` | Værtsnavn at lytte på | + +--- + +### afinstaller + +Afinstaller OpenCode og fjern alle relaterede filer. + +```bash +opencode uninstall +``` + +#### Flag + +| Flag | Kort | Beskrivelse | +| --------------- | ---- | ------------------------------------------------ | +| `--keep-config` | `-c` | Se konfigurationsfiler | +| `--keep-data` | `-d` | Gem sessionsdata og snapshots | +| `--dry-run` | | Vis, hvad der ville blive fjernet uden at fjerne | +| `--force` | `-f` | Spring bekræftelsesspørgsmål over | + +--- + +###opgradering + +Opdaterer opencode til den seneste version eller en specifik version. + +```bash +opencode upgrade [target] +``` + +For at opgradere til den nyeste version. + +```bash +opencode upgrade +``` + +For at opgradere til en bestemt version. + +```bash +opencode upgrade v0.1.48 +``` + +#### Flag + +| Flag | Kort | Beskrivelse | +| ---------- | ---- | -------------------------------------------------------------------- | +| `--method` | `-m` | Installationsmetoden, der blev brugt; krølle, npm, pnpm, bolle, bryg | + +--- + +## Globalt flag + +opencode CLI tager følgende globale flag. + +| Flag | Kort | Beskrivelse | +| -------------- | ---- | --------------------------------------- | +| `--help` | `-h` | Vis hjælp | +| `--version` | `-v` | Udskriftsversionsnummer | +| `--print-logs` | | Udskriv logfiler til stderr | +| `--log-level` | | Logniveau (DEBUG, INFO, ADVARSEL, FEJL) | + +--- + +## Miljøvariabler + +OpenCode kan konfigureres ved hjælp af miljøvariabler. + +| Variabel | Skriv | Beskrivelse | +| ------------------------------------- | ------ | --------------------------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | boolsk | Del automatisk session | +| `OPENCODE_GIT_BASH_PATH` | styrke | Sti til Git Bash eksekverbar på Windows | +| `OPENCODE_CONFIG` | styrke | Sti til konfigurationsfil | +| `OPENCODE_CONFIG_DIR` | styrke | Sti til konfigurationsmappe | +| `OPENCODE_CONFIG_CONTENT` | styrke | Indbygget json-konfigurationsindhold | +| `OPENCODE_DISABLE_AUTOUPDATE` | boolsk | Deaktiver automatisk opdateringskontrol | +| `OPENCODE_DISABLE_PRUNE` | boolsk | Deaktiver beskæring af gamle data | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | boolsk | Deaktiver automatisk opdatering af terminaltitel | +| `OPENCODE_PERMISSION` | styrke | Indbygget json-tilladelseskonfiguration | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | boolsk | Deaktiver standard plugins | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | boolsk | Deaktiver automatisk LSP-serverdownloads | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | boolsk | Aktive eksperimentelle modeller | +| `OPENCODE_DISABLE_AUTOCOMPACT` | boolsk | Deaktiver automatisk kontekstkomprimering | +| `OPENCODE_DISABLE_CLAUDE_CODE` | boolsk | Deaktiver læsning fra `.claude` (prompt + færdigheder) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | boolsk | Deaktiver læsning `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | boolsk | Deaktiver indlæsning af `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | boolsk | Deaktivering af modeller fra eksterne kilder | +| `OPENCODE_FAKE_VCS` | styrke | Falsk VCS-udbyder til testformål | +| `OPENCODE_DISABLE_FILETIME_CHECK` | boolsk | Deaktiver filtidskontrol for optimering | +| `OPENCODE_CLIENT` | styrke | Klient-id (standard til `cli`) | +| `OPENCODE_ENABLE_EXA` | boolsk | Aktiver Exa-websøgeværktøjer | +| `OPENCODE_SERVER_PASSWORD` | styrke | Aktiver grundlæggende godkendelse for `serve`/`web` | +| `OPENCODE_SERVER_USERNAME` | styrke | Tilsidesæt grundlæggende godkendelsesbrugernavn (standard `opencode`) | +| `OPENCODE_MODELS_URL` | styrke | Brugerdefineret URL til hentning af modelkonfiguration | + +--- + +### Eksperimentel + +Disse miljøvariabler muliggør eksperimentelle funktioner, der kan ændres eller fjernes. + +| Variabel | Skriv | Beskrivelse | +| ----------------------------------------------- | ------ | ------------------------------------------ | +| `OPENCODE_EXPERIMENTAL` | boolsk | Aktiver alle eksperimentelle funktioner | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | boolsk | Aktiver ikonopdagelse | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | boolsk | Deaktiver kopi ved valg i TUI | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | nummer | Standard timeout for bash-kommandoer i ms | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | nummer | Maks. output-tokens for LLM-svar | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | boolsk | Aktiver filovervågning for hele dir | +| `OPENCODE_EXPERIMENTAL_OXFMT` | boolsk | Aktiver oxfmt formatter | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | boolsk | Aktive eksperimenter LSP værktøj | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | boolsk | Deaktiver filovervågning | +| `OPENCODE_EXPERIMENTAL_EXA` | boolsk | Aktive eksperimenter Exa-funktioner | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | boolsk | Aktive forsøg LSP typekontrol | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | boolsk | Aktive eksperimentelle markdown-funktioner | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | boolsk | Aktiver plantilstand | diff --git a/packages/web/src/content/docs/da/commands.mdx b/packages/web/src/content/docs/da/commands.mdx new file mode 100644 index 000000000..89a02082c --- /dev/null +++ b/packages/web/src/content/docs/da/commands.mdx @@ -0,0 +1,323 @@ +--- +title: Kommandoer +description: Opret brugerdefinerede kommandoer til gentagne opgaver. +--- + +Brugerdefinerede kommandoer giver mulighed for at angive en prompt, du vil køre, når denne kommando udføres i TUI. + +```bash frame="none" +/my-command +``` + +Brugerdefinerede kommandoer er ud over de indbyggede kommandoer som `/init`, `/undo`, `/redo`, `/share`, `/help`. [Learn more](/docs/tui#commands). + +--- + +## Opret kommandofiler + +Opret markdown-filer i mappen `commands/` for at definere brugerdefinerede kommandoer. + +Opret `.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Frontmatter definerer kommandoegenskaber. Indholdet bliver skabelonen. + +Brug kommandoen ved at skrive `/` efterfulgt af kommandonavnet. + +```bash frame="none" +"/test" +``` + +--- + +## Konfigurer + +Du kan tilføje brugerdefinerede kommandoer gennem OpenCode-konfigurationen eller ved at oprette markdown-filer i `commands/`-mappen. + +--- + +### JSON + +Brug indstillingerne `command` i din OpenCode [config](/docs/config): + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Nu kan du køre denne kommando i TUI: + +```bash frame="none" +/test +``` + +--- + +### Markdown + +Du kan også definere kommandoer ved hjælp af markdown-filer. Placer dem i: + +- Globalt: `~/.config/opencode/commands/` +- Pr. projekt: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Markdown-filnavnet bliver kommandonavnet. For eksempel lader `test.md` +du løber: + +```bash frame="none" +/test +``` + +--- + +## Spørg config + +Spørgsmålene til de brugerdefinerede kommandoer understøtter flere specielle pladsholdere og syntaks. + +--- + +### Argumenter + +Send argumenter til kommandoer ved hjælp af pladsholderen `$ARGUMENTS`. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +Kør kommandoen med argumenter: + +```bash frame="none" +/component Button +``` + +Og `$ARGUMENTS` vil blive erstattet med `Button`. + +Du kan også få adgang til individuelle argumenter ved hjælp af positionelle parametre: + +- `$1` - Første argument +- `$2` - Andet argument +- `$3` - Tredje argument +- Og så videre... + +For eksempel: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +Kør kommandoen: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +Dette erstatter: + +- `$1` med `config.json` +- `$2` med `src` +- `$3` med `{ "key": "value" }` + +--- + +### Shell-output + +Brug _!`command`_ til at injicere [bash command](/docs/tui#bash-commands) output i din prompt. + +For eksempel, for at oprette en brugerdefineret kommando, der analyserer testdækning: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +Eller for at gennemgå de seneste ændringer: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +Kommandoer kører i dit projekts rodmappe, og deres output bliver en del af prompten. + +--- + +### Filreferencer + +Inkluder filer i din kommando ved hjælp af `@` efterfulgt af filnavnet. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +Filindholdet bliver automatisk integreret i prompten. + +--- + +## Indstillinger + +Lad os se nærmere på konfigurationsmulighederne. + +--- + +### Skabelon + +Indstillingen `template` definerer den prompt, der sendes til LLM, når kommandoen udføres. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +Dette er en **påkrævet** konfigurationsindstilling. + +--- + +### Beskrivelse + +Brug indstillingen `description` til at give en kort beskrivelse af, hvad kommandoen gør. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +Dette vises som beskrivelsen i TUI, når du indtaster kommandoen. + +--- + +### Agent + +Brug `agent`-konfigurationen til valgfrit at angive, hvilken [agent](/docs/agents) der skal udføre denne kommando. +Hvis dette er en [subagent](/docs/agents/#subagents), vil kommandoen som standard udløse en subagent påkaldelse. +For at deaktivere denne adfærd skal du indstille `subtask` til `false`. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +Dette er en **valgfri** konfigurationsindstilling. Hvis det ikke er angivet, er standarden din nuværende agent. + +--- + +### Underopgave + +Brug `subtask` boolean til at tvinge kommandoen til at udløse en [subagent](/docs/agents/#subagents) påkaldelse. +Dette er nyttigt, hvis du ønsker, at kommandoen ikke skal forurene din primære kontekst og vil **tvinge** agenten til at fungere som en underagent, +øjeblikkelig `mode` er sat til `primary` på [agent](/docs/agents) konfigurationen. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +Dette er en **valgfri** konfigurationsindstilling. + +--- + +### Model + +Brug `model`-konfigurationen til at tilsidesætte standardmodellen for denne kommando. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Dette er en **valgfri** konfigurationsindstilling. + +--- + +## Indbygget + +opencode indeholder flere indbyggede kommandoer som `/init`, `/undo`, `/redo`, `/share`, `/help`; [learn more](/docs/tui#commands). + +:::note +Brugerdefinerede kommandoer kan tilsidesætte indbyggede kommandoer. +::: + +Hvis du definerer en brugerdefineret kommando med samme navn, vil den tilsidesætte den indbyggede kommando. diff --git a/packages/web/src/content/docs/da/config.mdx b/packages/web/src/content/docs/da/config.mdx new file mode 100644 index 000000000..cc2770822 --- /dev/null +++ b/packages/web/src/content/docs/da/config.mdx @@ -0,0 +1,685 @@ +--- +title: Konfig +description: Ved at bruge OpenCode JSON konfig. +--- + +Du kan konfigurere OpenCode ved hjælp af en JSON-konfigurationsfil. + +--- + +## Format + +OpenCode understøtter både **JSON** og **JSONC** (JSON med kommentarer) formater. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## Steder + +Du kan placere din konfiguration et par forskellige steder, og de har en +forskellig rækkefølge. + +:::note +Konfigurationsfiler **flettes sammen**, erstattes ikke. +::: + +Konfigurationsfiler flettes sammen, erstattes ikke. Indstillinger fra følgende konfigurationssteder kombineret. Senere konfigurationer tilsidesætter kun tidligere konfigurationer for modstridende nøgler. Ikke-modstridende indstillinger fra alle konfigurationer bevares. + +For eksempel, hvis dine globale konfigurationssæt `theme: "opencode"` og `autoupdate: true`, og dine projektkonfigurationssæt `model: "anthropic/claude-sonnet-4-5"`, vil den endelige konfiguration integrere alle tre indstillinger. + +--- + +### Prioritetsrækkefølge + +Konfigurationskilder indlæses i denne rækkefølge (senere kilder tilsidesætter tidligere): + +1. **Fjernkonfiguration** (fra `.well-known/opencode`) - organisatoriske standardindstillinger +2. **Global config** (`~/.config/opencode/opencode.json`) - brugerpræferencer +3. **Tilpasset konfiguration** (`OPENCODE_CONFIG` env var) - tilpassede tilsidesættelser +4. **Project config** (`opencode.json` i projekt) - projektspecifikke indstillinger +5. **`.opencode` mapper** - agent, kommandoer, plugins +6. **Inline config** (`OPENCODE_CONFIG_CONTENT` env var) - runtime tilsidesættelser + +Dette betyder, at projektkonfigurationer kan tilsidesætte globale standardindstillinger, og globale konfigurationer kan tilsidesætte eksterne organisatoriske standarder. + +:::note +`.opencode` og `~/.config/opencode` bibliotekerne bruger **flertalsnavne** for undermapper: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/` og `themes/`. Enkelte navne (f.eks. `agent/`) understøtter også bagudkompatibilitet. +::: + +--- + +### Fjernbetjening + +Organisationer kan levere standardkonfiguration via `.well-known/opencode`-slutpunktet. Dette hentes automatisk, når du godkender med en udbyder, der understøtter det. + +Remote config indlæses først og fungerer som basislaget. Alle andre konfigurationskilder (global, projekt) kan tilsidesætte disse standardindstillinger. + +Hvis din organisation f.eks. leverer MCP-servere, der er deaktiveret som standard: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +Du kan aktivere specifikke servere i din lokale konfiguration: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### Global + +Placer din globale OpenCode-konfiguration i `~/.config/opencode/opencode.json`. Brug global konfiguration til brugerdækkende præferencer som temaer, udbydere eller nøglebindinger. + +Global config tilsidesætter eksterne organisatoriske standarder. + +--- + +### Pr. projekt + +Tilføj `opencode.json` i dit projektrod. Project config har den højeste forrang blandt standard config-filer - den tilsidesætter både globale og eksterne config. + +:::tip +Placer projektspecifik konfiguration i roden af ​​dit projekt. +::: + +Når OpenCode starter op, søger den efter en konfigurationsfil i det aktuelle kort eller går op til den nærmeste Git-mappe. + +Dette er også sikkert at blive tjekket ind i Git og bruger det samme skema som det globale. + +--- + +### Brugerdefineret sti + +Angiv en brugerdefineret konfigurationsfilsti ved hjælp af miljøvariablen `OPENCODE_CONFIG`. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +Brugerdefineret konfigurationsindlæses mellem globale konfigurationer og projektkonfigurationer i prioriteret rækkefølge. + +--- + +### Brugerdefineret bibliotek + +Angiv en brugerdefineret konfigurationsmappe ved hjælp af `OPENCODE_CONFIG_DIR` +miljøvariabel. Dette kort vil blive søgt efter agenter, kommandoer, +modes og plugins ligesom standard `.opencode` biblioteket, og bør +følge samme struktur. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +Den brugerdefinerede map indlæses efter den globale konfig og `.opencode` mapper, så den **kan tilsidesætte** deres indstillinger. + +--- + +## Skema + +Konfigurationsfilen har et skema, der defineres i [**`opencode.ai/config.json`**](https://opencode.ai/config.json). + +Din editor skal være i stand til at validere og autofuldføre baseret på skemaet. + +--- + +### TUI + +Du kan konfigurere TUI-specifikke indstillinger gennem indstillingen `tui`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +Tilgængelige muligheder: + +- `scroll_acceleration.enabled` - Aktiver macOS-stil rulleacceleration. **Har forrang frem for `scroll_speed`.** +- `scroll_speed` - Brugerdefineret rullehastighedsmultiplikator (standard: `3`, minimum: `1`). Ignoreres, hvis `scroll_acceleration.enabled` er `true`. +- `diff_style` - Kontroller diff-gengivelse. `"auto"` tilpasser sig terminalbredden, `"stacked"` viser altid en enkelt kolonne. + +[Learn more about using the TUI here](/docs/tui). + +--- + +### Server + +Du kan konfigurere serverindstillinger for kommandoerne `opencode serve` og `opencode web` gennem indstillingen `server`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +Tilgængelige muligheder: + +- `port` - Port til at lytte på. +- `hostname` - Værtsnavn at lytte på. Når `mdns` er aktiveret, og der ikke er angivet noget værtsnavn, er standarden `0.0.0.0`. +- `mdns` - Aktiver mDNS-tjenesteopdagelse. Dette gør det muligt for andre enheder på netværket at opdage din OpenCode-server. +- `mdnsDomain` - Brugerdefineret domænenavn til mDNS-tjeneste. Som standard er `opencode.local`. Nyttigt til at køre flere forekomster på det samme netværk. +- `cors` - Yderligere oprindelser for at tillade CORS ved brug af HTTP-serveren fra en browserbaseret klient. Værdier skal være fulde oprindelser (skema + vært + valgfri port), f.eks. `https://app.example.com`. + +[Learn more about the server here](/docs/server). + +--- + +### Værktøjer + +Du kan administrere de værktøjer, en LLM kan bruge, gennem indstillingen `tools`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[Learn more about tools here](/docs/tools). + +--- + +### Modeller + +Du kan konfigurere de udbydere og modeller, du vil bruge i din OpenCode-konfiguration, gennem mulighederne `provider`, `model` og `small_model`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +Indstillingen `small_model` konfigurerer en separat model til lette opgaver som titelgenerering. Som standard forsøger OpenCode at bruge en billigere model, hvis en er tilgængelig fra din udbyder, ellers falder den tilbage til din hovedmodel. + +Udbydermuligheder kan omfatte `timeout` og `setCacheKey`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - Anmodningstimeout i millisekunder (standard: 300000). Indstil til `false` for at deaktivere. +- `setCacheKey` - Sørg for, at en cache-nøgle altid er indstillet til den udpegede udbyder. + +Du kan også konfigurere [local models](/docs/models#local). [Learn more](/docs/models). + +--- + +#### Udbyder-specifikke muligheder + +Nogle udbydere understøtter yderligere konfigurationsmuligheder ud over de generiske `timeout` og `apiKey` indstillinger. + +##### Amazonas grundfjeld + +Amazon Bedrock understøtter AWS-specifik konfiguration: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - AWS region for grundfjeld (standard til `AWS_REGION` env var eller `us-east-1`) +- `profile` - AWS navngivet profil fra `~/.aws/credentials` (standard til `AWS_PROFILE` env var) +- `endpoint` - Brugerdefineret slutpunkt URL for VPC-endepunkter. Dette er et alias for den generiske `baseURL`-indstilling, der bruger AWS-specifik terminologi. Hvis begge er angivet, har `endpoint` forrang. + +:::note +Bærer-tokens (`AWS_BEARER_TOKEN_BEDROCK` eller `/connect`) har forrang over profilbaseret godkendelse. Se [authentication precedence](/docs/providers#authentication-precedence) for detaljer. +::: + +[Learn more about Amazon Bedrock configuration](/docs/providers#amazon-bedrock). + +--- + +### Temaer + +Du kan konfigurere det tema, du vil bruge i din OpenCode-konfiguration, gennem indstillingen `theme`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[Learn more here](/docs/themes). + +--- + +### Agent + +Du kan konfigurere opgaver specialiserede agenter til specifikke indstillinger gennem indstillingen `agent`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +Du kan også definere agenter ved at bruge markdown-filer i `~/.config/opencode/agents/` eller `.opencode/agents/`. [Learn more here](/docs/agents). + +--- + +### Standardagent + +Du kan indstille standardagenten ved at bruge indstillingen `default_agent`. Dette bestemmer, hvilken agent der bruges, når ingen er eksplicit angivet. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +Standardagenten skal være en primær agent (ikke en subagent). Dette kan være en indbygget agent som `"build"` eller `"plan"`, eller en [custom agent](/docs/agents), du har defineret. Hvis den angivne agent ikke eksisterer eller er en underagent, vil OpenCode falde tilbage til `"build"` med en advarsel. + +Denne indstilling gælder på tværs af alle grænseflader: TUI, CLI (`opencode run`), desktop-app og GitHub Action. + +--- + +### Deling + +Du kan konfigurere funktionen [share](/docs/share) gennem indstillingen `share`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +Dette kræver: + +- `"manual"` - Tillad manuel deling via kommandoer (standard) +- `"auto"` - Del automatisk nye samtaler +- `"disabled"` - Deaktiver deling helt + +Som standard er deling indstillet til manuel tilstand, hvor du eksplicit skal dele samtaler ved hjælp af kommandoen `/share`. + +--- + +### Kommandoer + +Du kan konfigurere brugerdefinerede kommandoer til gentagne opgaver gennem indstillingen `command`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +Du kan også definere kommandoer ved hjælp af markdown-filer i `~/.config/opencode/commands/` eller `.opencode/commands/`. [Learn more here](/docs/commands). + +--- + +### Nøglebindinger + +Du kan tilpasse dine nøglebindinger gennem indstillingen `keybinds`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[Learn more here](/docs/keybinds). + +--- + +### Autoopdatering + +OpenCode vil automatisk downloade alle nye opdateringer, når den starter op. Du kan deaktivere dette med indstillingen `autoupdate`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +Hvis du ikke ønsker opdatering, men ønsker at blive underrettet, når en ny version er tilgængelig, skal du indstille `autoupdate` til `"notify"`. +Bemærk, at dette kun virker, hvis det ikke blev installeret ved hjælp af en pakkehåndtering såsom Homebrew. + +--- + +### Formatere + +Du kan konfigurere kodeformatere gennem indstillingen `formatter`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[Learn more about formatters here](/docs/formatters). + +--- + +### Tilladelser + +Som standard opencode **tillader alle operationer** uden at kræve eksplicit godkendelse. Du kan ændre dette ved at bruge indstillingen `permission`. + +For at sikre, at værktøjerne `edit` og `bash` for eksempel kræver brugergodkendelse: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[Learn more about permissions here](/docs/permissions). + +--- + +### Komprimering + +Du kan styre kontekstkomprimeringsadfærd gennem indstillingen `compaction`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - Komprimer automatisk sessionen, når konteksten er fuld (standard: `true`). +- `prune` - Fjern gamle værktøjsudgange for at gemme tokens (standard: `true`). + +--- + +### Watcher + +Du kan konfigurere ignoreringsmønstre for filovervåger gennem indstillingen `watcher`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +Mønstre følger glob-syntaks. Brug dette til at udelukke støjende mapper fra filvisning. + +--- + +### MCP servere + +Du kan konfigurere MCP-servere, som du vil bruge, gennem indstillingen `mcp`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[Learn more here](/docs/mcp-servers). + +--- + +### Plugins + +[Plugins](/docs/plugins) udvide OpenCode med brugerdefinerede værktøjer, kroge og integrationer. + +Placer plugin-filer i `.opencode/plugins/` eller `~/.config/opencode/plugins/`. Du kan også indlæse plugins fra npm gennem indstillingen `plugin`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[Learn more here](/docs/plugins). + +--- + +### Instruktioner + +Du kan konfigurere brugervejledningen til den model, du kan gennem indstillingen `instructions`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Dette kræver en række stier og globmønstre til instruktionsfiler. [Læs mere +om regler her](/docs/rules). + +--- + +### Deaktiverede udbydere + +Du kan deaktivere udbydere, der indlæses automatisk gennem `disabled_providers`-indstillingen. Dette er nyttigt, når du vil forhindre visse udbydere i at blive indlæst, deres legitimationsoplysninger er tilgængelige. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +`disabled_providers` har prioritet over `enabled_providers`. +::: + +Indstillingen `disabled_providers` accepterer en række udbyder-id'er. Når en udbyder er deaktiveret: + +- Det vil ikke blive indlæst, omgivelserne miljøvariabler er indstillet. +- Den vil ikke blive indlæst, gennem API nøgler er konfigureret kommandoen `/connect`. +- Udbyderens modeller vises ikke på modelvalgslisten. + +--- + +### Aktiverede udbydere + +Du kan angive en tilladelsesliste over udbydere gennem muligheden `enabled_providers`. Når den er indstillet, vil kun de angivne udbydere blive aktiveret, og alle andre vil blive ignoreret. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +Dette er nyttigt, når du vil begrænse OpenCode til kun at bruge specifikke udbydere i stedet for at deaktivere dem én efter én. + +:::note +`disabled_providers` har prioritet over `enabled_providers`. +::: + +Hvis en udbyder optræder i både `enabled_providers` og `disabled_providers`, har `disabled_providers` prioritet for bagudkompatibilitet. + +--- + +### Eksperimentel + +Nøglen `experimental` indeholder muligheder, der er under aktiv udvikling. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::forsigtighed +Eksperimentelle muligheder er ikke stabile. De kan ændres eller fjernes uden varsel. +::: + +--- + +## Variabel + +Du kan bruge variabelsubstitution i dine konfigurationsfiler til at referere til miljøvariabler og filindhold. + +--- + +### Env vars + +Brug `{env:VARIABLE_NAME}` til at erstatte miljøvariabler: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +Hvis miljøvariablen ikke er indstillet, vil den blive erstattet med en tom streng. + +--- + +### Filer + +Brug `{file:path/to/file}` til at erstatte indholdet af en fil: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +Filstier kan være: + +- I forhold til konfigurationsfilbiblioteket +- Eller absolutte stier, der starter med `/` eller `~` + +Disse er nyttige til: + +- Opbevaring af følsomme data som API nøgler i separate filer. +- Inklusiv store instruktionsfiler uden at rode i din konfiguration. +- Deling af fælles konfigurationsuddrag på tværs af flere konfigurationsfiler. diff --git a/packages/web/src/content/docs/da/custom-tools.mdx b/packages/web/src/content/docs/da/custom-tools.mdx new file mode 100644 index 000000000..b0839b649 --- /dev/null +++ b/packages/web/src/content/docs/da/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: Brugerdefinerede værktøjer +description: Opret værktøjer, som LLM kan kalde opencode ind. +--- + +Brugerdefinerede værktøjer er funktioner, du opretter, som LLM kan kalde under samtaler. De arbejder sammen med opencodes [built-in tools](/docs/tools) som `read`, `write` og `bash`. + +--- + +## Oprettelse af et værktøj + +Værktøjer er defineret som **TypeScript**- eller **JavaScript**-filer. Værktøjsdefinitionen kan dog kalde scripts skrevet på **alle sprog** - TypeScript eller JavaScript bruges kun til selve værktøjsdefinitionen. + +--- + +### Placering + +De kan definere: + +- Lokalt ved at placere dem i biblioteket `.opencode/tools/` i dit projekt. +- Eller globalt ved at placere dem i `~/.config/opencode/tools/`. + +--- + +### Struktur + +Den nemmeste måde at oprette værktøjer på er at bruge `tool()`-hjælperen, som giver typesikkerhed og validering. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +**filnavnet** bliver **værktøjsnavnet**. Ovenstående opretter et `database` værktøj. + +--- + +#### Flere værktøjer pr. fil + +Du kan også eksportere flere værktøjer fra en enkelt fil. Hver eksport bliver **et separat værktøj** med navnet **`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +Dette skaber værktøjer: `math_add` og `math_multiply`. + +--- + +### Argumenter + +Du kan bruge `tool.schema`, som kun er [Zod](https://zod.dev), til at definere argumenttyper. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +Du kan også importere [Zod](https://zod.dev) direkte og returnere et almindeligt objekt: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### Kontekst + +Værktøjer modtager kontekst om den aktuelle session: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +Brug `context.directory` til sessionens arbejdsmappe. +Brug `context.worktree` til git-arbejdstræets rod. + +--- + +## Eksempler + +### Skriv et værktøj i Python + +Du kan skrive dine værktøjer på et hvilket som helst sprog, du ønsker. Her er et eksempel, der tilføjer til tal ved hjælp af Python. + +Først skal du oprette værktøjet som et Python-script: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +Opret derefter værktøjsdefinitionen, der kalder den: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +Her bruger vi [`Bun.$`](https://bun.com/docs/runtime/shell)-værktøjet til at køre Python-scriptet. diff --git a/packages/web/src/content/docs/da/ecosystem.mdx b/packages/web/src/content/docs/da/ecosystem.mdx new file mode 100644 index 000000000..1ce41d87b --- /dev/null +++ b/packages/web/src/content/docs/da/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: Økosystem +description: Projekter og integrationer bygget med OpenCode. +--- + +En samling af samfundsprojekter bygget på OpenCode. + +:::note +Vil du tilføje dit OpenCode-relaterede projekt til denne liste? Send en PR. +::: + +Du kan også tjekke \_\_TK_0 og [opencode.cafe](https://opencode.cafe), et fællesskab, der samler økosystemet og fællesskabet. + +--- + +## Plugins + +| Navn | Beskrivelse | +| --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | Kør automatisk OpenCode-sessioner i isolerede Daytona-sandkasser med git-synkronisering og live forhåndsvisninger | +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Injicer automatisk Helicone-sessionsoverskrifter til anmodningsgruppering | +| [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Autoinjicer TypeScript/Svelte-typer i fillæsninger med opslagsværktøjer | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Brug dit ChatGPT Plus/Pro abonnement i stedet for API kreditter | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Brug din eksisterende Gemini-plan i stedet for API fakturering | +| [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Brug Antigravitys gratis modeller i stedet for API fakturering | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Multi-branch devcontainer isolation med lavvandede kloner og automatisk tildelte porte | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Antigravity OAuth Plugin, med understøttelse af Google søgning og mere robust API håndtering | +| [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Optimer tokenbrug ved at beskære forældede værktøjsoutput | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Tilføj native websearch-understøttelse for understøttede udbydere med Google jordet stil | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Gør det muligt for AI-agenter at køre baggrundsprocesser i en PTY, send interaktive input til dem. | +| [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Instruktioner til ikke-interaktive shell-kommandoer - forhindrer hænger fra TTY-afhængige operationer | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Spor OpenCode brug med Wakatime | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Ryd op afmærkningstabeller produceret af LLMs | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | 10x hurtigere koderedigering med Morph Fast Apply API og dovne redigeringsmarkører | +| [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Baggrundsagenter, præbyggede LSP/AST/MCP værktøjer, kuraterede agenter, Claude Kodekompatibel | +| [opencode-notificator](https://github.com/panta82/opencode-notificator) | Skrivebordsmeddelelser og lydadvarsler for OpenCode-sessioner | +| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Skrivebordsmeddelelser og lydadvarsler for tilladelser, fuldførelse og fejlhændelser | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | AI-drevet automatisk Zellij-sessionsnavngivning baseret på OpenCode-kontekst | +| [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Tillad OpenCode-agenter til dovne load-prompter på efterspørgsel med færdighedsopdagelse og -injektion | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Vedvarende hukommelse på tværs af sessioner ved hjælp af Supermemory | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Interaktiv plangennemgang med visuel annotering og private/offline deling | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Udvid opencode /commands til et kraftfuldt orkestreringssystem med granulær flowkontrol | +| [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Planlæg tilbagevendende job ved hjælp af launchd (Mac) eller systemd (Linux) med cron-syntaks | +| [micode](https://github.com/vtemian/micode) | Struktureret brainstorm → Plan → Implementer workflow med session kontinuitet | +| [octto](https://github.com/vtemian/octto) | Interaktiv browser-UI til AI-brainstorming med formularer med flere spørgsmål | +| [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Claude Baggrundsagenter i kodestil med asynkron-delegering og kontekstvedholdenhed | +| [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Native OS-meddelelser for OpenCode – ved, hvornår opgaver er fuldført | +| [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Bundled multi-agent orkestreringssele – 16 komponenter, én installation | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Nulfriktions git-arbejdstræer for OpenCode | + +--- + +## Projekter + +| Navn | Beskrivelse | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | Discord-bot til at styre OpenCode-sessioner, bygget på SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Neovim-plugin til redaktør-bevidste prompter, bygget på API | +| [portal](https://github.com/hosenur/portal) | Mobile-first web UI til OpenCode over Tailscale/VPN | +| [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | Skabelon til at bygge OpenCode plugins | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Neovim-frontend til opencode - en terminalbaseret AI-kodningsagent | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Vercel AI SDK udbyder til brug af OpenCode via @opencode-ai/sdk | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | Web / Desktop App og VS Code udvidelse til OpenCode | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Obsidian plugin, der integrerer OpenCode i Obsidians brugergrænseflade | +| [OpenWork](https://github.com/different-ai/openwork) | Et open source-alternativ til Claude Cowork, drevet af OpenCode | +| [ocx](https://github.com/kdcokenny/ocx) | OpenCode udvidelsesmanager med bærbare, isolerede profiler. | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Desktop-, web-, mobil- og fjernklientapp til OpenCode | + +--- + +## Agent + +| Navn | Beskrivelse | +| ----------------------------------------------------------------- | ------------------------------------------------------------------------- | +| [Agentic](https://github.com/Cluster444/agentic) | Modulære AI-agenter og -kommandoer til struktureret udvikling | +| [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Konfigurationer, prompter, agenter og plugins til forbedrede arbejdsgange | diff --git a/packages/web/src/content/docs/da/enterprise.mdx b/packages/web/src/content/docs/da/enterprise.mdx new file mode 100644 index 000000000..cc6d8f282 --- /dev/null +++ b/packages/web/src/content/docs/da/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: Enterprise +description: Brug af OpenCode sikkert i din organisation. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise er for organisationer, der ønsker at sikre, at deres kode og data aldrig forlader deres infrastruktur. Det kan gøre dette ved at bruge en centraliseret konfiguration, der integreres med din SSO og interne AI-gateway. + +:::note +OpenCode gemmer ingen af ​​din kode eller kontekstdata. +::: + +Sådan kommer du i gang med OpenCode Enterprise: + +1. Lav en prøvetur internt med dit team. +2. **Kontakt os** for at diskutere priser og implementeringsmuligheder. + +--- + +## Prøve + +OpenCode er open source og gemmer ingen af ​​din kode eller kontekstdata, så dine udviklere kan simpelthen [get started](/docs/) og udføre en prøveversion. + +--- + +### Datahåndtering + +**OpenCode gemmer ikke din kode eller kontekstdata.** Al behandling sker lokalt eller gennem direkte API-opkald til din AI-udbyder. + +Det betyder, at så længe du bruger en udbyder, du stoler på, eller en intern +AI-gateway, du kan bruge OpenCode sikkert. + +Den eneste advarsel her er den valgfrie `/share`-funktion. + +--- + +#### Deling af samtaler + +Hvis en bruger aktiverer funktionen `/share`, sender samtalen og de data, der er knyttet til den, til den tjeneste, vi bruger til at hoste disse delesider på opencode.ai. + +Dataene serveres i øjeblikket gennem vores CDN's edge-netværk og cachelagres på kanten nær dine brugere. + +Vi anbefaler, at du deaktiverer dette for din prøveperiode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[Learn more about sharing](/docs/share). + +--- + +### Kodeejerskab + +**Du ejer al kode produceret af OpenCode.** Der er ingen licensbegrænsninger eller ejerskabskrav. + +--- + +## Priser + +Vi bruger en per-sæde-model til OpenCode Enterprise. Hvis du har din egen LLM-gateway, kræver vi ikke betaling for brugte tokens. For yderligere oplysninger om priser og implementeringsmuligheder, **kontakt os**. + +--- + +## Implementering + +Når du har afsluttet din prøveperiode, og du er klar til at bruge OpenCode kl +din organisation, kan du **kontakte os** for at diskutere +prissætning og implementeringsmuligheder. + +--- + +### Central Config + +Vi kan konfigurere OpenCode til at bruge en enkelt central konfiguration for hele din organisation. + +Denne centraliserede konfiguration kan integreres med din SSO-udbyder og sikrer, at alle brugere kan få adgang til din interne AI-gateway. + +--- + +### SSO-integration + +Gennem den centrale konfiguration kan OpenCode integreres med din organisationer SSO-udbyder til godkendelse. + +Denne giver OpenCode mulighed for at få legitimationsoplysninger til din interne AI-gateway gennem dette eksisterende identitetsadministrationssystem. + +--- + +### Intern AI-gateway + +Med den centrale konfiguration kan OpenCode også konfigureres til kun at bruge din interne AI-gateway. + +Du kan også deaktivere alle andre AI-udbydere og sikre, at alle anmodninger går gennem din organisations godkendte infrastruktur. + +--- + +### Self-hosting + +Selvom vi anbefaler at deaktivere delesiderne for at sikre, at dine data aldrig forsvinder +din organisation, kan vi også hjælpe dig med at selv hoste dem på din infrastruktur. + +Dette er i øjeblikket på vores køreplan. Hvis du er interesseret, **giv os besked**. + +--- + +## FAQ + +

+Hvad er OpenCode Enterprise? + +OpenCode Enterprise er for organisationer, der ønsker at sikre, at deres kode og data aldrig forlader deres infrastruktur. Det kan gøre dette ved at bruge en centraliseret konfiguration, der integreres med din SSO og interne AI-gateway. + +
+ +
+Hvordan kommer jeg i gang med OpenCode Enterprise? + +Du skal blot starte med en intern prøveperiode med dit team. OpenCode gemmer som standard ikke din kode eller kontekstdata, hvilket gør det nemt at komme i gang. + +Så **kontakt os** for at diskutere priser og implementeringsmuligheder. + +
+ +
+Hvordan fungerer virksomhedspriser? + +Vi tilbyder virksomhedspriser pr. sæde. Hvis du har din egen LLM-gateway, kræver vi ikke betaling for brugte tokens. For yderligere detaljer, **kontakt os** for et tilpasset tilbud baseret på din organisations behov. + +
+ +
+Er mine data sikret med OpenCode Enterprise? + +Ja. OpenCode gemmer ikke din kode eller kontekstdata. Al behandling sker lokalt eller gennem direkte API-opkald til din AI-udbyder. Med central konfiguration og SSO-integration forbliver dine data sikre i din organisationers infrastruktur. + +
+ +
+Kan vi bruge vores eget private NPM-register? + +OpenCode understøtter private npm registre gennem Buns oprindelige `.npmrc` filunderstøttelse. Hvis din organisation bruger et privat register, såsom JFrog Artifactory, Nexus eller lignende, skal du sikre dig, at udviklerne er godkendt, før de kører OpenCode. + +Sådan konfigurerer du godkendelse med dit private register: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +Dette opretter `~/.npmrc` med godkendelsesdetaljer. OpenCode vil automatisk +samle dette op. + +:::forsigtighed +Du skal være logget ind i det private register, før du kører OpenCode. +::: + +Alternativt kan du manuelt konfigurere en `.npmrc` fil: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Udviklere skal være logget ind på det private register, før de kører OpenCode for at sikre, at pakker kan installeres fra din virksomhedsregistrering. + +
diff --git a/packages/web/src/content/docs/da/formatters.mdx b/packages/web/src/content/docs/da/formatters.mdx new file mode 100644 index 000000000..438cdf1a7 --- /dev/null +++ b/packages/web/src/content/docs/da/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: Formatere +description: OpenCode bruger sprogspecifikke formatere. +--- + +OpenCode formaterer automatisk filer, efter de er skrevet eller redigeret ved hjælp af sprogspecifikke formatere. Dette sikrer, at den kode, der genereres, følger kodestilene for dit projekt. + +--- + +## Indbygget + +OpenCode leveres med flere indbyggede formatere til populære sprog og rammer. Nedenfor er en liste over de formatere, understøttede filtypenavne og kommandoer eller konfigurationsmuligheder, der har brug for. + +| Formater | Udvidelser | Krav | +| --------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | +| gofmt | .go | `gofmt` kommando tilgængelig | +| blande | .ex,.exs,.eex,.heex,.leex,.neex,.sface | `mix` kommando tilgængelig | +| smukkere | .js,.jsx,.ts,.tsx,.html,.css,.md,.json,.yaml og [more](https://prettier.io/docs/en/index.html) | `prettier` afhængighed i `package.json` | +| biome | .js,.jsx,.ts,.tsx,.html,.css,.md,.json,.yaml og [more](https://biomejs.dev/) | `biome.json(c)` konfigurationsfil | +| zig | .zig,.zon | `zig` kommando tilgængelig | +| klang-format | .c,.cpp,.h,.hpp,.ino og [more](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` konfigurationsfil | +| ktlint | .kt,.kts | `ktlint` kommando tilgængelig | +| ruff | .py,.pyi | `ruff` kommando tilgængelig med konfiguration | +| rustfmt | .rs | `rustfmt` kommando tilgængelig | +| cargofmt | .rs | `cargo fmt` kommando tilgængelig | +| uv | .py,.pyi | `uv` kommando tilgængelig | +| rubocop | .rb,.rake,.gemspec,.ru | `rubocop` kommando tilgængelig | +| standardrb | .rb,.rake,.gemspec,.ru | `standardrb` kommando tilgængelig | +| htmlbeautifier | .erb,.html.erb | `htmlbeautifier` kommando tilgængelig | +| luft | .R | `air` kommando tilgængelig | +| dart | .dart | `dart` kommando tilgængelig | +| ocamlformat | .ml,.mli | `ocamlformat` kommando tilgængelig og `.ocamlformat` config fil | +| terraform | .tf,.tfvars | `terraform` kommando tilgængelig | +| glimt | .glimt | `gleam` kommando tilgængelig | +| nixfmt | .nix | `nixfmt` kommando tilgængelig | +| shfmt | .sh,.bash | `shfmt` kommando tilgængelig | +| pint | .php | `laravel/pint` afhængighed i `composer.json` | +| oxfmt (Eksperimentel) | .js,.jsx,.ts,.tsx | `oxfmt` afhængighed i `package.json` og en [experimental env variable flag](/docs/cli/#experimental) | +| ormolu | .hs | `ormolu` kommando tilgængelig | + +Så hvis dit projekt har `prettier` i din `package.json`, vil OpenCode automatisk bruge det. + +--- + +## Sådan fungerer det + +Når OpenCode skriver eller redigerer en fil, vil det: + +1. Kontrollerer filtypenavnet mod alle aktiverede formatere. +2. Kører den relevante formateringskommando på filen. +3. Anvender formateringsændringerne automatisk. + +Denne proces sker i baggrunden, hvilket sikrer, at dine kodestile vedligeholdes uden nogen manuelle trin. + +--- + +## Konfigurer + +Du kan tilpasse formatere gennem afsnittet `formatter` i din OpenCode-konfiguration. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +Hver formateringskonfiguration understøtter følgende: + +| Ejendom | Skriv | Beskrivelse | +| ------------- | -------- | -------------------------------------------------------------------- | +| `disabled` | boolsk | Indstil dette til `true` for at deaktivere formateringsværktøjet | +| `command` | styrke[] | Kommandoen til at køre for formatering | +| `environment` | objekt | Miljøvariabler, der skal indstilles, når formateringsværktøjet køres | +| `extensions` | styrke[] | Filtypenavne, som denne formaterer skal håndtere | + +Lad os se på nogle eksempler. + +--- + +### Deaktivering af formatere + +For at deaktivere **alle** formatere globalt, skal du indstille `formatter` til `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +For at deaktivere en **specifik** formatter, skal du indstille `disabled` til `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Brugerdefinerede formatere + +Du kan tilsidesætte de indbyggede formattere eller tilføje nye ved at angive kommandoen, miljøvariabler og filtypenavne: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +**`$FILE` pladsholderen** i kommandoen vil blive erstattet med stien til filen, der formateres. diff --git a/packages/web/src/content/docs/da/github.mdx b/packages/web/src/content/docs/da/github.mdx new file mode 100644 index 000000000..046f3f15a --- /dev/null +++ b/packages/web/src/content/docs/da/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: Brug OpenCode i GitHub-problemer og pull-anmodninger. +--- + +OpenCode integreres med din GitHub arbejdsgang. Nævn `/opencode` eller `/oc` i din kommentar, og OpenCode vil udføre opgaver i din GitHub Actions-løber. + +--- + +## Funktioner + +- **Triageproblemer**: Bed OpenCode om at undersøge et problem og forklare dig det. +- **Ret og implementer**: Bed OpenCode om at løse et problem eller implementere en funktion. Og det vil fungere i en ny afdeling og indsende en PR med alle ændringerne. +- **Sikker**: OpenCode løber inde i din GitHubs løbere. + +--- + +## Installation + +Kør følgende kommando i et projekt, der er i en GitHub repo: + +```bash +opencode github install +``` + +Dette vil lede dig gennem installation af GitHub-appen, oprettelse af arbejdsgangen og opsætning af hemmeligheder. + +--- + +### Manuel opsætning + +Eller du kan indstille det manuelt. + +1. **Installationsprogrammet GitHub-appen** + + Gå over til [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). Sørg for, at det er installeret på mållageret. + +2. **Tilføj arbejdsgangen** + + Tilføj følgende workflow-fil til `.github/workflows/opencode.yml` i din repo. Sørg for at indstille de relevante `model` og nødvendige API nøgler i `env`. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **Opbevar API nøglerne i hemmeligheder** + + I din organisation eller dit projekt **indstillinger** skal du udvide **Hemmeligheder og variabler** til venstre og vælge **Handlinger**. Og tilføj de nødvendige API nøgler. + +--- + +## Konfiguration + +- `model`: Den model, der skal bruges med OpenCode. Antager formatet `provider/model`. Dette er **påkrævet**. +- `agent`: Agenten, der skal bruges. Skal være en primær agent. Falder tilbage til `default_agent` fra config eller `"build"`, hvis den ikke findes. +- `share`: Om OpenCode-sessionen skal dele. Standard er **sand** for offentlige arkiver. +- `prompt`: Valgfri brugerdefineret prompt for at tilsidesætte standardadfærden. Brug dette til at tilpasse, hvordan OpenCode behandler anmodninger. +- `token`: Valgfrit GitHub adgangstoken til at udføre operationer såsom oprettelse af kommentarer, begå ændringer og åbning af pull-anmodninger. Som standard bruger OpenCode installationsadgangstokenet fra OpenCode GitHub-appen, så commits, kommentarer og pull-anmodninger ser ud til at komme fra appen. + + Alternativt kan du bruge GitHub Action runners [built-in `GITHUB_TOKEN`](OpenCode) uden at installere OpenCode GitHub appen. Bare sørg for at give de nødvendige tilladelser i dit workflow: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + Du kan også bruge en [personal access tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT), hvis det foretrækkes. + +--- + +## Understøttede begivenheder + +OpenCode kan udløses af følgende GitHub hændelser: + +| Begivenhedstype | Udløst af | Detaljer | +| ----------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | Kommentarer og problemer eller PR | Nævn `/opencode` eller `/oc` i din kommentar. OpenCode læser kontekst og kan oprette filialer, åbne PR'er eller svare. | +| `pull_request_review_comment` | Kommenter specifikke kodelinjer i en PR | Nævn `/opencode` eller `/oc`, mens du gennemgår koden. OpenCode modtager filsti, linjenumre og diff-kontekst. | +| `issues` | Udgave åbnet eller redigeret | Udløs automatisk OpenCode, når problemer oprettes eller ændres. Kræver `prompt` input. | +| `pull_request` | PR åbnet eller opdateret | Udløs automatisk OpenCode, når PR'er åbnes, synkroniseres eller genåbnes. Nyttigt til automatiserede anmeldelser. | +| `schedule` | Cron-baseret tidsplan | Kør OpenCode efter en tidsplan. Kræver `prompt` input. Output går til logfiler og PR'er (intet problem ved kommentere). | +| `workflow_dispatch` | Manuel trigger fra GitHub UI | Udløs OpenCode efter behov via fanen Handlinger. Kræver `prompt` input. Output går til logfiler og PR'er. | + +### Skema Eksempel + +Kør OpenCode efter en tidsplan for at udføre automatiske opgaver: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +For planlagte begivenheder er `prompt` input **påkrævet**, da der ikke er nogen kommentarer at udtrække instruktioner fra. Planlagte arbejdsgange kører uden en brugerkontekst til kontrol af tilladelser, så arbejdsgangen skal give `contents: write` og `pull-requests: write`, hvis du forventer, at OpenCode skal oprette filialer eller PR'er. + +--- + +### Pull Request Eksempel + +Gennemgå automatisk PR'er, når de åbnes eller opdateres: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +For `pull_request` hændelser, hvis der ikke er angivet nogen `prompt`, vil OpenCode som standard gennemgå pull-anmodningen. + +--- + +### Issues Triage Eksempel + +Triage automatisk nye problemer. Dette eksempel filtrerer til konti ældre end 30 dage for at reducere spam: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +For `issues` begivenheder er `prompt` input **påkrævet**, da der ikke er nogen kommentarer at udtrække instruktioner fra. + +--- + +## Brugerdefinerede prompter + +Tilsidesæt standardprompten for at tilpasse OpenCodes adfærd til din arbejdsgang. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Dette er nyttigt til at håndhæve specifikke gennemgangskriterier, kodningsstandarder eller fokusområder, der er relevante for dit projekt. + +--- + +## Eksempler + +Her er nogle eksempler på, hvordan du kan bruge OpenCode i GitHub. + +- **Forklar et problem** + + Tilføj denne kommentar i et GitHub-nummer. + + ``` + /opencode explain this issue + ``` + + OpenCode vil læse hele tråden, inklusive alle kommentarer, og svare med en klar forklaring. + +- **Løs et problem** + + I et GitHub-problem skal du sige: + + ``` + /opencode fix this + ``` + + Og OpenCode vil oprette en ny filial, implementere ændringer og åbne en PR med ændringer. + +- **Gennemgå PR'er og foretag ændringer** + + Efterlad følgende kommentar på en GitHub PR. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + OpenCode vil implementere den ønskede ændring og forpligtelse til den samme PR. + +- **Gennemgå specifikke kodelinjer** + + Efterlad en kommentar direkte på kodelinjer i PR's faneblad "Filer". OpenCode detekterer automatisk filer, linjenumrene og diff-konteksten for at give præcise svar. + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + Når du kommenterer på specifikke linjer, modtager OpenCode: + - Den nøjagtige fil bliver gennemgået + - De specifikke kodelinjer + - Den omgivende forskellig kontekst + - Linjenummeroplysninger + + Dette giver mulighed for mere målrettede anmodninger uden at skulle angive filstier eller linjenumre manuelt. diff --git a/packages/web/src/content/docs/da/gitlab.mdx b/packages/web/src/content/docs/da/gitlab.mdx new file mode 100644 index 000000000..74fdd93d7 --- /dev/null +++ b/packages/web/src/content/docs/da/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: Brug OpenCode i GitLab-problemer og fletteanmodninger. +--- + +OpenCode integreres med din GitLab-arbejdsgang gennem din GitLab CI/CD-pipeline eller med GitLab Duo. + +I begge tilfælde vil OpenCode køre på dine GitLab-løbere. + +--- + +## GitLab CI + +OpenCode fungerer i en almindelig GitLab-pipeline. Du kan bygge det ind i en pipeline som en [CI component](https://docs.gitlab.com/ee/ci/components/) + +Her bruger vi en community-skabt CI/CD-komponent til OpenCode — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### Funktioner + +- **Brug tilpasset konfiguration pr. job**: Konfigurer OpenCode med en brugerdefineret konfigurationsmappe, for eksempel `./config/#custom-directory` for at aktivere eller deaktivere funktionalitet pr. OpenCode påkald. +- **Minimal opsætning**: CI-komponenten sætter OpenCode op i baggrunden, du behøver kun at oprette OpenCode-konfigurationen og den indledende prompt. +- **Fleksibel**: CI-komponenten understøtter flere input til at tilpasse dens adfærd + +--- + +### Opsætning + +1. Gem din OpenCode-godkendelse JSON som en filtype CI-miljøvariabel under **Indstillinger** > **CI/CD** > **Variabler**. Sørg for at markere dem som "Maskede og skjulte". +2. Tilføj følgende til din `.gitlab-ci.yml` fil. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +For flere input og use cases [check out the docs](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) for denne komponent. + +--- + +## GitLab Duo + +OpenCode integreres med din GitLab-arbejdsgang. +Nævn `@opencode` i en kommentar, og OpenCode vil udføre opgaver i din GitLab CI-pipeline. + +--- + +### Funktioner + +- **Triageproblemer**: Bed OpenCode om at undersøge et problem og forklare dig det. +- **Ret og implementer**: Bed OpenCode om at løse et problem eller implementere en funktion. + Det vil oprette en ny filial og rejse en fletteanmodning med ændringer. +- **Sikker**: OpenCode kører på dine GitLab-løbere. + +--- + +### Opsætning + +OpenCode kører i din GitLab CI/CD pipeline, her er hvad du skal bruge for at konfigurere det: + +:::tip +Tjek [**GitLab docs**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) for opdaterede instruktioner. +::: + +1. Konfigurer dit GitLab-miljø +2. Konfigurer CI/CD +3. Få en API nøgle til en AI-modeludbyder +4. Opret en servicekonto +5. Konfigurer CI/CD variabler +6. Opret en flow-konfigurationsfil, her er et eksempel: + +
+ + Flowkonfiguration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +Du kan henvise til [GitLab CLI agents docs](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) for detaljerede instruktioner. + +--- + +### Eksempler + +Her er nogle eksempler på, hvordan du kan bruge OpenCode i GitLab. + +:::tip +Du kan konfigurere til at bruge en anden udløsersætning end `@opencode`. +::: + +- **Forklar et problem** + + Tilføj denne kommentar i et GitLab-problem. + + ``` + @opencode explain this issue + ``` + + OpenCode vil læse spørgsmålet og svare med en klar forklaring. + +- **Løs et problem** + + I et GitLab-nummer skal du sige: + + ``` + @opencode fix this + ``` + + OpenCode vil oprette en ny filial, implementere ændringer og åbne en fletteanmodning med ændringer. + +- **Gennemgå anmodninger om fletning** + + Efterlad følgende kommentar til en GitLab-fletningsanmodning. + + ``` + @opencode review this merge request + ``` + + OpenCode vil gennemgå anmodningen om fletning og give feedback. diff --git a/packages/web/src/content/docs/da/ide.mdx b/packages/web/src/content/docs/da/ide.mdx new file mode 100644 index 000000000..17f9cec1e --- /dev/null +++ b/packages/web/src/content/docs/da/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: OpenCode-udvidelsen til VS Code, Cursor og andre IDE'er +--- + +OpenCode integreres med VS Code, Cursor eller enhver IDE, der understøtter en terminal. Bare kør `opencode` i terminalen for at komme i gang. + +--- + +## Brug + +- **Hurtig start**: Brug `Cmd+Esc` (Mac) eller `Ctrl+Esc` (Windows/Linux) til at åbne OpenCode i en delt terminalvisning, eller fokuser en eksisterende terminalsession, hvis en allerede kører. +- **Ny session**: Brug `Cmd+Shift+Esc` (Mac) eller `Ctrl+Shift+Esc` (Windows/Linux) til at starte en ny OpenCode terminalsession, mulighed en allerede er åben. Du kan også klikke på knappen OpenCode i brugergrænsefladen. +- **Kontekstbevidsthed**: Del automatisk dit nuværende valg eller din fane med OpenCode. +- **Filreferencegenveje**: Brug `Cmd+Option+K` (Mac) eller `Alt+Ctrl+K` (Linux/Windows) til at indsætte filreferencer. For eksempel `@File#L37-42`. + +--- + +## Installation + +Sådan installeres OpenCode på VS Code og populære gafler som Cursor, Windsurf, VSCodium: + +1. Åbn VS Code +2. Åbn den integrerede terminal +3. Kør `opencode` - udvidelsen installeres automatisk + +Hvis du på den anden side vil bruge din egen IDE, når du kører `/editor` eller `/export` fra TUI, skal du indstille `export EDITOR="code --wait"`. [Learn more](/docs/tui/#editor-setup). + +--- + +### Manuel installation + +Søg efter **OpenCode** i Extension Marketplace, og klik på **Installer**. + +--- + +### Fejlfinding + +Hvis udvidelsen ikke kan installeres automatisk: + +- Sørg for, at du kører `opencode` i den integrerede terminal. +- Bekræft, at CLI for din IDE er installeret: + - For VS Code: `code` kommando + - For Cursor: `cursor` kommando + - For Windsurf: `windsurf` kommando + - For VSCodium: `codium` kommando + - Hvis ikke, så kør `Cmd+Shift+P` (Mac) eller `Ctrl+Shift+P` (Windows/Linux) og søg efter "Shell Command: Install 'code' command in PATH" (eller tilsvarende for din IDE) +- Sørg for, at VS Code har tilladelse til at installere udvidelser diff --git a/packages/web/src/content/docs/da/index.mdx b/packages/web/src/content/docs/da/index.mdx new file mode 100644 index 000000000..51483a543 --- /dev/null +++ b/packages/web/src/content/docs/da/index.mdx @@ -0,0 +1,359 @@ +--- +title: Intro +description: Kom godt i gang med OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) er en open source AI-kodningsagent. Den er tilgængelig som en terminalbaseret grænseflade, desktop-app eller IDE-udvidelse. + +![OpenCode TUI with the opencode theme](../../../assets/lander/screenshot.png) + +Lad os komme i gang. + +--- + +#### Forudsætninger + +For at bruge OpenCode i din terminal skal du bruge: + +1. En moderne terminalemulator som: + - [WezTerm](https://wezterm.org), på tværs af platforme + - [Alacritty](https://alacritty.org), på tværs af platforme + - [Ghostty](https://ghostty.org), Linux og macOS + - [Kitty](https://sw.kovidgoyal.net/kitty/), Linux og macOS + +2. API nøgler til de LLM udbydere, du vil bruge. + +--- + +## Installationsprogram + +Den nemmeste måde at installere OpenCode på er gennem installationsscriptet. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +Du kan også installere det med følgende kommandoer: + +- **Bruger Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **Brug af Homebrew på macOS og Linux** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > Vi anbefaler at bruge OpenCode-hanen for at få de mest opdaterede udgivelser. Den officielle `brew install opencode`-formel vedligeholdes af Homebrew-teamet og opdateret sjældnere. + +- **Brug af Paru på Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### Windows + +:::tip[Anbefalet: Brug WSL] +For at få den bedste oplevelse på Windows anbefaler vi at bruge [Windows Subsystem for Linux (WSL)](/docs/windows-wsl). Det giver bedre ydeevne og fuld kompatibilitet med OpenCodes funktioner. +::: + +- **Brug af chokolade** + + ```bash + choco install opencode + ``` + +- **Brug af Scoop** + + ```bash + scoop install opencode + ``` + +- **Bruger NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **Brug af Mise** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **Brug af Docker** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +Support til installation af OpenCode på Windows ved hjælp af Bun er i gang. + +Du kan også få fat i binæren fra [Releases](https://github.com/anomalyco/opencode/releases). + +--- + +## Konfigurer + +Med OpenCode kan du bruge enhver LLM udbyder ved at konfigurere deres API nøgler. + +Hvis du er ny til at bruge LLM-udbydere, anbefaler vi at bruge [OpenCode Zen](/docs/zen). +Det er en udvalgt liste over modeller, der er blevet testet og verificeret af OpenCode +holde. + +1. Kør kommandoen `/connect` i TUI, vælg opencode, og gå til [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Log ind, tilføj dine faktureringsoplysninger, og kopier din API-nøgle. + +3. Indsæt din API nøgle. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +Alternativt kan du vælge en af ​​de andre udbydere. [Læs mere](/docs/providers#directory). + +--- + +## Initialiser + +Nu hvor du har konfigureret en udbyder, kan du navigere til et projekt, der +du vil arbejde på. + +```bash +cd /path/to/project +``` + +Og kør OpenCode. + +```bash +opencode +``` + +Derefter initialiseres OpenCode for projektet ved at køre følgende kommando. + +```bash frame="none" +/init +``` + +Dette får OpenCode til at analysere dit projekt og oprette en `AGENTS.md` fil i +projektets stang. + +:::tip +Du bør overgive dit projekter `AGENTS.md` fil til Git. +::: + +Dette hjælper OpenCode med at forstå projektstrukturen og kodningsmønstrene +brugt. + +--- + +## Brug + +Du er nu klar til at bruge OpenCode til at arbejde på dit projekt. Spørg det gerne +noget! + +Hvis du er ny til at bruge en AI-kodningsagent, er her nogle eksempler, der evt +hjælp. + +--- + +### Stil spørgsmål + +Du kan bede OpenCode om at forklare kodebasen for dig. + +:::tip +Brug `@`-tasten til at søge efter filer i projektet. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +Dette er nyttigt, hvis der er en del af kodebasen, som du ikke har arbejdet på. + +--- + +### Tilføj funktioner + +Du kan bede OpenCode om at tilføje nye funktioner til dit projekt. Selvom vi først anbefaler, at du beder den om at lave en plan. + +1. **Opret en plan** + + OpenCode har en _Plan mode_, der deaktiverer dens evne til at foretage ændringer og + foreslå i stedet _hvordan_ det vil implementere funktionen. + + Skift til det ved hjælp af **Tab**-tasten. Du vil se en indikator for dette i nederste højre hjørne. + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + Lad os nu beskrive, hvad vi vil have den til at gøre. + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + Du vil give OpenCode nok detaljer til at forstå, hvad du ønsker. Det hjælper + at tale med det, som om du taler med en juniorudvikler på dit team. + +Drikkepenge +Giv OpenCode masser af kontekst og eksempler for at hjælpe den med at forstå, hvad du +mangel. +::: + +2. **Gentag om planen** + + Når det giver dig en plan, kan du give den feedback eller tilføje flere detaljer. + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + +Drikkepenge +Træk og slip billeder i terminalen for at tilføje dem til prompten. +::: + +OpenCode kan scanne alle billeder, du giver dem og tilføje dem til prompten. Det kan du +gør dette ved at trække og slippe et billede ind i terminalen. + +3. **Byg funktionen** + + Når du føler dig godt tilpas med planen, skal du skifte tilbage til _Byggetilstand_ ved + trykke på **Tab**-tasten igen. + + ```bash frame="none" + + ``` + + Og beder den om at foretage ændringerne. + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### Foretag ændringer + +For mere ligetil ændringer kan du bede OpenCode om at bygge den direkte +uden at skulle gennemgå planen først. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +Du vil sikre dig, at du giver en god mængde detaljer, så OpenCode gør det rigtige +ændringer. + +--- + +### Fortryd ændringer + +Lad os sige, at du beder OpenCode om at foretage nogle ændringer. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Men du indser, at det ikke er, hvad du ønskede. Du **kan fortryde** ændringerne +ved hjælp af kommandoen `/undo`. + +```bash frame="none" +/undo +``` + +OpenCode vil nu vende tilbage til ændringerne, du har foretaget, og vise din oprindelige besked +igen. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Herfra kan du justere prompten og bede OpenCode om at prøve igen. + +:::tip +Du kan køre `/undo` flere gange for at fortryde flere ændringer. +::: + +Eller du **kan gentage** ændringerne ved hjælp af kommandoen `/redo`. + +```bash frame="none" +/redo +``` + +--- + +## Del + +De samtaler, du har med OpenCode, kan [deles med din +team](/docs/share). + +```bash frame="none" +/share +``` + +Dette vil oprette et link til den aktuelle samtale og kopiere det til denne udklipsholder. + +:::note +Samtaler dele ikke som standard. +::: + +Her er en [eksempelsamtale](https://opencode.ai/s/4XP1fce5) med OpenCode. + +--- + +## Tilpas + +Og det er det! Du er nu en professionel i at bruge OpenCode. + +For at gøre det til dit eget, anbefaler vi [picking a theme](/docs/themes), [customizing the keybinds](/docs/keybinds), [configuring code formatters](/docs/formatters), [creating custom commands](/docs/commands) eller at lege med [OpenCode config](/docs/config). diff --git a/packages/web/src/content/docs/da/keybinds.mdx b/packages/web/src/content/docs/da/keybinds.mdx new file mode 100644 index 000000000..ce774cedc --- /dev/null +++ b/packages/web/src/content/docs/da/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: Nøglebind +description: Tilpas dine nøglebindinger. +--- + +OpenCode har en liste over nøglebindinger, som du kan tilpasse gennem OpenCode-konfigurationen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## Ledernøgle + +OpenCode bruger en `leader` nøgle til de fleste smagsbindinger. Dette undgår konflikter i din terminal. + +Som standard er `ctrl+x` ledertasten, og de fleste handlinger kræver, at du først trykker på ledertasten og derefter genvejen. For eksempel, for at starte en ny session, skal du først trykke på `ctrl+x` og derefter trykke på `n`. + +Du behøver ikke bruge en ledernøgle til dine nøglebindinger, men vi anbefaler at du gør det. + +--- + +## Deaktiver smagsbinding + +Du kan deaktivere en nøglebinding ved at tilføje nøglen til din konfiguration med værdien "ingen". + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## Genveje til skrivebordsprompt + +OpenCode desktop app prompt input understøtter almindelige Readline/Emacs-style genveje til redigering af tekst. Disse er indbyggede og i øjeblikket ikke konfigurerede via `opencode.json`. + +| Genvej | Håndtering | +| -------- | ------------------------------------------- | +| `ctrl+a` | Flyt til starten af ​​den aktuelle linje | +| `ctrl+e` | Flyt til slutningen af ​​den aktuelle linje | +| `ctrl+b` | Flyt markøren et tegn tilbage | +| `ctrl+f` | Flyt markøren et tegn frem | +| `alt+b` | Flyt markøren et ord tilbage | +| `alt+f` | Flyt markøren et ord frem | +| `ctrl+d` | Slet tegn under markøren | +| `ctrl+k` | Dræb til slutningen af ​​linjen | +| `ctrl+u` | Dræb til starten af ​​linjen | +| `ctrl+w` | Dræb forrige ord | +| `alt+d` | Dræb næste ord | +| `ctrl+t` | Transponer tegn | +| `ctrl+g` | Annuller popovers / afbryd kørsel af svar | + +--- + +## Shift+Enter + +Nogle terminaler sender ikke modifikationsnøgler med Enter som standard. Du skal muligvis konfigurere din terminal til at sende `Shift+Enter` som en escape-sekvens. + +### Windows Terminal + +Åbn din `settings.json` på: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +Føj dette til `actions`-arrayet på rodniveau: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Føj dette til `keybindings`-arrayet på rodniveau: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Gem fil og genstart Windows Terminal eller åbn en ny fane. diff --git a/packages/web/src/content/docs/da/lsp.mdx b/packages/web/src/content/docs/da/lsp.mdx new file mode 100644 index 000000000..c6f42c18d --- /dev/null +++ b/packages/web/src/content/docs/da/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: LSP Servere +description: OpenCode integreres med dine LSP-servere. +--- + +OpenCode integreres med din sprogserverprotokol (LSP) for at hjælpe LLM med at interagere med din kodebase. Den bruger diagnostik til at give feedback til LLM. + +--- + +## Indbygget + +OpenCode leveres med flere indbyggede LSP-servere til populære sprog: + +| LSP Server | Udvidelser | Krav | +| ------------------- | --------------------------------------------------------- | --------------------------------------------------------------- | +| astro | .astro | Autoinstallationer til Astro-projekter | +| bash | .sh,.bash,.zsh,.ksh | Autoinstallerer bash-language-server | +| clangd | .c,.cpp,.cc,.cxx,.c++,.h,.hpp,.hh,.hxx,.h++ | Autoinstallationer for C/C++ projekter | +| csharp | .cs | `.NET SDK` installere | +| clojure-lsp | .clj,.cljs,.cljc,.edn | `clojure-lsp` kommando tilgængelig | +| dart | .dart | `dart` kommando tilgængelig | +| deno | .ts,.tsx,.js,.jsx,.mjs | `deno` kommando tilgængelig (auto-detects deno.json/deno.jsonc) | +| eliksir-ls | .ex,.exs | `elixir` kommando tilgængelig | +| eslint | .ts,.tsx,.js,.jsx,.mjs,.cjs,.mts,.cts,.vue | `eslint` afhængighed i projekt | +| fskarp | .fs,.fsi,.fsx,.fsscript | `.NET SDK` installere | +| glimt | .glimt | `gleam` kommando tilgængelig | +| gopls | .go | `go` kommando tilgængelig | +| hls | .hs,.lhs | `haskell-language-server-wrapper` kommando tilgængelig | +| jdtls | .java | `Java SDK (version 21+)` installere | +| kotlin-ls | .kt,.kts | Autoinstallationer til Kotlin-projekter | +| lua-ls | .lua | Autoinstallationer til Lua-projekter | +| nixd | .nix | `nixd` kommando tilgængelig | +| ocaml-lsp | .ml,.mli | `ocamllsp` kommando tilgængelig | +| oxlint | .ts,.tsx,.js,.jsx,.mjs,.cjs,.mts,.cts,.vue,.astro,.svelte | `oxlint` afhængighed i projekt | +| php intelephense | .php | Automatiske installationer til PHP-projekter | +| prisma | .prisma | `prisma` kommando tilgængelig | +| ophavsret | .py,.pyi | `pyright` afhængig installeret | +| rubin-lsp (rubocop) | .rb,.rake,.gemspec,.ru | `ruby` og `gem` kommandoer tilgængelige | +| rust | .rs | `rust-analyzer` kommando tilgængelig | +| sourcekit-lsp | .swift,.objc,.objcpp | `swift` installere (`xcode` på macOS) | +| svelte | .svelte | Autoinstallationer til Svelte-projekter | +| terraform | .tf,.tfvars | Automatiske installationer fra GitHub-udgivelser | +| lillemand | .typ,.typc | Automatiske installationer fra GitHub-udgivelser | +| maskinskrift | .ts,.tsx,.js,.jsx,.mjs,.cjs,.mts,.cts | `typescript` afhængighed i projekt | +| vue | .vue | Autoinstallationer til Vue-projekter | +| yaml-ls | .yaml,.yml | Autoinstallerer Red Hat yaml-language-server | +| zls | .zig,.zon | `zig` kommando tilgængelig | + +LSP-servere aktiveres automatisk, når en af ​​ovnstående filtypenavne opdages, og kravene er opfyldt. + +:::note +Du kan deaktivere automatisk LSP-serverdownloads ved at indstille miljøvariablen `OPENCODE_DISABLE_LSP_DOWNLOAD` til `true`. +::: + +--- + +## Sådan fungerer det + +Når opencode åbner en fil, vil den: + +1. Kontrollerer filtypenavnet mod alle aktiverede LSP-servere. +2. Starter den relevante LSP-server, hvis den ikke allerede kører. + +--- + +## Konfigurer + +Du kan tilpasse LSP-servere gennem sektionen `lsp` i din opencode-konfiguration. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Hver LSP- server understøtter følgende: + +| Ejendom | Skriv | Beskrivelse | +| ---------------- | -------- | --------------------------------------------------------- | +| `disabled` | boolsk | Indstil dette til `true` for at deaktivere LSP-serveren | +| `command` | styrke[] | Kommandoen til at starte LSP-serveren | +| `extensions` | styrke[] | Filtypenavne, som denne LSP-server skal håndtere | +| `env` | objekt | Miljøvariabler, der skal indstilles, når serveren starter | +| `initialization` | objekt | Initialiseringsmuligheder for at sende til LSP-serveren | + +Lad os se på nogle eksempler. + +--- + +### Miljøvariabler + +Brug egenskaben `env` til at indstille miljøvariabler, når du starter LSP-serveren: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### Initialiseringsmuligheder + +Brug egenskaben `initialization` til at videregive initialiseringsindstillinger til LSP-serveren. Disse er serverspecifikke indstillinger sendt under LSP `initialize` anmodningen: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +Initialiseringsmuligheder forskellige afhængige af LSP-serveren. Se din LSP-servers dokumentation for tilgængelige muligheder. +::: + +--- + +### Deaktivering af LSP-servere + +For at deaktivere **alle** LSP-servere globalt, skal du indstille `lsp` til `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +For at deaktivere en **specifik** LSP-server skal du indstille `disabled` til `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Brugerdefinerede LSP-servere + +Du kan tilføje brugerdefinerede LSP-servere ved at angive kommandoen og filtypenavne: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## Yderligere oplysninger + +### PHP Intelephense + +PHP Intelephense tilbyder premium funktioner gennem en licensnøgle. Du kan angive en licensnøgle ved at placere (kun) nøglen i en tekstfil på: + +- På macOS/Linux: `$HOME/intelephense/licence.txt` +- På Windows: `%USERPROFILE%/intelephense/licence.txt` + +Filen bør kun indeholde licensnøglen uden yderligere indhold. diff --git a/packages/web/src/content/docs/da/mcp-servers.mdx b/packages/web/src/content/docs/da/mcp-servers.mdx new file mode 100644 index 000000000..91f2e7cb9 --- /dev/null +++ b/packages/web/src/content/docs/da/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: MCP servere +description: Tilføj lokale og eksterne MCP værktøjer. +--- + +Du kan tilføje eksterne værktøjer til OpenCode ved hjælp af _Model Context Protocol_ eller MCP. OpenCode understøtter både lokale og eksterne servere. + +Når de er tilføjet, er MCP automatisk tilgængelig for LLM sammen med indbyggede værktøjer. + +--- + +#### Forse + +Når du bruger en MCP-server, føjes den til konteksten. Dette kan hurtigt stige, hvis du har mange værktøjer. Så vi anbefaler at være forsigtig med hvilke MCP-servere du bruger. + +:::tip +MCP-servere tilføjer til din kontekst, så du vil være forsigtig med, hvilke du aktiverer. +::: + +Visse MCP-servere, som GitHub MCP-servere, har en tendens til at tilføje mange tokens og kan nemt overskride kontekstgrænsen. + +--- + +## Aktiver + +Du kan definere MCP-servere i din [OpenCode Config](https://opencode.ai/docs/config/) under `mcp`. Tilføj hver MCP med et unikt navn. Du kan henvise til denne MCP ved navn, når du spørger LLM. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +Du kan også deaktivere en server ved at indstille `enabled` til `false`. Dette er nyttigt, hvis du midlertidigt vil deaktivere en server uden at fjerne den fra din konfiguration. + +--- + +### Tilsidesættelse af fjernindstillinger + +Organisationer kan levere standard MCP-servere via deres `.well-known/opencode`-slutpunkt. Disse servere kan være deaktiveret som standard, hvilket giver brugerne mulighed for at tilmelde sig dem, de har brug for. + +For at aktivere en specifik server fra din organisationers fjernkonfiguration skal du tilføje den til din lokale konfiguration med `enabled: true`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +Dine lokale konfigurationsværdier tilsidesætter fjernstandarderne. Se [config precedence](/docs/config#precedence-order) for flere detaljer. + +--- + +## Lokal + +Tilføj lokale MCP-servere ved hjælp af `type` til `"local"` i MCP-objektet. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +Kommandoen er, hvordan den lokale MCP-server starter. Du kan også sende en liste over miljøvariabler ind. + +For eksempel, her er, hvordan du kan tilføje test [`@modelcontextprotocol/server-everything`](MCP) MCP serveren. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +Og for at bruge det kan jeg tilføje `use the mcp_everything tool` til mine prompter. + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### Indstillinger + +Her er alle muligheder for at konfigurere en lokal MCP-server. + +| Mulighed | Skriv | Påkrævet | Beskrivelse | +| ------------- | ------- | -------- | ------------------------------------------------------------------------------------ | +| `type` | String | Y | Type MCP serverforbindelse, skal være `"local"`. | +| `command` | Array | Y | Kommando og argumenter til at køre MCP-serveren. | +| `environment` | Objekt | | Miljøvariabler, der skal indstilles, når serveren kører. | +| `enabled` | Boolean | | Aktiver eller deaktiver MCP-serveren ved opstart. | +| `timeout` | Nummer | | Timeout i ms for at hente værktøjer fra MCP-serveren. Standard er 5000 (5 sekunder). | + +--- + +## Fjernbetjening + +Tilføj ekstern MCP-server ved at indstille `type` til `"remote"`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` er URL for den eksterne MCP server, og med indstillingen `headers` kan du sende en liste over overskrifter ind. + +--- + +#### Indstillinger + +| Mulighed | Skriv | Påkrævet | Beskrivelse | +| --------- | ------- | -------- | ------------------------------------------------------------------------------------ | +| `type` | String | Y | Type MCP serverforbindelse, skal være `"remote"`. | +| `url` | String | Y | URL af den eksterne MCP-server. | +| `enabled` | Boolean | | Aktiver eller deaktiver MCP-serveren ved opstart. | +| `headers` | Objekt | | Overskrifter til at sende med anmodningen. | +| `oauth` | Objekt | | OAuth-godkendelseskonfiguration. Se afsnittet [OAuth](#oauth) nedenfor. | +| `timeout` | Nummer | | Timeout i ms for at hente værktøjer fra MCP-serveren. Standard er 5000 (5 sekunder). | + +--- + +## OAuth + +OpenCode håndterer automatisk OAuth-godkendelse for eksterne MCP-servere. Når en server kræver godkendelse, vil OpenCode: + +1. Registrer 401-svaret, og start OAuth-flowet +2. Brug **Dynamic Client Registration (RFC 7591)**, hvis det understøtter af serveren +3. Opbevar tokens sikkert til fremtidige anmodninger + +--- + +### Automatisk + +For de fleste OAuth-aktiverede MCP-servere kræver ingen speciel konfiguration. Bare konfigureret fjernserver: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +Hvis serveren kræver godkendelse, vil OpenCode bede dig om at godkende, når du prøver at bruge den første gang. Hvis ikke, kan du [manually trigger the flow](#authenticating) med `opencode mcp auth `. + +--- + +### Forudregistreret + +Hvis du har klientlegitimationsoplysninger fra MCP-serverudbyderen, kan du konfigurere dem: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### Godkender + +Du kan manuelt udløse godkendelse eller administrere legitimationsoplysninger. + +Godkendt med en specifik MCP-server: + +```bash +opencode mcp auth my-oauth-server +``` + +Liste over alle MCP-servere og deres godkendelsesstatus: + +```bash +opencode mcp list +``` + +Fjern gemte legitimationsoplysninger: + +```bash +opencode mcp logout my-oauth-server +``` + +Kommandoen `mcp auth` åbner din browser for godkendelse. Når du har godkendt, vil OpenCode opbevare tokens sikkert i `~/.local/share/opencode/mcp-auth.json`. + +--- + +#### Deaktiverer OAuth + +Hvis du vil deaktivere automatisk OAuth for en server (f.eks. for servere, der bruger API nøgler i stedet), skal du indstille `oauth` til `false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### OAuth-indstillinger + +| Mulighed | Skriv | Beskrivelse | +| -------------- | --------------- | ----------------------------------------------------------------------------------------- | +| `oauth` | Objekt \| falsk | OAuth-konfigurationsobjekt eller `false` for at deaktivere OAuth-auto-detektion. | +| `clientId` | String | OAuth-klient-id. Hvis det ikke er angivet, vil dynamisk klientregistrering blive forsøgt. | +| `clientSecret` | String | OAuth-klienthemmelighed, hvis det kræves af autorisationsserveren. | +| `scope` | String | OAuth-omfang at anmode om under godkendelse. | + +#### Fejlretning + +Hvis en ekstern MCP-server ikke kan godkendes, kan du diagnosticere problemer med: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +Kommandoen `mcp debug` viser den aktuelle godkendelsesstatus, tester HTTP-forbindelse og forsøger OAuth-opdagelsesflowet. + +--- + +## Administrator + +Dine MCPs er tilgængelige som værktøjer i **TK\_** sammen med indbyggede værktøjer. Så du kan administrere dem gennem OpenCode-konfigurationen som ethvert andet værktøj. + +--- + +### Global + +Det betyder, at du kan aktivere eller deaktivere dem globalt. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +Vi kan også bruge et globmønster til at deaktivere alle matchende MCPs. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +Her bruger vi globmønsteret `my-mcp*` til at deaktivere alle MCPs. + +--- + +### Pr. agent + +Hvis du har et stort antal MCP-servere, vil du måske kun aktivere dem pr. agent og deaktivere dem globalt. Sådan gør du: + +1. Deaktiver det som et værktøj globalt. +2. Aktiver MCP-serveren som et værktøj i din [agent config](/docs/agents#tools). + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### Glob-mønstre + +Glob-mønsteret bruger simple regex-globing-mønstre: + +- `*` matcher nul eller flere af ethvert tegn (f.eks. `"my-mcp*"` matcher `my-mcp_search`, `my-mcp_list` osv.) +- `?` matcher nøjagtigt ét tegn +- Alle andre karakterer matcher bogstaveligt talt + +:::note +MCP serverværktøjer er registreret med servernavn som præfiks, så for at deaktivere alle værktøjer til en server skal du blot bruge: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## Eksempler + +Nedenfor er eksempler på nogle almindelige MCP-servere. Du kan indsende en PR, hvis du vil dokumentere andre servere. + +--- + +### Vagtvagt + +Tilføj [Sentry MCP server](https://mcp.sentry.dev) for at interagere med dine Sentry-projekter og -problemer. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +Efter tilføjelse af konfigurationen skal du godkende med Sentry: + +```bash +opencode mcp auth sentry +``` + +Dette åbner et browservindue for at fuldføre OAuth-flowet og forbinde OpenCode til din Sentry-konto. + +Når du er godkendt, kan du bruge Sentry-værktøjer i dine prompter til at forespørge om problemer, projekter og fejldata. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Kontekst7 + +Tilføj [Context7 MCP server](https://github.com/upstash/context7) for at søge i dokumenter. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +Hvis du har tilmeldt dig en gratis konto, kan du bruge din API nøgle og få højere satsgrænser. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +Her antager vi, at du har sat miljøvariablen `CONTEXT7_API_KEY`. + +Føj `use context7` til dine prompter for at bruge Context7 MCP server. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +Alternativt kan du tilføje noget som dette til din [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep af Vercel + +Tilføj serveren [Grep by Vercel](https://grep.app) MCP for at søge gennem kodestykker på GitHub. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +Da vi navngav vores MCP-server `gh_grep`, kan du tilføje `use the gh_grep tool` til dine prompter for at få agenten til at bruge den. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +Alternativt kan du tilføje noget som dette til din [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/da/models.mdx b/packages/web/src/content/docs/da/models.mdx new file mode 100644 index 000000000..c929173fe --- /dev/null +++ b/packages/web/src/content/docs/da/models.mdx @@ -0,0 +1,223 @@ +--- +title: Modeller +description: Konfiguration af en LLM udbyder og model. +--- + +OpenCode bruger [AI SDK](https://ai-sdk.dev/) og [Models.dev](https://models.dev) til at understøtte **75+ LLM udbydere** og det understøtter at køre lokale modeller. + +--- + +## Udbydere + +De fleste populære udbydere er forudindlæst som standard. Hvis du har tilføjet legitimationsoplysningerne for en udbyder gennem kommandoen `/connect`, vil de være tilgængelige, når du starter OpenCode. + +Få mere at vide om [providers](/docs/providers). + +--- + +## Vælg en model + +Når du har konfigureret din udbyder, kan du vælge den ønskede model ved at indtaste: + +```bash frame="none" +/models +``` + +--- + +## Anbefalede modeller + +Der er mange modeller derude, og der kommer nye modeller hver uge. + +:::tip +Overvej at bruge en af ​​de modeller, vi anbefaler. +::: + +Der er dog kun få af dem, der er gode til både at generere kode og værktøjsopkald. + +Her er flere modeller, der fungerer godt med OpenCode, uden bestemt rækkefølge. (Dette er ikke en udtømmende liste og er heller ikke nødvendigvis opdateret): + +- GPT 5.2 +- GPT 5.1 Codex +- Claude Opus 4,5 +- Claude Sonnet 4,5 +- Minimax M2.1 +- Gemini 3 Pro + +--- + +## Indstil en standard + +For at indstille en af ​​disse som standardmodellen kan du indstille `model`-nøglen i din +OpenCode konfig. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Her er det fulde ID `provider_id/model_id`. For eksempel, hvis du bruger [OpenCode Zen](/docs/zen), vil du bruge `opencode/gpt-5.1-codex` til GPT 5.1 Codex. + +Hvis du har konfigureret en [custom provider](/docs/providers#custom), er `provider_id` nøglen fra `provider` delen af ​​din konfiguration, og `model_id` er nøglen fra `provider.models`. + +--- + +## Konfigurer modeller + +Du kan konfigurere en models muligheder globalt gennem konfigurationen. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Her konfigurerer vi globale indstillinger for to indbyggede modeller: `gpt-5` når de tilgås via `openai` udbyderen og `claude-sonnet-4-20250514` når de tilgås via `anthropic` udbyderen. +Den indbyggede udbyder og modelnavne kan findes på [Models.dev](https://models.dev). + +Du kan også konfigurere disse indstillinger for alle agenter, du bruger. Agentkonfigurationen tilsidesætter alle globale muligheder her. [Learn more](/docs/agents/#additional). + +Du kan også definere brugerdefinerede varianter, der udvider de indbyggede. Varianter giver dig mulighed for at konfigurere forskellige indstillinger for den samme model uden at oprette duplikerede poster: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## Varianter + +Mange modeller understøtter flere varianter med forskellige konfigurationer. OpenCode leveres med indbyggede standardvarianter til populære udbydere. + +### Indbyggede varianter + +OpenCode leveres med standardvarianter for mange udbydere: + +**Anthropic**: + +- `high` - Højt tænkende budget (standard) +- `max` - Maksimalt tænkebudget + +**OpenAI**: + +Varierer efter model, men nogenlunde: + +- `none` - Ingen begrundelse +- `minimal` - Minimal ræsonnement indsats +- `low` - Lav ræsonnement indsats +- `medium` - Middel ræsonnement indsats +- `high` - Høj ræsonnement indsats +- `xhigh` - Ekstra høj ræsonnement indsats + +**Google**: + +- `low` - Lavere effort/token budget +- `high` - Højere effort/token budget + +:::tip +Denne liste er ikke udtømmende. Mange andre udbydere har også indbyggede standardindstillinger. +::: + +### Brugerdefinerede varianter + +Du kan tilsidesætte eksisterende varianter eller tilføje dine egne: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### Cyklusvarianter + +Brug tastebindingen `variant_cycle` til hurtigt at skifte mellem varianter. [Learn more](/docs/keybinds). + +--- + +## Indlæser modeller + +Når OpenCode starter op, søger den efter modeller i følgende prioriterede rækkefølge: + +1. Kommandolinjeflaget `--model` eller `-m`. Formatet er det samme som i konfigurationsfilen: `provider_id/model_id`. + +2. Modellisten i OpenCode-konfigurationen. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + Formatet her er `provider/model`. + +3. Den sidst brugte model. + +4. Den første model med en intern prioritet. diff --git a/packages/web/src/content/docs/da/modes.mdx b/packages/web/src/content/docs/da/modes.mdx new file mode 100644 index 000000000..42964d434 --- /dev/null +++ b/packages/web/src/content/docs/da/modes.mdx @@ -0,0 +1,331 @@ +--- +title: Tilstande +description: Forskellige tilstande til forskellige anvendelsestilfælde. +--- + +:::forsigtighed +Tilstande er nu konfigureret gennem indstillingen `agent` i opencode-konfigurationen. De +`mode` mulighed er nu forældet. [Learn more](/docs/agents). +::: + +Tilstande i opencode giver dig mulighed for at tilpasse adfærd, værktøjer og prompter til forskellige brugstilfælde. + +Den kommer med to indbyggede tilstande: **build** og **plan**. Du kan tilpasse +disse eller konfigurer dine egne gennem opencode-konfigurationen. + +Du kan skifte mellem tilstande under en session eller konfigurere dem i din konfigurationsfil. + +--- + +## Indbygget + +opencode leveres med to indbyggede tilstande. + +--- + +### Byg + +Byg er **standard**-tilstanden med alle værktøjer aktiveret. Dette er standardtilstanden for udviklingsarbejde, hvor du har brug for fuld adgang til filhandlinger og systemkommandoer. + +--- + +### Plan + +En begrænset tilstand designet til planlægning og analyse. I plantilstand er følgende værktøjer deaktiveret som standard: + +- `write` - Kan ikke oprette nye filer +- `edit` - Kan ikke ændre eksisterende filer, undtagen filer placeret på `.opencode/plans/*.md` for at detaljere selve planen +- `patch` - Kan ikke anvende patches +- `bash` - Kan ikke udføre shell-kommandoer + +Denne tilstand er nyttig, når du vil have AI til at analysere kode, foreslå ændringer eller oprette planer uden at foretage egentlige ændringer af din kodebase. + +--- + +## Skifter + +Du kan skifte mellem tilstande under en session ved at bruge _Tab_-tasten. Eller din konfigurerede `switch_mode` nøglebinding. + +Se også: [Formatters](/docs/formatters) for information om konfiguration af kodeformatering. + +--- + +## Konfigurer + +Du kan tilpasse de indbyggede tilstande eller oprette dine egne gennem konfiguration. Tilstande kan konfigureres på to måder: + +### JSON Konfiguration + +Konfigurer tilstande i din `opencode.json`-konfigurationsfil: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Markdown-konfiguration + +Du kan også definere tilstande ved hjælp af markdown-filer. Placer dem i: + +- Globalt: `~/.config/opencode/modes/` +- Projekt: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Markdown-filnavnet bliver tilstandsnavnet (f.eks. opretter `review.md` en `review`-tilstand). + +Lad os se nærmere på disse konfigurationsmuligheder. + +--- + +### Model + +Brug `model`-konfigurationen til at tilsidesætte standardmodellen for denne tilstand. Nyttigt til brug af forskellige modeller optimeret til forskellige opgaver. For eksempel en hurtigere model til planlægning, en mere dygtig model til implementering. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Temperatur + +Styr tilfældigheden og kreativiteten af ​​AI's svar med `temperature`-konfigurationen. Lavere værdier gør svar mere fokuserede og deterministiske, mens højere værdier øger kreativitet og variabilitet. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Temperaturværdier varierer typisk fra 0,0 til 1,0: + +- **0.0-0.2**: Meget fokuserede og deterministiske svar, ideel til kodeanalyse og planlægning +- **0,3-0,5**: Afbalancerede svar med en vis kreativitet, god til generelle udviklingsopgaver +- **0.6-1.0**: Mere kreative og varierede svar, nyttige til brainstorming og udforskning + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Hvis der ikke er angivet nogen temperatur, bruger opencode modelspecifikke standarder (typisk 0 for de fleste modeller, 0,55 for Qwen-modeller). + +--- + +### Spørg + +Angiv en brugerdefineret systempromptfil for denne tilstand med `prompt`-konfigurationen. Promptfilen skal indeholde instruktioner, der er specifikke for tilstandens formål. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Denne sti er i forhold til, hvor konfigurationsfilen er placeret. Så dette virker for +både den globale opencode-konfiguration og den projektspecifikke konfiguration. + +--- + +### Værktøjer + +Kontroller, hvilke værktøjer der er tilgængelige i denne tilstand med `tools`-konfigurationen. Du kan aktivere eller deaktivere specifikke værktøjer ved at indstille dem til `true` eller `false`. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +Hvis der ikke er angivet nogen værktøjer, er alle værktøjer aktiveret som standard. + +--- + +#### Tilgængelige værktøjer + +Her er alle de værktøjer, der kan styres gennem tilstandskonfigurationen. + +| Værktøj | Beskrivelse | +| ----------- | -------------------------- | +| `bash` | Udfør shell-kommandoer | +| `edit` | Rediger eksisterende filer | +| `write` | Opret nye filer | +| `read` | Læs filindhold | +| `grep` | Søg filindhold | +| `glob` | Find filer efter mønster | +| `list` | Liste biblioteksindhold | +| `patch` | Anvend patches til filer | +| `todowrite` | Administrer todo-lister | +| `todoread` | Læs todo-lister | +| `webfetch` | Hent webindhold | + +--- + +## Brugerdefinerede tilstande + +Du kan oprette dine egne brugerdefinerede tilstande ved at tilføje dem til konfigurationen. Her er eksempler, der bruger begge tilgange: + +### Bruger JSON konfiguration + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Brug af markdown-filer + +Opret tilstandsfiler i `.opencode/modes/` for projektspecifikke tilstande eller `~/.config/opencode/modes/` for globale tilstande: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### Use cases + +Her er nogle almindelige brugstilfælde for forskellige tilstande. + +- **Build mode**: Fuldt udviklingsarbejde med alle værktøjer aktiveret +- **Plantilstand**: Analyse og planlægning uden at foretage ændringer +- **Anmeldelsestilstand**: Kodegennemgang med skrivebeskyttet adgang plus dokumentationsværktøjer +- **Fejlretningstilstand**: Fokuseret på undersøgelse med bash og læseværktøjer aktiveret +- **Docs-tilstand**: Dokumentationsskrivning med filhandlinger, men ingen systemkommandoer + +Du kan også finde ud af, at forskellige modeller er gode til forskellige brugssituationer. diff --git a/packages/web/src/content/docs/da/network.mdx b/packages/web/src/content/docs/da/network.mdx new file mode 100644 index 000000000..3274a7b3d --- /dev/null +++ b/packages/web/src/content/docs/da/network.mdx @@ -0,0 +1,57 @@ +--- +title: Netværk +description: Konfigurer proxyer og brugerdefinerede certifikater. +--- + +OpenCode understøtter standard proxymiljøvariabler og brugerdefinerede certifikater til virksomhedsnetværksmiljøer. + +--- + +## Proxy + +OpenCode respekterer standard proxy-miljøvariabler. + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::forsigtighed +TUI kommunikerer med en lokal HTTP-server. Du skal omgå proxyen for denne forbindelse for at forhindre routingsløjfer. +::: + +Du kan konfigurere serverens port og værtsnavn ved hjælp af [CLI flags](/docs/cli#run). + +--- + +### Godkend + +Hvis din proxy kræver grundlæggende godkendelse, skal du inkludere legitimationsoplysninger i URL. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::forsigtighed +Undgå hardkodning af adgangskoder. Brug miljøvariabler eller sikker lagring af legitimationsoplysninger. +::: + +For proxyer, der kræver avanceret godkendelse som NTLM eller Kerberos, kan du overveje at bruge en LLM Gateway, der understøtter din godkendelsesmetode. + +--- + +## Brugerdefinerede certifikater + +Hvis din virksomhed bruger tilpassede CA'er til HTTPS-forbindelser, skal du konfigurere OpenCode til at stole på dem. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +Dette virker for både proxy-forbindelser og direkte API-adgang. diff --git a/packages/web/src/content/docs/da/permissions.mdx b/packages/web/src/content/docs/da/permissions.mdx new file mode 100644 index 000000000..72c839833 --- /dev/null +++ b/packages/web/src/content/docs/da/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: Tilladelser +description: Kontroller, hvilke handlinger der kræver godkendelse for at køre. +--- + +OpenCode bruger `permission`-konfigurationen til at bestemme, om en given handling skal køre automatisk, bede dig om eller blokeres. + +Fra `v1.1.1` er den ældre `tools` booleske konfiguration forældet og er blevet flettet ind i `permission`. Den gamle `tools`-konfiguration er stadig understøttet for bagudkompatibilitet. + +--- + +## Handlinger + +Hver tilladelsesregel løses til en af: + +- `"allow"` — køre uden godkendelse +- `"ask"` — prompt om godkendelse +- `"deny"` — bloker handlingen + +--- + +## Konfiguration + +Du kan indstille tilladelser globalt (med `*`) og tilsidesætte specifikke værktøjer. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +Du kan også indstille alle tilladelser på én gang: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## Granulære regler (objektsyntaks) + +For de fleste tilladelser kan du bruge et objekt til at anvende forskellige handlinger baseret på værktøjsinputtet. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +Regler evalueres efter mønstermatch, hvor den **sidste matchende regel vinder**. Et almindeligt mønster er at sætte catch-all `"*"` reglen først og mere specifikke regler efter den. + +### Jokertegn + +Tilladelsesmønstre bruger simpel jokertegn-matchning: + +- `*` matcher nul eller flere af et hvilket som helst tegn +- `?` matcher nøjagtigt ét tegn +- Alle andre karakterer matcher bogstaveligt talt + +### Udvidelse af hjemmemappe + +Du kan bruge `~` eller `$HOME` i starten af ​​et mønster til at referere til din hjemmemappe. Dette er især nyttigt for [`external_directory`](#external-directories) regler. + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### Eksterne mapper + +Brug `external_directory` til at tillade værktøjsopkald, der berører stier uden for den arbejdsmappe, hvor OpenCode blev startet. Dette gælder for ethvert værktøj, der tager en sti som input (for eksempel `read`, `edit`, `list`, `glob`, `grep` og mange `bash` kommandoer). + +Hjemmeudvidelse (som `~/...`) påvirker kun, hvordan et mønster skrives. Det gør ikke en ekstern sti til en del af det aktuelle arbejdsområde, så stier uden for arbejdsbiblioteket skal stadig være tilladt via `external_directory`. + +For eksempel giver dette adgang til alt under `~/projects/personal/`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +Enhver mappe, der er tilladt her, arver de samme standarder som det aktuelle arbejdsområde. Siden [`read` defaults to `allow`](#defaults), er læsninger også tilladt for poster under `external_directory`, medmindre de tilsidesættes. Tilføj eksplicitte regler, når et værktøj skal begrænses i disse stier, såsom blokering af redigeringer, mens læsninger bevares: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +Hold listen fokuseret på betroede stier, og lag ekstra tillad eller afvis regler efter behov for andre værktøjer (for eksempel `bash`). + +--- + +## Tilgængelige tilladelser + +OpenCode tilladelser indtastes efter værktøjsnavn plus et par sikkerhedsafskærmninger: + +- `read` — læser en fil (matcher filstien) +- `edit` — alle filændringer (dækker `edit`, `write`, `patch`, `multiedit`) +- `glob` — fil-globing (matcher glob-mønsteret) +- `grep` — indholdssøgning (matcher regex-mønsteret) +- `list` — viser filer i en mappe (matcher mappestien) +- `bash` — kører shell-kommandoer (matcher parsede kommandoer som `git status --porcelain`) +- `task` — lancering af underagenter (matcher underagenttypen) +- `skill` — indlæsning af en færdighed (matcher færdighedsnavnet) +- `lsp` — kører LSP forespørgsler (i øjeblikket ikke-granulære) +- `todoread`, `todowrite` — reading/updating todo-listen +- `webfetch` — henter en URL (matcher URL) +- `websearch`, `codesearch` — web/code søgning (matcher forespørgslen) +- `external_directory` — udløses, når et værktøj berører stier uden for projektets arbejdsmappe +- `doom_loop` — udløses, når det samme værktøjskald gentages 3 gange med identisk input + +--- + +## Standarder + +Hvis du ikke angiver noget, starter OpenCode fra tilladelige standardindstillinger: + +- De fleste tilladelser er som standard `"allow"`. +- `doom_loop` og `external_directory` er som standard `"ask"`. +- `read` er `"allow"`, men `.env` filer nægtes som standard: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## Hvad "Spørg" gør + +Når OpenCode beder om godkendelse, tilbyder brugergrænsefladen tre resultater: + +- `once` — godkend netop denne anmodning +- `always` — godkend fremtidige anmodninger, der matcher de foreslåede mønstre (for resten af ​​den nuværende OpenCode session) +- `reject` — afvis anmodningen + +Sættet af mønstre, som `always` ville godkende, leveres af værktøjet (f.eks. hvidlister bash-godkendelser typisk et sikkert kommandopræfiks som `git status*`). + +--- + +## Agenter + +Du kan tilsidesætte tilladelser pr. agent. Agenttilladelser flettes med den globale konfiguration, og agentregler har forrang. [Learn more](/docs/agents#permissions) om agenttilladelser. + +:::note +Se afsnittet [Granular Rules (Object Syntax)](#granular-rules-object-syntax) ovenfor for mere detaljerede mønstermatchningseksempler. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +Du kan også konfigurere agenttilladelser i Markdown: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tip +Brug mønstermatchning til kommandoer med argumenter. `"grep *"` tillader `grep pattern file.txt`, mens `"grep"` alene ville blokere det. Kommandoer som `git status` fungerer for standardadfærd, men kræver eksplicit tilladelse (som `"git status *"`), når argumenter sendes. +::: diff --git a/packages/web/src/content/docs/da/plugins.mdx b/packages/web/src/content/docs/da/plugins.mdx new file mode 100644 index 000000000..689abdff0 --- /dev/null +++ b/packages/web/src/content/docs/da/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: Plugins +description: Skriv dine egne plugins for at udvide OpenCode. +--- + +Plugins giver dig mulighed for at udvide OpenCode ved at tilslutte sig forskellige begivenheder og tilpasse adfærd. Du kan oprette plugins for at tilføje nye funktioner, integrere med eksterne tjenester eller ændre OpenCodes standardadfærd. + +For eksempler, tjek [plugins](/docs/ecosystem#plugins) oprettet af fællesskabet. + +--- + +## Brug et plugin + +Der er to måder at indlæse plugins på. + +--- + +### Fra lokale filer + +Placer JavaScript- eller TypeScript-filer i plugin-mappen. + +- `.opencode/plugins/` - Plugins på projektniveau +- `~/.config/opencode/plugins/` - Globale plugins + +Filer i disse mapper indlæses automatisk ved opstart. + +--- + +### Fra npm + +Angiv npm-pakker i din konfigurationsfil. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +Både almindelige og omfangsrige npm-pakker understøttes. + +Gennemse tilgængelige plugins i [ecosystem](/docs/ecosystem#plugins). + +--- + +### Hvordan plugins installeres + +**npm plugins** installeres automatisk ved hjælp af Bun ved opstart. Pakker og deres afhængigheder cachelagres i `~/.cache/opencode/node_modules/`. + +**Lokale plugins** indlæses direkte fra plugin-biblioteket. For at bruge eksterne pakker skal du oprette en `package.json` i din konfigurationsmappe (se [Dependencies](#dependencies)), eller udgive pluginnet til npm og [add it to your config](/docs/config#plugins). + +--- + +### Indlæs rækkefølge + +Plugins indlæses fra alle kilder, og alle hooks kører i rækkefølge. Indlæsningsrækkefølgen er: + +1. Global konfiguration (`~/.config/opencode/opencode.json`) +2. Projektkonfiguration (`opencode.json`) +3. Global plugin-mappe (`~/.config/opencode/plugins/`) +4. Projekt plugin bibliotek (`.opencode/plugins/`) + +Dublerede npm-pakker med samme navn og version indlæses én gang. Et lokalt plugin og et npm plugin med lignende navne indlæses dog hver for sig. + +--- + +## Opret et plugin + +Et plugin er et **JavaScript/TypeScript modul**, der eksporterer et eller flere plugin +funktioner. Hver funktion modtager et kontekstobjekt og returnerer et hooks-objekt. + +--- + +### Afhængigheder + +Lokale plugins og brugerdefinerede værktøjer kan bruge eksterne npm-pakker. Tilføj en `package.json` til din konfigurationsmappe med de afhængigheder, du har brug for. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode kører `bun install` ved opstart for at installere disse. Dine plugins og værktøjer kan derefter importere dem. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### Grundlæggende struktur + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +Plugin-funktionen modtager: + +- `project`: Den aktuelle projektinformation. +- `directory`: Den aktuelle arbejdsmappe. +- `worktree`: Git worktree-stien. +- `client`: En opencode SDK klient til interaktion med AI. +- `-: Buns [shell API](https://bun.com/docs/runtime/shell) til udførelse af kommandoer. + +--- + +### TypeScript-understøttelse + +For TypeScript-plugins kan du importere typer fra plugin-pakken: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### Begivenheder + +Plugins kan abonnere på begivenheder som vist nedenfor i afsnittet Eksempler. Her er en liste over de forskellige arrangementer. + +#### Kommandohændelser + +- `command.executed` + +#### Filhændelser + +- `file.edited` +- `file.watcher.updated` + +#### Installationshændelser + +- `installation.updated` + +#### LSP Begivenheder + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### Beskedhændelser + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### Tilladelsesbegivenheder + +- `permission.asked` +- `permission.replied` + +#### Serverhændelser + +- `server.connected` + +#### Sessionsbegivenheder + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### Todo-begivenheder + +- `todo.updated` + +#### Shell-begivenheder + +- `shell.env` + +#### Værktøjsbegivenheder + +- `tool.execute.after` +- `tool.execute.before` + +#### TUI Begivenheder + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## Eksempler + +Her er nogle eksempler på plugins, du kan bruge til at udvide opencode. + +--- + +### Send meddelelser + +Send meddelelser, når visse hændelser indtræffer: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +Vi bruger `osascript` til at køre AppleScript på macOS. Her bruger vi det til at sende notifikationer. + +:::note +Hvis du bruger OpenCode desktop-appen, kan den sende systemmeddelelser automatisk, når et svar er klar, eller når en session fejler. +::: + +--- + +###.env-beskyttelse + +Undgå opencode i at læse `.env` filer: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### Injicer miljøvariabler + +Injicer miljøvariabler i al shell-udførelse (AI-værktøjer og brugerterminaler): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### Brugerdefinerede værktøjer + +Plugins kan også tilføje brugerdefinerede værktøjer til opencode: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +`tool`-hjælperen opretter et brugerdefineret værktøj, som opencode kan kalde. Det tager en Zod-skemafunktion og returnerer en værktøjsdefinition med: + +- `description`: Hvad værktøjet gør +- `args`: Zod-skema for værktøjets argumenter +- `execute`: Funktion, der kører, når værktøjet kaldes + +Dine tilpassede værktøjer vil være tilgængelige for opencode sammen med indbyggede værktøjer. + +--- + +### Logning + +Brug `client.app.log()` i stedet for `console.log` til struktureret logning: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +Niveauer: `debug`, `info`, `warn`, `error`. Se [SDK documentation](https://opencode.ai/docs/sdk) for detaljer. + +--- + +### Komprimeringskroge + +Tilpas konteksten inkluderet, når en session komprimeres: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +`experimental.session.compacting` krogen affyres, før LLM genererer en fortsættelsesoversigt. Brug den til at injicere domænespecifik kontekst, som standardkomprimeringsprompten ville gå glip af. + +Du kan også erstatte komprimeringsprompten helt ved at indstille `output.prompt`: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +Når `output.prompt` er indstillet, erstatter den standardkompressionsprompten fuldstændigt. `output.context`-arrayet ignoreres i dette tilfælde. diff --git a/packages/web/src/content/docs/da/providers.mdx b/packages/web/src/content/docs/da/providers.mdx new file mode 100644 index 000000000..98e214b78 --- /dev/null +++ b/packages/web/src/content/docs/da/providers.mdx @@ -0,0 +1,1889 @@ +--- +title: Leverandører +description: Bruke en hvilken som helst LLM-leverandør i OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode bruker [AI SDK](https://ai-sdk.dev/) og [Models.dev](https://models.dev) for å støtte **75+ LLM leverandører** og den støtter kjøring av lokale modeller. + +For å legge til en leverandør må du: + +1. Legg til API-nøklene for leverandøren ved å bruke kommandoen `/connect`. +2. Konfigurer leverandøren i OpenCode-konfigurasjonen. + +--- + +### Legitimasjon + +Når du legger til en leverandørs API-nøkler med `/connect`-kommandoen, lagres de +i `~/.local/share/opencode/auth.json`. + +--- + +### Konfig + +Du kan tilpasse leverandørene gjennom `provider`-delen i OpenCode +konfig. + +--- + +#### Base URL + +Du kan tilpasse basen URL for enhver leverandør ved å angi alternativet `baseURL`. Dette er nyttig når du bruker proxy-tjenester eller tilpassede endepunkter. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen er en liste over modeller levert av OpenCode-teamet som har vært +testet og verifisert for å fungere godt med OpenCode. [Finn ut mer](/docs/zen). + +:::tupp +Hvis du er ny, anbefaler vi å starte med OpenCode Zen. +::: + +1. Kjør kommandoen `/connect` i TUI, velg opencode og gå til [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Logg på, legg til faktureringsdetaljene dine og kopier API-nøkkelen. + +3. Lim inn API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør `/models` i TUI for å se listen over modeller vi anbefaler. + + ```txt + /models + ``` + +Det fungerer som alle andre leverandører i OpenCode og er helt valgfritt å bruke. + +--- + +## Katalog + +La oss se på noen av leverandørene i detalj. Hvis du vil legge til en leverandør til +liste, åpne gjerne en PR. + +:::note +Ser du ikke en leverandør her? Send inn en PR. +::: + +--- + +### 302.AI + +1. Gå over til [302.AI-konsollen](https://302.ai/), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **302.AI**. + + ```txt + /connect + ``` + +3. Skriv inn 302.AI API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +--- + +### Amazonas grunnfjell + +Slik bruker du Amazon Bedrock med OpenCode: + +1. Gå over til **modellkatalogen** i Amazon Bedrock-konsollen og be om + tilgang til modellene du ønsker. + + :::tupp + Du må ha tilgang til modellen du ønsker i Amazon Bedrock. + ::: + +2. **Konfigurer autentisering** ved å bruke en av følgende metoder: + + #### Miljøvariabler (hurtigstart) + + Angi en av disse miljøvariablene mens du kjører opencode: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + Eller legg dem til bash-profilen din: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### Konfigurasjonsfil (anbefalt) + + For prosjektspesifikk eller vedvarende konfigurasjon, bruk `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **Tilgjengelige alternativer:** + - `region` - AWS region (f.eks. `us-east-1`, `eu-west-1`) + - `profile` - AWS navngitt profil fra `~/.aws/credentials` + - `endpoint` - Egendefinert endepunkt URL for VPC endepunkter (alias for generisk `baseURL`-alternativ) + + :::tupp + Alternativer for konfigurasjonsfil har forrang over miljøvariabler. + ::: + + #### Avansert: VPC Sluttpunkter + + Hvis du bruker VPC endepunkter for Berggrunn: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::note + Alternativet `endpoint` er et alias for det generiske alternativet `baseURL`, ved å bruke AWS-spesifikk terminologi. Hvis både `endpoint` og `baseURL` er spesifisert, har `endpoint` forrang. + ::: + + #### Autentiseringsmetoder + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: Opprett en IAM-bruker og generer tilgangsnøkler i AWS-konsollen + - **`AWS_PROFILE`**: Bruk navngitte profiler fra `~/.aws/credentials`. Konfigurer først med `aws configure --profile my-profile` eller `aws sso login` + - **`AWS_BEARER_TOKEN_BEDROCK`**: Generer langsiktige API-nøkler fra Amazon Bedrock-konsollen + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: For EKS IRSA (IAM roller for tjenestekontoer) eller andre Kubernetes-miljøer med OIDC føderasjon. Disse miljøvariablene injiseres automatisk av Kubernetes når du bruker tjenestekontokommentarer. + + #### Autentiseringsprioritet + + Amazon Bedrock bruker følgende autentiseringsprioritet: + 1. **Bearer Token** - `AWS_BEARER_TOKEN_BEDROCK` miljøvariabel eller token fra kommandoen `/connect` + 2. **AWS legitimasjonskjede** - profil, tilgangsnøkler, delt legitimasjon, IAM roller, nettidentitetstokener (EKS IRSA), forekomstmetadata + + :::note + Når et bærertoken er angitt (via `/connect` eller `AWS_BEARER_TOKEN_BEDROCK`), har det forrang over alle AWS legitimasjonsmetoder inkludert konfigurerte profiler. + ::: + +3. Kjør kommandoen `/models` for å velge modellen du ønsker. + + ```txt + /models + ``` + +:::note +For egendefinerte slutningsprofiler, bruk modellen og leverandørnavnet i nøkkelen og sett egenskapen `id` til arn. Dette sikrer korrekt caching: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### Antropisk + +1. Når du har registrert deg, kjør kommandoen `/connect` og velg Antropisk. + + ```txt + /connect + ``` + +2. Her kan du velge alternativet **Claude Pro/Max** og det vil åpne nettleseren din + og ber deg om å autentisere. + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. Nå skal alle de antropiske modellene være tilgjengelige når du bruker kommandoen `/models`. + + ```txt + /models + ``` + +::: info +Å bruke Claude Pro/Max-abonnementet ditt i OpenCode støttes ikke offisielt av [Anthropic](https://anthropic.com). +::: + +##### Bruke API-tastene + +Du kan også velge **Opprett en API nøkkel** hvis du ikke har et Pro/Max-abonnement. Den åpner også nettleseren din og ber deg logge på Anthropic og gi deg en kode du kan lime inn i terminalen din. + +Eller hvis du allerede har en API-nøkkel, kan du velge **Angi API-nøkkel manuelt** og lime den inn i terminalen. + +--- + +### Azure OpenAI + +:::note +Hvis du støter på «Beklager, men jeg kan ikke hjelpe med den forespørselen»-feil, kan du prøve å endre innholdsfilteret fra **DefaultV2** til **Default** i Azure-ressursen. +::: + +1. Gå over til [Azure-portalen](https://portal.azure.com/) og lag en **Azure OpenAI**-ressurs. Du trenger: + - **Ressursnavn**: Dette blir en del av API-endepunktet (`https://RESOURCE_NAME.openai.azure.com/`) + - **API nøkkel**: Enten `KEY 1` eller `KEY 2` fra ressursen din + +2. Gå til [Azure AI Foundry](https://ai.azure.com/) og distribuer en modell. + + :::note + Distribusjonsnavnet må samsvare med modellnavnet for at opencode skal fungere skikkelig. + ::: + +3. Kjør kommandoen `/connect` og søk etter **Azure**. + + ```txt + /connect + ``` + +4. Skriv inn API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Angi ressursnavnet ditt som en miljøvariabel: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + Eller legg den til bash-profilen din: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. Kjør kommandoen `/models` for å velge den distribuerte modellen. + + ```txt + /models + ``` + +--- + +### Azure Cognitive Services + +1. Gå over til [Azure-portalen](https://portal.azure.com/) og lag en **Azure OpenAI**-ressurs. Du trenger: + - **Ressursnavn**: Dette blir en del av API-endepunktet (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) + - **API nøkkel**: Enten `KEY 1` eller `KEY 2` fra ressursen din + +2. Gå til [Azure AI Foundry](https://ai.azure.com/) og distribuer en modell. + + :::note + Distribusjonsnavnet må samsvare med modellnavnet for at opencode skal fungere skikkelig. + ::: + +3. Kjør kommandoen `/connect` og søk etter **Azure Cognitive Services**. + + ```txt + /connect + ``` + +4. Skriv inn API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Angi ressursnavnet ditt som en miljøvariabel: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + Eller legg den til bash-profilen din: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. Kjør kommandoen `/models` for å velge den distribuerte modellen. + + ```txt + /models + ``` + +--- + +### Baseten + +1. Gå over til [Baseten](https://app.baseten.co/), opprett en konto og generer en API nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Baseten**. + + ```txt + /connect + ``` + +3. Skriv inn din Baseten API nøkkel. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +--- + +### Cerebras + +1. Gå over til [Cerebras-konsollen](https://inference.cerebras.ai/), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Cerebras**. + + ```txt + /connect + ``` + +3. Skriv inn Cerebras API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### Cloudflare AI Gateway + +Cloudflare AI Gateway lar deg få tilgang til modeller fra OpenAI, Anthropic, Workers AI og mer gjennom et enhetlig endepunkt. Med [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) trenger du ikke separate API-nøkler for hver leverandør. + +1. Gå over til [Cloudflare-dashbordet](https://dash.cloudflare.com/), naviger til **AI** > **AI Gateway**, og lag en ny gateway. + +2. Angi konto ID og gateway ID som miljøvariabler. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. Kjør kommandoen `/connect` og søk etter **Cloudflare AI Gateway**. + + ```txt + /connect + ``` + +4. Skriv inn Cloudflare API-tokenet ditt. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + Eller angi den som en miljøvariabel. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + + Du kan også legge til modeller gjennom opencode-konfigurasjonen. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### Cortecs + +1. Gå over til [Cortecs-konsollen](https://cortecs.ai/), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Cortecs**. + + ```txt + /connect + ``` + +3. Skriv inn Cortecs API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### DeepSeek + +1. Gå over til [DeepSeek-konsollen](https://platform.deepseek.com/), opprett en konto og klikk på **Opprett ny API-nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **DeepSeek**. + + ```txt + /connect + ``` + +3. Skriv inn DeepSeek API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en DeepSeek-modell som _DeepSeek Reasoner_. + + ```txt + /models + ``` + +--- + +### Deep Infra + +1. Gå over til [Deep Infra-dashbordet](https://deepinfra.com/dash), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Deep Infra**. + + ```txt + /connect + ``` + +3. Skriv inn Deep Infra API nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +--- + +### Fastvare + +1. Gå over til [Firmware dashboard](https://app.firmware.ai/signup), opprett en konto og generer en API nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Firmware**. + + ```txt + /connect + ``` + +3. Skriv inn firmware API nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +--- + +### Fyrverkeri AI + +1. Gå over til [Fireworks AI-konsollen](https://app.fireworks.ai/), opprett en konto og klikk på **Create API Key**. + +2. Kjør kommandoen `/connect` og søk etter **Fireworks AI**. + + ```txt + /connect + ``` + +3. Skriv inn Fireworks AI API nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### GitLab Duo + +GitLab Duo gir AI-drevet agentchat med native verktøyoppringingsfunksjoner gjennom GitLabs antropiske proxy. + +1. Kjør kommandoen `/connect` og velg GitLab. + + ```txt + /connect + ``` + +2. Velg autentiseringsmetoden din: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### Bruke OAuth (anbefalt) + + Velg **OAuth** og nettleseren din åpnes for autorisasjon. + + #### Bruker personlig tilgangstoken + 1. Gå til [GitLab User Settings > Access Tokens](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. Klikk på **Legg til nytt token** + 3. Navn: `OpenCode`, omfang: `api` + 4. Kopier tokenet (starter med `glpat-`) + 5. Skriv den inn i terminalen + +3. Kjør kommandoen `/models` for å se tilgjengelige modeller. + + ```txt + /models + ``` + + Tre Claude-baserte modeller er tilgjengelige: + - **duo-chat-haiku-4-5** (standard) - Raske svar for raske oppgaver + - **duo-chat-sonnet-4-5** - Balansert ytelse for de fleste arbeidsflyter + - **duo-chat-opus-4-5** - Mest egnet for kompleks analyse + +:::note +Du kan også spesifisere 'GITLAB_TOKEN' miljøvariabel hvis du ikke vil +for å lagre token i opencode auth-lagring. +::: + +##### Selvhostet GitLab + +:::note[compliance note] +OpenCode bruker en liten modell for noen AI oppgaver som å generere økttittelen. +Den er konfigurert til å bruke gpt-5-nano som standard, hostet av Zen. For å låse OpenCode +for kun å bruke din egen GitLab-hostede forekomst, legg til følgende i din +`opencode.json` fil. Det anbefales også å deaktivere øktdeling. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +For selvhostede GitLab-forekomster: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +Hvis forekomsten din kjører en tilpasset AI-gateway: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +Eller legg til bash-profilen din: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +GitLab-administratoren din må aktivere følgende: + +1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) for brukeren, gruppen eller forekomsten +2. Funksjonsflagg (via Rails-konsollen): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### OAuth for selvvertsbaserte forekomster + +For å få Oauth til å fungere for din selvhostede forekomst, må du opprette +en ny applikasjon (Innstillinger → Programmer) med +tilbakeringing URL `http://127.0.0.1:8080/callback` og følgende omfang: + +- api (Få tilgang til API på dine vegne) +- read_user (Les din personlige informasjon) +- read_repository (tillater skrivebeskyttet tilgang til depotet) + +Utsett deretter applikasjonen ID som miljøvariabel: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +Mer dokumentasjon på [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth) hjemmeside. + +##### Konfigurasjon + +Tilpass gjennom `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API Verktøy (valgfritt, men sterkt anbefalt) + +For å få tilgang til GitLab-verktøy (sammenslåingsforespørsler, problemer, pipelines, CI/CD, etc.): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +Denne plugin-en gir omfattende GitLab-repository-administrasjonsfunksjoner, inkludert MR-anmeldelser, problemsporing, pipeline-overvåking og mer. + +--- + +### GitHub Copilot + +Slik bruker du GitHub Copilot-abonnementet med OpenCode: + +:::note +Noen modeller kan trenge en [Pro+ +abonnement](https://github.com/features/copilot/plans) å bruke. + +Noen modeller må aktiveres manuelt i [GitHub Copilot-innstillingene](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. Kjør kommandoen `/connect` og søk etter GitHub Copilot. + + ```txt + /connect + ``` + +2. Naviger til [github.com/login/device](https://github.com/login/device) og skriv inn koden. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. Kjør nå kommandoen `/models` for å velge modellen du ønsker. + + ```txt + /models + ``` + +--- + +### Google Vertex AI + +Slik bruker du Google Vertex AI med OpenCode: + +1. Gå over til **Model Garden** i Google Cloud Console og sjekk + modeller tilgjengelig i din region. + + :::note + Du må ha et Google Cloud-prosjekt med Vertex AI API aktivert. + ::: + +2. Angi de nødvendige miljøvariablene: + - `GOOGLE_CLOUD_PROJECT`: Google Cloud-prosjektet ditt ID + - `VERTEX_LOCATION` (valgfritt): Regionen for verteks AI (standard til `global`) + - Autentisering (velg en): + - `GOOGLE_APPLICATION_CREDENTIALS`: Bane til tjenestekontoen JSON nøkkelfil + - Autentiser med gcloud CLI: `gcloud auth application-default login` + + Sett dem mens du kjører opencode. + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + Eller legg dem til på bash-profilen din. + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::tupp +`global`-regionen forbedrer tilgjengeligheten og reduserer feil uten ekstra kostnad. Bruk regionale endepunkter (f.eks. `us-central1`) for krav til dataopphold. [Finn ut mer](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. Kjør kommandoen `/models` for å velge modellen du ønsker. + + ```txt + /models + ``` + +--- + +### Groq + +1. Gå over til [Groq-konsollen](https://console.groq.com/), klikk på **Create API Key**, og kopier nøkkelen. + +2. Kjør kommandoen `/connect` og søk etter Groq. + + ```txt + /connect + ``` + +3. Skriv inn API-nøkkelen for leverandøren. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge den du ønsker. + + ```txt + /models + ``` + +--- + +### Klemmer ansikt + +[Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers) gir tilgang til åpne modeller som støttes av 17+ leverandører. + +1. Gå over til [Hugging Face-innstillinger](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) for å opprette et token med tillatelse til å ringe til inferensleverandører. + +2. Kjør kommandoen `/connect` og søk etter **Hugging Face**. + + ```txt + /connect + ``` + +3. Skriv inn ditt Hugging Face-token. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Kimi-K2-Instruct_ eller _GLM-4.6_. + + ```txt + /models + ``` + +--- + +### Helikon + +[Helicone](https://helicone.ai) er en LLM observerbarhetsplattform som gir logging, overvåking og analyser for AI-applikasjonene dine. Helicone AI Gateway ruter forespørslene dine til riktig leverandør automatisk basert på modellen. + +1. Gå over til [Helicone](https://helicone.ai), opprett en konto og generer en API nøkkel fra dashbordet. + +2. Kjør kommandoen `/connect` og søk etter **Helicone**. + + ```txt + /connect + ``` + +3. Skriv inn Helicone API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +For flere leverandører og avanserte funksjoner som bufring og hastighetsbegrensning, sjekk [Helicone-dokumentasjonen](https://docs.helicone.ai). + +#### Valgfrie konfigurasjoner + +I tilfelle du ser en funksjon eller modell fra Helicone som ikke konfigureres automatisk gjennom opencode, kan du alltid konfigurere den selv. + +Her er [Helicone's Model Directory](https://helicone.ai/models), du trenger denne for å hente ID-ene til modellene du vil legge til. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### Egendefinerte topptekster + +Helicone støtter tilpassede overskrifter for funksjoner som bufring, brukersporing og øktadministrasjon. Legg dem til leverandørkonfigurasjonen din ved å bruke `options.headers`: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### Sesjonssporing + +Helicones [Sessions](https://docs.helicone.ai/features/sessions) funksjon lar deg gruppere relaterte LLM forespørsler sammen. Bruk [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) plugin for automatisk å logge hver OpenCode-samtale som en økt i Helicone. + +```bash +npm install -g opencode-helicone-session +``` + +Legg den til i konfigurasjonen din. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +Programtillegget injiserer `Helicone-Session-Id` og `Helicone-Session-Name` overskrifter i forespørslene dine. På Helicones Sessions-side vil du se hver OpenCode-samtale oppført som en separat økt. + +##### Vanlige helikonhoder + +| Overskrift | Beskrivelse | +| -------------------------- | -------------------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | Aktiver responsbufring (`true`/`false`) | +| `Helicone-User-Id` | Spor beregninger etter bruker | +| `Helicone-Property-[Name]` | Legg til egendefinerte egenskaper (f.eks. `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | Knytt forespørsler til spørsmålsversjoner | + +Se [Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory) for alle tilgjengelige overskrifter. + +--- + +### lama.cpp + +Du kan konfigurere opencode for å bruke lokale modeller gjennom [llama.cpps](https://github.com/ggml-org/llama.cpp) lama-server-verktøy + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +I dette eksemplet: + +- `llama.cpp` er den tilpassede leverandøren ID. Dette kan være hvilken som helst streng du vil. +- `npm` spesifiserer pakken som skal brukes for denne leverandøren. Her brukes `@ai-sdk/openai-compatible` for enhver OpenAI-kompatibel API. +- `name` er visningsnavnet for leverandøren i UI. +- `options.baseURL` er endepunktet for den lokale serveren. +- `models` er et kart over modell-ID-er til deres konfigurasjoner. Modellnavnet vil vises i modellvalglisten. + +--- + +### IO.NET + +IO.NET tilbyr 17 modeller optimert for ulike brukstilfeller: + +1. Gå over til [IO.NET-konsollen](https://ai.io.net/), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **IO.NET**. + + ```txt + /connect + ``` + +3. Skriv inn nøkkelen IO.NET API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +--- + +### LM Studio + +Du kan konfigurere opencode for å bruke lokale modeller gjennom LM Studio. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +I dette eksemplet: + +- `lmstudio` er den tilpassede leverandøren ID. Dette kan være hvilken som helst streng du vil. +- `npm` spesifiserer pakken som skal brukes for denne leverandøren. Her brukes `@ai-sdk/openai-compatible` for enhver OpenAI-kompatibel API. +- `name` er visningsnavnet for leverandøren i UI. +- `options.baseURL` er endepunktet for den lokale serveren. +- `models` er et kart over modell-ID-er til deres konfigurasjoner. Modellnavnet vil vises i modellvalglisten. + +--- + +### Måneskudd AI + +Slik bruker du Kimi K2 fra Moonshot AI: + +1. Gå over til [Moonshot AI-konsollen](https://platform.moonshot.ai/console), opprett en konto og klikk på **Opprett API-nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **Moonshot AI**. + + ```txt + /connect + ``` + +3. Skriv inn Moonshot API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge _Kimi K2_. + + ```txt + /models + ``` + +--- + +### MiniMax + +1. Gå over til [MiniMax API-konsollen](https://platform.minimax.io/login), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **MiniMax**. + + ```txt + /connect + ``` + +3. Skriv inn MiniMax API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _M2.1_. + + ```txt + /models + ``` + +--- + +### Nebius Token Factory + +1. Gå over til [Nebius Token Factory-konsollen](https://tokenfactory.nebius.com/), opprett en konto og klikk på **Legg til nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **Nebius Token Factory**. + + ```txt + /connect + ``` + +3. Skriv inn Nebius Token Factory API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Ollama + +Du kan konfigurere opencode for å bruke lokale modeller gjennom Ollama. + +:::tupp +Ollama kan automatisk konfigurere seg selv for OpenCode. Se [Ollama-integrasjonsdokumentene](https://docs.ollama.com/integrations/opencode) for detaljer. +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +I dette eksemplet: + +- `ollama` er den tilpassede leverandøren ID. Dette kan være hvilken som helst streng du vil. +- `npm` spesifiserer pakken som skal brukes for denne leverandøren. Her brukes `@ai-sdk/openai-compatible` for enhver OpenAI-kompatibel API. +- `name` er visningsnavnet for leverandøren i UI. +- `options.baseURL` er endepunktet for den lokale serveren. +- `models` er et kart over modell-ID-er til deres konfigurasjoner. Modellnavnet vil vises i modellvalglisten. + +:::tupp +Hvis verktøykall ikke fungerer, prøv å øke `num_ctx` i Ollama. Start rundt 16k - 32k. +::: + +--- + +### Ollama Cloud + +Slik bruker du Ollama Cloud med OpenCode: + +1. Gå over til [https://ollama.com/](https://ollama.com/) og logg på eller opprett en konto. + +2. Naviger til **Innstillinger** > **Nøkler** og klikk på **Legg til API nøkkel** for å generere en ny API nøkkel. + +3. Kopier API-nøkkelen for bruk i OpenCode. + +4. Kjør kommandoen `/connect` og søk etter **Ollama Cloud**. + + ```txt + /connect + ``` + +5. Skriv inn din Ollama Cloud API nøkkel. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **Viktig**: Før du bruker skymodeller i OpenCode, må du hente modellinformasjonen lokalt: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. Kjør kommandoen `/models` for å velge din Ollama Cloud-modell. + + ```txt + /models + ``` + +--- + +### OpenAI + +Vi anbefaler at du registrerer deg for [ChatGPT Plus eller Pro](https://chatgpt.com/pricing). + +1. Når du har registrert deg, kjør kommandoen `/connect` og velg OpenAI. + + ```txt + /connect + ``` + +2. Her kan du velge alternativet **ChatGPT Plus/Pro** og det åpner nettleseren din + og ber deg om å autentisere. + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. Nå skal alle OpenAI-modellene være tilgjengelige når du bruker kommandoen `/models`. + + ```txt + /models + ``` + +##### Bruke API-tastene + +Hvis du allerede har en API-nøkkel, kan du velge **Angi API-nøkkel manuelt** og lime den inn i terminalen. + +--- + +### OpenCode Zen + +OpenCode Zen er en liste over testede og verifiserte modeller levert av OpenCode-teamet. [Finn ut mer](/docs/zen). + +1. Logg på **OpenCode Zen** og klikk på **Create API Key**. + +2. Kjør kommandoen `/connect` og søk etter **OpenCode Zen**. + + ```txt + /connect + ``` + +3. Skriv inn OpenCode API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### OpenRouter + +1. Gå over til [OpenRouter-dashbordet](https://openrouter.ai/settings/keys), klikk på **Create API Key**, og kopier nøkkelen. + +2. Kjør kommandoen `/connect` og søk etter OpenRouter. + + ```txt + /connect + ``` + +3. Skriv inn API-nøkkelen for leverandøren. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Mange OpenRouter-modeller er forhåndslastet som standard, kjør kommandoen `/models` for å velge den du ønsker. + + ```txt + /models + ``` + + Du kan også legge til flere modeller gjennom opencode-konfigurasjonen. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. Du kan også tilpasse dem gjennom opencode-konfigurasjonen. Her er et eksempel på å spesifisere en leverandør + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP AI Kjerne + +SAP AI Core gir tilgang til 40+ modeller fra OpenAI, Anthropic, Google, Amazon, Meta, Mistral og AI21 gjennom en enhetlig plattform. + +1. Gå til din [SAP BTP Cockpit](https://account.hana.ondemand.com/), naviger til din SAP AI kjernetjenesteforekomst, og lag en tjenestenøkkel. + + :::tupp + Tjenestenøkkelen er et JSON-objekt som inneholder `clientid`, `clientsecret`, `url` og `serviceurls.AI_API_URL`. Du finner AI kjerneforekomsten din under **Tjenester** > **Forekomster og abonnementer** i BTP cockpiten. + ::: + +2. Kjør kommandoen `/connect` og søk etter **SAP AI Core**. + + ```txt + /connect + ``` + +3. Skriv inn tjenestenøkkelen JSON. + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + Eller angi miljøvariabelen `AICORE_SERVICE_KEY`: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + Eller legg den til bash-profilen din: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. Angi eventuelt distribusjon ID og ressursgruppe: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::note + Disse innstillingene er valgfrie og bør konfigureres i henhold til SAP AI kjerneoppsettet. + ::: + +5. Kjør kommandoen `/models` for å velge fra 40+ tilgjengelige modeller. + + ```txt + /models + ``` + +--- + +### OVHcloud AI endepunkter + +1. Gå over til [OVHcloud-panelet](https://ovh.com/manager). Naviger til `Public Cloud`-delen, `AI & Machine Learning` > `AI Endpoints` og i `API Keys`-fanen klikker du på **Opprett en ny API-nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **OVHcloud AI endepunkter**. + + ```txt + /connect + ``` + +3. Skriv inn OVHcloud AI Endpoints API nøkkel. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Scaleway + +Slik bruker du [Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/) med OpenCode: + +1. Gå over til [Scaleway Console IAM innstillinger](https://console.scaleway.com/iam/api-keys) for å generere en ny API nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Scaleway**. + + ```txt + /connect + ``` + +3. Skriv inn Scaleway API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _devstral-2-123b-instruct-2512_ eller _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Sammen AI + +1. Gå over til [Together AI-konsollen](https://api.together.ai), opprett en konto og klikk på **Legg til nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **Together AI**. + + ```txt + /connect + ``` + +3. Skriv inn Together AI API nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Venezia AI + +1. Gå over til [Venezia AI-konsollen](https://venice.ai), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Venezia AI**. + + ```txt + /connect + ``` + +3. Skriv inn Venezia AI API nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Llama 3.3 70B_. + + ```txt + /models + ``` + +--- + +### Vercel AI Gateway + +Vercel AI Gateway lar deg få tilgang til modeller fra OpenAI, Anthropic, Google, xAI og mer gjennom et enhetlig endepunkt. Modeller tilbys til listepris uten påslag. + +1. Gå over til [Vercel dashboard](https://vercel.com/), naviger til fanen **AI Gateway**, og klikk på **API nøkler** for å opprette en ny API nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Vercel AI Gateway**. + + ```txt + /connect + ``` + +3. Skriv inn Vercel AI Gateway API nøkkel. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +Du kan også tilpasse modeller gjennom opencode-konfigurasjonen. Her er et eksempel på spesifisering av leverandørrutingsrekkefølge. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +Noen nyttige rutealternativer: + +| Alternativ | Beskrivelse | +| ------------------- | ------------------------------------------------------------- | +| `order` | Providersekvens for å prøve | +| `only` | Begrens til spesifikke leverandører | +| `zeroDataRetention` | Bruk kun leverandører med null retningslinjer for datalagring | + +--- + +### xAI + +1. Gå over til [xAI-konsollen](https://console.x.ai/), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **xAI**. + + ```txt + /connect + ``` + +3. Skriv inn xAI API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Grok Beta_. + + ```txt + /models + ``` + +--- + +### Z.AI + +1. Gå over til [Z.AI API-konsollen](https://z.ai/manage-apikey/apikey-list), opprett en konto og klikk på **Opprett en ny API-nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **Z.AI**. + + ```txt + /connect + ``` + + Hvis du abonnerer på **GLM Coding Plan**, velg **Z.AI Coding Plan**. + +3. Skriv inn Z.AI API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _GLM-4.7_. + + ```txt + /models + ``` + +--- + +### ZenMux + +1. Gå over til [ZenMux-dashbordet](https://zenmux.ai/settings/keys), klikk på **Create API Key**, og kopier nøkkelen. + +2. Kjør kommandoen `/connect` og søk etter ZenMux. + + ```txt + /connect + ``` + +3. Skriv inn API-nøkkelen for leverandøren. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Mange ZenMux-modeller er forhåndslastet som standard, kjør kommandoen `/models` for å velge den du ønsker. + + ```txt + /models + ``` + + Du kan også legge til flere modeller gjennom opencode-konfigurasjonen. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## Egendefinert leverandør + +Slik legger du til en **OpenAI-kompatibel**-leverandør som ikke er oppført i `/connect`-kommandoen: + +:::tupp +Du kan bruke hvilken som helst OpenAI-kompatibel leverandør med opencode. De fleste moderne AI-leverandører tilbyr OpenAI-kompatible APIer. +::: + +1. Kjør kommandoen `/connect` og rull ned til **Annet**. + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. Skriv inn en unik ID for leverandøren. + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note + Velg en minneverdig ID, du vil bruke denne i konfigurasjonsfilen din. + ::: + +3. Skriv inn API-nøkkelen for leverandøren. + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. Opprett eller oppdater `opencode.json`-filen i prosjektkatalogen: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + Her er konfigurasjonsalternativene: + - **npm**: AI SDK pakke å bruke, `@ai-sdk/openai-compatible` for OpenAI-kompatible leverandører + - **navn**: Visningsnavn i UI. + - **modeller**: Tilgjengelige modeller. + - **options.baseURL**: API endepunkt URL. + - **options.apiKey**: Angi API-nøkkelen hvis du ikke bruker auth. + - **options.headers**: Angi egendefinerte overskrifter. + + Mer om de avanserte alternativene i eksemplet nedenfor. + +5. Kjør kommandoen `/models` og din egendefinerte leverandør og modeller vil vises i utvalgslisten. + +--- + +##### Eksempel + +Her er et eksempel på innstilling av alternativene `apiKey`, `headers` og modell `limit`. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +Konfigurasjonsdetaljer: + +- **apiKey**: Angi med `env` variabel syntaks, [finn ut mer](/docs/config#env-vars). +- **overskrifter**: Egendefinerte overskrifter sendt med hver forespørsel. +- **limit.context**: Maksimalt inndatatoken som modellen godtar. +- **limit.output**: Maksimalt antall tokens modellen kan generere. + +`limit`-feltene lar OpenCode forstå hvor mye kontekst du har igjen. Standardleverandører henter disse automatisk fra models.dev. + +--- + +## Feilsøking + +Hvis du har problemer med å konfigurere en leverandør, sjekk følgende: + +1. **Sjekk autentiseringsoppsettet**: Kjør `opencode auth list` for å se om legitimasjonen + for leverandøren legges til konfigurasjonen din. + + Dette gjelder ikke leverandører som Amazon Bedrock, som er avhengige av miljøvariabler for godkjenning. + +2. For tilpassede leverandører, sjekk opencode-konfigurasjonen og: + - Sørg for at leverandøren ID som brukes i `/connect`-kommandoen samsvarer med ID i opencode-konfigurasjonen. + – Den riktige npm-pakken brukes for leverandøren. Bruk for eksempel `@ai-sdk/cerebras` for Cerebras. Og for alle andre OpenAI-kompatible leverandører, bruk `@ai-sdk/openai-compatible`. + - Kontroller at riktig API-endepunkt er brukt i `options.baseURL`-feltet. diff --git a/packages/web/src/content/docs/da/rules.mdx b/packages/web/src/content/docs/da/rules.mdx new file mode 100644 index 000000000..e34097381 --- /dev/null +++ b/packages/web/src/content/docs/da/rules.mdx @@ -0,0 +1,180 @@ +--- +title: Regler +description: Set custom instructions for opencode. +--- + +Du kan gi tilpassede instruksjoner for å OpenCode ved å opprette en `AGENTS.md`-fil. Dette ligner på Cursors regler. Den inneholder instruksjoner som vil bli inkludert i LLMs kontekst for å tilpasse oppførselen til ditt spesifikke prosjekt. + +--- + +## Initialiser + +For å lage en ny `AGENTS.md` fil, kan du kjøre kommandoen `/init` i opencode. + +:::tupp +Du bør overgi prosjektets `AGENTS.md`-fil til Git. +::: + +Dette vil skanne prosjektet og alt dets innhold for å forstå hva prosjektet handler om og generere en `AGENTS.md`-fil med det. Dette hjelper opencode å navigere i prosjektet bedre. + +Hvis du har en eksisterende `AGENTS.md`-fil, vil denne prøve å legge til den. + +--- + +## Eksempel + +Du kan også bare lage denne filen manuelt. Her er et eksempel på noen ting du kan legge inn i en `AGENTS.md`-fil. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +Vi legger til prosjektspesifikke instruksjoner her, og dette vil bli delt på tvers av teamet ditt. + +--- + +## Typer + +opencode støtter også lesing av `AGENTS.md`-filen fra flere steder. Og dette tjener forskjellige formål. + +### Prosjekt + +Plasser en `AGENTS.md` i prosjektroten for prosjektspesifikke regler. Disse gjelder kun når du arbeider i denne katalogen eller dens underkataloger. + +### Globalt + +Du kan også ha globale regler i en `~/.config/opencode/AGENTS.md`-fil. Dette blir brukt på alle opencode-økter. + +Siden dette ikke er forpliktet til Git eller delt med teamet ditt, anbefaler vi å bruke dette til å spesifisere eventuelle personlige regler som LLM bør følge. + +### Claude-kodekompatibilitet + +For brukere som migrerer fra Claude Code, støtter OpenCode Claude Codes filkonvensjoner som fallbacks: + +- **Prosjektregler**: `CLAUDE.md` i prosjektkatalogen din (brukes hvis ingen `AGENTS.md` eksisterer) +- **Globale regler**: `~/.claude/CLAUDE.md` (brukes hvis ingen `~/.config/opencode/AGENTS.md` eksisterer) +- **Skills**: `~/.claude/skills/` — se [Agent Skills](/docs/skills/) for detaljer + +For å deaktivere Claude Code-kompatibilitet, sett en av disse miljøvariablene: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## Forrang + +Når opencode starter, ser den etter regelfiler i denne rekkefølgen: + +1. **Lokale filer** ved å gå opp fra gjeldende katalog (`AGENTS.md`, `CLAUDE.md`) +2. **Global fil** på `~/.config/opencode/AGENTS.md` +3. **Claude Code-fil** på `~/.claude/CLAUDE.md` (med mindre de er deaktivert) + +Den første matchende filen vinner i hver kategori. For eksempel, hvis du har både `AGENTS.md` og `CLAUDE.md`, brukes bare `AGENTS.md`. På samme måte har `~/.config/opencode/AGENTS.md` forrang over `~/.claude/CLAUDE.md`. + +--- + +## Egendefinerte instruksjoner + +Du kan spesifisere egendefinerte instruksjonsfiler i din `opencode.json` eller den globale `~/.config/opencode/opencode.json`. Dette lar deg og teamet ditt gjenbruke eksisterende regler i stedet for å måtte duplisere dem til AGENTS.md. + +Eksempel: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Du kan også bruke eksterne URL-er for å laste instruksjoner fra nettet. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +Fjerninstruksjoner hentes med 5 sekunders tidsavbrudd. + +Alle instruksjonsfilene er kombinert med `AGENTS.md`-filene dine. + +--- + +## Refererer til eksterne filer + +Selv om opencode ikke automatisk analyserer filreferanser i `AGENTS.md`, kan du oppnå lignende funksjonalitet på to måter: + +### Bruker opencode.json + +Den anbefalte tilnærmingen er å bruke feltet `instructions` i `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Manuelle instruksjoner i AGENTS.md + +Du kan lære opencode å lese eksterne filer ved å gi eksplisitte instruksjoner i `AGENTS.md`. Her er et praktisk eksempel: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +Denne tilnærmingen lar deg: + +- Lag modulære, gjenbrukbare regelfiler +- Del regler på tvers av prosjekter via symbolkoblinger eller git-undermoduler +- Hold AGENTS.md kortfattet mens du refererer til detaljerte retningslinjer +- Sørg for at opencode laster filer kun når det er nødvendig for den spesifikke oppgaven + +:::tupp +For monorepos eller prosjekter med delte standarder er bruk av `opencode.json` med glob-mønstre (som `packages/*/AGENTS.md`) mer vedlikeholdbart enn manuelle instruksjoner. +::: diff --git a/packages/web/src/content/docs/da/sdk.mdx b/packages/web/src/content/docs/da/sdk.mdx new file mode 100644 index 000000000..ee5ed97aa --- /dev/null +++ b/packages/web/src/content/docs/da/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: Typesikker JS-klient for åpen kodeserver. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Åpenkoden JS/TS SDK gir en typesikker klient for samhandling med serveren. +Bruk den til å bygge integrasjoner og kontrollere opencode programmatisk. + +[Finn ut mer](/docs/server) om hvordan serveren fungerer. For eksempler, sjekk ut [prosjektene](/docs/ecosystem#projects) bygget av fellesskapet. + +--- + +## Installer + +Installer SDK fra npm: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## Opprett klient + +Opprett en forekomst av opencode: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +Dette starter både en server og en klient + +#### Alternativer + +| Alternativ | Skriv | Beskrivelse | Standard | +| ---------- | ------------- | -------------------------------- | ----------- | +| `hostname` | `string` | Server vertsnavn | `127.0.0.1` | +| `port` | `number` | Serverport | `4096` | +| `signal` | `AbortSignal` | Avbryt signal for kansellering | `undefined` | +| `timeout` | `number` | Tidsavbrudd i ms for serverstart | `5000` | +| `config` | `Config` | Konfigurasjonsobjekt | `{}` | + +--- + +## Konfig + +Du kan sende et konfigurasjonsobjekt for å tilpasse virkemåten. Forekomsten henter fortsatt din `opencode.json`, men du kan overstyre eller legge til konfigurasjon inline: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## Kun klient + +Hvis du allerede har en kjørende forekomst av opencode, kan du opprette en klientforekomst for å koble til den: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### Alternativer + +| Alternativ | Skriv inn | Beskrivelse | Standard | +| --------------- | ---------- | ---------------------------------- | ----------------------- | +| `baseUrl` | `string` | URL av serveren | `http://localhost:4096` | +| `fetch` | `function` | Egendefinert hentingimplementering | `globalThis.fetch` | +| `parseAs` | `string` | Svarparsingmetode | `auto` | +| `responseStyle` | `string` | Returstil: `data` eller `fields` | `fields` | +| `throwOnError` | `boolean` | Kast feil i stedet for retur | `false` | + +--- + +## Typer + +SDK inkluderer TypeScript-definisjoner for alle API-typer. Importer dem direkte: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +Alle typer er generert fra serverens OpenAPI-spesifikasjon og tilgjengelig i types-filen. + +--- + +## Feil + +SDK kan gi feil som du kan fange opp og håndtere: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## APIer + +SDK avslører alle server-APIer gjennom en typesikker klient. + +--- + +### Globalt + +| Metode | Beskrivelse | Svar | +| ----------------- | ---------------------------- | ------------------------------------ | +| `global.health()` | Sjekk serverhelse og versjon | `{ healthy: true, version: string }` | + +--- + +#### Eksempler + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### App + +| Metode | Beskrivelse | Svar | +| -------------- | -------------------------------- | ------------------------------------------- | +| `app.log()` | Skriv en loggoppføring | `boolean` | +| `app.agents()` | Liste alle tilgjengelige agenter | Agent[] | + +--- + +#### Eksempler + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### Prosjekt + +| Metode | Beskrivelse | Svar | +| ------------------- | -------------------------- | ---------------------------------------------- | +| `project.list()` | Liste over alle prosjekter | Prosjekt[] | +| `project.current()` | Få nåværende prosjekt | Prosjekt | + +--- + +#### Eksempler + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### Sti + +| Metode | Beskrivelse | Svar | +| ------------ | ----------------- | ---------------------------------------- | +| `path.get()` | Få gjeldende bane | Path | + +--- + +#### Eksempler + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### Konfig + +| Metode | Beskrivelse | Svar | +| -------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` | Få konfigurasjonsinformasjon | Config | +| `config.providers()` | Liste leverandører og standardmodeller | `{ providers: `Tilbyder[]`, default: { [key: string]: string } }` | + +--- + +#### Eksempler + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### økter + +| Metode | Beskrivelse | Merknader | +| ---------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| `session.list()` | Liste økter | Returnerer Session[] | +| `session.get({ path })` | Få økt | Returnerer Session | +| `session.children({ path })` | Liste over barneøkter | Returnerer Session[] | +| `session.create({ body })` | Opprett økt | Returnerer Session | +| `session.delete({ path })` | Slett økt | Returnerer `boolean` | +| `session.update({ path, body })` | Oppdater øktegenskaper | Returnerer Session | +| `session.init({ path, body })` | Analyser appen og lag `AGENTS.md` | Returnerer `boolean` | +| `session.abort({ path })` | Avbryt en løpeøkt | Returnerer `boolean` | +| `session.share({ path })` | Del økten | Returnerer Session | +| `session.unshare({ path })` | Slutt å dele økten | Returnerer Session | +| `session.summarize({ path, body })` | Oppsummer økten | Returnerer `boolean` | +| `session.messages({ path })` | Liste meldinger i en økt | Returnerer `{ info: `Message`, parts: `Del[]`}[]` | +| `session.message({ path })` | Få meldingsdetaljer | Returnerer `{ info: `Message`, parts: `Del[]`}` | +| `session.prompt({ path, body })` | Send melding | `body.noReply: true` returnerer UserMessage (kun kontekst). Standard returnerer AssistantMessage med AI svar | +| `session.command({ path, body })` | Send kommando til økt | Returnerer `{ info: `AssistantMessage`, parts: `Del[]`}` | +| `session.shell({ path, body })` | Kjør en shell-kommando | Returnerer AssistantMessage | +| `session.revert({ path, body })` | Tilbakestill en melding | Returnerer Session | +| `session.unrevert({ path })` | Gjenopprett tilbakestilte meldinger | Returnerer Session | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | Svar på en tillatelsesforespørsel | Returnerer `boolean` | + +--- + +#### Eksempler + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### Filer + +| Metode | Beskrivelse | Svar | +| ------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------ | +| `find.text({ query })` | Søk etter tekst i filer | En rekke matchobjekter med `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `find.files({ query })` | Finn filer og kataloger etter navn | `string[]` (baner) | +| `find.symbols({ query })` | Finn arbeidsområdesymboler | Symbol[] | +| `file.read({ query })` | Les en fil | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | Få status for sporede filer | Fil[] | + +`find.files` støtter noen få valgfrie søkefelt: + +- `type`: `"file"` eller `"directory"` +- `directory`: overstyr prosjektroten for søket +- `limit`: maksimalt antall resultater (1–200) + +--- + +#### Eksempler + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +| Metode | Beskrivelse | Svar | +| ------------------------------ | ---------------------------- | --------- | +| `tui.appendPrompt({ body })` | Legg til tekst i ledeteksten | `boolean` | +| `tui.openHelp()` | Åpne hjelpedialogen | `boolean` | +| `tui.openSessions()` | Åpne øktvelgeren | `boolean` | +| `tui.openThemes()` | Åpne temavelgeren | `boolean` | +| `tui.openModels()` | Åpne modellvelgeren | `boolean` | +| `tui.submitPrompt()` | Send inn gjeldende ledetekst | `boolean` | +| `tui.clearPrompt()` | Fjern ledeteksten | `boolean` | +| `tui.executeCommand({ body })` | Utfør en kommando | `boolean` | +| `tui.showToast({ body })` | Vis toastvarsel | `boolean` | + +--- + +#### Eksempler + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### Auth + +| Metode | Beskrivelse | Svar | +| ------------------- | ------------------------------- | --------- | +| `auth.set({ ... })` | Angi autentiseringslegitimasjon | `boolean` | + +--- + +#### Eksempler + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### Hendelser + +| Metode | Beskrivelse | Svar | +| ------------------- | ------------------------------ | ------------------------------ | +| `event.subscribe()` | Server-sendte hendelser stream | Server-sendte hendelser stream | + +--- + +#### Eksempler + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/da/server.mdx b/packages/web/src/content/docs/da/server.mdx new file mode 100644 index 000000000..04d2e9221 --- /dev/null +++ b/packages/web/src/content/docs/da/server.mdx @@ -0,0 +1,287 @@ +--- +title: Server +description: Samhandle med opencode-server over HTTP. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Kommandoen `opencode serve` kjører en hodeløs HTTP-server som avslører et OpenAPI-endepunkt som en opencode-klient kan bruke. + +--- + +### Bruk + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### Alternativer + +| Flagg | Beskrivelse | Standard | +| --------------- | ---------------------------------------------- | ---------------- | +| `--port` | Port å lytte på | `4096` | +| `--hostname` | Vertsnavn å lytte på | `127.0.0.1` | +| `--mdns` | Aktiver mDNS-oppdagelse | `false` | +| `--mdns-domain` | Egendefinert domenenavn for mDNS-tjeneste | `opencode.local` | +| `--cors` | Ytterligere nettleseropprinnelse for å tillate | `[]` | + +`--cors` kan passeres flere ganger: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### Autentisering + +Sett `OPENCODE_SERVER_PASSWORD` for å beskytte serveren med HTTP grunnleggende autentisering. Brukernavnet er standard til `opencode`, eller sett `OPENCODE_SERVER_USERNAME` for å overstyre det. Dette gjelder både `opencode serve` og `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### Slik fungerer det + +Når du kjører `opencode` starter den en TUI og en server. Der TUI er +klient som snakker med serveren. Serveren viser en OpenAPI 3.1-spesifikasjon +endepunkt. Dette endepunktet brukes også til å generere en [SDK](/docs/sdk). + +:::tupp +Bruk opencode-serveren til å samhandle med opencode programmatisk. +::: + +Denne arkitekturen lar opencode støtte flere klienter og lar deg samhandle med opencode programmatisk. + +Du kan kjøre `opencode serve` for å starte en frittstående server. Hvis du har +opencode TUI kjører, vil `opencode serve` starte en ny server. + +--- + +#### Koble til en eksisterende server + +Når du starter TUI, tildeler den tilfeldig en port og vertsnavn. Du kan i stedet sende inn `--hostname` og `--port` [flagg](/docs/cli). Bruk deretter denne til å koble til serveren. + +[`/tui`](#tui) endepunktet kan brukes til å kjøre TUI gjennom serveren. Du kan for eksempel forhåndsutfylle eller kjøre en forespørsel. Dette oppsettet brukes av OpenCode [IDE](/docs/ide) plugins. + +--- + +## Spes + +Serveren publiserer en OpenAPI 3.1-spesifikasjon som kan vises på: + +``` +http://:/doc +``` + +For eksempel `http://localhost:4096/doc`. Bruk spesifikasjonen til å generere klienter eller inspisere forespørsels- og svartyper. Eller se den i en Swagger-utforsker. + +--- + +## APIer + +OpenCode-serveren viser følgende APIer. + +--- + +### Globalt + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ---------------- | -------------------------------- | ------------------------------------ | +| `GET` | `/global/health` | Få serverhelse og versjon | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | Få globale hendelser (SSE strøm) | Eventstrøm | + +--- + +### Prosjekt + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------------------ | --------------------------- | ---------------------------------------------- | +| `GET` | `/project` | Liste over alle prosjekter | Prosjekt[] | +| `GET` | `/project/current` | Få det nåværende prosjektet | Prosjekt | + +--- + +### Bane og VCS + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------- | ---------------------------------- | ------------------------------------------- | +| `GET` | `/path` | Få gjeldende bane | Path | +| `GET` | `/vcs` | Få VCS info for gjeldende prosjekt | VcsInfo | + +--- + +### Forekomst + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------------------- | ------------------------ | --------- | +| `POST` | `/instance/dispose` | Kast gjeldende forekomst | `boolean` | + +--- + +### Konfig + +| Metode | Sti | Beskrivelse | Svar | +| ------- | ------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` | Få konfigurasjonsinformasjon | Config | +| `PATCH` | `/config` | Oppdater konfigurasjon | Config | +| `GET` | `/config/providers` | Liste leverandører og standardmodeller | `{ providers: `Tilbyder[]`, default: { [key: string]: string } }` | + +--- + +### Leverandør + +| Metode | Sti | Beskrivelse | Svar | +| ------ | -------------------------------- | ----------------------------------------------- | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` | Liste alle leverandører | `{ all: `Tilbyder[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | Få leverandørautentiseringsmetoder | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | Autoriser en leverandør ved å bruke OAuth | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | Håndtere OAuth-tilbakeringing for en leverandør | `boolean` | + +--- + +### økter + +| Metode | Sti | Beskrivelse | Merknader | +| -------- | ---------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------- | +| `GET` | `/session` | Liste alle økter | Returnerer Session[] | +| `POST` | `/session` | Opprett en ny økt | body: `{ parentID?, title? }`, returnerer Session | +| `GET` | `/session/status` | Få øktstatus for alle økter | Returnerer `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | Få øktdetaljer | Returnerer Session | +| `DELETE` | `/session/:id` | Slett en økt og alle dens data | Returnerer `boolean` | +| `PATCH` | `/session/:id` | Oppdater øktegenskaper | body: `{ title? }`, returnerer Session | +| `GET` | `/session/:id/children` | Få en økts barneøkter | Returnerer Session[] | +| `GET` | `/session/:id/todo` | Få gjøremålslisten for en økt | Returnerer Todo[] | +| `POST` | `/session/:id/init` | Analyser appen og lag `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returnerer `boolean` | +| `POST` | `/session/:id/fork` | Fork en eksisterende økt ved en melding | body: `{ messageID? }`, returnerer Session | +| `POST` | `/session/:id/abort` | Avbryt en løpeøkt | Returnerer `boolean` | +| `POST` | `/session/:id/share` | Del en økt | Returnerer Session | +| `DELETE` | `/session/:id/share` | Slutt å dele en økt | Returnerer Session | +| `GET` | `/session/:id/diff` | Få diff for denne økten | spørring: `messageID?`, returnerer FileDiff[] | +| `POST` | `/session/:id/summarize` | Oppsummer økten | body: `{ providerID, modelID }`, returnerer `boolean` | +| `POST` | `/session/:id/revert` | Tilbakestill en melding | body: `{ messageID, partID? }`, returnerer `boolean` | +| `POST` | `/session/:id/unrevert` | Gjenopprett alle tilbakestilte meldinger | Returnerer `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | Svar på en tillatelsesforespørsel | body: `{ response, remember? }`, returnerer `boolean` | + +--- + +### Meldinger + +| Metode | Sti | Beskrivelse | Merknader | +| ------ | --------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `GET` | `/session/:id/message` | Liste meldinger i en økt | spørring: `limit?`, returnerer `{ info: `Message`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` | Send en melding og vent på svar | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, returnerer `{ info: `Message`, parts: `Part[]`}` | +| `GET` | `/session/:id/message/:messageID` | Få meldingsdetaljer | Returnerer `{ info: `Message`, parts: `Del[]`}` | +| `POST` | `/session/:id/prompt_async` | Send en melding asynkront (ingen vent) | body: samme som `/session/:id/message`, returnerer `204 No Content` | +| `POST` | `/session/:id/command` | Utfør en skråstrek-kommando | body: `{ messageID?, agent?, model?, command, arguments }`, returnerer `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/shell` | Kjør en shell-kommando | body: `{ agent, model?, command }`, returnerer `{ info: `Message`, parts: `Part[]`}` | + +--- + +### Kommandoer + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ---------- | --------------------- | ---------------------------------------------- | +| `GET` | `/command` | Liste alle kommandoer | Kommando[] | + +--- + +### Filer + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------ | +| `GET` | `/find?pattern=` | Søk etter tekst i filer | En rekke matchobjekter med `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | Finn filer og kataloger etter navn | `string[]` (baner) | +| `GET` | `/find/symbol?query=` | Finn arbeidsområdesymboler | Symbol[] | +| `GET` | `/file?path=` | Liste filer og kataloger | FilNode[] | +| `GET` | `/file/content?path=

` | Les en fil | Filinnhold | +| `GET` | `/file/status` | Få status for sporede filer | Fil[] | + +#### `/find/file` spørringsparametere + +- `query` (obligatorisk) - søkestreng (uklar samsvar) +- `type` (valgfritt) - begrense resultatene til `"file"` eller `"directory"` +- `directory` (valgfritt) — overstyr prosjektroten for søket +- `limit` (valgfritt) - maks. resultater (1–200) +- `dirs` (valgfritt) - eldre flagg (`"false"` returnerer kun filer) + +--- + +### Verktøy (eksperimentelt) + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------------------------------------------- | -------------------------------------------- | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` | Vis alle verktøy-ID-er | ToolIDs | +| `GET` | `/experimental/tool?provider=

&model=` | List verktøy med JSON-skjemaer for en modell | ToolList | + +--- + +### LSP, formattere og MCP + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------------ | ---------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | Få LSP serverstatus | LSPStatus[] | +| `GET` | `/formatter` | Få formateringsstatus | FormatterStatus[] | +| `GET` | `/mcp` | Få MCP serverstatus | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | Legg til MCP server dynamisk | body: `{ name, config }`, returnerer MCP statusobjekt | + +--- + +### Agenter + +| Metode | Sti | Beskrivelse | Svar | +| ------ | -------- | -------------------------------- | ------------------------------------------- | +| `GET` | `/agent` | Liste alle tilgjengelige agenter | Agent[] | + +--- + +### Logging + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------ | --------------------------------------------------------------------- | --------- | +| `POST` | `/log` | Skriv loggoppføring. Brødtekst: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ----------------------- | ------------------------------------------- | -------------------------- | +| `POST` | `/tui/append-prompt` | Legg til tekst i ledeteksten | `boolean` | +| `POST` | `/tui/open-help` | Åpne hjelpedialogen | `boolean` | +| `POST` | `/tui/open-sessions` | Åpne øktvelgeren | `boolean` | +| `POST` | `/tui/open-themes` | Åpne temavelgeren | `boolean` | +| `POST` | `/tui/open-models` | Åpne modellvelgeren | `boolean` | +| `POST` | `/tui/submit-prompt` | Send inn gjeldende ledetekst | `boolean` | +| `POST` | `/tui/clear-prompt` | Fjern ledeteksten | `boolean` | +| `POST` | `/tui/execute-command` | Utfør en kommando (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | Vis toast (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | Vent på neste kontrollforespørsel | Kontrollforespørselsobjekt | +| `POST` | `/tui/control/response` | Svar på en kontrollforespørsel (`{ body }`) | `boolean` | + +--- + +### Auth + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ----------- | --------------------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | Angi autentiseringslegitimasjon. Brødtekst må samsvare med leverandørskjema | `boolean` | + +--- + +### Hendelser + +| Metode | Sti | Beskrivelse | Svar | +| ------ | -------- | -------------------------------------------------------------------------------------------------- | ------------------------------ | +| `GET` | `/event` | Server-sendte hendelsesstrøm. Første arrangement er `server.connected`, deretter bussarrangementer | Server-sendte hendelser stream | + +--- + +### Dokumenter + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------ | ------------------------- | ----------------------------------- | +| `GET` | `/doc` | OpenAPI 3.1-spesifikasjon | HTML side med OpenAPI-spesifikasjon | diff --git a/packages/web/src/content/docs/da/share.mdx b/packages/web/src/content/docs/da/share.mdx new file mode 100644 index 000000000..16dff7c52 --- /dev/null +++ b/packages/web/src/content/docs/da/share.mdx @@ -0,0 +1,128 @@ +--- +title: Dele +description: Del dine OpenCode-samtaler. +--- + +OpenCodes delingsfunksjon lar deg lage offentlige lenker til dine OpenCode-samtaler, slik at du kan samarbeide med lagkamerater eller få hjelp fra andre. + +:::note +Delte samtaler er offentlig tilgjengelige for alle med linken. +::: + +--- + +## Slik fungerer det + +Når du deler en samtale, OpenCode: + +1. Oppretter en unik offentlig URL for økten din +2. Synkroniserer samtaleloggen din til serverne våre +3. Gjør samtalen tilgjengelig via den delbare lenken — `opncd.ai/s/` + +--- + +## Deling + +OpenCode støtter tre delingsmoduser som kontrollerer hvordan samtaler deles: + +--- + +### Manuell (standard) + +Som standard bruker OpenCode manuell delingsmodus. Økter deles ikke automatisk, men du kan dele dem manuelt ved å bruke kommandoen `/share`: + +``` +/share +``` + +Dette vil generere en unik URL som vil bli kopiert til utklippstavlen din. + +For å eksplisitt angi manuell modus i [konfigurasjonsfilen](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### Automatisk deling + +Du kan aktivere automatisk deling for alle nye samtaler ved å sette alternativet `share` til `"auto"` i [konfigurasjonsfilen](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +Med automatisk deling aktivert, vil hver nye samtale automatisk bli delt og en kobling vil bli generert. + +--- + +### Deaktivert + +Du kan deaktivere deling helt ved å sette alternativet `share` til `"disabled"` i [konfigurasjonsfilen](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +For å håndheve dette på tvers av teamet ditt for et gitt prosjekt, legg det til `opencode.json` i prosjektet ditt og sjekk inn i Git. + +--- + +## Opphev deling + +Slik slutter du å dele en samtale og fjerner den fra offentlig tilgang: + +``` +/unshare +``` + +Dette vil fjerne delelinken og slette dataene knyttet til samtalen. + +--- + +## Personvern + +Det er et par ting du må huske på når du deler en samtale. + +--- + +### Datalagring + +Delte samtaler forblir tilgjengelige til du eksplisitt opphever deling av dem. Dette +inkluderer: + +- Full samtalehistorikk +- Alle meldinger og svar +- Metadata for økter + +--- + +### Anbefalinger + +- Del kun samtaler som ikke inneholder sensitiv informasjon. +- Se gjennom samtaleinnholdet før du deler. +- Opphev deling av samtaler når samarbeidet er fullført. +- Unngå å dele samtaler med proprietær kode eller konfidensielle data. +- For sensitive prosjekter, deaktiver deling helt. + +--- + +## For bedrifter + +For bedriftsimplementeringer kan delingsfunksjonen være: + +- **Deaktivert** helt for overholdelse av sikkerhet +- **Begrenset** til brukere som kun er autentisert gjennom SSO +- **Selvvert** på din egen infrastruktur + +[Finn ut mer](/docs/enterprise) om bruk av opencode i organisasjonen din. diff --git a/packages/web/src/content/docs/da/skills.mdx b/packages/web/src/content/docs/da/skills.mdx new file mode 100644 index 000000000..21168ef4b --- /dev/null +++ b/packages/web/src/content/docs/da/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "Agentferdigheter" +description: "Definer gjenbrukbar atferd via SKILL.md-definisjoner" +--- + +Agentferdigheter lar OpenCode oppdage gjenbrukbare instruksjoner fra repo- eller hjemmekatalogen din. +Ferdigheter lastes inn på forespørsel via det opprinnelige `skill`-verktøyet – agenter ser tilgjengelige ferdigheter og kan laste inn hele innholdet når det er nødvendig. + +--- + +## Plasser filer + +Opprett én mappe per ferdighetsnavn og legg inn en `SKILL.md` i den. +OpenCode søker etter disse stedene: + +- Prosjektkonfigurasjon: `.opencode/skills//SKILL.md` +- Global konfigurasjon: `~/.config/opencode/skills//SKILL.md` +- Prosjekt Claude-kompatibel: `.claude/skills//SKILL.md` +- Global Claude-kompatibel: `~/.claude/skills//SKILL.md` +- Prosjektagent-kompatibel: `.agents/skills//SKILL.md` +- Global agent-kompatibel: `~/.agents/skills//SKILL.md` + +--- + +## Forstå oppdagelsen + +For prosjektlokale stier går OpenCode opp fra din nåværende arbeidskatalog til den når git-arbeidstreet. +Den laster alle matchende `skills/*/SKILL.md` i `.opencode/` og alle matchende `.claude/skills/*/SKILL.md` eller `.agents/skills/*/SKILL.md` underveis. + +Globale definisjoner lastes også inn fra `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` og `~/.agents/skills/*/SKILL.md`. + +--- + +## Skriv frontmaterie + +Hver `SKILL.md` må starte med YAML frontmatter. +Bare disse feltene gjenkjennes: + +- `name` (påkrevd) +- `description` (påkrevd) +- `license` (valgfritt) +- `compatibility` (valgfritt) +- `metadata` (valgfritt, streng-til-streng kart) + +Ukjente frontmatter-felter ignoreres. + +--- + +## Bekreft navn + +`name` må: + +- Bestå av 1–64 tegn +- Vær alfanumerisk med små bokstaver med skilletegn med enkelt bindestrek +- Ikke begynne eller slutte med `-` +- Ikke inneholde påfølgende `--` +- Match katalognavnet som inneholder `SKILL.md` + +Ekvivalent regulært uttrykk: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## Følg lengdereglene + +`description` må bestå av 1-1024 tegn. +Hold det spesifikt nok til at agenten kan velge riktig. + +--- + +## Bruk et eksempel + +Lag `.opencode/skills/git-release/SKILL.md` slik: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## Gjenkjenne verktøybeskrivelsen + +OpenCode viser tilgjengelige ferdigheter i `skill` verktøybeskrivelsen. +Hver oppføring inneholder ferdighetsnavnet og beskrivelsen: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +Agenten laster inn en ferdighet ved å kalle verktøyet: + +``` +skill({ name: "git-release" }) +``` + +--- + +## Konfigurer tillatelser + +Kontroller hvilke ferdigheter agenter har tilgang til ved å bruke mønsterbaserte tillatelser i `opencode.json`: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Tillatelse | Atferd | +| ---------- | ----------------------------------------- | +| `allow` | Ferdigheter lastes umiddelbart | +| `deny` | Ferdighet skjult for agent, tilgang avvist | +| `ask` | Bruker bedt om godkjenning før lasting | + +Mønstre støtter jokertegn: `internal-*` samsvarer med `internal-docs`, `internal-tools` osv. + +--- + +## Overstyring per agent + +Gi spesifikke agenter andre tillatelser enn de globale standardinnstillingene. + +**For egendefinerte agenter** (i agent frontmatter): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**For innebygde agenter** (i `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## Deaktiver ferdighetsverktøyet + +Deaktiver ferdigheter fullstendig for agenter som ikke bør bruke dem: + +**For egendefinerte agenter**: + +```yaml +--- +tools: + skill: false +--- +``` + +**For innebygde agenter**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +Når den er deaktivert, blir ``-delen utelatt helt. + +--- + +## Feilsøk lasting + +Hvis en ferdighet ikke vises: + +1. Kontroller at `SKILL.md` er stavet med store bokstaver +2. Sjekk at frontmatter inkluderer `name` og `description` +3. Sørg for at ferdighetsnavnene er unike på alle steder +4. Sjekk tillatelser – ferdigheter med `deny` er skjult for agenter diff --git a/packages/web/src/content/docs/da/themes.mdx b/packages/web/src/content/docs/da/themes.mdx new file mode 100644 index 000000000..d7f2fb377 --- /dev/null +++ b/packages/web/src/content/docs/da/themes.mdx @@ -0,0 +1,369 @@ +--- +title: Temaer +description: Velg et innebygd tema eller definer ditt eget. +--- + +Med OpenCode kan du velge fra ett av flere innebygde temaer, bruke et tema som tilpasser seg terminaltemaet ditt, eller definere ditt eget tilpassede tema. + +Som standard bruker OpenCode vårt eget `opencode`-tema. + +--- + +## Terminalkrav + +For at temaer skal vises riktig med fullfargepalett, må terminalen din støtte **truecolor** (24-biters farger). De fleste moderne terminaler støtter dette som standard, men du må kanskje aktivere det: + +- **Sjekk støtte**: Kjør `echo $COLORTERM` - den skal gi ut `truecolor` eller `24bit` +- **Aktiver truecolor**: Sett miljøvariabelen `COLORTERM=truecolor` i skallprofilen din +- **Terminalkompatibilitet**: Sørg for at terminalemulatoren din støtter 24-bits farger (de fleste moderne terminaler som iTerm2, Alacritty, Kitty, Windows Terminal og nyere versjoner av GNOME Terminal gjør det) + +Uten truecolor-støtte kan temaer vises med redusert fargenøyaktighet eller falle tilbake til nærmeste 256-fargers tilnærming. + +--- + +## Innebygde temaer + +OpenCode kommer med flere innebygde temaer. + +| Navn | Beskrivelse | +| ---------------------- | ---------------------------------------------------------------------------- | +| `system` | Tilpasser seg terminalens bakgrunnsfarge | +| `tokyonight` | Basert på [Tokyonight](https://github.com/folke/tokyonight.nvim)-temaet | +| `everforest` | Basert på [Everforest](https://github.com/sainnhe/everforest)-temaet | +| `ayu` | Basert på [Ayu](https://github.com/ayu-theme) mørke tema | +| `catppuccin` | Basert på [Catppuccin](https://github.com/catppuccin)-temaet | +| `catppuccin-macchiato` | Basert på [Catppuccin](https://github.com/catppuccin)-temaet | +| `gruvbox` | Basert på [Gruvbox](https://github.com/morhetz/gruvbox)-temaet | +| `kanagawa` | Basert på [Kanagawa](https://github.com/rebelot/kanagawa.nvim)-temaet | +| `nord` | Basert på [Nord](https://github.com/nordtheme/nord)-temaet | +| `matrix` | Hacker-stil grønt på svart tema | +| `one-dark` | Basert på [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) Mørkt tema | + +Og mer, vi legger stadig til nye temaer. + +--- + +## Systemtema + +`system`-temaet er designet for å automatisk tilpasse seg terminalens fargevalg. I motsetning til tradisjonelle temaer som bruker faste farger, er _system_-temaet: + +- **Genererer gråskala**: Oppretter en tilpasset gråskala basert på terminalens bakgrunnsfarge, og sikrer optimal kontrast. +- **Bruker ANSI farger**: Bruker standard ANSI farger (0-15) for syntaksutheving og UI elementer, som respekterer terminalens fargepalett. +- **Bevarer terminalens standardinnstillinger**: Bruker `none` for tekst- og bakgrunnsfarger for å opprettholde terminalens opprinnelige utseende. + +Systemtemaet er for brukere som: + +- Vil at OpenCode skal matche terminalens utseende +- Bruk tilpassede terminalfargeskjemaer +- Foretrekker et konsistent utseende på tvers av alle terminalapplikasjoner + +--- + +## Bruke et tema + +Du kan velge et tema ved å hente frem temavalg med kommandoen `/theme`. Eller du kan spesifisere det i [config](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Egendefinerte temaer + +OpenCode støtter et fleksibelt JSON-basert temasystem som lar brukere enkelt lage og tilpasse temaer. + +--- + +### Hierarki + +Temaer lastes inn fra flere kataloger i følgende rekkefølge der senere kataloger overstyrer tidligere: + +1. **Innebygde temaer** - Disse er innebygd i binæren +2. **Brukerkonfigurasjonskatalog** - Definert i `~/.config/opencode/themes/*.json` eller `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Prosjektrotkatalog** - Definert i `/.opencode/themes/*.json` +4. **Gjeldende arbeidskatalog** - Definert i `./.opencode/themes/*.json` + +Hvis flere kataloger inneholder et tema med samme navn, vil temaet fra katalogen med høyere prioritet bli brukt. + +--- + +### Opprette et tema + +For å lage et tilpasset tema, lag en JSON-fil i en av temakatalogene. + +For brukeromfattende temaer: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +Og for prosjektspesifikke temaer. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON format + +Temaer bruker et fleksibelt JSON-format med støtte for: + +- **Sekskantfarger**: `"#ffffff"` +- **ANSI farger**: `3` (0-255) +- **Fargereferanser**: `"primary"` eller egendefinerte definisjoner +- **Mørke/lyse varianter**: `{"dark": "#000", "light": "#fff"}` +- **Ingen farge**: `"none"` - Bruker terminalens standardfarge eller transparent + +--- + +### Fargedefinisjoner + +`defs`-delen er valgfri, og den lar deg definere gjenbrukbare farger som kan refereres til i temaet. + +--- + +### Terminalstandarder + +Spesialverdien `"none"` kan brukes for hvilken som helst farge for å arve terminalens standardfarge. Dette er spesielt nyttig for å lage temaer som passer sømløst med terminalens fargeskjema: + +- `"text": "none"` - Bruker terminalens standard forgrunnsfarge +- `"background": "none"` - Bruker terminalens standard bakgrunnsfarge + +--- + +### Eksempel + +Her er et eksempel på et tilpasset tema: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/da/tools.mdx b/packages/web/src/content/docs/da/tools.mdx new file mode 100644 index 000000000..0b4da5ca3 --- /dev/null +++ b/packages/web/src/content/docs/da/tools.mdx @@ -0,0 +1,379 @@ +--- +title: Verktøy +description: Administrer verktøyene en LLM kan bruke. +--- + +Verktøy lar LLM utføre handlinger i kodebasen din. OpenCode kommer med et sett med innebygde verktøy, men du kan utvide det med [egendefinerte verktøy](/docs/custom-tools) eller [MCP servere](/docs/mcp-servers). + +Som standard er alle verktøy **aktivert** og trenger ikke tillatelse for å kjøre. Du kan kontrollere verktøyets oppførsel gjennom [tillatelser](/docs/permissions). + +--- + +## Konfigurer + +Bruk feltet `permission` for å kontrollere verktøyets oppførsel. Du kan tillate, avslå eller kreve godkjenning for hvert verktøy. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +Du kan også bruke jokertegn for å kontrollere flere verktøy samtidig. For eksempel, for å kreve godkjenning for alle verktøy fra en MCP-server: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[Finn ut mer](/docs/permissions) om konfigurering av tillatelser. + +--- + +## Innebygd + +Her er alle de innebygde verktøyene som er tilgjengelige i OpenCode. + +--- + +### bash + +Utfør skallkommandoer i prosjektmiljøet ditt. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +Dette verktøyet lar LLM kjøre terminalkommandoer som `npm install`, `git status` eller en hvilken som helst annen shell-kommando. + +--- + +### rediger + +Endre eksisterende filer ved å bruke eksakte strengerstatninger. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Dette verktøyet utfører nøyaktige redigeringer av filer ved å erstatte eksakte teksttreff. Det er den primære måten LLM endrer kode på. + +--- + +### skriv + +Opprett nye filer eller overskriv eksisterende. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Bruk denne for å la LLM lage nye filer. Den vil overskrive eksisterende filer hvis de allerede eksisterer. + +:::note +`write`-verktøyet kontrolleres av tillatelsen `edit`, som dekker alle filendringer (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### lest + +Les filinnholdet fra kodebasen din. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +Dette verktøyet leser filer og returnerer innholdet. Den støtter lesing av spesifikke linjeområder for store filer. + +--- + +### grep + +Søk i filinnhold ved hjelp av regulære uttrykk. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Rask innholdssøk på tvers av kodebasen din. Støtter full regex-syntaks og filmønsterfiltrering. + +--- + +### glob + +Finn filer etter mønstermatching. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +Søk etter filer ved å bruke glob-mønstre som `**/*.js` eller `src/**/*.ts`. Returnerer samsvarende filbaner sortert etter endringstid. + +--- + +### liste + +List filer og kataloger i en gitt bane. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +Dette verktøyet viser kataloginnhold. Den aksepterer glob-mønstre for å filtrere resultater. + +--- + +### lsp (eksperimentell) + +Samhandle med dine konfigurerte LSP-servere for å få kodeintelligensfunksjoner som definisjoner, referanser, sveveinformasjon og anropshierarki. + +:::note +Dette verktøyet er bare tilgjengelig når `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (eller `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +Støttede operasjoner inkluderer `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` og `outgoingCalls`. + +For å konfigurere hvilke LSP-servere som er tilgjengelige for prosjektet ditt, se [LSP-servere](/docs/lsp). + +--- + +### patch + +Bruk patcher på filer. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Dette verktøyet bruker oppdateringsfiler til kodebasen din. Nyttig for å påføre diff og lapper fra forskjellige kilder. + +:::note +`patch`-verktøyet kontrolleres av tillatelsen `edit`, som dekker alle filendringer (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### ferdighet + +Last inn en [ferdighet](/docs/skills) (en `SKILL.md` fil) og returner innholdet i samtalen. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### for å skrive + +Administrer gjøremålslister under kodingsøkter. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +Oppretter og oppdaterer oppgavelister for å spore fremdrift under komplekse operasjoner. LLM bruker dette til å organisere flertrinnsoppgaver. + +:::note +Dette verktøyet er deaktivert for subagenter som standard, men du kan aktivere det manuelt. [Finn ut mer](/docs/agents/#permissions) +::: + +--- + +### todoread + +Les eksisterende gjøremålslister. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +Leser gjeldende gjøremålslistestatus. Brukes av LLM for å spore hvilke oppgaver som venter eller er fullført. + +:::note +Dette verktøyet er deaktivert for subagenter som standard, men du kan aktivere det manuelt. [Finn ut mer](/docs/agents/#permissions) +::: + +--- + +### webhenting + +Hent nettinnhold. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +Lar LLM hente og lese nettsider. Nyttig for å slå opp dokumentasjon eller forske på nettressurser. + +--- + +### nettsøk + +Søk på nettet for informasjon. + +:::note +Dette verktøyet er bare tilgjengelig når du bruker OpenCode-leverandøren eller når miljøvariabelen `OPENCODE_ENABLE_EXA` er satt til en sannverdi (f.eks. `true` eller `1`). + +Slik aktiverer du når du starter OpenCode: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Utfører nettsøk med Exa AI for å finne relevant informasjon på nettet. Nyttig for å undersøke emner, finne aktuelle hendelser eller samle informasjon utover treningsdataavbruddet. + +Ingen API-nøkkel kreves — verktøyet kobles direkte til Exa AIs vertsbaserte MCP-tjeneste uten autentisering. + +:::tupp +Bruk `websearch` når du trenger å finne informasjon (oppdagelse), og `webfetch` når du trenger å hente innhold fra en bestemt URL (henting). +::: + +--- + +### spørsmål + +Still brukeren spørsmål under utførelse. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +Dette verktøyet lar LLM stille spørsmål til brukeren under en oppgave. Det er nyttig for: + +- Samle brukerpreferanser eller krav +- Avklarende tvetydige instruksjoner +- Få beslutninger om gjennomføringsvalg +- Tilbyr valg om hvilken retning du skal ta + +Hvert spørsmål inkluderer en overskrift, spørsmålsteksten og en liste over alternativer. Brukere kan velge fra de angitte alternativene eller skrive inn et tilpasset svar. Når det er flere spørsmål, kan brukerne navigere mellom dem før de sender inn alle svarene. + +--- + +## Egendefinerte verktøy + +Egendefinerte verktøy lar deg definere dine egne funksjoner som LLM kan kalle. Disse er definert i konfigurasjonsfilen din og kan kjøre vilkårlig kode. + +[Finn ut mer](/docs/custom-tools) om å lage tilpassede verktøy. + +--- + +## MCP servere + +MCP (Model Context Protocol) servere lar deg integrere eksterne verktøy og tjenester. Dette inkluderer databasetilgang, API-integrasjoner og tredjepartstjenester. + +[Les mer](/docs/mcp-servers) om konfigurering av MCP-servere. + +--- + +## Internaler + +Internt bruker verktøy som `grep`, `glob` og `list` [ripgrep](https://github.com/BurntSushi/ripgrep) under panseret. Som standard respekterer ripgrep `.gitignore`-mønstre, noe som betyr at filer og kataloger som er oppført i `.gitignore` vil bli ekskludert fra søk og oppføringer. + +--- + +### Ignorer mønstre + +For å inkludere filer som normalt vil bli ignorert, lag en `.ignore`-fil i prosjektroten. Denne filen kan eksplisitt tillate visse stier. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +For eksempel lar denne `.ignore` filen ripgrep søke i `node_modules/`, `dist/` og `build/` kataloger selv om de er oppført i `.gitignore`. diff --git a/packages/web/src/content/docs/da/troubleshooting.mdx b/packages/web/src/content/docs/da/troubleshooting.mdx new file mode 100644 index 000000000..37ee70c3e --- /dev/null +++ b/packages/web/src/content/docs/da/troubleshooting.mdx @@ -0,0 +1,300 @@ +--- +title: Feilsøking +description: Vanlige problemer og hvordan de kan løses. +--- + +For å feilsøke problemer med OpenCode, start med å sjekke loggene og lokale data den lagrer på disken. + +--- + +## Logger + +Loggfiler skrives til: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.local\share\opencode\log` + +Loggfiler navngis med tidsstempler (f.eks. `2025-01-09T123456.log`) og de siste 10 loggfilene beholdes. + +Du kan angi loggnivået med kommandolinjealternativet `--log-level` for å få mer detaljert feilsøkingsinformasjon. For eksempel `opencode --log-level DEBUG`. + +--- + +## Lagring + +opencode lagrer øktdata og andre applikasjonsdata på disken på: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.local\share\opencode` + +Denne katalogen inneholder: + +- `auth.json` - Autentiseringsdata som API-nøkler, OAuth-tokens +- `log/` - Applikasjonslogger +- `project/` - Prosjektspesifikke data som økt- og meldingsdata + - Hvis prosjektet er innenfor en Git-repo, lagres det i `.//storage/` + - Hvis det ikke er en Git-repo, lagres det i `./global/storage/` + +--- + +## Desktop-app + +OpenCode Desktop kjører en lokal OpenCode-server (`opencode-cli` sidevognen) i bakgrunnen. De fleste problemene er forårsaket av en plugin som fungerer dårlig, en ødelagt cache eller en dårlig serverinnstilling. + +### Raske sjekker + +- Avslutt og start appen på nytt. +- Hvis appen viser en feilskjerm, klikker du på **Start på nytt** og kopierer feildetaljene. +- Bare macOS: `OpenCode`-meny -> **Last nettvisning på nytt** (hjelper hvis UI er tom/frosset). + +--- + +### Deaktiver plugins + +Hvis skrivebordsappen krasjer ved oppstart, henger eller oppfører seg merkelig, start med å deaktivere plugins. + +#### Sjekk den globale konfigurasjonen + +Åpne den globale konfigurasjonsfilen og se etter en `plugin`-nøkkel. + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (eller `~/.config/opencode/opencode.json`) +- **macOS/Linux** (eldre installasjoner): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.config\opencode\opencode.jsonc` + +Hvis du har konfigurert plugins, deaktiver dem midlertidig ved å fjerne nøkkelen eller sette den til en tom matrise: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### Sjekk plugin-kataloger + +OpenCode kan også laste lokale plugins fra disken. Flytt disse midlertidig ut av veien (eller gi nytt navn til mappen) og start skrivebordsappen på nytt: + +- **Globale plugins** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.config\opencode\plugins` +- **Prosjektplugins** (bare hvis du bruker konfigurasjon per prosjekt) + - `/.opencode/plugins/` + +Hvis appen begynner å fungere igjen, aktiverer du plugins én om gangen for å finne ut hvilken som forårsaker problemet. + +--- + +### Tøm hurtigbufferen + +Hvis deaktivering av plugins ikke hjelper (eller en plugin-installasjon sitter fast), tøm hurtigbufferen slik at OpenCode kan gjenoppbygge den. + +1. Avslutt OpenCode Desktop helt. +2. Slett hurtigbufferkatalogen: + +- **macOS**: Finder -> `Cmd+Shift+G` -> lim inn `~/.cache/opencode` +- **Linux**: slett `~/.cache/opencode` (eller kjør `rm -rf ~/.cache/opencode`) +- **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.cache\opencode` + +3. Start OpenCode Desktop på nytt. + +--- + +### Løs problemer med servertilkobling + +OpenCode Desktop kan enten starte sin egen lokale server (standard) eller koble til en server URL du har konfigurert. + +Hvis du ser en **"Tilkobling mislyktes"**-dialogboks (eller appen kommer aldri forbi splash-skjermen), se etter en tilpasset server URL. + +#### Slett standardserveren for skrivebordet URL + +Fra startskjermen klikker du på servernavnet (med statusprikken) for å åpne servervelgeren. I delen **Standardserver** klikker du på **Slett**. + +#### Fjern `server.port` / `server.hostname` fra konfigurasjonen din + +Hvis `opencode.json(c)` inneholder en `server`-del, fjern den midlertidig og start skrivebordsappen på nytt. + +#### Sjekk miljøvariabler + +Hvis du har `OPENCODE_PORT` satt i miljøet ditt, vil skrivebordsappen prøve å bruke den porten for den lokale serveren. + +- Deaktiver `OPENCODE_PORT` (eller velg en ledig port) og start på nytt. + +--- + +### Linux: Wayland / X11 problemer + +På Linux kan noen Wayland-oppsett forårsake tomme vinduer eller kompositorfeil. + +- Hvis du er på Wayland og appen er tom/krasj, prøv å starte med `OC_ALLOW_WAYLAND=1`. +- Hvis det gjør ting verre, fjern det og prøv å starte under en X11-økt i stedet. + +--- + +### Windows: WebView2 kjøretid + +På Windows krever OpenCode Desktop Microsoft Edge **WebView2 Runtime**. Hvis appen åpnes i et tomt vindu eller ikke starter, installer/oppdater WebView2 og prøv igjen. + +--- + +### Windows: Generelle ytelsesproblemer + +Hvis du opplever treg ytelse, problemer med filtilgang eller terminalproblemer på Windows, kan du prøve å bruke [WSL (Windows Subsystem for Linux)](/docs/windows-wsl). WSL gir et Linux-miljø som fungerer mer sømløst med funksjonene til OpenCode. + +--- + +### Varsler vises ikke + +OpenCode Desktop viser bare systemvarsler når: + +- varsler er aktivert for OpenCode i OS-innstillingene dine, og +- appvinduet er ikke fokusert. + +--- + +### Tilbakestill skrivebordsapplagring (siste utvei) + +Hvis appen ikke starter og du ikke kan slette innstillingene fra UI, tilbakestill skrivebordsappens lagrede tilstand. + +1. Avslutt OpenCode Desktop. +2. Finn og slett disse filene (de finnes i OpenCode Desktop-appens datakatalog): + +- `opencode.settings.dat` (stasjonær standardserver URL) +- `opencode.global.dat` og `opencode.workspace.*.dat` (UI tilstand som nylige servere/prosjekter) + +Slik finner du katalogen raskt: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (søk deretter etter filnavnene ovenfor) +- **Linux**: søk under `~/.local/share` etter filnavnene ovenfor +- **Windows**: Trykk `WIN+R` -> `%APPDATA%` (søk deretter etter filnavnene ovenfor) + +--- + +## Får hjelp + +Hvis du opplever problemer med OpenCode: + +1. **Rapporter problemer på GitHub** + + Den beste måten å rapportere feil eller be om funksjoner på er gjennom vårt GitHub-lager: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + Før du oppretter et nytt problem, søk i eksisterende problemer for å se om problemet ditt allerede er rapportert. + +2. **Bli med i vår Discord** + + For sanntidshjelp og fellesskapsdiskusjon, bli med i vår Discord-server: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Vanlige problemer + +Her er noen vanlige problemer og hvordan du kan løse dem. + +--- + +### OpenCode vil ikke starte + +1. Sjekk loggene for feilmeldinger +2. Prøv å kjøre med `--print-logs` for å se utdata i terminalen +3. Sørg for at du har den nyeste versjonen med `opencode upgrade` + +--- + +### Autentiseringsproblemer + +1. Prøv å autentisere på nytt med kommandoen `/connect` i TUI +2. Sjekk at API-nøklene dine er gyldige +3. Sørg for at nettverket ditt tillater tilkoblinger til leverandørens API + +--- + +### Modellen er ikke tilgjengelig + +1. Sjekk at du har autentisert deg med leverandøren +2. Kontroller at modellnavnet i konfigurasjonen er riktig +3. Noen modeller kan kreve spesifikk tilgang eller abonnement + +Hvis du støter på `ProviderModelNotFoundError` er du mest sannsynlig feil +refererer til en modell et sted. +Modeller skal refereres slik: `/` + +Eksempler: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +For å finne ut hvilke modeller du har tilgang til, kjør `opencode models` + +--- + +### ProviderInitError + +Hvis du støter på en ProviderInitError, har du sannsynligvis en ugyldig eller ødelagt konfigurasjon. + +For å løse dette: + +1. Kontroller først at leverandøren din er riktig konfigurert ved å følge [leverandørveiledningen](/docs/providers) +2. Hvis problemet vedvarer, prøv å tømme den lagrede konfigurasjonen: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + På Windows, trykk `WIN+R` og slett: `%USERPROFILE%\.local\share\opencode` + +3. Autentiser på nytt med leverandøren din ved å bruke kommandoen `/connect` i TUI. + +--- + +### AI_APICallError og leverandørpakkeproblemer + +Hvis du støter på API anropsfeil, kan dette skyldes utdaterte leverandørpakker. opencode installerer dynamisk leverandørpakker (OpenAI, Anthropic, Google, etc.) etter behov og cacher dem lokalt. + +For å løse problemer med leverandørpakke: + +1. Tøm leverandørens pakkebuffer: + + ```bash + rm -rf ~/.cache/opencode + ``` + + På Windows, trykk `WIN+R` og slett: `%USERPROFILE%\.cache\opencode` + +2. Start opencode på nytt for å installere de nyeste leverandørpakkene på nytt + +Dette vil tvinge opencode til å laste ned de nyeste versjonene av leverandørpakkene, som ofte løser kompatibilitetsproblemer med modellparametere og API endringer. + +--- + +### Kopier/lim inn fungerer ikke på Linux + +Linux-brukere må ha ett av følgende utklippstavleverktøy installert for at kopier/lim inn-funksjonalitet skal fungere: + +**For X11-systemer:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**For Wayland-systemer:** + +```bash +apt install -y wl-clipboard +``` + +**For hodeløse miljøer:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode vil oppdage om du bruker Wayland og foretrekker `wl-clipboard`, ellers vil den prøve å finne utklippstavleverktøy i rekkefølgen: `xclip` og `xsel`. diff --git a/packages/web/src/content/docs/da/tui.mdx b/packages/web/src/content/docs/da/tui.mdx new file mode 100644 index 000000000..58b9b547e --- /dev/null +++ b/packages/web/src/content/docs/da/tui.mdx @@ -0,0 +1,390 @@ +--- +title: TUI +description: Bruke OpenCode-terminalbrukergrensesnittet. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode gir et interaktivt terminalgrensesnitt eller TUI for å jobbe med prosjektene dine med en LLM. + +Å kjøre OpenCode starter TUI for gjeldende katalog. + +```bash +opencode +``` + +Eller du kan starte den for en bestemt arbeidskatalog. + +```bash +opencode /path/to/project +``` + +Når du er i TUI, kan du spørre den med en melding. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## Filreferanser + +Du kan referere til filer i meldingene dine ved å bruke `@`. Dette gjør et uklar filsøk i gjeldende arbeidskatalog. + +:::tupp +Du kan også bruke `@` til å referere til filer i meldingene dine. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +Innholdet i filen legges automatisk til samtalen. + +--- + +## Bash-kommandoer + +Start en melding med `!` for å kjøre en shell-kommando. + +```bash frame="none" +!ls -la +``` + +Utdataene fra kommandoen legges til samtalen som et verktøyresultat. + +--- + +## Kommandoer + +Når du bruker OpenCode TUI, kan du skrive `/` etterfulgt av et kommandonavn for raskt å utføre handlinger. For eksempel: + +```bash frame="none" +/help +``` + +De fleste kommandoer har også tastebinding som bruker `ctrl+x` som ledernøkkel, der `ctrl+x` er standard ledernøkkel. [Finn ut mer](/docs/keybinds). + +Her er alle tilgjengelige skråstrekkommandoer: + +--- + +### koble til + +Legg til en leverandør til OpenCode. Lar deg velge fra tilgjengelige leverandører og legge til deres API-nøkler. + +```bash frame="none" +/connect +``` + +--- + +### kompakt + +Komprimer gjeldende økt. _Alias_: `/summarize` + +```bash frame="none" +/compact +``` + +**Nøkkelbinding:** `ctrl+x c` + +--- + +### detaljer + +Veksle verktøyutførelsesdetaljer. + +```bash frame="none" +/details +``` + +**Nøkkelbinding:** `ctrl+x d` + +--- + +### redaktør + +Åpne eksternt redigeringsprogram for å skrive meldinger. Bruker redigeringssettet i miljøvariabelen `EDITOR`. [Finn ut mer](#editor-setup). + +```bash frame="none" +/editor +``` + +**Nøkkelbinding:** `ctrl+x e` + +--- + +### avslutt + +Avslutt OpenCode. _Aliaser_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Nøkkelbinding:** `ctrl+x q` + +--- + +### eksport + +Eksporter gjeldende samtale til Markdown og åpne i standardredigeringsprogrammet. Bruker redigeringssettet i miljøvariabelen `EDITOR`. [Finn ut mer](#editor-setup). + +```bash frame="none" +/export +``` + +**Nøkkelbinding:** `ctrl+x x` + +--- + +### hjelp + +Vis hjelpedialogen. + +```bash frame="none" +/help +``` + +**Nøkkelbinding:** `ctrl+x h` + +--- + +### init + +Opprett eller oppdater `AGENTS.md`-fil. [Finn ut mer](/docs/rules). + +```bash frame="none" +/init +``` + +**Nøkkelbinding:** `ctrl+x i` + +--- + +### modeller + +Liste over tilgjengelige modeller. + +```bash frame="none" +/models +``` + +**Nøkkelbinding:** `ctrl+x m` + +--- + +### ny + +Start en ny økt. _Alias_: `/clear` + +```bash frame="none" +/new +``` + +**Nøkkelbinding:** `ctrl+x n` + +--- + +### gjør om + +Gjenta en tidligere angret melding. Kun tilgjengelig etter bruk av `/undo`. + +:::tupp +Eventuelle filendringer vil også bli gjenopprettet. +::: + +Internt bruker dette Git til å administrere filendringene. Så ditt prosjekt **må +være et Git-depot**. + +```bash frame="none" +/redo +``` + +**Nøkkelbinding:** `ctrl+x r` + +--- + +### økter + +List opp og bytt mellom økter. _Aliaser_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Nøkkelbinding:** `ctrl+x l` + +--- + +### del + +Del gjeldende økt. [Finn ut mer](/docs/share). + +```bash frame="none" +/share +``` + +**Nøkkelbinding:** `ctrl+x s` + +--- + +### temaer + +Liste over tilgjengelige temaer. + +```bash frame="none" +/theme +``` + +**Nøkkelbinding:** `ctrl+x t` + +--- + +### tenker + +Veksle mellom synligheten av tenke-/resonneringsblokker i samtalen. Når den er aktivert, kan du se modellens resonneringsprosess for modeller som støtter utvidet tenkning. + +:::note +Denne kommandoen kontrollerer bare om tenkeblokker **vises** - den aktiverer eller deaktiverer ikke modellens resonneringsmuligheter. For å veksle mellom faktiske resonneringsmuligheter, bruk `ctrl+t` for å bla gjennom modellvarianter. +::: + +```bash frame="none" +/thinking +``` + +--- + +### angre + +Angre siste melding i samtalen. Fjerner den siste brukermeldingen, alle påfølgende svar og eventuelle filendringer. + +:::tupp +Eventuelle filendringer vil også bli tilbakestilt. +::: + +Internt bruker dette Git til å administrere filendringene. Så ditt prosjekt **må +være et Git-depot**. + +```bash frame="none" +/undo +``` + +**Nøkkelbinding:** `ctrl+x u` + +--- + +### avbryt deling + +Opphev deling av gjeldende økt. [Finn ut mer](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## Redaktøroppsett + +Både kommandoene `/editor` og `/export` bruker redigeringsprogrammet som er spesifisert i miljøvariabelen `EDITOR`. + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + + For å gjøre det permanent, legg dette til i skallprofilen din; + `~/.bashrc`, `~/.zshrc` osv. + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + + For å gjøre det permanent, bruk **Systemegenskaper** > **Miljø + Variabler**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + + For å gjøre det permanent, legg dette til i PowerShell-profilen din. + + + + +Populære redigeringsalternativer inkluderer: + +- `code` - Visual Studio Code +- `cursor` - Cursor +- `windsurf` - Vindsurfing +- `nvim` - Neovim-redaktør +- `vim` - Vim editor +- `nano` - Nano-editor +- `notepad` - Windows Notisblokk +- `subl` - Sublim tekst + +:::note +Noen redaktører som VS Code må startes med flagget `--wait`. +::: + +Noen redaktører trenger kommandolinjeargumenter for å kjøre i blokkeringsmodus. `--wait`-flagget gjør at redigeringsprosessen blokkeres til den lukkes. + +--- + +## Konfigurer + +Du kan tilpasse TUI-oppførselen gjennom OpenCode-konfigurasjonsfilen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### Alternativer + +- `scroll_acceleration` - Aktiver rulleakselerasjon i macOS-stil for jevn, naturlig rulling. Når aktivert, øker rullehastigheten med raske rullebevegelser og forblir presis for langsommere bevegelser. **Denne innstillingen har forrang over `scroll_speed` og overstyrer den når den er aktivert.** +- `scroll_speed` - Styrer hvor raskt TUI ruller når du bruker rullekommandoer (minimum: `1`). Standard er `3`. **Merk: Dette ignoreres hvis `scroll_acceleration.enabled` er satt til `true`.** + +--- + +## Tilpasning + +Du kan tilpasse ulike aspekter av TUI-visningen ved å bruke kommandopaletten (`ctrl+x h` eller `/help`). Disse innstillingene vedvarer ved omstarter. + +--- + +#### Visning av brukernavn + +Veksle om brukernavnet ditt vises i chat-meldinger. Få tilgang til dette gjennom: + +- Kommandopalett: Søk etter "brukernavn" eller "skjul brukernavn" +- Innstillingen vedvarer automatisk og vil bli husket over TUI økter diff --git a/packages/web/src/content/docs/da/web.mdx b/packages/web/src/content/docs/da/web.mdx new file mode 100644 index 000000000..931fffa34 --- /dev/null +++ b/packages/web/src/content/docs/da/web.mdx @@ -0,0 +1,142 @@ +--- +title: Web +description: Brug af OpenCode i din browser. +--- + +OpenCode kan køre som en webapplikation i din browser, hvilket giver den samme kraftfulde AI-kodningsoplevelse uden behov for en terminal. + +![OpenCode Web - Ny session](../../../assets/web/web-homepage-new-session.png) + +## Kom godt i gang + +Start webgrænsefladen ved at køre: + +```bash +opencode web +``` + +Dette starter en lokal server på `127.0.0.1` med en tilfældig tilgængelig port og åbner automatisk OpenCode i din standardbrowser. + +:::caution +Hvis `OPENCODE_SERVER_PASSWORD` ikke er indstillet, vil serveren være usikret. Dette er fint til lokal brug, men bør indstilles til netværksadgang. +::: + +:::tip[Windows Users] +For den bedste oplevelse skal du køre `opencode web` fra [WSL](/docs/windows-wsl) i stedet for PowerShell. Dette sikrer korrekt filsystemadgang og terminalintegration. +::: + +--- + +## Konfiguration + +Du kan konfigurere webserveren ved hjælp af kommandolinjeflag eller i din [config-fil](/docs/config). + +### Port + +Som standard vælger OpenCode en tilgængelig port. Du kan angive en port: + +```bash +opencode web --port 4096 +``` + +### Værtsnavn + +Som standard binder serveren til `127.0.0.1` (kun lokal vært). Sådan gør du OpenCode tilgængelig på dit netværk: + +```bash +opencode web --hostname 0.0.0.0 +``` + +Når du bruger `0.0.0.0`, vil OpenCode vise både lokale adresser og netværksadresser: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### mDNS-opdagelse + +Aktiver mDNS for at gøre din server synlig på det lokale netværk: + +```bash +opencode web --mdns +``` + +Dette indstiller automatisk værtsnavnet til `0.0.0.0` og annoncerer serveren som `opencode.local`. + +Du kan tilpasse mDNS-domænenavnet til at køre flere forekomster på det samme netværk: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +For at tillade yderligere domæner til CORS (nyttigt til brugerdefinerede frontends): + +```bash +opencode web --cors https://example.com +``` + +### Godkendelse + +For at beskytte adgangen skal du angive en adgangskode ved hjælp af `OPENCODE_SERVER_PASSWORD` miljøvariablen: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +Brugernavnet er som standard `opencode`, men kan ændres med `OPENCODE_SERVER_USERNAME`. + +--- + +## Brug af webgrænsefladen + +Når den er startet, giver webgrænsefladen adgang til dine OpenCode-sessioner. + +### Sessioner + +Se og administrer dine sessioner fra hjemmesiden. Du kan se aktive sessioner og starte nye. + +![OpenCode Web - Active Session](../../../assets/web/web-homepage-active-session.png) + +### Serverstatus + +Klik på "Se servere" for at se tilsluttede servere og deres status. + +![OpenCode Web - Se servere](../../../assets/web/web-homepage-see-servers.png) + +--- + +## Tilslutning af en terminal + +Du kan vedhæfte en terminal TUI til en kørende webserver: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +Dette giver dig mulighed for at bruge både webgrænsefladen og terminalen samtidigt og dele de samme sessioner og tilstand. + +--- + +## Konfigurationsfil + +Du kan også konfigurere serverindstillinger i din `opencode.json`-konfigurationsfil: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +Kommandolinjeflag har forrang over konfigurationsfilindstillinger. diff --git a/packages/web/src/content/docs/da/windows-wsl.mdx b/packages/web/src/content/docs/da/windows-wsl.mdx new file mode 100644 index 000000000..37be04963 --- /dev/null +++ b/packages/web/src/content/docs/da/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: Kør OpenCode på Windows med WSL for den bedste oplevelse. +--- + +import { Steps } from "@astrojs/starlight/components" + +Selvom OpenCode kan køre direkte på Windows, anbefaler vi at bruge [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) for den bedste oplevelse. WSL giver et Linux-miljø, der fungerer problemfrit med OpenCodes funktioner. + +:::tip[Hvorfor WSL?] +WSL giver bedre filsystemydelse, fuld terminalunderstøttelse og kompatibilitet med de udviklingsværktøjer, som OpenCode er afhængig af. +::: + +--- + +## Opsætning + + + +1. **Installer WSL** + + Hvis du ikke allerede har gjort det, så [installer WSL](https://learn.microsoft.com/en-us/windows/wsl/install) med Microsofts officielle vejledning. + +2. **Installer OpenCode i WSL** + + Når WSL er sat op, skal du åbne din WSL-terminal og installere OpenCode med en af [installationsmetoderne](/docs/). + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **Brug OpenCode fra WSL** + + Gå til din projektmappe (få adgang til Windows-filer via `/mnt/c/`, `/mnt/d/` osv.) og kør OpenCode. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## Desktop-app + WSL-server + +Hvis du foretrækker OpenCode Desktop-appen, men vil køre serveren i WSL: + +1. **Start serveren i WSL** med `--hostname 0.0.0.0` for at tillade eksterne forbindelser: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Forbind Desktop-appen** til `http://localhost:4096` + +:::note +Hvis `localhost` ikke virker i din opsætning, så forbind i stedet med WSL-IP-adressen (fra WSL: `hostname -I`) og brug `http://:4096`. +::: + +:::caution +Når du bruger `--hostname 0.0.0.0`, skal du sætte `OPENCODE_SERVER_PASSWORD` for at sikre serveren. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Webklient + WSL + +For den bedste weboplevelse på Windows: + +1. **Kør `opencode web` i WSL-terminalen** i stedet for PowerShell: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Åbn fra din Windows-browser** på `http://localhost:` (OpenCode udskriver URL'en) + +Når du kører `opencode web` fra WSL, får du korrekt filsystemadgang og terminalintegration, samtidig med at det stadig er tilgængeligt fra din Windows-browser. + +--- + +## Adgang til Windows-filer + +WSL kan få adgang til alle dine Windows-filer via `/mnt/`-mappen: + +- `C:`-drev → `/mnt/c/` +- `D:`-drev → `/mnt/d/` +- Og så videre... + +Eksempel: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +For den mest problemfri oplevelse kan du overveje at klone/kopiere dit repo ind i WSL-filsystemet (for eksempel under `~/code/`) og køre OpenCode derfra. +::: + +--- + +## Tips + +- Lad OpenCode køre i WSL for projekter, der ligger på Windows-drev - filadgangen er problemfri +- Brug VS Codes [WSL-udvidelse](https://code.visualstudio.com/docs/remote/wsl) sammen med OpenCode for et integreret udviklingsworkflow +- Din OpenCode-konfiguration og dine sessioner gemmes i WSL-miljøet i `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/da/zen.mdx b/packages/web/src/content/docs/da/zen.mdx new file mode 100644 index 000000000..4503f7c40 --- /dev/null +++ b/packages/web/src/content/docs/da/zen.mdx @@ -0,0 +1,254 @@ +--- +title: Zen +description: Utvalgt liste over modeller levert av OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen er en liste over testede og verifiserte modeller levert av OpenCode-teamet. + +:::note +OpenCode Zen er for øyeblikket i beta. +::: + +Zen fungerer som alle andre leverandører i OpenCode. Du logger på OpenCode Zen og får +din API nøkkel. Den er **helt valgfri** og du trenger ikke bruke den for å bruke den +OpenCode. + +--- + +## Bakgrunn + +Det er et stort antall modeller der ute, men bare noen få av dem +disse modellene fungerer godt som kodeagenter. I tillegg er de fleste tilbydere +konfigurert veldig annerledes; slik at du får veldig forskjellig ytelse og kvalitet. + +:::tupp +Vi testet en utvalgt gruppe modeller og leverandører som fungerer godt med OpenCode. +::: + +Så hvis du bruker en modell gjennom noe som OpenRouter, kan du aldri bli det +sikker på om du får den beste versjonen av modellen du ønsker. + +For å fikse dette gjorde vi et par ting: + +1. Vi testet en utvalgt gruppe modeller og snakket med teamene deres om hvordan + best kjøre dem. +2. Vi samarbeidet deretter med noen få leverandører for å sikre at disse ble servert + riktig. +3. Til slutt benchmarket vi kombinasjonen av modell/leverandør og kom frem + med en liste som vi har lyst til å anbefale. + +OpenCode Zen er en AI gateway som gir deg tilgang til disse modellene. + +--- + +## Slik fungerer det + +OpenCode Zen fungerer som alle andre leverandører i OpenCode. + +1. Du logger på **OpenCode Zen**, legg til fakturering + detaljer, og kopier API-nøkkelen. +2. Du kjører kommandoen `/connect` i TUI, velger OpenCode Zen og limer inn API-nøkkelen. +3. Kjør `/models` i TUI for å se listen over modeller vi anbefaler. + +Du belastes per forespørsel, og du kan legge til kreditt på kontoen din. + +--- + +## Endepunkter + +Du kan også få tilgang til modellene våre gjennom følgende API-endepunkter. + +| Modell | Modell ID | Endepunkt | AI SDK Pakke | +| ------------------- | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 Codex | gpt-5.2-kodeks | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex | gpt-5.1-kodeks | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Codex | gpt-5-kodeks | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Sonnet 4.5 | claude-sonnett-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Sonnet 4 | claude-sonnett-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Gratis | minimax-m2.1-fri | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Gratis | glm-4.7-fri | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Gratis | kimi-k2.5-fri | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 Tenker | kimi-k2-tenking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3-koder 480B | qwen3-koder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Stor sylteagurk | stor sylteagurk | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +[modell-id](/docs/config/#models) i OpenCode-konfigurasjonen +bruker formatet `opencode/`. For eksempel, for GPT 5.2 Codex, ville du +bruk `opencode/gpt-5.2-codex` i konfigurasjonen din. + +--- + +### Modeller + +Du kan hente hele listen over tilgjengelige modeller og deres metadata fra: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## Priser + +Vi støtter en pay-as-you-go-modell. Nedenfor er prisene **per 1 million tokens**. + +| Modell | Inngang | Utgang | Bufret Les | Bufret skriv | +| --------------------------------- | ------- | ------ | ---------- | ------------ | +| Stor sylteagurk | Gratis | Gratis | Gratis | - | +| MiniMax M2.1 Gratis | Gratis | Gratis | Gratis | - | +| MiniMax M2.1 | $0,30 | $1,20 | $0,10 | - | +| GLM 4.7 Gratis | Gratis | Gratis | Gratis | - | +| GLM 4.7 | $0,60 | $2,20 | $0,10 | - | +| GLM 4.6 | $0,60 | $2,20 | $0,10 | - | +| Kimi K2.5 Gratis | Gratis | Gratis | Gratis | - | +| Kimi K2.5 | $0,60 | $3,00 | $0,08 | - | +| Kimi K2 Tenker | $0,40 | $2,50 | - | - | +| Kimi K2 | $0,40 | $2,50 | - | - | +| Qwen3-koder 480B | $0,45 | $1,50 | - | - | +| Claude Sonnet 4.5 (≤ 200K tokens) | $3,00 | $15,00 | $0,30 | $3,75 | +| Claude Sonnet 4.5 (> 200K tokens) | $6,00 | $22,50 | $0,60 | $7,50 | +| Claude Sonnet 4 (≤ 200K tokens) | $3,00 | $15,00 | $0,30 | $3,75 | +| Claude Sonnet 4 (> 200K tokens) | $6,00 | $22,50 | $0,60 | $7,50 | +| Claude Haiku 4.5 | $1,00 | $5,00 | $0,10 | $1,25 | +| Claude Haiku 3.5 | $0,80 | $4,00 | $0,08 | $1,00 | +| Claude Opus 4.6 (≤ 200K tokens) | $5,00 | $25,00 | $0,50 | $6,25 | +| Claude Opus 4.6 (> 200K tokens) | $10,00 | $37,50 | $1,00 | $12,50 | +| Claude Opus 4.5 | $5,00 | $25,00 | $0,50 | $6,25 | +| Claude Opus 4.1 | $15,00 | $75,00 | $1,50 | $18,75 | +| Gemini 3 Pro (≤ 200K tokens) | $2,00 | $12,00 | $0,20 | - | +| Gemini 3 Pro (> 200K tokens) | $4,00 | $18,00 | $0,40 | - | +| Gemini 3 Flash | $0,50 | $3,00 | $0,05 | - | +| GPT 5.2 | $1,75 | $14,00 | $0,175 | - | +| GPT 5.2 Codex | $1,75 | $14,00 | $0,175 | - | +| GPT 5.1 | $1,07 | $8,50 | $0,107 | - | +| GPT 5.1 Codex | $1,07 | $8,50 | $0,107 | - | +| GPT 5.1 Codex Max | $1,25 | $10,00 | $0,125 | - | +| GPT 5.1 Codex Mini | $0,25 | $2,00 | $0,025 | - | +| GPT 5 | $1,07 | $8,50 | $0,107 | - | +| GPT 5 Codex | $1,07 | $8,50 | $0,107 | - | +| GPT 5 Nano | Gratis | Gratis | Gratis | - | + +Du legger kanskje merke til _Claude Haiku 3.5_ i brukshistorikken din. Dette er en [lavprismodell](/docs/config/#models) som brukes til å generere titlene på øktene dine. + +:::note +Kredittkortgebyrer overføres til kostpris (4,4 % + $0,30 per transaksjon); vi belaster ikke noe utover det. +::: + +De gratis modellene: + +- GLM 4.7 Free er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle tilbakemeldinger og forbedre modellen. +- Kimi K2.5 Gratis er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle tilbakemeldinger og forbedre modellen. +- MiniMax M2.1 Free er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle tilbakemeldinger og forbedre modellen. +- Big Pickle er en stealth-modell som er gratis på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle tilbakemeldinger og forbedre modellen. + +Contact us if you have any questions. + +--- + +### Last inn automatisk + +Hvis saldoen din går under $5, vil Zen automatisk laste inn $20 på nytt. + +Du kan endre beløpet for automatisk påfylling. Du kan også deaktivere automatisk reload helt. + +--- + +### Månedlige grenser + +Du kan også angi en månedlig bruksgrense for hele arbeidsområdet og for hver +medlem av teamet ditt. + +La oss for eksempel si at du setter en månedlig bruksgrense til $20, Zen vil ikke bruke +mer enn $20 på en måned. Men hvis du har automatisk reload aktivert, kan Zen ende opp +belaster deg mer enn $20 hvis saldoen din går under $5. + +--- + +## Personvern + +Alle våre modeller er vert i US. Leverandørene våre følger en nulloppbevaringspolicy og bruker ikke dataene dine til modellopplæring, med følgende unntak: + +- Big Pickle: I løpet av gratisperioden kan innsamlede data brukes til å forbedre modellen. +- GLM 4.7 Gratis: I løpet av gratisperioden kan innsamlede data brukes til å forbedre modellen. +- Kimi K2.5 Gratis: I løpet av gratisperioden kan innsamlede data brukes til å forbedre modellen. +- MiniMax M2.1 Gratis: I løpet av gratisperioden kan innsamlede data brukes til å forbedre modellen. +- OpenAI APIer: Forespørsler oppbevares i 30 dager i samsvar med [OpenAIs datapolicyer](https://platform.openai.com/docs/guides/your-data). +- Anthropic APIer: Forespørsler oppbevares i 30 dager i samsvar med [Anthropics datapolicyer](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## For lag + +Zen fungerer også utmerket for team. Du kan invitere lagkamerater, tildele roller, kuratere +modellene laget ditt bruker, og mer. + +:::note +Arbeidsområder er for øyeblikket gratis for team som en del av betaversjonen. +::: + +Å administrere arbeidsområdet ditt er for øyeblikket gratis for team som en del av betaversjonen. Det blir vi +deler mer informasjon om prisene snart. + +--- + +### Roller + +Du kan invitere lagkamerater til arbeidsområdet ditt og tildele roller: + +- **Admin**: Administrer modeller, medlemmer, API-nøkler og fakturering +- **Medlem**: Administrer kun sine egne API-nøkler + +Administratorer kan også sette månedlige forbruksgrenser for hvert medlem for å holde kostnadene under kontroll. + +--- + +### Modelltilgang + +Administratorer kan aktivere eller deaktivere spesifikke modeller for arbeidsområdet. Forespørsler til en deaktivert modell vil returnere en feil. + +Dette er nyttig for tilfeller der du ønsker å deaktivere bruken av en modell som +samler inn data. + +--- + +### Ta med egen nøkkel + +Du kan bruke dine egne OpenAI- eller Anthropic API-nøkler mens du fortsatt har tilgang til andre modeller i Zen. + +Når du bruker dine egne nøkler, faktureres tokens direkte av leverandøren, ikke av Zen. + +For eksempel kan organisasjonen din allerede ha en nøkkel for OpenAI eller Anthropic +og du vil bruke det i stedet for det Zen gir. + +--- + +## Mål + +Vi opprettet OpenCode Zen for å: + +1. **Benchmark** de beste modellene/leverandørene for kodingsagenter. +2. Ha tilgang til alternativene for **høyeste kvalitet** og ikke nedgrader ytelsen eller rute til billigere leverandører. +3. Gi videre eventuelle **prisfall** ved å selge til kostpris; så den eneste markeringen er å dekke behandlingsgebyrene våre. +4. Ha **ingen låsing** ved å la deg bruke den med en hvilken som helst annen kodeagent. Og la deg alltid bruke en hvilken som helst annen leverandør med OpenCode også. diff --git a/packages/web/src/content/docs/de/1-0.mdx b/packages/web/src/content/docs/de/1-0.mdx new file mode 100644 index 000000000..ac7694608 --- /dev/null +++ b/packages/web/src/content/docs/de/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: Migration zu 1.0 +description: Was ist neu in OpenCode 1.0. +--- + +OpenCode 1.0 ist eine komplette Neufassung des TUI. + +Wir sind vom go+bubbletea-basierten TUI, das Leistungs- und Leistungsprobleme aufwies, zu einem internen Framework (OpenTUI) übergegangen, das in zig+solidjs geschrieben wurde. + +Der neue TUI funktioniert wie der alte, da er eine Verbindung zum gleichen Opencode-Server herstellt. + +--- + +## Upgrading + +Sie sollten nicht automatisch auf 1.0 aktualisiert werden, wenn Sie derzeit eine frühere Version verwenden +Version. Einige ältere Versionen von OpenCode greifen jedoch immer auf die neueste Version zu. + +Führen Sie zum manuellen Upgrade Folgendes aus: + +```bash +$ opencode upgrade 1.0.0 +``` + +Führen Sie Folgendes aus, um ein Downgrade auf 0.x durchzuführen + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## UX ändert sich + +Der Sitzungsverlauf ist stärker komprimiert und zeigt nur alle Details des Bearbeitungs- und Bash-Tools an. + +Wir haben eine Befehlsleiste hinzugefügt, durch die schnell alles fließt. Drücken Sie Strg+P, um es in einem beliebigen Kontext aufzurufen und alles zu sehen, was Sie tun können. + +Eine Sitzungsseitenleiste (kann umgeschaltet werden) mit nützlichen Informationen hinzugefügt. + +Wir haben einige Funktionen entfernt, von denen wir nicht sicher waren, ob sie tatsächlich jemand nutzte. Wenn etwas Wichtiges fehlt, öffnen Sie bitte eine Ausgabe und wir werden es schnell wieder hinzufügen. + +--- + +## Bahnbrechende Veränderungen + +### Tastenkombinationen umbenannt + +- Nachrichten_revert -> Nachrichten_Rückgängig machen +- switch_agent -> agent_cycle +- switch_agent_reverse -> agent_cycle_reverse +- switch_mode -> agent_cycle +- switch_mode_reverse -> agent_cycle_reverse + +### Tastenkombinationen entfernt + +- message_layout_toggle +- message_next +- Nachrichten_vorherige +- file_diff_toggle +- file_search +- file_close +- Dateiliste +- app_help +- project_init +- Werkzeugdetails +- think_blocks diff --git a/packages/web/src/content/docs/de/acp.mdx b/packages/web/src/content/docs/de/acp.mdx new file mode 100644 index 000000000..04c5c67ac --- /dev/null +++ b/packages/web/src/content/docs/de/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACP-Unterstützung +description: Verwenden Sie OpenCode in jedem ACP-kompatiblen Editor. +--- + +OpenCode unterstützt [Agent Client Protocol](https://agentclientprotocol.com) oder (ACP), sodass Sie es direkt in kompatiblen Editoren und IDEs verwenden können. + +:::tip +Eine Liste der Editoren und Tools, die ACP unterstützen, finden Sie unter [ACP progress report](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP ist ein offenes Protokoll, das die Kommunikation zwischen Code-Editoren und AI-Codierungsagenten standardisiert. + +--- + +## Konfigurieren + +Um OpenCode über ACP zu verwenden, konfigurieren Sie Ihren Editor für die Ausführung des Befehls `opencode acp`. + +Der Befehl startet OpenCode als ACP-kompatiblen Unterprozess, der über stdio über JSON-RPC mit Ihrem Editor kommuniziert. + +Nachfolgend finden Sie Beispiele für beliebte Editoren, die ACP unterstützen. + +--- + +### Zed + +Fügen Sie Ihrer [Zed](https://zed.dev)-Konfiguration (`~/.config/zed/settings.json`) Folgendes hinzu: + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +Um es zu öffnen, verwenden Sie die Aktion `agent: new thread` in der **Befehlspalette**. + +Sie können auch eine Tastenkombination binden, indem Sie Ihren `keymap.json` bearbeiten: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### JetBrains IDEs + +Fügen Sie zu Ihrem [JetBrains IDE](https://www.jetbrains.com/) acp.json gemäß [documentation](https://www.jetbrains.com/help/ai-assistant/acp.html) hinzu: + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +Um es zu öffnen, verwenden Sie den neuen Agenten „OpenCode“ in der Chat-Agentenauswahl AI. + +--- + +### Avante.nvim + +Fügen Sie Ihrer [Avante.nvim](https://github.com/yetone/avante.nvim)-Konfiguration Folgendes hinzu: + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +Wenn Sie Umgebungsvariablen übergeben müssen: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +Um OpenCode als ACP-Agent in [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) zu verwenden, fügen Sie Folgendes zu Ihrer Neovim-Konfiguration hinzu: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +Diese Konfiguration richtet CodeCompanion so ein, dass OpenCode als ACP-Agent für den Chat verwendet wird. + +Wenn Sie Umgebungsvariablen (wie `OPENCODE_API_KEY`) übergeben müssen, finden Sie ausführliche Informationen zu [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) in der Dokumentation zu CodeCompanion.nvim. + +## Support + +OpenCode funktioniert über ACP genauso wie im Terminal. Alle Funktionen werden unterstützt: + +:::note +Einige integrierte Schrägstrichbefehle wie `/undo` und `/redo` werden derzeit nicht unterstützt. +::: + +- Integrierte Tools (Dateioperationen, Terminalbefehle usw.) +- Benutzerdefinierte Tools und Slash-Befehle +- MCP-Server, die in Ihrer OpenCode-Konfiguration konfiguriert sind +- Projektspezifische Regeln von `AGENTS.md` +- Benutzerdefinierte Formatierer und Linters +- Agenten- und Berechtigungssystem diff --git a/packages/web/src/content/docs/de/agents.mdx b/packages/web/src/content/docs/de/agents.mdx new file mode 100644 index 000000000..7503658be --- /dev/null +++ b/packages/web/src/content/docs/de/agents.mdx @@ -0,0 +1,747 @@ +--- +title: Agenten +description: Konfigurieren und verwenden Sie spezielle Agenten. +--- + +Agenten sind spezialisierte AI-Assistenten, die für bestimmte Aufgaben und Arbeitsabläufe konfiguriert werden können. Sie ermöglichen Ihnen die Erstellung gezielter Werkzeuge mit benutzerdefinierten Eingabeaufforderungen, Modellen und Werkzeugzugriff. + +:::tip +Verwenden Sie den Planagenten, um Code zu analysieren und Vorschläge zu überprüfen, ohne Codeänderungen vorzunehmen. +::: + +Sie können während einer Sitzung zwischen Agenten wechseln oder sie mit der Erwähnung `@` aufrufen. + +--- + +## Typen + +Es gibt zwei Arten von Agenten in OpenCode; Primäragenten und Subagenten. + +--- + +### Primäragenten + +Primäragenten sind die Hauptassistenten, mit denen Sie direkt interagieren. Sie können sie mit der **Tabulatortaste** oder Ihrer konfigurierten Tastenkombination `switch_agent` durchblättern. Diese Agenten kümmern sich um Ihr Hauptgespräch. Der Werkzeugzugriff wird über Berechtigungen konfiguriert – zum Beispiel sind bei „Build“ alle Werkzeuge aktiviert, während „Plan“ eingeschränkt ist. + +:::tip +Sie können die **Tabulatortaste** verwenden, um während einer Sitzung zwischen primären Agenten zu wechseln. +::: + +OpenCode verfügt über zwei integrierte Primäragenten: **Build** und **Plan**. Auch +Schauen Sie sich diese unten an. + +--- + +### Subagenten + +Unteragenten sind spezialisierte Assistenten, die Primäragenten für bestimmte Aufgaben aufrufen können. Sie können sie auch manuell aufrufen, indem Sie sie in Ihren Nachrichten **@erwähnen**. + +OpenCode verfügt über zwei integrierte Subagenten: **General** und **Explore**. Wir werden uns das weiter unten ansehen. + +--- + +## Eingebaut + +OpenCode verfügt über zwei integrierte Primäragenten und zwei integrierte Subagenten. + +--- + +### Verwenden Sie Build + +_Modus_: `primary` + +Build ist der **Standard**-Primäragent mit allen aktivierten Tools. Dies ist der Standardagent für Entwicklungsarbeiten, bei dem Sie vollen Zugriff auf Dateioperationen und Systembefehle benötigen. + +--- + +### Nutzungsplan + +_Modus_: `primary` + +Ein eingeschränkter Agent, der für Planung und Analyse entwickelt wurde. Wir verwenden ein Berechtigungssystem, um Ihnen mehr Kontrolle zu geben und unbeabsichtigte Änderungen zu verhindern. +Standardmäßig sind alle folgenden Elemente auf `ask` gesetzt: + +- `file edits`: Alle Schreibvorgänge, Patches und Bearbeitungen +- `bash`: Alle Bash-Befehle + +Dieser Agent ist nützlich, wenn Sie möchten, dass LLM Code analysiert, Änderungen vorgeschlagen oder Pläne erstellt werden, ohne tatsächliche Änderungen an Ihrer Codebasis vorzunehmen. + +--- + +### Verwenden Sie es allgemein + +_Modus_: `subagent` + +Ein Allzweckagent zur Recherche komplexerer Fragen und zur Ausführung mehrstufiger Aufgaben. Verfügt über vollständigen Zugriff auf das Tool (außer Todo), sodass bei Bedarf Dateiänderungen vorgenommen werden können. Verwenden Sie Matrizen, um mehrere Arbeitseinheiten parallel auszuführen. + +--- + +### Verwenden Sie „Erkunden“. + +_Modus_: `subagent` + +Ein schneller, schreibgeschützter Agent zum Erkunden von Codebasen. Dateien können nicht geändert werden. Verwenden Sie dies, wenn Sie Dateien schnell anhand von Mustern finden, Code nach Schlüsselwörtern durchsuchen oder Fragen zur Codebasis beantworten müssen. + +--- + +### Verwenden Sie Dichtung + +_Modus_: `primary` + +Versteckter Systemagent, der lange Kontext in einer kleineren Zusammenfassung komprimiert. Es wird bei Bedarf automatisch ausgeführt und ist im UI nicht auswählbar. + +--- + +### Titel verwenden + +_Modus_: `primary` + +Versteckter Systemagent, der kurze Sitzungstitel generiert. Es läuft automatisch und ist im UI nicht auswählbar. + +--- + +### Zusammenfassung verwenden + +_Modus_: `primary` + +Versteckter Systemagent, der Sitzungszusammenfassungen erstellt. Es läuft automatisch und ist im UI nicht auswählbar. + +--- + +## Verwendung + +1. Verwenden Sie für primäre Agenten die **Tabulatortaste**, um während einer Sitzung durch sie zu blättern. Sie können auch Ihre konfigurierte `switch_agent`-Tastenkombination verwenden. + +2. Subagenten können aufgerufen werden: + - **Automatisch** durch primäre Agenten für spezielle Aufgaben basierend auf ihren Beschreibungen. + - Manuell durch **@ Erwähnung** eines Subagenten in Ihrer Nachricht. Zum Beispiel. + + ```txt frame="none" + @general help me search for this function + ``` + +3. **Navigation zwischen Sitzungen**: Wenn Subagenten ihre eigenen untergeordneten Sitzungen erstellen, können Sie zwischen der übergeordneten Sitzung und allen untergeordneten Sitzungen sorgfältig handeln, indem Sie Folgendes verwenden: + - **\+Rechts** (oder Ihre konfigurierte `session_child_cycle`-Tastenkombination), um vorwärts durch Eltern → Kind1 → Kind2 → ... → Eltern zu blättern + - **\+Links** (oder Ihre konfigurierte `session_child_cycle_reverse`-Tastenkombination), um rückwärts durch übergeordnetes Element ← untergeordnetes Element1 ← untergeordnetes Element2 ← ... ← übergeordnetes Element zu blättern + + Dadurch können Sie nahtlos zwischen der Hauptkonversation und der spezialisierten Subagentenarbeit wechseln. + +--- + +## Konfigurieren + +Sie können die integrierten Agenten anpassen oder über die Konfiguration eigene erstellen. Agenten können auf zwei Arten konfiguriert werden: + +--- + +### JSON + +Konfigurieren Sie Agenten in Ihrer `opencode.json`-Konfigurationsdatei: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Markdown + +Sie können Agenten auch mithilfe von Markdown-Dateien definieren. Platzieren Sie sie in: + +- Global: `~/.config/opencode/agents/` +- Pro Projekt: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Der Name der Markdown-Datei wird zum Agentennamen. Beispielsweise erstellte `review.md` einen `review`-Agenten. + +--- + +## Options + +Schauen Sie sich diese Konfigurationsmöglichkeiten im Detail an. + +--- + +### Beschreibung + +Verwenden Sie die Option `description`, um eine kurze Beschreibung darüber bereitzustellen, was der Agent tut und wann er verwendet werden soll. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +Dies ist eine **erforderliche** Konfigurationsoption. + +--- + +### Temperature + +Steuern Sie die Zufälligkeit und Kreativität der Antworten von LLM mit der `temperature`-Konfiguration. + +Höchste Werte machen die Antworten fokussierter und deterministischer, während höhere Werte die Kreativität und Variabilität steigern. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Temperaturwerte liegen typischerweise zwischen 0.0 und 1.0: + +- **0.0-0.2**: Sehr fokussierte und deterministische Antworten, ideal für Code-Analyse und Planung +- **0.3-0.5**: Ausgewogene Antworten mit etwas Kreativität, gut für allgemeine Entwicklungsaufgaben +- **0.6-1.0**: Kreativere und vielfältigere Antworten, nützlich für Brainstorming und Erkundung + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Wenn keine Temperatur angegeben ist, verwendet OpenCode modellspezifische Standardwerte; typischerweise 0 für die meisten Modelle, 0.55 für Qwen-Modelle. + +--- + +### Maximale Schritte + +Steuern Sie die maximale Anzahl an Agenteniterationen, die ein Agent durchführen kann, bevor er gezwungen wird, nur mit Text zu antworten. Dadurch können Benutzer, die die Kosten kontrollieren möchten, ein Limit für Agentenaktionen festlegen. + +Wenn dies nicht festgelegt ist, iteriert der Agent weiter, bis das Modell den Stopp beschließt oder der Benutzer die Sitzung unterbricht. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +Wenn das Limit erreicht ist, erhält der Agent eine spezielle Systemaufforderung, die ihn anweist, mit einer Zusammenfassung seiner Arbeit und empfohlenen verbleibenden Aufgaben zu antworten. + +:::caution +Das alte Feld `maxSteps` ist veraltet. Verwenden Sie stattdessen `steps`. +::: + +--- + +### Disable + +Auf `true` setzen, um den Agenten zu deaktivieren. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Prompt + +Geben Sie mit der `prompt`-Konfiguration eine benutzerdefinierte Systemaufforderungsdatei für diese Agenten an. Die Eingabeaufforderungsdatei sollte Anweisungen enthalten, die speziell auf den Zweck des Agenten zugeschnitten sind. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Dieser Pfad ist relativ zum Speicherort der Konfigurationsdatei. Dies funktioniert sowohl für die globale OpenCode-Konfiguration als auch für die projektspezifische Konfiguration. + +--- + +### Modell + +Verwenden Sie die `model`-Konfiguration, um das Modell für diese Agenten zu überschreiben. Nützlich für die Verwendung verschiedener Modelle, die für verschiedene Aufgaben optimiert sind. Zum Beispiel ein schnelleres Modell für die Planung, ein leistungsfähigeres Modell für die Umsetzung. + +:::tip +Wenn Sie kein Modell angeben, verwenden Sie den primären Agenten [model globally configured](/docs/config#models), während die Subagenten das Modell des primären Agenten verwenden, der den Subagenten aufgerufen hat. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +Das Modell ID in Ihrer OpenCode-Konfiguration verwendet das Format `provider/model-id`. Wenn Sie beispielsweise [OpenCode Zen](/docs/zen) verwenden, würden Sie `opencode/gpt-5.1-codex` für GPT 5.1 Codex verwenden. + +--- + +### Tools + +Steuern Sie mit der `tools`-Konfiguration, welche Tools in diesem Agent verfügbar sind. Sie können bestimmte Tools aktivieren oder deaktivieren, indem Sie sie auf `true` oder `false` setzen. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +Die agentenspezifische Konfiguration überschreibt die globale Konfiguration. +::: + +Sie können Platzhalter auch verwenden, um mehrere Werkzeuge gleichzeitig zu steuern. So deaktivieren Sie beispielsweise alle Tools von einem MCP-Server: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[Learn more about tools](/docs/tools). + +--- + +### Permissions + +Sie können Berechtigungen konfigurieren, um zu verwalten, welche Aktionen ein Agent ausführen kann. Derzeit können die Berechtigungen für die Tools `edit`, `bash` und `webfetch` wie folgt konfiguriert werden: + +- `"ask"` – Bitten Sie um Genehmigung, bevor Sie das Tool ausführen +- `"allow"` – Alle Vorgänge ohne Genehmigung zulassen +- `"deny"` – Deaktivieren Sie das Tool + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +Sie können diese Berechtigungen pro Agent überschreiben. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +Sie können Berechtigungen auch in Markdown-Agenten festlegen. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +Sie können Berechtigungen für bestimmte Bash-Befehle festlegen. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +Dies kann ein Kugelmuster annehmen. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +Und Sie können den Platzhalter `*` auch verwenden, um Berechtigungen für alle Befehle zu verwalten. +Da die letzte übereinstimmende Regel Vorrang hat, setzen Sie zuerst den Platzhalter `*` und danach bestimmte Regeln. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[Learn more about permissions](/docs/permissions). + +--- + +### Mode + +Steuern Sie den Modus des Agenten mit der `mode`-Konfiguration. Mit der Option `mode` wird festgelegt, wie der Agent verwendet werden kann. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +Die Option `mode` kann auf `primary`, `subagent` oder `all` gesetzt werden. Wenn kein `mode` angegeben ist, wird standardmäßig `all` verwendet. + +--- + +### Hidden + +Verstecken Sie einen Subagenten im Autovervollständigungsmenü `@` mit `hidden: true`. Nützlich für interne Subagenten, die nur programmgesteuert von anderen Agenten über das Task-Tool aufgerufen werden sollten. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +Dies wirkt sich nur auf die Benutzersichtbarkeit im Autovervollständigungsmenü aus. Versteckte Agenten können weiterhin vom Modell über das Aufgabentool aufgerufen werden, sofern die Berechtigungen dies zulassen. + +:::note +Gilt nur für `mode: subagent`-Agenten. +::: + +--- + +### Aufgabenberechtigungen + +Steuern Sie, welche Subagenten ein Agent über das Task-Tool mit `permission.task` aufrufen kann. Verwendet Glob-Muster für eine flexible Zuordnung. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +Bei der Einstellung `deny` wird der Subagent vollständig aus der Beschreibung des Aufgabentools entfernt, sodass das Modell nicht versucht, ihn aufzurufen. + +:::tip +Die Regeln werden der Reihe nach ausgewertet und die **letzte übereinstimmende Regel gewinnt**. Im obigen Beispiel entspricht `orchestrator-planner` sowohl `*` (verweigern) als auch `orchestrator-*` (zulassen), aber da `orchestrator-*` nach `*` kommt, ist das Ergebnis `allow`. +::: + +:::tip +Benutzer können jeden Subagenten immer direkt über das Autovervollständigungsmenü `@` aufrufen, auch wenn die Aufgabenberechtigungen des Agenten sterben würden. +::: + +--- + +### Color + +Passen Sie das visuelle Erscheinungsbild des Agenten im UI mit der Option `color` an. Dies wirkt sich darauf aus, wie der Agent in der Benutzeroberfläche angezeigt wird. + +Verwenden Sie eine gültige Hex-Farbe (e.g., `#FF5733`) oder Designfarbe: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### Top P + +Steuern Sie die Antwortvielfalt mit der Option `top_p`. Alternative zur Temperatur zur Kontrolle des Zufalls. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +Die Werte reichen von 0.0 bis 1.0. Die meisten Werte sind fokussierter, die höheren Werte vielfältiger. + +--- + +### Additional + +Alle anderen Optionen, die Sie in Ihrer Agentenkonfiguration angeben, werden als Modelloptionen **direkt** an den Anbieter weitergeleitet. Dadurch können Sie anbieterspezifische Funktionen und Parameter nutzen. + +Mit den Argumentationsmodellen von OpenAI können Sie beispielsweise den Argumentationsaufwand steuern: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +Diese zusätzlichen Optionen sind modell- und anbieterspezifisch. Überprüfen Sie die Dokumentation Ihres Anbieters auf verfügbare Parameter. + +:::tip +Führen Sie `opencode models` aus, um eine Liste der verfügbaren Modelle anzubieten. +::: + +--- + +## Erstellen Sie Agenten + +Mit dem folgenden Befehl können Sie neue Agenten erstellen: + +```bash +opencode agent create +``` + +Dieser interaktive Befehl führt zu Folgendem: + +1. Fragen Sie, wo der Agent gespeichert werden soll. global oder projektspezifisch. +2. Beschreibung dessen, was der Agent tun soll. +3. Generieren Sie eine entsprechende Systemaufforderung und -kennung. +4. Hier können Sie auswählen, auf welche Tools der Agent zugreifen kann. +5. Erstellen Sie abschließend eine Markdown-Datei mit der Agentenkonfiguration. + +--- + +## Anwendungsfälle + +Hier sind einige häufige Anwendungsfälle für verschiedene Agenten. + +- **Build-Agent**: Vollständige Entwicklungsarbeit mit allen aktivierten Tools +- **Planagent**: Analyse und Planung ohne Änderungen +- **Review-Agent**: Codeüberprüfung mit schreibgeschütztem Zugriff plus Dokumentationstools +- **Debug-Agent**: Konzentriert sich auf die Untersuchung mit aktivierten Bash- und Lesetools +- **Docs-Agent**: Schreiben von Dokumentationen mit Dateioperationen, aber ohne Systembefehle + +--- + +## Examples + +Hier sind einige Beispielagenten, die für Sie nützlich sein könnten. + +:::tip +Haben Sie einen Agenten, den Sie gerne teilen möchten? [Submit a PR](https://github.com/anomalyco/opencode). +::: + +--- + +### Dokumentationsagent + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### Sicherheitsprüfer + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/de/cli.mdx b/packages/web/src/content/docs/de/cli.mdx new file mode 100644 index 000000000..eccddc6c0 --- /dev/null +++ b/packages/web/src/content/docs/de/cli.mdx @@ -0,0 +1,601 @@ +--- +title: CLI +description: OpenCode CLI Optionen und Befehle. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +Der OpenCode CLI startet standardmäßig den [TUI](/docs/tui), wenn er ohne Argumente ausgeführt wird. + +```bash +opencode +``` + +Es akzeptiert aber auch Befehle, wie auf dieser Seite dokumentiert. Dadurch können Sie programmgesteuert mit OpenCode interagieren. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui + +Starten Sie die Terminalbenutzeroberfläche OpenCode. + +```bash +opencode [project] +``` + +#### Flaggen + +| Flagge | Kurz | Beschreibung | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | Setzen Sie die letzte Sitzung fort | +| `--session` | `-s` | Sitzung ID zum Fortfahren | +| `--prompt` | | Zur Verwendung auffordern | +| `--model` | `-m` | Zu verwendendes Modell in der Form provider/model | +| `--agent` | | Zu verwendender Agent | +| `--port` | | Port zum Abhören | +| `--hostname` | | Hostname zum Abhören | + +--- + +## Befehle + +Der OpenCode CLI verfügt außerdem über die folgenden Befehle. + +--- + +### agent + +Agenten für OpenCode verwalten. + +```bash +opencode agent [command] +``` + +--- + +### attach + +Schließen Sie ein Terminal an einen bereits laufenden OpenCode-Backend-Server an, der über die Befehle `serve` oder `web` gestartet wurde. + +```bash +opencode attach [url] +``` + +Dies ermöglicht die Verwendung von TUI mit einem Remote-Backend OpenCode. Zum Beispiel: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### Flaggen + +| Flagge | Kurz | Beschreibung | +| ----------- | ----- | --------------------------------- | +| `--dir` | | Arbeitsverzeichnis zum Starten von TUI in | +| `--session` | `-s` | Sitzung ID zum Fortfahren | + +--- + +#### create + +Erstellen Sie einen neuen Agenten mit benutzerdefinierter Konfiguration. + +```bash +opencode agent create +``` + +Dieser Befehl führt Sie durch die Erstellung eines neuen Agenten mit einer benutzerdefinierten Systemeingabeaufforderung und Toolkonfiguration. + +--- + +#### list + +Hören Sie sich alle verfügbaren Agenten an. + +```bash +opencode agent list +``` + +--- + +### auth + +Befehl zum Verwalten von Anmeldeinformationen und Anmelden für Anbieter. + +```bash +opencode auth [command] +``` + +--- + +#### login + +OpenCode wird von der Anbieterliste bei [Models.dev](https://models.dev) unterstützt, sodass Sie `opencode auth login` verwenden können, um API-Schlüssel für jeden Anbieter zu konfigurieren, den Sie verwenden möchten. Dies wird in `~/.local/share/opencode/auth.json` gespeichert. + +```bash +opencode auth login +``` + +Wenn OpenCode startet, lädt es den Anbieter aus der Anmeldeinformationsdatei. Und ob in Ihren Umgebungen Schlüssel sind oder in Ihrem Projekt eine `.env`-Datei vorhanden ist. + +--- + +#### list + +Listet alle authentifizierten Anbieter auf, wie in der Anmeldeinformationsdatei gespeichert. + +```bash +opencode auth list +``` + +Oder die Kurzversion. + +```bash +opencode auth ls +``` + +--- + +#### logout + +Melden Sie sich von einem Anbieter ab, ohne dass es aus der Anmeldeinformationsdatei gelöscht wird. + +```bash +opencode auth logout +``` + +--- + +### github + +Verwalten Sie den GitHub-Agenten für die Repository-Automatisierung. + +```bash +opencode github [command] +``` + +--- + +#### installieren + +Installieren Sie den GitHub-Agenten in Ihrem Repository. + +```bash +opencode github install +``` + +Dadurch wird der erforderliche GitHub-Aktionsworkflow eingerichtet und Sie durch den Konfigurationsprozess geführt. [Learn more](/docs/github). + +--- + +#### laufen + +Führen Sie den GitHub-Agenten aus. Dies wird normalerweise in GitHub-Aktionen verwendet. + +```bash +opencode github run +``` + +##### Flaggen + +| Flagge | Beschreibung | +| --------- | -------------------------------------- | +| `--event` | GitHub Scheinereignis zum Ausführen des Agenten für | +| `--token` | GitHub persönliches Zugriffstoken | + +--- + +### mcp + +Verwalten Sie den Model Context Protocol-Server. + +```bash +opencode mcp [command] +``` + +--- + +#### add + +Fügen Sie Ihrer Konfiguration einen MCP-Server hinzu. + +```bash +opencode mcp add +``` + +Dieser Befehl führt Sie durch das Hinzufügen eines lokalen oder Remote-Servers MCP. + +--- + +#### list + +Hören Sie sich alle konfigurierten MCP-Server und deren Verbindungsstatus an. + +```bash +opencode mcp list +``` + +Oder nutzen Sie die Kurzversion. + +```bash +opencode mcp ls +``` + +--- + +#### auth + +Authentifizieren Sie sich mit einem OAuth-fähigen MCP-Server. + +```bash +opencode mcp auth [name] +``` + +Wenn Sie keinen Servernamen angeben, werden Sie autorisiert, einen der verfügbaren OAuth-fähigen Server auszuwählen. + +Sie können auch OAuth-fähige Server und deren Authentifizierungsstatus auflisten. + +```bash +opencode mcp auth list +``` + +Oder nutzen Sie die Kurzversion. + +```bash +opencode mcp auth ls +``` + +--- + +#### logout + +Entfernen Sie OAuth-Anmeldeinformationen für einen MCP-Server. + +```bash +opencode mcp logout [name] +``` + +--- + +#### debug + +Beheben Sie OAuth-Verbindungsprobleme für einen MCP-Server. + +```bash +opencode mcp debug +``` + +--- + +### models + +Hören Sie sich alle verfügbaren Modelle der konfigurierten Anbieter an. + +```bash +opencode models [provider] +``` + +Dieser Befehl zeigt alle bei Ihren konfigurierten Anbietern verfügbaren Modelle im Format `provider/model` an. + +Dies ist nützlich, um die genauen Modellnamen herauszufinden, die in [your config](/docs/config/) verwendet werden sollen. + +Sie können optional einen Anbieter ID übergeben, um Modelle nach diesem Anbieter zu filtern. + +```bash +opencode models anthropic +``` + +#### Flaggen + +| Flagge | Beschreibung | +| ----------- | ------------------------------------------------------------ | +| `--refresh` | Aktualisieren Sie den Modellcache von models.dev | +| `--verbose` | Verwenden Sie eine ausführlichere Modellausgabe (einschließlich Metadaten wie Kosten) | + +Verwenden Sie das Flag `--refresh`, um die zwischengespeicherte Modellliste zu aktualisieren. Dies ist nützlich, wenn einem Anbieter neue Modelle hinzugefügt wurden und Sie diese in OpenCode sehen möchten. + +```bash +opencode models --refresh +``` + +--- + +### laufen + +Führen Sie Opencode im nicht interaktiven Modus aus, indem Sie direkt eine Eingabeaufforderung übergeben. + +```bash +opencode run [message..] +``` + +Dies ist nützlich für die Skripterstellung, die Automatisierung oder wenn Sie eine schnelle Antwort wünschen, ohne den vollständigen TUI zu starten. Zum Beispiel. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +Sie können auch eine Verbindung zu einer laufenden `opencode serve`-Instanz herstellen, um bei jedem Lauf Kaltstartzeiten für den MCP-Server zu vermeiden: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### Flaggen + +| Flagge | Kurz | Beschreibung | +| ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | | Der auszuführende Befehl: Nachricht für args | verwenden +| `--continue` | `-c` | Setzen Sie die letzte Sitzung fort | +| `--session` | `-s` | Sitzung ID zum Fortfahren | +| `--share` | | Teilen Sie die Sitzung | +| `--model` | `-m` | Zu verwendendes Modell in der Form provider/model | +| `--agent` | | Zu verwendender Agent | +| `--file` | `-f` | Datei(en) zum Anhängen an die Nachricht | +| `--format` | | Format: Standard (formatiert) oder JSON (rohe JSON-Ereignisse) | +| `--title` | | Titel für die Sitzung (verwendet eine verkürzte Eingabeaufforderung, wenn kein Wert angegeben wird) | +| `--attach` | | An einen laufenden Opencode-Server anschließen (e.g., http://localhost:4096) | +| `--port` | | Port für den lokalen Server (standardmäßig zufälliger Port) | + +--- + +### serve + +Starten Sie einen Headless-OpenCode-Server für den API-Zugriff. Sehen Sie sich [server docs](/docs/server) für die vollständige HTTP-Schnittstelle an. + +```bash +opencode serve +``` + +Dadurch wird ein HTTP-Server gestartet, der API-Zugriff auf Opencode-Funktionalität ohne die TUI-Schnittstelle bietet. Legen Sie `OPENCODE_SERVER_PASSWORD` fest, um die HTTP-Basisauthentifizierung zu aktivieren (Benutzername ist standardmäßig `opencode`). + +#### Flaggen + +| Flagge | Beschreibung | +| ------------ | ------------------------------------------ | +| `--port` | Port zum Abhören | +| `--hostname` | Hostname zum Abhören | +| `--mdns` | mDNS-Erkennung aktivieren | +| `--cors` | Zusätzliche Browserursprung(e), um CORS | zulassen + +--- + +### Sitzung + +Verwalten Sie OpenCode-Sitzungen. + +```bash +opencode session [command] +``` + +--- + +#### list + +Hören Sie sich alle OpenCode-Sitzungen an. + +```bash +opencode session list +``` + +##### Flaggen + +| Flagge | Kurz | Beschreibung | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` | Auf N letzte Sitzungen beschränken | +| `--format` | | Ausgabeformat: Tabelle oder JSON (Tabelle) | + +--- + +### stats + +Zeigen Sie Token-Nutzungs- und Kostenstatistiken für Ihre OpenCode-Sitzungen an. + +```bash +opencode stats +``` + +#### Flaggen + +| Flagge | Beschreibung | +| ----------- | --------------------------------------------------------------------------- | +| `--days` | Statistiken für die letzten N Tage anzeigen (alle Zeiten) | +| `--tools` | Anzahl der angebotenen Werkzeuge (alle) | +| `--models` | Aufschlüsselung der Modellnutzung anzeigen (standardmäßig ausgeblendet). Übergeben Sie eine Zahl, um das obere N | . +| `--project` | Nach Projekt filtern (alle Projekte, leere Zeichenfolge: aktuelles Projekt) | + +--- + +### export + +Sitzungsdaten als JSON exportieren. + +```bash +opencode export [sessionID] +``` + +Wenn Sie keine Sitzung ID angeben, werden Sie berechtigt, eine der verfügbaren Sitzungen auszuwählen. + +--- + +### import + +Importieren Sie Sitzungsdaten aus einer JSON-Datei oder einer OpenCode-Freigabe URL. + +```bash +opencode import +``` + +Sie können aus einer lokalen Datei oder einer OpenCode-Freigabe URL importieren. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### web + +Starten Sie einen Headless-OpenCode-Server mit einer Weboberfläche. + +```bash +opencode web +``` + +Dadurch wird ein HTTP-Server gestartet und ein Webbrowser geöffnet, um über eine Webschnittstelle auf OpenCode zuzugreifen. Legen Sie `OPENCODE_SERVER_PASSWORD` fest, um die HTTP-Basisauthentifizierung zu aktivieren (Benutzername ist standardmäßig `opencode`). + +#### Flaggen + +| Flagge | Beschreibung | +| ------------ | ------------------------------------------ | +| `--port` | Port zum Abhören | +| `--hostname` | Hostname zum Abhören | +| `--mdns` | mDNS-Erkennung aktivieren | +| `--cors` | Zusätzliche Browserursprung(e), um CORS | zulassen + +--- + +### acp + +Starten Sie einen ACP-Server (Agent Client Protocol). + +```bash +opencode acp +``` + +Dieser Befehl startet einen ACP-Server, der über stdin/stdout mit nd-JSON kommuniziert. + +#### Flaggen + +| Flagge | Beschreibung | +| ------------ | --------------------- | +| `--cwd` | Arbeitsverzeichnis | +| `--port` | Port zum Abhören | +| `--hostname` | Hostname zum Abhören | + +--- + +### uninstall + +Deinstallieren Sie OpenCode und entfernen Sie alle zugehörigen Dateien. + +```bash +opencode uninstall +``` + +#### Flaggen + +| Flagge | Kurz | Beschreibung | +| --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` | Konfigurationsdateien behalten | +| `--keep-data` | `-d` | Sitzungsdaten und Snapshots aufbewahren | +| `--dry-run` | | Zeigt, was entfernt werden würde, ohne | zu entfernen +| `--force` | `-f` | Bestätigungsaufforderungen überspringen | + +--- + +### upgrade + +Aktualisiert Opencode auf die neueste Version oder eine bestimmte Version. + +```bash +opencode upgrade [target] +``` + +Um auf die neueste Version zu aktualisieren. + +```bash +opencode upgrade +``` + +Um auf eine bestimmte Version zu aktualisieren. + +```bash +opencode upgrade v0.1.48 +``` + +#### Flaggen + +| Flagge | Kurz | Beschreibung | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` | Die verwendete Installationsmethode; Curl, NPM, PNPM, Brötchen, Brauen | + +--- + +## Globale Flaggen + +Der Opencode CLI akzeptiert die folgenden globalen Flags. + +| Flagge | Kurz | Beschreibung | +| -------------- | ----- | ------------------------------------ | +| `--help` | `-h` | Hilfe anzeigen | +| `--version` | `-v` | Versionsnummer drucken | +| `--print-logs` | | Protokolle nach Standard drucken | +| `--log-level` | | Protokollebene (DEBUG, INFO, WARN, ERROR) | + +--- + +## Umgebungsvariablen + +OpenCode kann mithilfe von Umgebungsvariablen konfiguriert werden. + +| Variable | Geben Sie | eine Beschreibung | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | boolescher Wert | Sitzungen automatisch teilen | +| `OPENCODE_GIT_BASH_PATH` | Zeichenfolge | Pfad zur ausführbaren Git Bash-Datei unter Windows | +| `OPENCODE_CONFIG` | Zeichenfolge | Pfad zur Konfigurationsdatei | +| `OPENCODE_CONFIG_DIR` | Zeichenfolge | Pfad zum Konfigurationsverzeichnis | +| `OPENCODE_CONFIG_CONTENT` | Zeichenfolge | Inline-JSON-Konfigurationsinhalt | +| `OPENCODE_DISABLE_AUTOUPDATE` | boolescher Wert | Automatische Update-Prüfungen deaktivieren | +| `OPENCODE_DISABLE_PRUNE` | boolescher Wert | Bereinigung alter Daten deaktivieren | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | boolescher Wert | Deaktivieren Sie die automatische Aktualisierung von Terminaltiteln | +| `OPENCODE_PERMISSION` | Zeichenfolge | Inline-JSON-Berechtigungskonfiguration | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | boolescher Wert | Standard-Plugins deaktivieren | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | boolescher Wert | Automatische LSP-Server-Downloads deaktivieren | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | boolescher Wert | Experimentelle Modelle aktivieren | +| `OPENCODE_DISABLE_AUTOCOMPACT` | boolescher Wert | Automatische Kontextkomprimierung deaktivieren | +| `OPENCODE_DISABLE_CLAUDE_CODE` | boolescher Wert | Deaktivieren Sie das Lesen von `.claude` (Eingabeaufforderung + Fähigkeiten) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | boolescher Wert | Deaktivieren Sie das Lesen von `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | boolescher Wert | Deaktivieren Sie das Laden von `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | boolescher Wert | Deaktivieren Sie das gesammelte Modell von Remote-Quellen | +| `OPENCODE_FAKE_VCS` | Zeichenfolge | Gefälschter VCS-Anbieter zu Testzwecken | +| `OPENCODE_DISABLE_FILETIME_CHECK` | boolescher Wert | Dateizeitprüfung zur Optimierung deaktivieren | +| `OPENCODE_CLIENT` | Zeichenfolge | Client-ID (standardmäßig `cli`) | +| `OPENCODE_ENABLE_EXA` | boolescher Wert | Exa-Websuchtools aktivieren | +| `OPENCODE_SERVER_PASSWORD` | Zeichenfolge | Aktivieren Sie die Basisauthentifizierung für `serve`/`web` | +| `OPENCODE_SERVER_USERNAME` | Zeichenfolge | Benutzernamen für die Basisauthentifizierung überschreiben (Standard `opencode`) | +| `OPENCODE_MODELS_URL` | Zeichenfolge | Benutzerdefinierte URL zum Erhalten der Modellkonfiguration | + +--- + +### Experimental + +Diese Umgebungsvariablen ermöglichen experimentelle Funktionen, die sich ändern oder entfernen können. + +| Variable | Geben Sie | eine Beschreibung | +| ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | boolescher Wert | Alle experimentellen Funktionen aktivieren | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | boolescher Wert | Symbolerkennung aktivieren | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | boolescher Wert | Kopieren bei Auswahl in TUI | deaktivieren +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | Zahl | Standard-Timeout für Bash-Befehle in ms | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | Zahl | Maximale Ausgabetokens für LLM-Antworten | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | boolescher Wert | Dateiüberwachung für das gesamte Verzeichnis aktivieren | +| `OPENCODE_EXPERIMENTAL_OXFMT` | boolescher Wert | Oxfmt-Formatierer aktivieren | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | boolescher Wert | Experimentelles LSP-Tool aktivieren | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | boolescher Wert | Dateiüberwachung deaktivieren | +| `OPENCODE_EXPERIMENTAL_EXA` | boolescher Wert | Experimentelle Exa-Funktionen aktivieren | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | boolescher Wert | Experimentelle LSP-Typprüfung aktivieren | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | boolescher Wert | Experimentelle Markdown-Funktionen aktivieren | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | boolescher Wert | Planmodus aktivieren | diff --git a/packages/web/src/content/docs/de/commands.mdx b/packages/web/src/content/docs/de/commands.mdx new file mode 100644 index 000000000..4a9731a01 --- /dev/null +++ b/packages/web/src/content/docs/de/commands.mdx @@ -0,0 +1,323 @@ +--- +title: Befehle +description: Erstellen Sie benutzerdefinierte Befehle für sich wiederholende Aufgaben. +--- + +Mit benutzerdefinierten Befehlen können Sie eine Eingabeaufforderung angeben, die ausgeführt werden soll, wenn dieser Befehl im TUI ausgeführt wird. + +```bash frame="none" +/my-command +``` + +Benutzerdefinierte Befehle gibt es zusätzlich zu den integrierten Befehlen wie `/init`, `/undo`, `/redo`, `/share`, `/help`. [Learn more](/docs/tui#commands). + +--- + +## Befehlsdateien erstellen + +Erstellen Sie Markdown-Dateien im Verzeichnis `commands/`, um benutzerdefinierte Befehle zu definieren. + +Erstellen Sie `.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Der Frontmatter definiert Befehlseigenschaften. Der Inhalt wird zur Vorlage. + +Verwenden Sie den Befehl, indem Sie `/` folgen vom Befehlsnamen eingeben. + +```bash frame="none" +"/test" +``` + +--- + +## Konfigurieren + +Sie können benutzerdefinierte Befehle über die OpenCode-Konfiguration hinzufügen oder indem Sie Markdown-Dateien im Verzeichnis `commands/` erstellen. + +--- + +### JSON + +Verwenden Sie die Option `command` in Ihrem OpenCode [config](/docs/config): + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Jetzt können Sie diesen Befehl im TUI ausführen: + +```bash frame="none" +/test +``` + +--- + +### Markdown + +Sie können Befehle auch mithilfe von Markdown-Dateien definieren. Platzieren Sie sie in: + +- Global: `~/.config/opencode/commands/` +- Pro Projekt: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Der Name der Markdown-Datei wird zum Befehlsnamen. Zum Beispiel `test.md` lässt +Du läufst: + +```bash frame="none" +/test +``` + +--- + +## Prompt-Konfiguration + +Die Eingabeaufforderungen für die benutzerdefinierten Befehle unterstützen mehrere spezielle Platzhalter und Syntax. + +--- + +### Arguments + +Übergeben Sie Argumente an Befehle mithilfe des Platzhalters `$ARGUMENTS`. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +Führen Sie den Befehl mit Argumenten aus: + +```bash frame="none" +/component Button +``` + +Und `$ARGUMENTS` wird durch `Button` ersetzt. + +Sie können auch über Positionsparameter auf einzelne Argumente zugreifen: + +- `$1` – Erstes Argument +- `$2` – Zweites Argument +- `$3` – Drittes Argument +- Und so weiter... + +Zum Beispiel: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +Führen Sie den Befehl aus: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +Dies ersetzt: + +- `$1` mit `config.json` +- `$2` mit `src` +- `$3` mit `{ "key": "value" }` + +--- + +### Shell-Ausgabe + +Verwenden Sie _!`command`_, um die Ausgabe [bash command](/docs/tui#bash-commands) in Ihre Eingabeaufforderung einzufügen. + +So erstellen Sie beispielsweise einen benutzerdefinierten Befehl, der die Testabdeckung analysiert: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +Oder um die letzten Änderungen zu überprüfen: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +Befehle werden im Stammverzeichnis Ihres Projekts ausgeführt und ihre Ausgabe wird Teil der Eingabeaufforderung. + +--- + +### Dateiverweise + +Fügen Sie Dateien in Ihren Befehl ein, indem Sie `@` folgend vom Dateinamen verwenden. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +Der Dateiinhalt wird automatisch in die Eingabeaufforderung einbezogen. + +--- + +## Options + +Schauen wir uns die Konfigurationsmöglichkeiten im Detail an. + +--- + +### Template + +Die Option `template` die Eingabeaufforderung, die an LLM gesendet wird, wenn der Befehl ausgeführt wird. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +Dies ist eine **erforderliche** Konfigurationsoption. + +--- + +### Beschreibung + +Verwenden Sie die Option `description`, um eine kurze Beschreibung der Funktion des Befehls bereitzustellen. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +Dies wird als Beschreibung im TUI angezeigt, wenn Sie den Befehl eingeben. + +--- + +### Agent + +Verwenden Sie die `agent`-Konfiguration, um optional anzugeben, welche [agent](/docs/agents) diesen Befehl ausführen soll. +Wenn es sich um einen [subagent](/docs/agents/#subagents) handelt, löst der Befehl standardmäßig einen Subagentenaufruf aus. +Um dieses Verhalten zu deaktivieren, setzen Sie `subtask` auf `false`. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +Dies ist eine **optionale** Konfigurationsoption. Wenn nicht angegeben, wird standardmäßig Ihr aktueller Agent verwendet. + +--- + +### Subtask + +Verwenden Sie den booleschen Wert `subtask`, um zu erzwingen, dass der Befehl einen [subagent](/docs/agents/#subagents)-Aufruf auslöst. +Dies ist nützlich, wenn Sie möchten, dass der Befehl Ihren primären Kontext nicht verunreinigt und den Agenten dazu zwingt, als Subagent zu fungieren. +auch wenn `mode` in der [agent](/docs/agents)-Konfiguration auf `primary` gesetzt ist. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +Dies ist eine **optionale** Konfigurationsoption. + +--- + +### Modell + +Verwenden Sie die `model`-Konfiguration, um das Standardmodell für diesen Befehl zu überschreiben. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Dies ist eine **optionale** Konfigurationsoption. + +--- + +## Eingebaut + +Opencode enthält mehrere integrierte Befehle wie `/init`, `/undo`, `/redo`, `/share`, `/help`; [learn more](/docs/tui#commands). + +:::note +Benutzerdefinierte Befehle können integrierte Befehle überschreiben. +::: + +Wenn Sie einen benutzerdefinierten Befehl mit demselben Namen definieren, überschreibt dieser den integrierten Befehl. diff --git a/packages/web/src/content/docs/de/config.mdx b/packages/web/src/content/docs/de/config.mdx new file mode 100644 index 000000000..e76e744b7 --- /dev/null +++ b/packages/web/src/content/docs/de/config.mdx @@ -0,0 +1,685 @@ +--- +title: Konfig +description: Verwenden Sie die Konfiguration OpenCode JSON. +--- + +Sie können OpenCode mithilfe einer JSON-Konfigurationsdatei konfigurieren. + +--- + +## Format + +OpenCode unterstützt die Formate **JSON** und **JSONC** (JSON mit Kommentaren). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## Locations + +Sie können Ihre Konfiguration an verschiedenen Orten platzieren und sie haben eine +andere Rangfolge. + +:::note +Konfigurationsdateien werden **zusammengeführt**, nicht ersetzt. +::: + +Konfigurationsdateien werden zusammengeführt und nicht ersetzt. Einstellungen aus den folgenden Konfigurationsspeicherorten werden kombiniert. Spätere Konfigurationen überschreiben frühere nur bei Schlüsselkonflikten. Es bleiben keine widersprüchlichen Einstellungen aus allen Konfigurationen erhalten. + +Wenn Ihre globale Konfiguration beispielsweise `theme: "opencode"` und `autoupdate: true` und Ihre Projektkonfiguration `model: "anthropic/claude-sonnet-4-5"` festlegt, umfasst die endgültige Konfiguration alle drei Einstellungen. + +--- + +### Rangfolge + +Konfigurationsquellen werden in dieser Reihenfolge geladen (spätere Quellen überschreiben frühere): + +1. **Remote-Konfiguration** (von `.well-known/opencode`) – Organisationsstandards +2. **Globale Konfiguration** (`~/.config/opencode/opencode.json`) – Benutzereinstellungen +3. **Benutzerdefinierte Konfiguration** (`OPENCODE_CONFIG` env var) – benutzerdefinierte Überschreibungen +4. **Projektkonfiguration** (`opencode.json` im Projekt) – projektspezifische Einstellungen +5. **`.opencode` Verzeichnisse** – Agenten, Befehle, Plugins +6. **Inline-Konfiguration** (`OPENCODE_CONFIG_CONTENT` env var) – Laufzeitüberschreibungen + +Dies bedeutet, dass Projektkonfigurationen globale Standardeinstellungen überschreiben können und globale Konfigurationen Remote-Organisationsstandards überschreiben können. + +:::note +Die Verzeichnisse `.opencode` und `~/.config/opencode` verwenden **Pluralnamen** für Unterverzeichnisse: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/` und `themes/`. Aus Gründen der Abwärtskompatibilität werden auch einzelne Namen (e.g., `agent/`) unterstützt. +::: + +--- + +### Remote + +Organisationen können die Standardkonfiguration über den Endpunkt `.well-known/opencode` bereitstellen. Dieser wird automatisch abgerufen, wenn Sie sich bei einem Anbieter authentifizieren, der dies unterstützt. + +Zuerst wird die Remote-Konfiguration geladen, die als Basisschicht dient. Alle anderen Konfigurationsquellen (global, Projekt) können diese Standardeinstellungen überschreiben. + +Wenn Ihre Organisation beispielsweise MCP-Server bereitstellt, sind die standardmäßig deaktiviert: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +Sie können bestimmte Server in Ihrer lokalen Konfiguration aktivieren: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### Global + +Platzieren Sie Ihre globale OpenCode-Konfiguration in `~/.config/opencode/opencode.json`. Verwenden Sie die globale Konfiguration für benutzerweite Einstellungen wie Themen, Anbieter oder Tastenkombinationen. + +Die globale Konfiguration überschreibt die Standardeinstellungen der Remote-Organisation. + +--- + +### Pro Projekt + +Fügen Sie `opencode.json` in Ihrem Projektstamm hinzu. Die Projektkonfiguration hat unter den Standardkonfigurationsdateien die höchste Priorität – sie überschreibt sowohl globale als auch Remote-Konfigurationen. + +:::tip +Platzieren Sie die projektspezifische Konfiguration im Stammverzeichnis Ihres Projekts. +::: + +Wenn OpenCode gestartet wird, sucht es im aktuellen Verzeichnis nach einer Konfigurationsdatei oder durchsucht das nächstgelegene Git-Verzeichnis. + +Dies kann auch sicher in Git eingecheckt werden und dasselbe Schema wie das globale verwenden. + +--- + +### Benutzerdefinierter Pfad + +Geben Sie mithilfe der Umgebungsvariablen `OPENCODE_CONFIG` einen benutzerdefinierten Konfigurationsdateipfad an. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +Die benutzerdefinierte Konfiguration wird in der Rangfolge zwischen globalen und Projektkonfigurationen geladen. + +--- + +### Benutzerdefiniertes Verzeichnis + +Geben Sie mit `OPENCODE_CONFIG_DIR` ein benutzerdefiniertes Konfigurationsverzeichnis an. +Umgebungsvariable. Dieses Verzeichnis wird nach Agenten, Befehlen, +Modi und Plugins genau wie das Standardverzeichnis `.opencode` und sollten +folgen der gleichen Struktur. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +Das benutzerdefinierte Verzeichnis wird nach den Verzeichnissen global config und `.opencode` geladen, sodass es deren Einstellungen **überschreiben** kann. + +--- + +## Schema + +Die Konfigurationsdatei verfügt über ein Schema, das in [**`opencode.ai/config.json`**](https://opencode.ai/config.json) definiert ist. + +Ihr Editor sollte in der Lage sein, basierend auf dem Schema zu validieren und automatisch zu vervollständigen. + +--- + +### TUI + +Sie können TUI-spezifische Einstellungen über die Option `tui` konfigurieren. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +Verfügbare Optionen: + +- `scroll_acceleration.enabled` – Scrollbeschleunigung im macOS-Stil aktivieren. **Hat Vorrang vor `scroll_speed`.** +- `scroll_speed` – Benutzerdefinierter Scrollgeschwindigkeitsmultiplikator (Standard: `3`, Minimum: `1`). Wird ignoriert, wenn `scroll_acceleration.enabled` gleich `true` ist. +- `diff_style` – Steuern Sie das Diff-Rendering. `"auto"` passt sich der Terminalbreite an, `"stacked"` zeigt immer eine einzelne Spalte an. + +[Learn more about using the TUI here](/docs/tui). + +--- + +### Server + +Sie können Servereinstellungen für die Befehle `opencode serve` und `opencode web` über die Option `server` konfigurieren. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +Verfügbare Optionen: + +- `port` – Port zum Abhören. +- `hostname` – Hostname zum Abhören. Wenn `mdns` aktiviert ist und kein Hostname festgelegt ist, wird standardmäßig `0.0.0.0` verwendet. +- `mdns` – mDNS-Diensterkennung aktivieren. Dadurch können andere Geräte im Netzwerk Ihres OpenCode-Servers erkannt werden. +- `mdnsDomain` – Benutzerdefinierter Domänenname für den mDNS-Dienst. Standardmäßig ist `opencode.local`. Nützlich für die Ausführung mehrerer Instanzen im selben Netzwerk. +- `cors` – Zusätzliche Ursprünge, um CORS zu ermöglichen, wenn der HTTP-Server von einem browserbasierten Client aus verwendet wird. Die Werte müssen vollständige Ursprünge haben (Schema + Host + optionaler Port), z. B. `https://app.example.com`. + +[Learn more about the server here](/docs/server). + +--- + +### Tools + +Sie können die Tools, die ein LLM verwenden kann, über die Option `tools` verwalten. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[Learn more about tools here](/docs/tools). + +--- + +### Models + +Sie können die Anbieter und Modelle, die Sie in Ihrer OpenCode-Konfiguration verwenden möchten, über die Optionen `provider`, `model` und `small_model` konfigurieren. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +Die Option `small_model` konfiguriert ein separates Modell für einfache Aufgaben wie die Titelgenerierung. Standardmäßig versucht OpenCode, ein günstigeres Modell zu verwenden, sofern eines bei Ihrem Anbieter verfügbar ist, andernfalls greift es auf Ihr Hauptmodell zurück. + +Zu den Anbieteroptionen können `timeout` und `setCacheKey` gehören: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` – Anforderungszeitlimit in Millisekunden (Standard: 300000). Zum Deaktivieren auf `false` setzen. +- `setCacheKey` – Stellen Sie sicher, dass immer ein Cache-Schlüssel für den angegebenen Anbieter festgelegt ist. + +Sie können auch [local models](/docs/models#local) konfigurieren. [Learn more](/docs/models). + +--- + +#### Anbieterspezifische Optionen + +Einige Anbieter unterstützen zusätzliche Konfigurationsoptionen über die allgemeinen Einstellungen `timeout` und `apiKey` hinaus. + +##### Amazonas-Grundgestein + +Amazon Bedrock unterstützt AWS-spezifische Konfigurationen: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` – AWS-Region für Bedrock (standardmäßig `AWS_REGION` env var oder `us-east-1`) +- `profile` – AWS benanntes Profil von `~/.aws/credentials` (standardmäßig `AWS_PROFILE` Umgebungsvariable) +- `endpoint` – Benutzerdefinierter Endpunkt URL für VPC-Endpunkte. Dies ist ein Alias ​​​​für die generische Option `baseURL` unter Verwendung der AWS-spezifischen Terminologie. Wenn beide angegeben sind, hat `endpoint` Vorrang. + +:::note +Inhabertoken (`AWS_BEARER_TOKEN_BEDROCK` oder `/connect`) haben Vorrang vor der profilbasierten Authentifizierung. Weitere Informationen finden Sie unter [authentication precedence](/docs/providers#authentication-precedence). +::: + +[Learn more about Amazon Bedrock configuration](/docs/providers#amazon-bedrock). + +--- + +### Themes + +Sie können das Thema, das Sie in Ihrer OpenCode-Konfiguration verwenden möchten, über die Option `theme` konfigurieren. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[Learn more here](/docs/themes). + +--- + +### Agents + +Über die Option `agent` können Sie spezielle Agenten für bestimmte Aufgaben konfigurieren. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +Sie können Agenten auch mithilfe von Markdown-Dateien in `~/.config/opencode/agents/` oder `.opencode/agents/` definieren. [Learn more here](/docs/agents). + +--- + +### Standardagent + +Sie können den Standardagenten mit der Option `default_agent` festlegen. Dadurch wird bestimmt, welcher Agent verwendet wird, wenn keiner explizit angegeben wird. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +Der Standardagent muss ein Primäragent (kein Subagent) sein. Dies kann ein integrierter Agent wie `"build"` oder `"plan"` oder ein von Ihnen definierter [custom agent](/docs/agents) sein. Wenn der angegebene Agent nicht existiert oder ein Subagent ist, greift OpenCode mit einer Warnung auf `"build"` zurück. + +Diese Einstellung gilt für alle Schnittstellen: TUI, CLI (`opencode run`), Desktop-App und GitHub Aktion. + +--- + +### Sharing + +Sie können die Funktion [share](/docs/share) über die Option `share` konfigurieren. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +Dazu braucht es: + +- `"manual"` – Manuelles Teilen über Befehle zulassen (Standard) +- `"auto"` – Neue Konversationen automatisch teilen +- `"disabled"` – Teile vollständig deaktivieren + +Standardmäßig ist die Freigabe auf den manuellen Modus eingestellt, in dem Sie Konversationen explizit mit dem Befehl `/share` teilen müssen. + +--- + +### Befehle + +Sie können benutzerdefinierte Befehle für sich wiederholende Aufgaben über die Option `command` konfigurieren. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +Sie können Befehle auch mithilfe von Markdown-Dateien in `~/.config/opencode/commands/` oder `.opencode/commands/` definieren. [Learn more here](/docs/commands). + +--- + +### Keybinds + +Sie können Ihre Tastenkombinationen über die Option `keybinds` anpassen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[Learn more here](/docs/keybinds). + +--- + +### Autoupdate + +OpenCode lädt beim Start automatisch alle neuen Updates herunter. Sie können dies mit der Option `autoupdate` deaktivieren. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +Wenn Sie keine Updates wünschen, aber dringend möchten, wenn eine neue Version verfügbar ist, setzen Sie `autoupdate` auf `"notify"`. +Beachten Sie, dass dies nur funktioniert, wenn es nicht mit einem Paketmanager wie Homebrew installiert wurde. + +--- + +### Formatters + +Sie können Codeformatierer über die Option `formatter` konfigurieren. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[Learn more about formatters here](/docs/formatters). + +--- + +### Permissions + +Opencode erlaubt standardmäßig alle Vorgänge, ohne dass eine ausdrückliche Genehmigung erforderlich ist. Sie können dies mit der Option `permission` ändern. + +Um beispielsweise sicherzustellen, dass die Tools `edit` und `bash` eine Benutzergenehmigung erfordern: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[Learn more about permissions here](/docs/permissions). + +--- + +### Compaction + +Sie können das Verhalten der Kontextkomprimierung über die Option `compaction` steuern. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` – Die Sitzung wird automatisch komprimieren, wenn der Kontext voll ist (Standard: `true`). +- `prune` – Alte Tool-Ausgaben entfernen, um Token zu sparen (Standard: `true`). + +--- + +### Watcher + +Sie können Datei-Watcher-Ignoriermuster über die Option `watcher` konfigurieren. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +Muster folgen der Glob-Syntax. Verwenden Sie diese Option, um verrauschte Verzeichnisse von der Dateiüberwachung auszuschließen. + +--- + +### MCP Server + +Sie können den MCP-Server, den Sie verwenden möchten, über die Option `mcp` konfigurieren. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[Learn more here](/docs/mcp-servers). + +--- + +### Plugins + +[Plugins](/docs/plugins) erweitert OpenCode mit benutzerdefinierten Tools, Hooks und Integrationen. + +Platzieren Sie Ihre Plugin-Dateien in `.opencode/plugins/` oder `~/.config/opencode/plugins/`. Sie können Plugins auch über die Option `plugin` von npm laden. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[Learn more here](/docs/plugins). + +--- + +### Instructions + +Sie können die Anweisungen für das von Ihnen verwendete Modell über die Option `instructions` konfigurieren. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Dies erfordert eine Reihe von Pfaden und Glob-Mustern zu Anweisungsdateien. [Erfahren Sie mehr +über Regeln hier](/docs/rules). + +--- + +### Behinderte Anbieter + +Sie können Anbieter, die automatisch geladen werden, über die Option `disabled_providers` deaktivieren. Dies ist nützlich, wenn Sie verhindern möchten, dass bestimmte Anbieter geladen werden, selbst wenn deren Anmeldeinformationen verfügbar sind. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +Der `disabled_providers` hat Vorrang vor `enabled_providers`. +::: + +Die Option `disabled_providers` akzeptiert ein Array des Anbieters IDs. Wenn ein Anbieter deaktiviert ist: + +- Es wird nicht geladen, selbst wenn Umgebungsvariablen festgelegt sind. +- Es wird nicht geladen, selbst wenn API-Schlüssel über den Befehl `/connect` konfiguriert werden. +- Die Modelle des Anbieters erscheinen nicht in der Modellauswahlliste. + +--- + +### Aktivierte Anbieter + +Sie können über die Option `enabled_providers` eine Zulassungsliste für Anbieter angeben. Wenn diese Option festgelegt ist, werden nur die angegebenen Anbieter aktiviert und alle anderen werden ignoriert. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +Dies ist nützlich, wenn Sie OpenCode darauf beschränken möchten, nur bestimmte Anbieter zu verwenden, anstatt sie einzeln zu deaktivieren. + +:::note +Der `disabled_providers` hat Vorrang vor `enabled_providers`. +::: + +Wenn ein Anbieter sowohl in `enabled_providers` als auch in `disabled_providers` vorkommt, hat `disabled_providers` aus Gründen der Abwärtskompatibilität Vorrang. + +--- + +### Experimental + +Der Schlüssel `experimental` enthält Optionen, die sich in der aktiven Entwicklung befinden. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::caution +Experimentelle Optionen sind nicht stabil. Sie können ohne vorherige Ankündigung geändert oder entfernt werden. +::: + +--- + +## Variables + +Sie können die Variablenersetzung in Ihren Konfigurationsdateien verwenden, um auf Umgebungsvariablen und Dateiinhalte zu verweisen. + +--- + +### Umgebungsvars + +Verwenden Sie `{env:VARIABLE_NAME}`, um Umgebungsvariablen zu ersetzen: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +Wenn die Umgebungsvariable nicht gesetzt ist, wird sie durch eine leere Zeichenfolge ersetzt. + +--- + +### Files + +Verwenden Sie `{file:path/to/file}`, um den Inhalt einer Datei zu ersetzen: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +Dateipfade können sein: + +- Relativ zum Konfigurationsdateiverzeichnis +- Oder absolute Pfade beginnend mit `/` oder `~` + +Diese sind nützlich für: + +- Bewahren Sie vertrauliche Daten wie API-Schlüssel in separaten Dateien auf. +- Einschließlich große Anweisungsdateien, ohne Ihre Konfiguration zu überladen. +- Gemeinsame Nutzung gemeinsamer Konfigurationsausschnitte über mehrere Konfigurationsdateien hinweg. diff --git a/packages/web/src/content/docs/de/custom-tools.mdx b/packages/web/src/content/docs/de/custom-tools.mdx new file mode 100644 index 000000000..3b89ac1d8 --- /dev/null +++ b/packages/web/src/content/docs/de/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: Benutzerdefinierte Werkzeuge +description: Erstellen Sie Tools, die der LLM in Opencode aufrufen kann. +--- + +Benutzerdefinierte Tools sind von Ihnen erstellte Funktionen, die der LLM während Gesprächen aufrufen kann. Sie arbeiten neben [built-in tools](/docs/tools) von Opencode wie `read`, `write` und `bash`. + +--- + +## Ein Werkzeug erstellen + +Werkzeuge werden als **TypeScript**- oder **JavaScript**-Dateien definiert. Die Werkzeugdefinition kann jedoch Skripte aufrufen, die in **jeder Sprache** geschrieben sind – TypeScript oder JavaScript wird nur für die Werkzeugdefinition selbst verwendet. + +--- + +### Location + +Sie können wie folgt definiert werden: + +- Lokal, indem Sie sie im Verzeichnis `.opencode/tools/` Ihres Projekts platzieren. +- Oder global, indem Sie sie in `~/.config/opencode/tools/` platzieren. + +--- + +### Structure + +Der einfachste Weg, Tools zu erstellen, ist die Verwendung des `tool()`-Helfers, der Typsicherheit und Validierung bietet. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +Der **Dateiname** wird zum **Toolnamen**. Das Obige erstellt ein `database`-Tool. + +--- + +#### Mehrere Werkzeuge pro Datei + +Sie können auch mehrere Tools aus einer einzigen Datei exportieren. Jeder Export wird zu **einem separaten Tool** mit dem Namen **`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +Dadurch werden zwei Tools erstellt: `math_add` und `math_multiply`. + +--- + +### Arguments + +Sie können `tool.schema` verwenden, was nur [Zod](https://zod.dev) ist, um Argumenttypen zu definieren. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +Sie können [Zod](https://zod.dev) auch direkt importieren und ein ähnliches Objekt zurückgeben: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### Context + +Tools erhalten Kontext zur aktuellen Sitzung: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +Verwenden Sie `context.directory` für das Sitzungsarbeitsverzeichnis. +Verwenden Sie `context.worktree` für das Stammverzeichnis des Git-Arbeitsbaums. + +--- + +## Examples + +### Schreiben Sie ein Tool in Python + +Sie können Ihre Tools in jeder gewünschten Sprache schreiben. Hier ist ein Beispiel, das mit Python zwei Zahlen addiert. + +Erstellen Sie zunächst das Tool als Python-Skript: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +Erstellen Sie dann die Werkzeugdefinition, die es aufruft: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +Hier verwenden wir das Dienstprogramm [`Bun.$`](https://bun.com/docs/runtime/shell), um das Python-Skript auszuführen. diff --git a/packages/web/src/content/docs/de/ecosystem.mdx b/packages/web/src/content/docs/de/ecosystem.mdx new file mode 100644 index 000000000..8f0070459 --- /dev/null +++ b/packages/web/src/content/docs/de/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: Ökosystem +description: Mit OpenCode erstellte Projekte und Integrationen. +--- + +Eine Sammlung von Community-Projekten, die auf OpenCode basieren. + +:::note +Möchten Sie Ihr OpenCode-bezogenes Projekt zu dieser Liste hinzufügen? Senden Sie einen PR. +::: + +Sie können sich auch [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) und [opencode.cafe](https://opencode.cafe) ansehen, eine Community, die das Ökosystem und die Community zusammenfasst. + +--- + +## Plugins + +| Name | Beschreibung | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | Führen Sie OpenCode-Sitzungen automatisch in isolierten Daytona-Sandboxes mit Git-Synchronisierung und Live-Vorschauen aus | +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Helicone-Sitzungsheader für die Anforderungsgruppierung automatisch einfügen | +| [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | TypeScript/Svelte-Typen mit Suchtools automatisch in Dateilesevorgänge einfügen | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Verwenden Sie Ihr ChatGPT Plus/Pro-Abonnement anstelle von API Credits | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Verwenden Sie Ihren bestehenden Gemini-Plan anstelle der API-Abrechnung | +| [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Nutzen Sie die kostenlosen Modelle von Antigravity anstelle der API-Abrechnung | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Multi-Branch-Devcontainer-Isolierung mit flachen Klonen und automatisch zugewiesenen Ports | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Antigravity OAuth-Plugin mit Unterstützung für die Google-Suche und robustere API-Verarbeitung | +| [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Optimieren Sie die Token-Nutzung, indem Sie veraltete Tool-Ausgaben bereinigen | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Fügen Sie native Websuchunterstützung für unterstützte Anbieter mit Google Grounded Style hinzu | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Ermöglicht AI-Agenten, Hintergrundprozesse in einem PTY auszuführen und ihnen interaktive Eingaben zu senden. | +| [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Anweisungen für nicht interaktive Shell-Befehle – verhindert Abstürze bei TTY-abhängigen Vorgängen | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Verfolgen Sie die Nutzung von OpenCode mit Wakatime | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Von LLMs | erstellte Abschriftentabellen bereinigen +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | 10x schnellere Codebearbeitung mit Morph Fast Apply API und Lazy-Edit-Markern | +| [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Hintergrundagenten, vorgefertigte LSP/AST/MCP-Tools, kuratierte Agenten, Claude Code-kompatibel | +| [opencode-notificator](https://github.com/panta82/opencode-notificator) | Desktop-Benachrichtigungen und akustische Warnungen für OpenCode-Sitzungen | +| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Desktop-Benachrichtigungen und akustische Warnungen für Berechtigungs-, Abschluss- und Fehlerereignisse | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | AI-gestützte automatische Benennung von Zellij-Sitzungen basierend auf dem OpenCode-Kontext | +| [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Ermöglichen Sie OpenCode-Agenten das verzögerte Laden von Eingabeaufforderungen bei Bedarf mit Skill-Erkennung und -Injektion | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Persistenter Speicher über Sitzungen hinweg mit Supermemory | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Interaktive Planüberprüfung mit visueller Anmerkung und private/offline-Freigabe | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Erweitern Sie Opencode /commands zu einem leistungsstarken Orchestrierungssystem mit granularer Flusskontrolle | +| [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Planen Sie wiederkehrende Jobs mit launchd (Mac) oder systemd (Linux) mit Cron-Syntax | +| [micode](https://github.com/vtemian/micode) | Strukturiertes Brainstorming → Planen → Workflow mit Sitzungskontinuität Implementierung | +| [octto](https://github.com/vtemian/octto) | Interaktiver Browser UI für AI Brainstorming mit Formularen mit mehreren Fragen | +| [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Hintergrundagenten im Claude Code-Stil mit asynchroner Delegation und Kontextpersistenz | +| [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Native OS-Benachrichtigungen für OpenCode – wissen, wann Aufgaben erledigt sind | +| [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Gebündelter Multi-Agent-Orchestrierungs-Harness – 16 Komponenten, eine Installation | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Reibungslose Git-Arbeitsbäume für OpenCode | + +--- + +## Projects + +| Name | Beschreibung | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | Discord-Bot zur Steuerung von OpenCode-Sitzungen, basierend auf SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Neovim-Plugin für editorfähige Eingabeaufforderungen, basierend auf API | +| [portal](https://github.com/hosenur/portal) | Mobile-First-Web UI für OpenCode über Tailscale/VPN | +| [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | Vorlage zum Erstellen von OpenCode-Plugins | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Neovim-Frontend für Opencode – ein terminalbasierter AI-Coding-Agent | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Vercel AI SDK Anbieter für die Verwendung von OpenCode über @opencode-ai/sdk | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | Web-/Desktop-App und VS Code-Erweiterung für OpenCode | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Obsidian-Plugin, das OpenCode in Obsidians UI | einbettet +| [OpenWork](https://github.com/different-ai/openwork) | Eine Open-Source-Alternative zu Claude Cowork, unterstützt von OpenCode | +| [ocx](https://github.com/kdcokenny/ocx) | OpenCode Erweiterungsmanager mit portablen, isolierten Profilen. | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Desktop-, Web-, Mobil- und Remote-Client-App für OpenCode | + +--- + +## Agents + +| Name | Beschreibung | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [Agentic](https://github.com/Cluster444/agentic) | Modulare AI-Agenten und -Befehle für strukturierte Entwicklung | +| [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Konfigurationen, Eingabeaufforderungen, Agenten und Plugins für verbesserte Arbeitsabläufe | diff --git a/packages/web/src/content/docs/de/enterprise.mdx b/packages/web/src/content/docs/de/enterprise.mdx new file mode 100644 index 000000000..adb0f05f5 --- /dev/null +++ b/packages/web/src/content/docs/de/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: Unternehmen +description: Sichere Verwendung von OpenCode in Ihrem Unternehmen. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise ist für Organisationen gedacht, die sicherstellen möchten, dass ihr Code und ihre Daten niemals ihre Infrastruktur verlassen. Dies kann durch die Verwendung einer zentralen Konfiguration erreicht werden, die in Ihr SSO- und internes AI-Gateway integriert ist. + +:::note +OpenCode speichert keine Ihrer Code- oder Kontextdaten. +::: + +So starten Sie mit OpenCode Enterprise: + +1. Führen Sie einen internen Test mit Ihrem Team durch. +2. **Kontaktieren Sie uns**, um Preise und Implementierungsoptionen zu besprechen. + +--- + +## Trial + +OpenCode ist Open Source und speichert keine Ihrer Code- oder Kontextdaten, sodass Ihr Entwickler einfach [get started](/docs/) und eine Testversion durchführen kann. + +--- + +### Datenverarbeitung + +**OpenCode speichert Ihren Code oder Ihre Kontextdaten nicht.** Die gesamte Verarbeitung erfolgt lokal oder durch direkte API-Aufrufe an Ihren AI-Anbieter. + +Das heißt, solange Sie einen Anbieter Ihres Vertrauens oder einen internen nutzen +AI-Gateway können Sie OpenCode sicher verwenden. + +Die einzige Einschränkung hier ist die optionale Funktion `/share`. + +--- + +#### Gespräche teilen + +Wenn ein Benutzer die Funktion `/share` aktiviert, werden die Konversation und die damit verbundenen Daten an den Dienst gesendet, den wir zum Hosten dieser Freigabeseiten unter opencode.ai verwenden. + +Die Daten werden derzeit über das Edge-Netzwerk unseres CDN bereitgestellt und am Edge in der Nähe Ihres Benutzers zwischengespeichert. + +Wir empfehlen Ihnen, dies für Ihre Testversion zu deaktivieren. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[Learn more about sharing](/docs/share). + +--- + +### Code-Besitz + +**Der gesamte von OpenCode erstellte Code gehört Ihnen.** Es bestehen keine Lizenzbeschränkungen oder Eigentumsansprüche. + +--- + +## Pricing + +Für OpenCode Enterprise verwenden wir ein Pro-Sitz-Modell. Wenn Sie über ein eigenes LLM-Gateway verfügen, berechnen wir keine Gebühren für die verwendeten Token. Für weitere Informationen zu Preisen und Implementierungsoptionen **kontaktieren Sie uns**. + +--- + +## Deployment + +Sobald Sie Ihre Testversion abgeschlossen haben und bereit sind, OpenCode unter zu verwenden +Für Ihre Organisation können Sie **uns kontaktieren**, um dies zu besprechen +Preisgestaltung und Umsetzungsmöglichkeiten. + +--- + +### Zentrale Konfiguration + +Wir können OpenCode so einrichten, dass eine einzige zentrale Konfiguration für Ihre gesamte Organisation verwendet wird. + +Diese zentralisierte Konfiguration kann in Ihren SSO-Anbieter integriert werden und stellt sicher, dass alle Benutzer nur auf Ihr internes AI-Gateway zugreifen. + +--- + +### SSO-Integration + +Über die zentrale Konfiguration kann OpenCode zur Authentifizierung in den SSO-Anbieter Ihrer Organisation integriert werden. + +Dadurch kann OpenCode Anmeldeinformationen für Ihr internes AI-Gateway über Ihr eigenes Identitätsverwaltungssystem abrufen. + +--- + +### Internes AI-Gateway + +Mit der zentralen Konfiguration kann OpenCode auch so konfiguriert werden, dass nur Ihr internes AI-Gateway verwendet wird. + +Sie können auch alle anderen AI-Anbieter deaktivieren und so sicherstellen, dass alle Anfragen über die genehmigte Infrastruktur Ihrer Organisation laufen. + +--- + +### Self-hosting + +Wir empfehlen jedoch, die Freigabeseiten zu deaktivieren, um sicherzustellen, dass Ihre Daten niemals verloren gehen +In Ihrer Organisation können wir Ihnen auch dabei helfen, sie selbst in Ihrer Infrastruktur zu hosten. + +Dies steht derzeit auf unserer Roadmap. Wenn Sie Interesse haben, **lassen Sie es uns wissen**. + +--- + +## FAQ + +

+What is OpenCode Enterprise? + +OpenCode Enterprise ist für Organisationen gedacht, die sicherstellen möchten, dass ihr Code und ihre Daten niemals ihre Infrastruktur verlassen. Dies kann durch die Verwendung einer zentralen Konfiguration erreicht werden, die in Ihr SSO- und internes AI-Gateway integriert ist. + +
+ +
+How do I get started with OpenCode Enterprise? + +Beginnen Sie einfach mit einem internen Test mit Ihrem Team. OpenCode speichert standardmäßig weder Ihren Code noch Ihre Kontextdaten, was den Einstieg erleichtert. + +Dann **kontaktieren Sie uns**, um Preise und Implementierungsoptionen zu besprechen. + +
+ +
+How does enterprise pricing work? + +Wir bieten Enterprise-Preise pro Sitzplatz an. Wenn Sie über ein eigenes LLM-Gateway verfügen, berechnen wir keine Gebühren für die verwendeten Token. Für weitere Informationen **kontaktieren Sie uns** für ein individuelles Angebot, das auf die Bedürfnisse Ihrer Organisation zugeschnitten ist. + +
+ +
+Is my data secure with OpenCode Enterprise? + +Ja. OpenCode speichert Ihren Code oder Ihre Kontextdaten nicht. Die gesamte Verarbeitung erfolgt lokal oder durch direkte API-Anrufe an Ihren AI-Anbieter. Dank zentraler Konfiguration und SSO-Integration bleiben Ihre Daten innerhalb der Infrastruktur Ihres Unternehmens sicher. + +
+ +
+Can we use our own private NPM registry? + +OpenCode unterstützt private NPM-Registrierungen durch Buns native `.npmrc`-Dateiunterstützung. Wenn Ihre Organisation eine private Registrierung wie JFrog Artifactory, Nexus oder ähnliches verwendet, stellen Sie sicher, dass der Entwickler authentifiziert ist, bevor Sie OpenCode ausführen. + +So richten Sie die Authentifizierung mit Ihrer privaten Registrierung ein: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +Dadurch wird `~/.npmrc` mit Authentifizierungsdetails erstellt. OpenCode wird automatisch +Hebe das auf. + +:::caution +Sie müssen bei der privaten Registrierung angemeldet sein, bevor Sie OpenCode ausführen. +::: + +Alternativ können Sie eine `.npmrc`-Datei manuell konfigurieren: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Entwickler müssen vor der Ausführung von OpenCode bei der privaten Registrierung angemeldet sein, um sicherzustellen, dass Pakete aus Ihrer Unternehmensregistrierung installiert werden können. + +
diff --git a/packages/web/src/content/docs/de/formatters.mdx b/packages/web/src/content/docs/de/formatters.mdx new file mode 100644 index 000000000..f5301ea97 --- /dev/null +++ b/packages/web/src/content/docs/de/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: Formatierer +description: OpenCode verwendet sprachspezifische Formatierer. +--- + +OpenCode formatiert Dateien automatisch, nachdem sie mit sprachspezifischen Formatierern geschrieben oder bearbeitet wurden. Dadurch wird sichergestellt, dass der generierte Code dem Codestil Ihres Projekts entspricht. + +--- + +## Eingebaut + +OpenCode verfügt über mehrere integrierte Formatierer für gängige Sprachen und Frameworks. Nachfolgend finden Sie eine Liste der Formatierer, unterstützten Dateierweiterungen und benötigten Befehle oder Konfigurationsoptionen. + +| Formatierer | Erweiterungen | Anforderungen | +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| gofmt | .go | `gofmt`-Befehl verfügbar | +| mischen | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix`-Befehl verfügbar | +| hübscher | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml und [more](https://prettier.io/docs/en/index.html) | `prettier`-Abhängigkeit in `package.json` | +| Biom | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml und [more](https://biomejs.dev/) | `biome.json(c)` Konfigurationsdatei | +| Zickzack | .zig, .zon | `zig`-Befehl verfügbar | +| clang-format | .c, .cpp, .h, .hpp, .ino und [more](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` Konfigurationsdatei | +| ktlint | .kt, .kts | `ktlint`-Befehl verfügbar | +| Halskrause | .py, .pyi | `ruff`-Befehl verfügbar mit config | +| rustfmt | .rs | `rustfmt`-Befehl verfügbar | +| frachtfmt | .rs | `cargo fmt`-Befehl verfügbar | +| UV | .py, .pyi | `uv`-Befehl verfügbar | +| rubocop | .rb, .rake, .gemspec, .ru | `rubocop`-Befehl verfügbar | +| standardrb | .rb, .rake, .gemspec, .ru | `standardrb`-Befehl verfügbar | +| htmlbeautifier | .erb, .html.erb | `htmlbeautifier`-Befehl verfügbar | +| Luft | .R | `air`-Befehl verfügbar | +| Dart | .dart | `dart`-Befehl verfügbar | +| ocamlformat | .ml, .mli | `ocamlformat` Befehl verfügbar und `.ocamlformat` Konfigurationsdatei | +| Terraform | .tf, .tfvars | `terraform`-Befehl verfügbar | +| Glanz | .glanz | `gleam`-Befehl verfügbar | +| nixfmt | .nix | `nixfmt`-Befehl verfügbar | +| shfmt | .sh, .bash | `shfmt`-Befehl verfügbar | +| Pint | .php | `laravel/pint`-Abhängigkeit in `composer.json` | +| oxfmt (Experimentell) | .js, .jsx, .ts, .tsx | `oxfmt`-Abhängigkeit in `package.json` und einer [experimental env variable flag](/docs/cli/#experimental) | +| Ormolu | .hs | `ormolu`-Befehl verfügbar | + +Wenn Ihr Projekt auch `prettier` in Ihrem `package.json` hat, wird OpenCode automatisch verwendet. + +--- + +## Wie es funktioniert + +Wenn OpenCode eine Datei schreibt oder bearbeitet, geschieht Folgendes: + +1. Überprüft die Dateierweiterung anhand aller aktivierten Formatierer. +2. Führt den entsprechenden Formatierungsbefehl für die Datei aus. +3. Wendet die Formatierungsänderungen automatisch an. + +Dieser Prozess findet im Hintergrund statt und stellt sicher, dass Ihr Codestile ohne manuelle Schritte beibehalten werden. + +--- + +## Konfigurieren + +Sie können Formatierer über den Abschnitt `formatter` in Ihrer OpenCode-Konfiguration anpassen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +Jede Formatierungskonfiguration unterstützt Folgendes: + +| Eigentum | Geben Sie | eine Beschreibung | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` | boolescher Wert | Setzen Sie dies auf `true`, um den Formatierer | zu deaktivieren +| `command` | string[] | Der zum Formatieren auszuführende Befehl | +| `environment` | Objekt | Umgebungsvariablen, die beim Ausführen des Formatierers | festgelegt werden sollen +| `extensions` | string[] | Dateierweiterungen, die dieser Formatierer verarbeiten soll | + +Schauen wir uns einige Beispiele an. + +--- + +### Formatierer deaktivieren + +Um **alle** Formatierer global zu deaktivieren, setzen Sie `formatter` auf `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +Um einen **bestimmten** Formatierer zu deaktivieren, setzen Sie `disabled` auf `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Benutzerdefinierter Formatierer + +Sie können den integrierten Formatierer überschreiben oder neu hinzufügen, indem Sie den Befehl, Umgebungsvariablen und Dateierweiterungen angeben: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +Der Platzhalter **`$FILE`** im Befehl wird durch den Pfad zur zu formatierenden Datei ersetzt. diff --git a/packages/web/src/content/docs/de/github.mdx b/packages/web/src/content/docs/de/github.mdx new file mode 100644 index 000000000..fe20cbe21 --- /dev/null +++ b/packages/web/src/content/docs/de/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: Verwenden Sie OpenCode in GitHub-Problemen und Pull-Requests. +--- + +OpenCode lässt sich in Ihren GitHub-Workflow integrieren. Erwähnen Sie `/opencode` oder `/oc` in Ihrem Kommentar, und OpenCode führt Aufgaben in Ihrem GitHub Actions-Runner aus. + +--- + +## Features + +- **Triage-Probleme**: Bitten Sie OpenCode, ein Problem zu untersuchen und es Ihnen zu erklären. +- **Reparieren und implementieren**: Bitten Sie OpenCode, ein Problem zu beheben oder eine Funktion zu implementieren. Und es funktioniert in einem neuen Zweig und sendet ein PR mit allen Änderungen. +- **Sicher**: OpenCode läuft in den Runnern Ihres GitHub. + +--- + +## Installation + +Führen Sie den folgenden Befehl in einem Projekt aus, das sich in einem GitHub-Repository befindet: + +```bash +opencode github install +``` + +Dies führt Sie durch die Installation der GitHub-App, das Erstellen des Workflows und das Einrichten von Geheimnissen. + +--- + +### Manuelle Einrichtung + +Oder Sie können es manuell einrichten. + +1. **Installieren Sie die GitHub-App** + + Gehen Sie zu [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). Stellen Sie sicher, dass es im Ziel-Repository installiert ist. + +2. **Den Workflow hinzufügen** + + Fügen Sie die folgende Workflowdatei zu `.github/workflows/opencode.yml` in Ihrem Repository hinzu. Stellen Sie sicher, dass Sie in `env` die entsprechenden Schlüssel `model` und API festlegen. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **Speichern Sie die API-Schlüssel in Geheimnissen** + + Erweitern Sie in den **Einstellungen** Ihrer Organisation oder Ihres Projekts links **Geheimnisse und Variablen** und wählen Sie **Aktionen** aus. Und fügen Sie die erforderlichen API-Schlüssel hinzu. + +--- + +## Configuration + +- `model`: Das mit OpenCode zu verwendende Modell. Nimmt das Format `provider/model` an. Dies ist **erforderlich**. +- `agent`: Der zu verwendende Agent. Muss ein Hauptagent sein. Fällt aus der Konfiguration auf `default_agent` oder `"build"` zurück, wenn es nicht gefunden wird. +- `share`: Ob die OpenCode-Sitzung geteilt werden soll. Der Standardwert ist **true** für öffentliche Repositorys. +- `prompt`: Optionale benutzerdefinierte Eingabeaufforderung zum Überschreiben des Standardverhaltens. Verwenden Sie dies, um anzupassen, wie OpenCode Anfragen verarbeitet. +- `token`: Optionales GitHub-Zugriffstoken zum Ausführen von Vorgängen wie dem Erstellen von Kommentaren, dem Festschreiben von Änderungen und dem Öffnen von Pull-Anfragen. Standardmäßig verwendet OpenCode das Installationszugriffstoken der OpenCode GitHub-App, sodass Commits, Kommentare und Pull-Anfragen so aussehen, als würden sie von der App kommen. + + Alternativ können Sie [built-in `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) des GitHub Action Runners verwenden, ohne die OpenCode GitHub App zu installieren. Stellen Sie einfach sicher, dass Sie in Ihrem Workflow die erforderlichen Berechtigungen erteilen: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + Sie können bei Bedarf auch einen [personal access tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) verwenden. + +--- + +## Unterstützte Veranstaltungen + +OpenCode kann durch die folgenden GitHub-Ereignisse ausgelöst werden: + +| Ereignistyp | Ausgelöst durch | Einzelheiten | +| ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | Kommentieren Sie ein Problem oder PR | Erwähnen Sie `/opencode` oder `/oc` in Ihrem Kommentar. OpenCode liest den Kontext und kann Verzweigungen erstellen, PRs öffnen oder antworten. | +| `pull_request_review_comment` | Kommentieren Sie bestimmte Codezeilen in einem PR | Erwähnen Sie `/opencode` oder `/oc` beim Überprüfen des Codes. OpenCode empfängt Dateipfad, Zeilennummern und Diff-Kontext. | +| `issues` | Problem geöffnet oder bearbeitet | Lösen Sie OpenCode automatisch aus, wenn Probleme erstellt oder geändert werden. Erfordert `prompt`-Eingabe. | +| `pull_request` | PR geöffnet oder aktualisiert | Lösen Sie OpenCode automatisch aus, wenn PRs geöffnet, synchronisiert oder erneut geöffnet werden. Nützlich für automatisierte Bewertungen. | +| `schedule` | Cron-basierter Zeitplan | Führen Sie OpenCode nach einem Zeitplan aus. Erfordert `prompt`-Eingabe. Die Ausgabe geht an Protokolle und PRs (kein Kommentar zu diesem Problem). | +| `workflow_dispatch` | Manueller Trigger von GitHub UI | Lösen Sie OpenCode bei Bedarf über die Registerkarte „Aktionen“ aus. Erfordert `prompt`-Eingabe. Die Ausgabe erfolgt an Protokolle und PRs. | + +### Beispiel für einen Zeitplan + +Führen Sie OpenCode nach einem Zeitplan aus, um automatisierte Aufgaben auszuführen: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +Für geplante Ereignisse ist die Eingabe `prompt` **erforderlich**, da es keinen Kommentar gibt, aus dem Anweisungen extrahiert werden können. Geplante Workflows werden ohne Benutzerkontext zur Berechtigungsprüfung ausgeführt. Daher muss der Workflow `contents: write` und `pull-requests: write` gewähren, wenn Sie erwarten, dass OpenCode Zweige oder PRs erstellt. + +--- + +### Pull-Request-Beispiel + +Überprüfen Sie PRs automatisch, wenn sie geöffnet oder aktualisiert werden: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Wenn für `pull_request`-Ereignisse kein `prompt` bereitgestellt wird, überprüft OpenCode standardmäßig die Pull-Anfrage. + +--- + +### Beispiel für eine Triage von Problemen + +Neue Probleme automatisch selektieren. In diesem Beispiel wird nach Konten gefiltert, die älter als 30 Tage sind, um Spam zu reduzieren: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +Für `issues`-Ereignisse ist die Eingabe `prompt` **erforderlich**, da es keinen Kommentar gibt, aus dem Anweisungen extrahiert werden können. + +--- + +## Benutzerdefinierte Eingabeaufforderungen + +Überschreiben Sie die Standardaufforderung, um das Verhalten von OpenCode für Ihren Workflow anzupassen. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Dies ist nützlich, um bestimmte Prüfkriterien, Kodierungsstandards oder Schwerpunktbereiche durchzusetzen, die für Ihr Projekt relevant sind. + +--- + +## Examples + +Hier sind einige Beispiele, wie Sie OpenCode in GitHub verwenden können. + +- **Erklären Sie ein Problem** + + Fügen Sie diesen Kommentar in einer GitHub-Ausgabe hinzu. + + ``` + /opencode explain this issue + ``` + + OpenCode liest den gesamten Thread, einschließlich aller Kommentare, und antwortet mit einer klaren Erklärung. + +- **Ein Problem beheben** + + Sagen Sie in einer GitHub-Ausgabe: + + ``` + /opencode fix this + ``` + + Und OpenCode erstellt einen neuen Zweig, implementiert die Änderungen und öffnet ein PR mit den Änderungen. + +- **PRs überprüfen und Änderungen vornehmen** + + Hinterlassen Sie den folgenden Kommentar auf einem GitHub PR. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + OpenCode implementiert die angeforderte Änderung und schreibt sie an denselben PR fest. + +- **Überprüfen Sie bestimmte Codezeilen** + + Hinterlassen Sie einen Kommentar direkt zu den Codezeilen auf der Registerkarte „Dateien“ von PR. OpenCode erkennt automatisch die Datei, Zeilennummern und den Diff-Kontext, um präzise Antworten bereitzustellen. + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + Beim Kommentieren bestimmter Zeilen erhält OpenCode: + - Die genaue Datei, die überprüft wird + - Die spezifischen Codezeilen + - Der umgebende Diff-Kontext + - Informationen zur Zeilennummer + + Dies ermöglicht gezieltere Anfragen, ohne dass Dateipfade oder Zeilennummern manuell angegeben werden müssen. diff --git a/packages/web/src/content/docs/de/gitlab.mdx b/packages/web/src/content/docs/de/gitlab.mdx new file mode 100644 index 000000000..9bebf46fb --- /dev/null +++ b/packages/web/src/content/docs/de/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: Verwenden Sie OpenCode in GitLab-Problemen und Zusammenführungsanfragen. +--- + +OpenCode lässt sich über Ihre GitLab CI/CD-Pipeline oder mit GitLab Duo in Ihren GitLab-Workflow integrieren. + +In beiden Fällen läuft OpenCode auf Ihren GitLab-Läufern. + +--- + +## GitLab CI + +OpenCode funktioniert in einer regulären GitLab-Pipeline. Sie können es als [CI component](https://docs.gitlab.com/ee/ci/components/) in eine Pipeline einbauen. + +Hier verwenden wir eine von der Community erstellte CI/CD-Komponente für OpenCode – [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### Features + +- **Benutzerdefinierte Konfiguration pro Job verwenden**: Konfigurieren Sie OpenCode mit einem benutzerdefinierten Konfigurationsverzeichnis, zum Beispiel `./config/#custom-directory`, um die Funktionalität pro OpenCode-Aufruf zu aktivieren oder zu deaktivieren. +- **Minimale Einrichtung**: Die CI-Komponente richtet OpenCode im Hintergrund ein. Sie müssen lediglich die OpenCode-Konfiguration und die erste Eingabeaufforderung erstellen. +- **Flexibel**: Die CI-Komponente unterstützt mehrere Eingaben zum Anpassen ihres Verhaltens + +--- + +### Setup + +1. Speichern Sie Ihre OpenCode-Authentifizierung JSON als Umgebungsvariablen vom Dateityp CI unter **Einstellungen** > **CI/CD** > **Variablen**. Stellen Sie sicher, dass Sie sie als „Maskiert und ausgeblendet“ markieren. +2. Fügen Sie Folgendes zu Ihrer `.gitlab-ci.yml`-Datei hinzu. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +Weitere Eingaben und Anwendungsfälle finden Sie unter [check out the docs](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) für diese Komponente. + +--- + +## GitLab Duo + +OpenCode lässt sich in Ihren GitLab-Workflow integrieren. +Erwähnen Sie `@opencode` in einem Kommentar und OpenCode führt Aufgaben innerhalb Ihrer GitLab CI-Pipeline aus. + +--- + +### Features + +- **Triage-Probleme**: Bitten Sie OpenCode, ein Problem zu untersuchen und es Ihnen zu erklären. +- **Reparieren und implementieren**: Bitten Sie OpenCode, ein Problem zu beheben oder eine Funktion zu implementieren. + Es wird ein neuer Zweig erstellt und eine Zusammenführungsanforderung mit den Änderungen ausgelöst. +- **Sicher**: OpenCode läuft auf Ihren GitLab-Läufern. + +--- + +### Setup + +OpenCode wird in Ihrer GitLab CI/CD-Pipeline ausgeführt. Folgendes müssen Sie zum Einrichten benötigen: + +:::tip +Aktuelle Anweisungen finden Sie im [**GitLab docs**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/). +::: + +1. Konfigurieren Sie Ihre GitLab-Umgebung +2. CI/CD einrichten +3. Holen Sie sich einen AI-Modellanbieterschlüssel API +4. Erstellen Sie ein Dienstkonto +5. Konfigurieren Sie CI/CD-Variablen +6. Erstellen Sie eine Flow-Konfigurationsdatei, hier ist ein Beispiel: + +
+ + Flow configuration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +Ausführliche Anweisungen finden Sie unter [GitLab CLI agents docs](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/). + +--- + +### Examples + +Hier sind einige Beispiele, wie Sie OpenCode in GitLab verwenden können. + +:::tip +Sie können die Verwendung einer anderen Triggerphrase als `@opencode` konfigurieren. +::: + +- **Erklären Sie ein Problem** + + Fügen Sie diesen Kommentar in einer GitLab-Ausgabe hinzu. + + ``` + @opencode explain this issue + ``` + + OpenCode liest das Problem und antwortet mit einer klaren Erklärung. + +- **Ein Problem beheben** + + Sagen Sie in einer GitLab-Ausgabe: + + ``` + @opencode fix this + ``` + + OpenCode erstellt einen neuen Zweig, implementiert die Änderungen und öffnet eine Zusammenführungsanforderung mit den Änderungen. + +- **Zusammenführungsanfragen prüfen** + + Hinterlassen Sie den folgenden Kommentar zu einer GitLab-Merge-Anfrage. + + ``` + @opencode review this merge request + ``` + + OpenCode prüft die Zusammenführungsanfrage und gibt Feedback. diff --git a/packages/web/src/content/docs/de/ide.mdx b/packages/web/src/content/docs/de/ide.mdx new file mode 100644 index 000000000..802894e3c --- /dev/null +++ b/packages/web/src/content/docs/de/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: Die OpenCode-Erweiterung für VS Code, Cursor und andere IDEs +--- + +OpenCode lässt sich in VS Code, Cursor oder jeden IDE integrieren, der ein Terminal unterstützt. Führen Sie einfach `opencode` im Terminal aus, um zu beginnen. + +--- + +## Verwendung + +- **Schnellstart**: Verwenden Sie `Cmd+Esc` (Mac) oder `Ctrl+Esc` (Windows/Linux), um OpenCode in einer geteilten Terminalansicht zu öffnen, oder fokussieren Sie eine dieser Terminalsitzung, falls bereits eine ausgeführt wird. +- **Neue Sitzung**: Verwenden Sie `Cmd+Shift+Esc` (Mac) oder `Ctrl+Shift+Esc` (Windows/Linux), um eine neue OpenCode-Terminalsitzung zu starten, auch wenn eine bereits geöffnet ist. Sie können auch auf die OpenCode-Schaltfläche im UI klicken. +- **Kontextbewusstsein**: Teilen Sie Ihre aktuelle Auswahl oder Registerkarte automatisch mit OpenCode. +- **Verknüpfungen zu Dateiverweisen**: Verwenden Sie `Cmd+Option+K` (Mac) oder `Alt+Ctrl+K` (Linux/Windows), um Dateiverweisen einzufügen. Beispiel: `@File#L37-42`. + +--- + +## Installation + +So installieren Sie OpenCode auf VS Code und beliebten Forks wie Cursor, Windsurf, VSCodium: + +1. Öffnen Sie den VS-Code +2. Öffnen Sie das integrierte Terminal +3. Führen Sie `opencode` aus – die Erweiterung wird automatisch installiert + +Wenn Sie andererseits Ihr eigenes IDE verwenden möchten, wenn Sie `/editor` oder `/export` von TUI ausführen, müssen Sie `export EDITOR="code --wait"` festlegen. [Learn more](/docs/tui/#editor-setup). + +--- + +### Manuelle Installation + +Suchen Sie im Extension Marketplace nach **OpenCode** und klicken Sie auf **Installieren**. + +--- + +### Troubleshooting + +Wenn die Erweiterung nicht automatisch installiert werden kann: + +- Stellen Sie sicher, dass Sie `opencode` im integrierten Terminal ausführen. +- Bestätigen Sie, dass CLI für Ihr IDE installiert ist: + - Für VS Code: `code` Befehl + - Für Cursor: Befehl `cursor` + - Für Windsurfen: Befehl `windsurf` + - Für VSCodium: Befehl `codium` + - Wenn nicht, führen Sie `Cmd+Shift+P` (Mac) oder `Ctrl+Shift+P` (Windows/Linux) aus und suchen Sie nach „Shell Command: Install 'code' command in PATH“ (oder dem Äquivalent für Ihr IDE). +- Stellen Sie sicher, dass der VS-Code über die Berechtigung zum Installieren von Erweiterungen verfügt diff --git a/packages/web/src/content/docs/de/index.mdx b/packages/web/src/content/docs/de/index.mdx new file mode 100644 index 000000000..92f67e7af --- /dev/null +++ b/packages/web/src/content/docs/de/index.mdx @@ -0,0 +1,359 @@ +--- +title: Einführung +description: Beginnen Sie mit OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) ist ein Open-Source-Coding-Agent für AI. Es ist als terminalbasierte Schnittstelle, Desktop-App oder IDE-Erweiterung verfügbar. + +![OpenCode TUI with the opencode theme](../../../assets/lander/screenshot.png) + +Fangen wir an. + +--- + +#### Voraussetzungen + +Um OpenCode in Ihrem Terminal verwenden zu können, benötigen Sie: + +1. Ein moderner Terminal-Emulator, zum Beispiel: + - [WezTerm](https://wezterm.org), cross-platform + - [Alacritty](https://alacritty.org), plattformübergreifend + - [Ghostty](https://ghostty.org), Linux und macOS + - [Kitty](https://sw.kovidgoyal.net/kitty/), Linux und macOS + +2. API-Schlüssel für die LLM-Anbieter, die Sie verwenden möchten. + +--- + +## Installieren + +Der einfachste Weg, OpenCode zu installieren, ist über das Installationsskript. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +Sie können es auch mit den folgenden Befehlen installieren: + +- **Mit Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **Homebrew unter macOS und Linux verwenden** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > Wir empfehlen die Verwendung des OpenCode-Tapes für die aktuellsten Versionen. Die offizielle `brew install opencode`-Formel wird vom Homebrew-Team gepflegt und seltener aktualisiert. + +- **Verwendung von Paru unter Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### Windows + +:::tip[Empfohlen: Verwenden Sie WSL] +Für das beste Erlebnis unter Windows empfehlen wir die Verwendung von [Windows Subsystem for Linux (WSL)](/docs/windows-wsl). Es bietet eine bessere Leistung und vollständige Kompatibilität mit den Funktionen von OpenCode. +::: + +- **Verwendung von Schokolade** + + ```bash + choco install opencode + ``` + +- **Scoop verwenden** + + ```bash + scoop install opencode + ``` + +- **Mit NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **Mit Mise** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **Verwendung von Docker** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +Die Unterstützung für die Installation von OpenCode unter Windows mit Bun ist derzeit in Arbeit. + +Sie können die Binärdatei auch aus [Releases](https://github.com/anomalyco/opencode/releases) abrufen. + +--- + +## Konfigurieren + +Mit OpenCode können Sie jeden LLM-Anbieter verwenden, indem Sie dessen API-Schlüssel konfigurieren. + +Wenn Sie mit der Verwendung von LLM-Anbietern noch nicht vertraut sind, empfehlen wir die Verwendung von [OpenCode Zen](/docs/zen). +Es handelt sich um eine kuratierte Liste von Modellen, die von OpenCode getestet und verifiziert wurden +team. + +1. Führen Sie den Befehl `/connect` in TUI aus, wählen Sie Opencode aus und gehen Sie zu [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Melden Sie sich an, geben Sie Ihre Rechnungsdaten ein und kopieren Sie Ihren API-Schlüssel. + +3. Fügen Sie Ihren API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +Alternativ können Sie auch einen der anderen Anbieter auswählen. [Mehr erfahren](/docs/providers#directory). + +--- + +## Initialize + +Nachdem Sie nun einen Anbieter konfiguriert haben, können Sie zu einem Projekt navigieren +an dem du arbeiten möchtest. + +```bash +cd /path/to/project +``` + +Und führen Sie OpenCode aus. + +```bash +opencode +``` + +Als nächstes initialisieren Sie OpenCode für das Projekt, indem Sie den folgenden Befehl ausführen. + +```bash frame="none" +/init +``` + +Dadurch wird OpenCode dazu veranlasst, Ihr Projekt zu analysieren und eine `AGENTS.md`-Datei zu erstellen +das Projektstammverzeichnis. + +:::tip +Sie sollten die `AGENTS.md`-Datei Ihres Projekts an Git übergeben. +::: + +Dies hilft OpenCode, die Projektstruktur und die Codierungsmuster zu verstehen +used. + +--- + +## Verwendung + +Sie können nun OpenCode verwenden, um an Ihrem Projekt zu arbeiten. Fragen Sie ruhig danach +anything! + +Wenn Sie mit der Verwendung eines AI-Codierungsagenten noch nicht vertraut sind, finden Sie hier einige Beispiele, die hilfreich sein könnten +help. + +--- + +### Stellen Sie Fragen + +Sie können OpenCode bitten, Ihnen die Codebasis zu erklären. + +:::tip +Verwenden Sie die Taste `@`, um eine Fuzzy-Suche nach Dateien im Projekt durchzuführen. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +Dies ist hilfreich, wenn es einen Teil der Codebasis gibt, an dem Sie nicht gearbeitet haben. + +--- + +### Funktionen hinzufügen + +Sie können OpenCode bitten, Ihrem Projekt neue Funktionen hinzuzufügen. Wir empfehlen jedoch, es zunächst um die Erstellung eines Plans zu bitten. + +1. **Erstellen Sie einen Plan** + + OpenCode verfügt über einen _Planmodus_, der seine Fähigkeit, Änderungen vorzunehmen, deaktiviert + Schlagen Sie stattdessen vor, wie die Funktion implementiert wird. + + Wechseln Sie mit der **Tabulatortaste** dorthin. In der unteren rechten Ecke sehen Sie einen Indikator dafür. + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + Beschreiben wir nun, was es tun soll. + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + Sie möchten OpenCode genügend Details geben, um zu verstehen, was Sie wollen. Es hilft + mit ihm zu sprechen, als ob Sie mit einem Junior-Entwickler in Ihrem Team sprechen würden. + + :::tip + Geben Sie OpenCode reichlich Kontext und Beispiele, damit es versteht, was Sie möchten + want. + ::: + +2. **Den Plan wiederholen** + + Sobald Sie einen Plan erhalten, können Sie ihm Feedback geben oder weitere Details hinzufügen. + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::tip + Ziehen Sie Bilder per Drag-and-Drop in das Terminal, um sie zur Eingabeaufforderung hinzuzufügen. + ::: + + OpenCode kann alle von Ihnen bereitgestellten Bilder scannen und zur Eingabeaufforderung hinzufügen. Du kannst + Ziehen Sie dazu ein Bild per Drag & Drop in das Terminal. + +3. **Funktion erstellen** + + Wenn Sie mit dem Plan zufrieden sind, wechseln Sie zurück in den _Build-Modus_ + indem Sie erneut die **Tabulatortaste** drücken. + + ```bash frame="none" + + ``` + + Und es bitten, die Änderungen vorzunehmen. + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### Nehmen Sie Änderungen vor + +Für einfachere Änderungen können Sie OpenCode bitten, es direkt zu erstellen +ohne den Plan vorher überprüfen zu müssen. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +Sie möchten sicherstellen, dass Sie viele Details bereitstellen, damit OpenCode das Richtige tut +changes. + +--- + +### Änderungen rückgängig machen + +Nehmen wir an, Sie bitten OpenCode, einige Änderungen vorzunehmen. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Aber Sie erkennen, dass es nicht das ist, was Sie wollten. Sie können die Änderungen **rückgängig machen** +mit dem Befehl `/undo`. + +```bash frame="none" +/undo +``` + +OpenCode macht nun die von Ihnen vorgenommenen Änderungen rückgängig und zeigt Ihre ursprüngliche Nachricht an +again. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Von hier aus können Sie die Eingabeaufforderung anpassen und OpenCode bitten, es erneut zu versuchen. + +:::tip +Sie können `/undo` mehrmals ausführen, um mehrere Änderungen rückgängig zu machen. +::: + +Oder Sie **können** die Änderungen mit dem Befehl `/redo` wiederholen. + +```bash frame="none" +/redo +``` + +--- + +## Aktie + +Die Gespräche, die Sie mit OpenCode führen, können [mit Ihrem geteilt werden +Team](/docs/share). + +```bash frame="none" +/share +``` + +Dadurch wird ein Link zur aktuellen Konversation erstellt und in Ihre Zwischenablage kopiert. + +:::note +Gespräche werden standardmäßig nicht geteilt. +::: + +Hier ist ein [Beispielgespräch](https://opencode.ai/s/4XP1fce5) mit OpenCode. + +--- + +## Customize + +Und das ist es! Sie sind jetzt ein Profi im Umgang mit OpenCode. + +Um es zu Ihrem eigenen zu machen, empfehlen wir [picking a theme](/docs/themes), [customizing the keybinds](/docs/keybinds), [configuring code formatters](/docs/formatters), [creating custom commands](/docs/commands) oder experimentieren Sie mit [OpenCode config](/docs/config). diff --git a/packages/web/src/content/docs/de/keybinds.mdx b/packages/web/src/content/docs/de/keybinds.mdx new file mode 100644 index 000000000..24afb1ec8 --- /dev/null +++ b/packages/web/src/content/docs/de/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: Tastenkombinationen +description: Passen Sie Ihre Tastenkombinationen an. +--- + +OpenCode verfügt über eine Liste von Tastenkombinationen, die Sie über die OpenCode-Konfiguration anpassen können. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## Führungsschlüssel + +OpenCode verwendet für die meisten Tastenkombinationen einen `leader`-Schlüssel. Dies vermeidet Konflikte in Ihrem Terminal. + +Standardmäßig ist `ctrl+x` die Führungstaste und bei den meisten Aktionen müssen Sie zuerst die Führungstaste und dann die Tastenkombination drücken. Um beispielsweise eine neue Sitzung zu starten, drücken Sie zuerst `ctrl+x` und dann `n`. + +Sie müssen für Ihre Tastenkombinationen keine Führungstaste verwenden, wir empfehlen jedoch, dies zu tun. + +--- + +## Tastenkombination deaktivieren + +Sie können eine Tastenkombination deaktivieren, indem Sie den Schlüssel mit dem Wert „none“ zu Ihrer Konfiguration hinzufügen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## Verknüpfungen zur Desktop-Eingabeaufforderung + +Die Eingabeaufforderungseingabe der OpenCode-Desktop-App unterstützt gängige Readline/Emacs-style-Verknüpfungen zum Bearbeiten von Text. Diese sind integriert und derzeit nicht über `opencode.json` konfigurierbar. + +| Verknüpfung | Aktion | +| -------- | ---------------------------------------- | +| `ctrl+a` | Zum Anfang der aktuellen Zeile gehen | +| `ctrl+e` | Zum Ende der aktuellen Zeile gehen | +| `ctrl+b` | Cursor um ein Zeichen zurückbewegen | +| `ctrl+f` | Cursor um ein Zeichen vorwärts bewegen | +| `alt+b` | Cursor um ein Wort zurückbewegen | +| `alt+f` | Bewegen Sie den Cursor ein Wort vorwärts | +| `ctrl+d` | Zeichen unter Cursor | löschen +| `ctrl+k` | Bis zum Zeilenende töten | +| `ctrl+u` | Bis zum Zeilenanfang töten | +| `ctrl+w` | Vorheriges Wort töten | +| `alt+d` | Nächstes Wort töten | +| `ctrl+t` | Zeichen transponieren | +| `ctrl+g` | Popovers abbrechen / Ausführung der Antwort abbrechen | + +--- + +## Umschalt+Eingabetaste + +Einige Terminals senden standardmäßig keine Zusatztasten mit der Eingabetaste. Möglicherweise müssen Sie Ihr Terminal so konfigurieren, dass es `Shift+Enter` als Escape-Sequenz sendet. + +### Windows-Terminal + +Öffnen Sie Ihr `settings.json` unter: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +Fügen Sie dies dem `actions`-Array auf Stammebene hinzu: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Fügen Sie dies dem `keybindings`-Array auf Stammebene hinzu: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Speichern Sie die Datei und starten Sie das Windows-Terminal neu oder öffnen Sie einen neuen Tab. diff --git a/packages/web/src/content/docs/de/lsp.mdx b/packages/web/src/content/docs/de/lsp.mdx new file mode 100644 index 000000000..f7448d1af --- /dev/null +++ b/packages/web/src/content/docs/de/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: LSP Server +description: OpenCode lässt sich in Ihren LSP-Server integrieren. +--- + +OpenCode lässt sich in Ihr Language Server Protocol (LSP) integrieren, um die Interaktion von LLM mit Ihrer Codebasis zu unterstützen. Es verwendet Diagnosefunktionen, um dem LLM Feedback zu geben. + +--- + +## Eingebaut + +OpenCode verfügt über mehrere integrierte LSP-Server für gängige Sprachen: + +| LSP Server | Erweiterungen | Anforderungen | +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +| Astro | .astro | Automatische Installation für Astro-Projekte | +| bash | .sh, .bash, .zsh, .ksh | Installiert den Bash-Language-Server | automatisch +| klirrend | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Automatische Installation für C/C++-Projekte | +| csharp | .cs | `.NET SDK` installed | +| clojure-lsp | .clj, .cljs, .cljc, .edn | `clojure-lsp`-Befehl verfügbar | +| Dart | .dart | `dart`-Befehl verfügbar | +| deno | .ts, .tsx, .js, .jsx, .mjs | `deno`-Befehl verfügbar (automatische Erkennung von deno.json/deno.jsonc) | +| Elixier-ls | .ex, .exs | `elixir`-Befehl verfügbar | +| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` dependency in project | +| fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` installed | +| Glanz | .glanz | `gleam`-Befehl verfügbar | +| gopls | .go | `go`-Befehl verfügbar | +| hls | .hs, .lhs | `haskell-language-server-wrapper`-Befehl verfügbar | +| jdtls | .java | `Java SDK (version 21+)` installiert | +| kotlin-ls | .kt, .kts | Automatische Installation für Kotlin-Projekte | +| lua-ls | .lua | Automatische Installation für Lua-Projekte | +| nixd | .nix | `nixd`-Befehl verfügbar | +| ocaml-lsp | .ml, .mli | `ocamllsp`-Befehl verfügbar | +| oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | `oxlint` dependency in project | +| PHP Intelepense | .php | Automatische Installation für PHP-Projekte | +| Prisma | .prisma | `prisma`-Befehl verfügbar | +| pyright | .py, .pyi | `pyright` dependency installed | +| ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | Befehle `ruby` und `gem` verfügbar | +| Rost | .rs | `rust-analyzer`-Befehl verfügbar | +| sourcekit-lsp | .swift, .objc, .objcpp | `swift` installed (`xcode` on macOS) | +| schlank | .svelte | Automatische Installation für Svelte-Projekte | +| Terraform | .tf, .tfvars | Automatische Installation von GitHub-Releases | +| winziger Nebel | .typ, .typc | Automatische Installation von GitHub-Releases | +| typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` dependency in project | +| vue | .vue | Automatische Installation für Vue-Projekte | +| yaml-ls | .yaml, .yml | Installiert den Red Hat Yaml-Language-Server | automatisch +| zls | .zig, .zon | `zig`-Befehl verfügbar | + +LSP-Server werden automatisch aktiviert, wenn eine der oben genannten Dateierweiterungen erkannt wird und die Anforderungen erfüllt sind. + +:::note +Sie können LSP-Server-Downloads automatisch deaktivieren, indem Sie die Umgebungsvariable `OPENCODE_DISABLE_LSP_DOWNLOAD` auf `true` setzen. +::: + +--- + +## Wie es funktioniert + +Wenn Opencode eine Datei öffnet, geschieht Folgendes: + +1. Überprüft die Dateierweiterung anhand aller aktivierten LSP-Server. +2. Startet den entsprechenden LSP-Server, falls er noch nicht ausgeführt wird. + +--- + +## Konfigurieren + +Sie können LSP-Server über den Abschnitt `lsp` in Ihrer Opencode-Konfiguration anpassen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Jeder LSP-Server unterstützt Folgendes: + +| Eigentum | Geben Sie | ein Beschreibung | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` | boolescher Wert | Setzen Sie dies auf `true`, um den LSP-Server zu deaktivieren +| `command` | string[] | Der Befehl zum Starten des LSP-Servers | +| `extensions` | string[] | Dateierweiterungen, die dieser LSP-Server verarbeiten soll | +| `env` | Objekt | Umgebungsvariablen, die beim Starten des Servers festgelegt werden | +| `initialization` | Objekt | Initialisierungsoptionen zum Senden an den LSP-Server | + +Schauen wir uns einige Beispiele an. + +--- + +### Umgebungsvariablen + +Verwenden Sie die Eigenschaft `env`, um Umgebungsvariablen festzulegen, wenn Sie den Server LSP starten: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### Initialisierungsoptionen + +Verwenden Sie die Eigenschaft `initialization`, um Initialisierungsoptionen an den Server LSP zu übergeben. Dies sind serverspezifische Einstellungen, die während der LSP `initialize`-Anfrage gesendet werden: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +Die Initialisierungsoptionen variieren je nach LSP-Server. Überprüfen Sie die Dokumentation Ihres LSP-Servers auf verfügbare Optionen. +::: + +--- + +### Deaktivieren von LSP-Servern + +Um **alle** LSP-Server global zu deaktivieren, setzen Sie `lsp` auf `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +Um einen **bestimmten** LSP-Server zu deaktivieren, setzen Sie `disabled` auf `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Benutzerdefinierter LSP-Server + +Sie können einen benutzerdefinierten LSP-Server hinzufügen, indem Sie den Befehl und die Dateierweiterungen angeben: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## Weitere Informationen + +### PHP Intelepense + +PHP Intelepense bietet Premium-Funktionen über einen Lizenzschlüssel. Sie können einen Lizenzschlüssel bereitstellen, indem Sie (nur) den Schlüssel in eine Textdatei einfügen unter: + +- Auf macOS/Linux: `$HOME/intelephense/licence.txt` +- Unter Windows: `%USERPROFILE%/intelephense/licence.txt` + +Die Datei sollte nur den Lizenzschlüssel ohne zusätzlichen Inhalt enthalten. diff --git a/packages/web/src/content/docs/de/mcp-servers.mdx b/packages/web/src/content/docs/de/mcp-servers.mdx new file mode 100644 index 000000000..f287365b0 --- /dev/null +++ b/packages/web/src/content/docs/de/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: MCP Server +description: Fügen Sie lokale und Remote-MCP-Tools hinzu. +--- + +Sie können externe Tools zu OpenCode hinzufügen, indem Sie das _Model Context Protocol_ oder MCP verwenden. OpenCode unterstützt sowohl lokale als auch Remote-Server. + +Nach dem Hinzufügen stehen MCP-Tools automatisch neben den integrierten Tools für LLM zur Verfügung. + +--- + +#### Caveats + +Wenn Sie einen MCP-Server verwenden, wird dieser zum Kontext hinzugefügt. Wenn Sie viele Werkzeuge haben, können Sie das schnell zusammenfassen. Wir empfehlen daher, vorsichtig zu sein, welchen MCP-Server Sie verwenden. + +:::tip +MCP-Server ergänzen Ihren Kontext, daher sollten Sie vorsichtig sein, welchen Server Sie aktivieren. +::: + +Bestimmte MCP-Server, wie der GitHub-Server MCP, neigen dazu, viele Token hinzuzufügen und können leicht das Kontextlimit überschreiten. + +--- + +## Enable + +Sie können den MCP-Server in Ihrem [OpenCode Config](https://opencode.ai/docs/config/) unter `mcp` definieren. Fügen Sie jedem MCP einen eindeutigen Namen hinzu. Sie können bei der Eingabe von LLM namentlich auf diesen MCP verweisen. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +Sie können einen Server auch deaktivieren, indem Sie `enabled` auf `false` setzen. Dies ist nützlich, wenn Sie einen Server vorübergehend deaktivieren möchten, ohne ihn aus Ihrer Konfiguration zu entfernen. + +--- + +### Überschreiben von Remote-Standardwerten + +Organisationen können über ihren `.well-known/opencode`-Endpunkt Standard-MCP-Server bereitstellen. Diese Server sind möglicherweise standardmäßig deaktiviert, sodass Benutzer sich für den Server entscheiden können, die sie benötigen. + +Um einen bestimmten Server aus der Remote-Konfiguration Ihrer Organisation zu aktivieren, fügen Sie ihn mit `enabled: true` zu Ihrer lokalen Konfiguration hinzu: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +Ihre lokalen Konfigurationswerte überschreiben die Remote-Standardwerte. Weitere Einzelheiten finden Sie unter [config precedence](/docs/config#precedence-order). + +--- + +## Local + +Fügen Sie lokale MCP-Server mit `type` bis `"local"` innerhalb des MCP-Objekts hinzu. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +Mit dem Befehl wird der lokale MCP-Server gestartet. Sie können auch eine Liste von Umgebungsvariablen übergeben. + +So können Sie beispielsweise den Testserver [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP hinzufügen. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +Und um es zu verwenden, kann ich `use the mcp_everything tool` zu meinen Eingabeaufforderungen hinzufügen. + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### Options + +Hier finden Sie alle Optionen zum Konfigurieren eines lokalen MCP-Servers. + +| Option | Geben Sie | ein Erforderlich | Beschreibung | +| ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | Zeichenfolge | Y | Typ der MCP-Serververbindung, muss `"local"` sein. | +| `command` | Array | Y | Befehl und Argumente zum Ausführen des MCP-Servers. | +| `environment` | Objekt | | Umgebungsvariablen, die beim Ausführen des Servers festgelegt werden sollen. | +| `enabled` | Boolescher Wert | | Aktivieren oder deaktivieren Sie den MCP-Server beim Start. | +| `timeout` | Nummer | | Timeout in ms für das Abrufen von Tools vom MCP-Server. Standardmäßig ist 5000 (5 Sekunden). | + +--- + +## Remote + +Fügen Sie den Remote-MCP-Server hinzu, indem Sie `type` auf `"remote"` setzen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +Der `url` ist der URL des Remote-Servers MCP und mit der Option `headers` können Sie eine Liste von Headern übergeben. + +--- + +#### Options + +| Option | Geben Sie | ein Erforderlich | Beschreibung | +| --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | Zeichenfolge | Y | Typ der MCP-Serververbindung, muss `"remote"` sein. | +| `url` | Zeichenfolge | Y | URL des Remote-Servers MCP. | +| `enabled` | Boolescher Wert | | Aktivieren oder deaktivieren Sie den MCP-Server beim Start. | +| `headers` | Objekt | | Header, die mit der Anfrage gesendet werden sollen. | +| `oauth` | Objekt | | OAuth-Authentifizierungskonfiguration. Siehe Abschnitt [OAuth](#oauth) unten. | +| `timeout` | Nummer | | Timeout in ms für das Abrufen von Tools vom MCP-Server. Standardmäßig ist 5000 (5 Sekunden). | + +--- + +## OAuth + +OpenCode übernimmt automatisch die OAuth-Authentifizierung für Remote-MCP-Server. Wenn ein Server eine Authentifizierung erfordert, wird OpenCode Folgendes tun: + +1. Erkennen Sie die 401-Antwort und initiieren Sie den OAuth-Fluss +2. Verwenden Sie **Dynamische Client-Registrierung (RFC 7591)**, sofern vom Server unterstützt +3. Bewahren Sie Token sicher für zukünftige Anfragen auf + +--- + +### Automatic + +Für die meisten OAuth-fähigen MCP-Server ist keine spezielle Konfiguration erforderlich. Konfigurieren Sie einfach den Remote-Server: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +Wenn der Server eine Authentifizierung erfordert, werden Sie von OpenCode beim ersten Versuch, ihn zu verwenden, zur Authentifizierung autorisiert. Wenn nicht, können Sie [manually trigger the flow](#authenticating) mit `opencode mcp auth ` verwenden. + +--- + +### Pre-registered + +Wenn Sie über Client-Anmeldeinformationen vom Serveranbieter MCP verfügen, können Sie diese konfigurieren: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### Authenticating + +Sie können die Authentifizierung manuell auslösen oder Anmeldeinformationen verwalten. + +Authentifizieren Sie sich bei einem bestimmten MCP-Server: + +```bash +opencode mcp auth my-oauth-server +``` + +Hören Sie alle MCP-Server und ihren Authentifizierungsstatus auf: + +```bash +opencode mcp list +``` + +Gespeicherte Zugangsdaten entfernen: + +```bash +opencode mcp logout my-oauth-server +``` + +Der Befehl `mcp auth` öffnet Ihren Browser zur Autorisierung. Nach der Autorisierung speichert OpenCode die Token sicher in `~/.local/share/opencode/mcp-auth.json`. + +--- + +#### OAuth deaktivieren + +Wenn Sie automatisches OAuth für einen Server deaktivieren möchten (e.g., für Server, die stattdessen API-Schlüssel verwenden), setzen Sie `oauth` auf `false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### OAuth-Optionen + +| Option | Geben Sie | ein Beschreibung | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` | Objekt \| falsch | OAuth-Konfigurationsobjekt oder `false`, um die automatische OAuth-Erkennung zu deaktivieren. | +| `clientId` | Zeichenfolge | OAuth-Client ID. Wenn nicht angegeben, wird eine dynamische Client-Registrierung versucht. | +| `clientSecret` | Zeichenfolge | OAuth-Client-Geheimnis, falls vom Autorisierungsserver erforderlich. | +| `scope` | Zeichenfolge | OAuth-Bereiche, die während der Autorisierung angefordert werden sollen. | + +#### Debugging + +Wenn die Authentifizierung eines Remote-Servers MCP fehlschlägt, können Sie Probleme diagnostizieren mit: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +Der Befehl `mcp debug` zeigt den aktuellen Authentifizierungsstatus an, testet die HTTP-Konnektivität und versucht den OAuth-Erkennungsfluss. + +--- + +## Manage + +Ihre MCPs sind neben integrierten Tools auch als Tools in OpenCode verfügbar. Sie können sie also wie jedes andere Tool über die OpenCode-Konfiguration verwalten. + +--- + +### Global + +Das bedeutet, dass Sie sie global aktivieren oder deaktivieren können. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +Wir können auch ein Glob-Muster verwenden, um alle passenden MCPs zu deaktivieren. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +Hier verwenden wir das Glob-Muster `my-mcp*`, um alle MCPs zu deaktivieren. + +--- + +### Pro Agent + +Wenn Sie über eine große Anzahl von MCP-Servern verfügen, möchten Sie diese möglicherweise nur pro Agent aktivieren und global deaktivieren. Gehen Sie dazu wie folgt vor: + +1. Deaktivieren Sie es global als Tool. +2. Aktivieren Sie in Ihrem [agent config](/docs/agents#tools) den MCP-Server als Tool. + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### Glob-Muster + +Das Glob-Muster verwendet einfache Regex-Globbing-Muster: + +- `*` entspricht null oder mehr Zeichen (e.g., `"my-mcp*"` entspricht `my-mcp_search`, `my-mcp_list` usw.) +- `?` matches exactly one character +- Alle anderen Zeichen stimmen wörtlich überein + +:::note +MCP-Servertools werden mit dem Servernamen als Präfix registriert. Um alle Tools für einen Server zu deaktivieren, verwenden Sie einfach Folgendes: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## Examples + +Nachfolgend finden Sie Beispiele einiger gängiger MCP-Server. Sie können ein PR einreichen, wenn Sie einen anderen Server dokumentieren möchten. + +--- + +### Sentry + +Fügen Sie [Sentry MCP server](https://mcp.sentry.dev) hinzu, um mit Ihren Sentry-Projekten und -Problemen zu interagieren. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +Authentifizieren Sie sich nach dem Hinzufügen der Konfiguration mit Sentry: + +```bash +opencode mcp auth sentry +``` + +Dadurch wird ein Browserfenster geöffnet, um den OAuth-Ablauf abzuschließen und OpenCode mit Ihrem Sentry-Konto zu verbinden. + +Nach der Authentifizierung können Sie Sentry-Tools in Ihren Eingabeaufforderungen verwenden, um Probleme, Projekte und Fehlerdaten abzufragen. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Context7 + +Fügen Sie [Context7 MCP server](https://github.com/upstash/context7) hinzu, um Dokumente zu durchsuchen. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +Wenn Sie sich für ein kostenloses Konto angemeldet haben, können Sie Ihren API-Schlüssel verwenden und höhere Ratenlimits erhalten. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +Hier gehen wir davon aus, dass Sie die Umgebungsvariable `CONTEXT7_API_KEY` festgelegt haben. + +Fügen Sie `use context7` zu Ihren Eingabeaufforderungen hinzu, um den Context7 MCP-Server zu verwenden. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +Alternativ können Sie so etwas zu Ihrem [AGENTS.md](/docs/rules/) hinzufügen. + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep von Vercel + +Fügen Sie den Server [Grep by Vercel](https://grep.app) MCP hinzu, um Codefragmente auf GitHub zu durchsuchen. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +Da wir unseren MCP-Server `gh_grep` genannt haben, können Sie `use the gh_grep tool` zu Ihren Eingabeaufforderungen hinzufügen, um den Agenten dazu zu bringen, ihn zu verwenden. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +Alternativ können Sie so etwas zu Ihrem [AGENTS.md](/docs/rules/) hinzufügen. + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/de/models.mdx b/packages/web/src/content/docs/de/models.mdx new file mode 100644 index 000000000..c605f451a --- /dev/null +++ b/packages/web/src/content/docs/de/models.mdx @@ -0,0 +1,223 @@ +--- +title: Modelle +description: Konfigurieren eines LLM-Anbieters und -Modells. +--- + +OpenCode verwendet [AI SDK](https://ai-sdk.dev/) und [Models.dev](https://models.dev) zur Unterstützung von **75+ LLM-Anbietern** und unterstützt die Ausführung lokaler Modelle. + +--- + +## Providers + +Die meisten gängigen Anbieter sind standardmäßig vorinstalliert. Wenn Sie die Anmeldeinformationen für einen Anbieter über den Befehl `/connect` hinzugefügt haben, sind diese verfügbar, wenn Sie OpenCode starten. + +Erfahren Sie mehr über [providers](/docs/providers). + +--- + +## Wählen Sie ein Modell aus + +Sobald Sie Ihren Anbieter konfiguriert haben, können Sie das gewünschte Modell auswählen, indem Sie Folgendes eingeben: + +```bash frame="none" +/models +``` + +--- + +## Empfohlene Modelle + +Es gibt viele Modelle da draußen und jede Woche kommen neue Modelle heraus. + +:::tip +Erwägen Sie die Verwendung eines der von uns empfohlenen Modelle. +::: + +Allerdings gibt es nur wenige von ihnen, die sowohl gut darin sind, Code zu generieren als auch Tools aufzurufen. + +Hier sind mehrere Modelle, die gut mit OpenCode funktionieren, in keiner bestimmten Reihenfolge. (Dies ist weder eine vollständige noch eine unbedingt aktuelle Liste): + +- GPT 5.2 +- GPT 5.1 Kodex +- Claude Opus 4.5 +- Claude Sonett 4.5 +- Minimax M2.1 +- Gemini 3 Pro + +--- + +## Legen Sie einen Standard fest + +Um eines davon als Standardmodell festzulegen, können Sie den Schlüssel `model` in Ihrem festlegen +OpenCode config. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Hier ist der vollständige ID `provider_id/model_id`. Wenn Sie beispielsweise [OpenCode Zen](/docs/zen) verwenden, würden Sie `opencode/gpt-5.1-codex` für GPT 5.1 Codex verwenden. + +Wenn Sie einen [custom provider](/docs/providers#custom) konfiguriert haben, ist `provider_id` der Schlüssel aus dem `provider`-Teil Ihrer Konfiguration und `model_id` der Schlüssel aus `provider.models`. + +--- + +## Modelle konfigurieren + +Sie können die Optionen eines Modells global über die Konfiguration konfigurieren. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Hier konfigurieren wir globale Einstellungen für zwei integrierte Modelle: `gpt-5` bei Zugriff über den `openai`-Anbieter und `claude-sonnet-4-20250514` bei Zugriff über den `anthropic`-Anbieter. +Die integrierten Anbieter- und Modellnamen finden Sie unter [Models.dev](https://models.dev). + +Sie können diese Optionen auch für alle von Ihnen verwendeten Agenten konfigurieren. Die Agentenkonfiguration beschreibt hier alle globalen Optionen. [Learn more](/docs/agents/#additional). + +Sie können auch benutzerdefinierte Varianten definieren, die integrierte Varianten erweitern. Mit Varianten können Sie unterschiedliche Einstellungen für dasselbe Modell konfigurieren, ohne doppelte Einträge zu erstellen: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## Variants + +Viele Modelle unterstützen mehrere Varianten mit unterschiedlichen Konfigurationen. OpenCode wird mit integrierten Standardvarianten für beliebte Anbieter ausgeliefert. + +### Einbauvarianten + +OpenCode wird für viele Anbieter mit Standardvarianten ausgeliefert: + +**Anthropisch**: + +- `high` – Budget für hohes Denken (Standard) +- `max` – Maximales Denkbudget + +**OpenAI**: + +Variiert je nach Modell, aber ungefähr: + +- `none` – Keine Begründung +- `minimal` – Minimaler Argumentationsaufwand +- `low` – Geringer Denkaufwand +- `medium` – Mittlerer Denkaufwand +- `high` – Hoher Denkaufwand +- `xhigh` – Extra hoher Argumentationsaufwand + +**Google**: + +- `low` – Beliebtestes effort/token-Budget +- `high` – Höheres effort/token-Budget + +:::tip +Diese Liste ist nicht vollständig. Viele andere Anbieter verfügen ebenfalls über integrierte Standardeinstellungen. +::: + +### Benutzerdefinierte Varianten + +Sie können vorhandene Varianten überschreiben oder eigene hinzufügen: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### Zyklusvarianten + +Verwenden Sie die Tastenkombination `variant_cycle`, um schnell zwischen Varianten zu wechseln. [Learn more](/docs/keybinds). + +--- + +## Laden von Modellen + +Wenn OpenCode startet, sucht es nach Modellen in der folgenden Prioritätsreihenfolge: + +1. Das Befehlszeilenflag `--model` oder `-m`. Das Format ist das gleiche wie in der Konfigurationsdatei: `provider_id/model_id`. + +2. Die Modellliste in der OpenCode-Konfiguration. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + Das Format hier ist `provider/model`. + +3. Das zuletzt verwendete Modell. + +4. Das erste Modell, das eine interne Priorität verwendet. diff --git a/packages/web/src/content/docs/de/modes.mdx b/packages/web/src/content/docs/de/modes.mdx new file mode 100644 index 000000000..d03d56730 --- /dev/null +++ b/packages/web/src/content/docs/de/modes.mdx @@ -0,0 +1,331 @@ +--- +title: Modi +description: Verschiedene Modi für unterschiedliche Anwendungsfälle. +--- + +:::caution +Modi werden jetzt über die Option `agent` in der Opencode-Konfiguration konfiguriert. Der +Die Option `mode` ist jetzt veraltet. [Learn more](/docs/agents). +::: + +Mit den Modi in Opencode können Sie das Verhalten, die Tools und die Eingabeaufforderungen für verschiedene Anwendungsfälle anpassen. + +Es verfügt über zwei integrierte Modi: **Build** und **Plan**. Sie können anpassen +diese oder konfigurieren Sie Ihre eigenen über die Opencode-Konfiguration. + +Sie können während einer Sitzung zwischen den Modi wechseln oder diese in Ihrer Konfigurationsdatei konfigurieren. + +--- + +## Built-in + +Opencode verfügt über zwei integrierte Modi. + +--- + +### Build + +Build ist der **Standardmodus**, bei dem alle Tools aktiviert sind. Dies ist der Standardmodus für Entwicklungsarbeiten, bei dem Sie vollen Zugriff auf Dateioperationen und Systembefehle benötigen. + +--- + +### Plan + +Ein eingeschränkter Modus für Planung und Analyse. Im Planmodus sind die folgenden Tools standardmäßig deaktiviert: + +- `write` – Es können keine neuen Dateien erstellt werden +- `edit` – Vorhandene Dateien können nicht geändert werden, mit Ausnahme der Dateien unter `.opencode/plans/*.md`, um den Plan selbst detailliert darzustellen +- `patch` – Patches können nicht angewendet werden +- `bash` – Shell-Befehle können nicht ausgeführt werden + +Dieser Modus ist nützlich, wenn Sie möchten, dass AI Code analysiert, Änderungen vorschlägt oder Pläne erstellt, ohne tatsächliche Änderungen an Ihrer Codebasis vorzunehmen. + +--- + +## Switching + +Sie können während einer Sitzung mit der _Tab_-Taste zwischen den Modi wechseln. Oder Ihre konfigurierte `switch_mode`-Tastenkombination. + +Siehe auch: [Formatters](/docs/formatters) für Informationen zur Codeformatierungskonfiguration. + +--- + +## Configure + +Sie können die integrierten Modi anpassen oder über die Konfiguration eigene erstellen. Modi können auf zwei Arten konfiguriert werden: + +### JSON Konfiguration + +Konfigurieren Sie Modi in Ihrer `opencode.json`-Konfigurationsdatei: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Markdown-Konfiguration + +Sie können Modi auch mithilfe von Markdown-Dateien definieren. Platzieren Sie sie in: + +- Global: `~/.config/opencode/modes/` +- Projekt: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Der Name der Markdown-Datei wird zum Modusnamen (e.g., `review.md` erstellt einen `review`-Modus). + +Schauen wir uns diese Konfigurationsmöglichkeiten im Detail an. + +--- + +### Model + +Verwenden Sie die `model`-Konfiguration, um das Standardmodell für diesen Modus zu überschreiben. Nützlich für die Verwendung verschiedener Modelle, die für verschiedene Aufgaben optimiert sind. Zum Beispiel ein schnelleres Modell für die Planung, ein leistungsfähigeres Modell für die Umsetzung. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Temperature + +Steuern Sie die Zufälligkeit und Kreativität der Antworten von AI mit der `temperature`-Konfiguration. Niedrigere Werte machen die Antworten fokussierter und deterministischer, während höhere Werte die Kreativität und Variabilität steigern. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Temperaturwerte liegen typischerweise zwischen 0.0 und 1.0: + +- **0.0-0.2**: Sehr fokussierte und deterministische Antworten, ideal für Code-Analyse und Planung +- **0.3-0.5**: Ausgewogene Antworten mit etwas Kreativität, gut für allgemeine Entwicklungsaufgaben +- **0.6-1.0**: Kreativere und vielfältigere Antworten, nützlich für Brainstorming und Erkundung + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Wenn keine Temperatur angegeben ist, verwendet Opencode modellspezifische Standardwerte (normalerweise 0 für die meisten Modelle, 0.55 für Qwen-Modelle). + +--- + +### Prompt + +Geben Sie mit der `prompt`-Konfiguration eine benutzerdefinierte Systemaufforderungsdatei für diesen Modus an. Die Eingabeaufforderungsdatei sollte spezifische Anweisungen für den Zweck des Modus enthalten. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Dieser Pfad ist relativ zum Speicherort der Konfigurationsdatei. Das funktioniert also +sowohl die globale Opencode-Konfiguration als auch die projektspezifische Konfiguration. + +--- + +### Tools + +Steuern Sie mit der `tools`-Konfiguration, welche Tools in diesem Modus verfügbar sind. Sie können bestimmte Tools aktivieren oder deaktivieren, indem Sie sie auf `true` oder `false` setzen. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +Wenn keine Tools angegeben sind, sind alle Tools standardmäßig aktiviert. + +--- + +#### Verfügbare Werkzeuge + +Hier sind alle Tools aufgeführt, die über den Konfigurationsmodus gesteuert werden können. + +| Werkzeug | Beschreibung | +| ----------- | ----------------------- | +| `bash` | Shell-Befehle ausführen | +| `edit` | Vorhandene Dateien ändern | +| `write` | Neue Dateien erstellen | +| `read` | Dateiinhalt lesen | +| `grep` | Dateiinhalte durchsuchen | +| `glob` | Dateien nach Muster suchen | +| `list` | Verzeichnisinhalte auflisten | +| `patch` | Patches auf Dateien anwenden | +| `todowrite` | Aufgabenlisten verwalten | +| `todoread` | Aufgabenlisten lesen | +| `webfetch` | Webinhalte abrufen | + +--- + +## Benutzerdefinierte Modi + +Sie können Ihre eigenen benutzerdefinierten Modi erstellen, indem Sie diese zur Konfiguration hinzufügen. Hier sind Beispiele für beide Ansätze: + +### Verwenden der JSON-Konfiguration + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Verwendung von Markdown-Dateien + +Erstellen Sie Modusdateien in `.opencode/modes/` für projektspezifische Modi oder `~/.config/opencode/modes/` für globale Modi: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### Anwendungsfälle + +Hier sind einige häufige Anwendungsfälle für verschiedene Modi. + +- **Build-Modus**: Vollständige Entwicklungsarbeit mit allen aktivierten Tools +- **Planmodus**: Analyse und Planung ohne Änderungen +- **Überprüfungsmodus**: Codeüberprüfung mit schreibgeschütztem Zugriff plus Dokumentationstools +- **Debug-Modus**: Konzentriert sich auf die Untersuchung mit aktivierten Bash- und Lesetools +- **Docs-Modus**: Dokumentationsschreiben mit Dateioperationen, aber ohne Systembefehle + +Möglicherweise stellen Sie auch fest, dass unterschiedliche Modelle für unterschiedliche Anwendungsfälle geeignet sind. diff --git a/packages/web/src/content/docs/de/network.mdx b/packages/web/src/content/docs/de/network.mdx new file mode 100644 index 000000000..5bbd92fbe --- /dev/null +++ b/packages/web/src/content/docs/de/network.mdx @@ -0,0 +1,57 @@ +--- +title: Netzwerk +description: Konfigurieren Sie Proxys und benutzerdefinierte Zertifikate. +--- + +OpenCode unterstützt Standard-Proxy-Umgebungsvariablen und benutzerdefinierte Zertifikate für Unternehmensnetzwerkumgebungen. + +--- + +## Proxy + +OpenCode respects standard proxy environment variables. + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::caution +Der TUI kommuniziert mit einem lokalen HTTP-Server. Sie müssen den Proxy für diese Verbindung umgehen, um Routing-Schleifen zu verhindern. +::: + +Sie können den Port und den Hostnamen des Servers mit [CLI flags](/docs/cli#run) konfigurieren. + +--- + +### Authenticate + +Wenn Ihr Proxy eine Basisauthentifizierung erfordert, geben Sie Anmeldeinformationen in URL ein. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::caution +Vermeiden Sie hartkodierte Passwörter. Verwenden Sie Umgebungsvariablen oder einen sicheren Speicher für Anmeldeinformationen. +::: + +Für Proxys, die eine erweiterte Authentifizierung wie NTLM oder Kerberos erfordern, sollten Sie die Verwendung eines LLM-Gateways in Betracht ziehen, das Ihre Authentifizierungsmethode unterstützt. + +--- + +## Benutzerdefinierte Zertifikate + +Wenn Ihr Unternehmen benutzerdefinierte Zertifizierungsstellen für HTTPS-Verbindungen verwendet, konfigurieren Sie OpenCode so, dass es ihnen vertraut. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +Dies funktioniert sowohl für Proxy-Verbindungen als auch für den direkten API-Zugriff. diff --git a/packages/web/src/content/docs/de/permissions.mdx b/packages/web/src/content/docs/de/permissions.mdx new file mode 100644 index 000000000..9cac6a616 --- /dev/null +++ b/packages/web/src/content/docs/de/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: Berechtigungen +description: Steuern Sie, für welche Aktionen eine Genehmigung erforderlich ist. +--- + +OpenCode verwendet die `permission`-Konfiguration, um zu entscheiden, ob eine bestimmte Aktion automatisch ausgeführt werden soll, Sie dazu auffordern oder blockiert werden soll. + +Ab `v1.1.1` ist die alte boolesche Konfiguration `tools` veraltet und wurde in `permission` zusammengeführt. Die alte `tools`-Konfiguration wird aus Gründen der Abwärtskompatibilität weiterhin unterstützt. + +--- + +## Actions + +Jede Berechtigungsregel wird zu einem der folgenden aufgelöst: + +- `"allow"` – ohne Genehmigung ausführen +- `"ask"` — prompt for approval +- `"deny"` – Aktion blockieren + +--- + +## Configuration + +Sie können Berechtigungen global festlegen (mit `*`) und bestimmte Tools überschreiben. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +Sie können auch alle Berechtigungen auf einmal festlegen: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## Granulare Regeln (Objektsyntax) + +Bei den meisten Berechtigungen können Sie ein Objekt verwenden, um basierend auf der Werkzeugeingabe verschiedene Aktionen anzuwenden. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +Regeln werden nach Musterübereinstimmung ausgewertet, wobei die **letzte übereinstimmende Regel gewinnt**. Ein gängiges Muster besteht darin, zuerst die Catch-All-Regel `"*"` und danach spezifischere Regeln zu platzieren. + +### Wildcards + +Berechtigungsmuster verwenden einen einfachen Platzhalterabgleich: + +- `*` matches zero or more of any character +- `?` matches exactly one character +- Alle anderen Zeichen stimmen wörtlich überein + +### Erweiterung des Home-Verzeichnisses + +Sie können `~` oder `$HOME` am Anfang eines Musters verwenden, um auf Ihr Home-Verzeichnis zu verweisen. Dies ist besonders nützlich für [`external_directory`](#external-directories)-Regeln. + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### Externe Verzeichnisse + +Verwenden Sie `external_directory`, um Toolaufrufe zuzulassen, die Pfade außerhalb des Arbeitsverzeichnisses berühren, in dem OpenCode gestartet wurde. Dies gilt für jedes Werkzeug, das einen Pfad als Eingabe verwendet (z. B. `read`, `edit`, `list`, `glob`, `grep` und viele `bash`-Befehle). + +Die Home-Erweiterung (wie `~/...`) wirkt sich nur darauf aus, wie ein Muster geschrieben wird. Dadurch wird ein externer Pfad nicht zum Teil des aktuellen Arbeitsbereichs, daher müssen Pfade außerhalb des Arbeitsverzeichnisses weiterhin über `external_directory` zulässig sein. + +Dies ermöglicht beispielsweise den Zugriff auf alles unter `~/projects/personal/`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +Jedes hier zulässige Verzeichnis erbt dieselben Standardeinstellungen wie der aktuelle Arbeitsbereich. Seit [`read` defaults to `allow`](#defaults) sind Lesevorgänge auch für Einträge unter `external_directory` zulässig, sofern sie nicht überschrieben werden. Fügen Sie explizite Regeln hinzu, wenn ein Tool in diesen Pfaden eingeschränkt werden soll, z. B. das Blockieren von Bearbeitungen, während Lesevorgänge beibehalten werden: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +Konzentrieren Sie sich in der Liste auf vertrauenswürdige Pfade und fügen Sie bei Bedarf zusätzliche Zulassungs- oder Ablehnungsregeln für andere Tools hinzu (z. B. `bash`). + +--- + +## Verfügbare Berechtigungen + +OpenCode permissions are keyed by tool name, plus a couple of safety guards: + +- `read` – eine Datei lesen (entspricht dem Dateipfad) +- `edit` – alle Dateiänderungen (umfasst `edit`, `write`, `patch`, `multiedit`) +- `glob` – Datei-Globbing (entspricht dem Glob-Muster) +- `grep` – Inhaltssuche (entspricht dem Regex-Muster) +- `list` – Auflistung der Dateien in einem Verzeichnis (entspricht dem Verzeichnispfad) +- `bash` – Ausführen von Shell-Befehlen (entspricht analysierten Befehlen wie `git status --porcelain`) +- `task` – Subagenten starten (entspricht dem Subagententyp) +- `skill` – Laden einer Fertigkeit (entspricht dem Fertigkeitsnamen) +- `lsp` — running LSP queries (currently non-granular) +- `todoread`, `todowrite` – reading/updating die Aufgabenliste +- `webfetch` – Abrufen eines URL (entspricht dem URL) +- `websearch`, `codesearch` – web/code Suche (entspricht der Abfrage) +- `external_directory` – wird ausgelöst, wenn ein Tool Pfade außerhalb des Projektarbeitsverzeichnisses berührt +- `doom_loop` – wird ausgelöst, wenn derselbe Werkzeugaufruf dreimal mit identischer Eingabe wiederholt wird + +--- + +## Defaults + +Wenn Sie nichts angeben, beginnt OpenCode mit zulässigen Standardeinstellungen: + +- Die meisten Berechtigungen sind standardmäßig auf `"allow"` eingestellt. +- `doom_loop` und `external_directory` sind standardmäßig `"ask"`. +- `read` is `"allow"`, but `.env` files are denied by default: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## Was „Fragen“ bewirkt + +Wenn OpenCode zur Genehmigung auffordert, bietet UI drei Ergebnisse: + +- `once` — approve just this request +- `always` – zukünftige Anfragen genehmigen, die den vorgeschlagenen Mustern entsprechen (für den Rest der aktuellen OpenCode-Sitzung) +- `reject` – die Anfrage ablehnen + +Der Satz von Mustern, die `always` genehmigen würde, wird vom Tool bereitgestellt (Beispiel: Bash-Genehmigungen setzen normalerweise ein sicheres Befehlspräfix wie `git status*` auf die Whitelist). + +--- + +## Agents + +Sie können Berechtigungen pro Agent überschreiben. Agentenberechtigungen werden mit der globalen Konfiguration zusammengeführt und Agentenregeln haben Vorrang. [Learn more](/docs/agents#permissions) über Agentenberechtigungen. + +:::note +Ausführlichere Mustervergleichsbeispiele finden Sie oben im Abschnitt [Granular Rules (Object Syntax)](#granular-rules-object-syntax). +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +Sie können Agentenberechtigungen auch in Markdown konfigurieren: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tip +Verwenden Sie den Mustervergleich für Befehle mit Argumenten. `"grep *"` erlaubt `grep pattern file.txt`, während `"grep"` allein es blockieren würde. Befehle wie `git status` funktionieren für das Standardverhalten, erfordern jedoch eine explizite Erlaubnis (wie `"git status *"`), wenn Argumente übergeben werden. +::: diff --git a/packages/web/src/content/docs/de/plugins.mdx b/packages/web/src/content/docs/de/plugins.mdx new file mode 100644 index 000000000..d8c30fcfd --- /dev/null +++ b/packages/web/src/content/docs/de/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: Plugins +description: Schreiben Sie Ihre eigenen Plugins, um OpenCode zu erweitern. +--- + +Mit Plugins können Sie OpenCode erweitern, indem Sie verschiedene Ereignisse einbinden und das Verhalten anpassen. Sie können Plugins erstellen, um neue Funktionen hinzuzufügen, externe Dienste zu integrieren oder das Standardverhalten von OpenCode zu ändern. + +Beispiele finden Sie im von der Community erstellten [plugins](/docs/ecosystem#plugins). + +--- + +## Verwenden Sie ein Plugin + +Es gibt zwei Möglichkeiten, Plugins zu laden. + +--- + +### Aus lokalen Dateien + +Platzieren Sie JavaScript- oder TypeScript-Dateien im Plugin-Verzeichnis. + +- `.opencode/plugins/` – Plugins auf Projektebene +- `~/.config/opencode/plugins/` – Globale Plugins + +Dateien in diesen Verzeichnissen werden beim Start automatisch geladen. + +--- + +### Von npm + +Geben Sie npm-Pakete in Ihrer Konfigurationsdatei an. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +Es werden sowohl reguläre als auch bereichsbezogene NPM-Pakete unterstützt. + +Durchsuchen Sie die verfügbaren Plugins im [ecosystem](/docs/ecosystem#plugins). + +--- + +### Wie Plugins installiert werden + +**NPM-Plugins** werden beim Start automatisch mit Bun installiert. Pakete und ihre Abhängigkeiten werden in `~/.cache/opencode/node_modules/` zwischengespeichert. + +**Lokale Plugins** werden direkt aus dem Plugin-Verzeichnis geladen. Um externe Pakete zu verwenden, müssen Sie ein `package.json` in Ihrem Konfigurationsverzeichnis erstellen (siehe [Dependencies](#dependencies)) oder das Plugin auf npm und [add it to your config](/docs/config#plugins) veröffentlichen. + +--- + +### Auftrag laden + +Plugins werden aus allen Quellen geladen und alle Hooks werden nacheinander ausgeführt. Die Ladereihenfolge lautet: + +1. Globale Konfiguration (`~/.config/opencode/opencode.json`) +2. Projektkonfiguration (`opencode.json`) +3. Globales Plugin-Verzeichnis (`~/.config/opencode/plugins/`) +4. Projekt-Plugin-Verzeichnis (`.opencode/plugins/`) + +Doppelte npm-Pakete mit demselben Namen und derselben Version werden einmal geladen. Allerdings werden ein lokales Plugin und ein NPM-Plugin mit ähnlichen Namen beide separat geladen. + +--- + +## Erstellen Sie ein Plugin + +A plugin is a **JavaScript/TypeScript module** that exports one or more plugin +Funktionen. Jede Funktion empfängt ein Kontextobjekt und gibt ein Hooks-Objekt zurück. + +--- + +### Dependencies + +Lokale Plugins und benutzerdefinierte Tools können externe npm-Pakete verwenden. Fügen Sie Ihrem Konfigurationsverzeichnis ein `package.json` mit den benötigten Abhängigkeiten hinzu. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode führt beim Start `bun install` aus, um diese zu installieren. Ihre Plugins und Tools können sie dann importieren. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### Grundstruktur + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +Die Plugin-Funktion erhält: + +- `project`: Die aktuellen Projektinformationen. +- `directory`: Das aktuelle Arbeitsverzeichnis. +- `worktree`: Der Git-Worktree-Pfad. +- `client`: Ein Opencode-SDK-Client für die Interaktion mit AI. +- `$`: Buns [shell API](https://bun.com/docs/runtime/shell) zum Ausführen von Befehlen. + +--- + +### TypeScript support + +Für TypeScript-Plugins können Sie Typen aus dem Plugin-Paket importieren: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### Events + +Plugins können Ereignisse abonnieren, wie unten im Abschnitt „Beispiele“ gezeigt. Hier finden Sie eine Liste der verschiedenen verfügbaren Veranstaltungen. + +#### Befehlsereignisse + +- `command.executed` + +#### Dateiereignisse + +- `file.edited` +- `file.watcher.updated` + +#### Installationsereignisse + +- `installation.updated` + +#### LSP Ereignisse + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### Nachrichtenereignisse + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### Berechtigungsereignisse + +- `permission.asked` +- `permission.replied` + +#### Serverereignisse + +- `server.connected` + +#### Sitzungsereignisse + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### Todo-Events + +- `todo.updated` + +#### Shell-Events + +- `shell.env` + +#### Tool-Ereignisse + +- `tool.execute.after` +- `tool.execute.before` + +#### TUI Ereignisse + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## Examples + +Hier sind einige Beispiele für Plugins, mit denen Sie Opencode erweitern können. + +--- + +### Senden Sie Benachrichtigungen + +Senden Sie Benachrichtigungen, wenn bestimmte Ereignisse eintreten: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +Wir verwenden `osascript`, um AppleScript unter macOS auszuführen. Hier verwenden wir es zum Versenden von Benachrichtigungen. + +:::note +Wenn Sie die OpenCode-Desktop-App verwenden, kann diese automatisch Systembenachrichtigungen senden, wenn eine Antwort bereit ist oder wenn in einer Sitzung ein Fehler auftritt. +::: + +--- + +### .env protection + +Verhindern Sie, dass Opencode `.env`-Dateien liest: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### Umgebungsvariablen einfügen + +Fügen Sie Umgebungsvariablen in alle Shell-Ausführungen ein (AI-Tools und Benutzerterminals): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### Benutzerdefinierte Werkzeuge + +Plugins können Opencode auch benutzerdefinierte Tools hinzufügen: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +Der `tool`-Helfer erstellt ein benutzerdefiniertes Tool, das Opencode aufrufen kann. Es verwendet eine Zod-Schemafunktion und gibt eine Tooldefinition zurück mit: + +- `description`: Was das Tool macht +- `args`: Zod-Schema für die Argumente des Tools +- `execute`: Funktion, die ausgeführt wird, wenn das Tool aufgerufen wird + +Ihre benutzerdefinierten Tools stehen neben den integrierten Tools für Opencode zur Verfügung. + +--- + +### Logging + +Verwenden Sie `client.app.log()` anstelle von `console.log` für die strukturierte Protokollierung: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +Ebenen: `debug`, `info`, `warn`, `error`. Weitere Informationen finden Sie unter [SDK documentation](https://opencode.ai/docs/sdk). + +--- + +### Verdichtungshaken + +Passen Sie den Kontext an, der beim Komprimieren einer Sitzung einbezogen wird: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +Der Hook `experimental.session.compacting` wird ausgelöst, bevor der Hook LLM eine Fortsetzungszusammenfassung generiert. Verwenden Sie es, um domänenspezifischen Kontext einzufügen, der der standardmäßigen Komprimierungsaufforderung entgehen würde. + +Sie können die Komprimierungsaufforderung auch vollständig ersetzen, indem Sie `output.prompt` festlegen: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +Wenn `output.prompt` festgelegt ist, ersetzt es die standardmäßige Komprimierungsaufforderung vollständig. Das Array `output.context` wird in diesem Fall ignoriert. diff --git a/packages/web/src/content/docs/de/providers.mdx b/packages/web/src/content/docs/de/providers.mdx new file mode 100644 index 000000000..5a1421d8f --- /dev/null +++ b/packages/web/src/content/docs/de/providers.mdx @@ -0,0 +1,1889 @@ +--- +title: Anbieter +description: Verwendung eines beliebigen LLM-Anbieters in OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode verwendet [AI SDK](https://ai-sdk.dev/) und [Models.dev](https://models.dev) zur Unterstützung von **75+ LLM-Anbietern** und unterstützt die Ausführung lokaler Modelle. + +Um einen Anbieter hinzuzufügen, müssen Sie: + +1. Fügen Sie die API-Schlüssel für den Anbieter mit dem Befehl `/connect` hinzu. +2. Konfigurieren Sie den Anbieter in Ihrer OpenCode-Konfiguration. + +--- + +### Credentials + +Wenn Sie die API-Schlüssel eines Anbieters mit dem Befehl `/connect` hinzufügen, werden diese gespeichert +in `~/.local/share/opencode/auth.json`. + +--- + +### Config + +Sie können die Anbieter über den Abschnitt `provider` in Ihrem OpenCode anpassen +config. + +--- + +#### Basis URL + +Sie können den Basis-URL für jeden Anbieter anpassen, indem Sie die Option `baseURL` festlegen. Dies ist nützlich, wenn Sie Proxy-Dienste oder benutzerdefinierte Endpunkte verwenden. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen ist eine Liste von Modellen, die vom OpenCode-Team bereitgestellt wurden +Getestet und verifiziert, dass es gut mit OpenCode funktioniert. [Learn more](/docs/zen). + +:::tip +Wenn Sie neu sind, empfehlen wir Ihnen, mit OpenCode Zen zu beginnen. +::: + +1. Führen Sie den Befehl `/connect` in TUI aus, wählen Sie Opencode aus und gehen Sie zu [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Melden Sie sich an, geben Sie Ihre Rechnungsdaten ein und kopieren Sie Ihren API-Schlüssel. + +3. Fügen Sie Ihren API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie `/models` in TUI aus, um die Liste der von uns empfohlenen Modelle anzuzeigen. + + ```txt + /models + ``` + +Es funktioniert wie jeder andere Anbieter in OpenCode und ist völlig optional. + +--- + +## Directory + +Schauen wir uns einige der Anbieter im Detail an. Wenn Sie einen Anbieter hinzufügen möchten +Liste, zögern Sie nicht, ein PR zu öffnen. + +:::note +Sehen Sie hier keinen Anbieter? Senden Sie einen PR. +::: + +--- + +### 302.AI + +1. Gehen Sie zu [302.AI console](https://302.ai/), erstellen Sie ein Konto und generieren Sie einen API-Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **302.AI**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Schlüssel 302.AI API ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell auszuwählen. + + ```txt + /models + ``` + +--- + +### Amazonas-Grundgestein + +So verwenden Sie Amazon Bedrock mit OpenCode: + +1. Gehen Sie zum **Modellkatalog** in der Amazon Bedrock-Konsole und fordern Sie an + Zugriff auf die gewünschten Modelle. + + :::tip + Sie müssen Zugriff auf das gewünschte Modell in Amazon Bedrock haben. + ::: + +2. **Konfigurieren Sie die Authentifizierung** mit einer der folgenden Methoden: + + #### Umgebungsvariablen (Schnellstart) + + Legen Sie eine dieser Umgebungsvariablen fest, während Sie Opencode ausführen: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + Oder fügen Sie sie Ihrem Bash-Profil hinzu: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### Konfigurationsdatei (empfohlen) + + Für eine projektspezifische oder dauerhafte Konfiguration verwenden Sie `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **Verfügbare Optionen:** + - `region` - AWS region (e.g., `us-east-1`, `eu-west-1`) + - `profile` - AWS named profile from `~/.aws/credentials` + - `endpoint` – Benutzerdefinierter Endpunkt URL für VPC-Endpunkte (Alias ​​für generische `baseURL`-Option) + + :::tip + Konfigurationsdateioptionen haben Vorrang vor Umgebungsvariablen. + ::: + + #### Erweitert: VPC Endpunkte + + Wenn Sie VPC-Endpunkte für Bedrock verwenden: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::note + Die Option `endpoint` ist ein Alias ​​für die generische Option `baseURL` und verwendet AWS-spezifische Terminologie. Wenn sowohl `endpoint` als auch `baseURL` angegeben sind, hat `endpoint` Vorrang. + ::: + + #### Authentifizierungsmethoden + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: Erstellen Sie einen IAM-Benutzer und generieren Sie Zugriffsschlüssel in der AWS-Konsole + - **`AWS_PROFILE`**: Benannte Profile von `~/.aws/credentials` verwenden. Zuerst mit `aws configure --profile my-profile` oder `aws sso login` konfigurieren + - **`AWS_BEARER_TOKEN_BEDROCK`**: Generieren Sie langfristige API-Schlüssel aus der Amazon Bedrock-Konsole + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: Für EKS IRSA (IAM Rollen für Dienstkonten) oder andere Kubernetes-Umgebungen mit OIDC-Verbund. Diese Umgebungsvariablen werden von Kubernetes automatisch eingefügt, wenn Dienstkontoanmerkungen verwendet werden. + + #### Authentifizierungspriorität + + Amazon Bedrock verwendet die folgende Authentifizierungspriorität: + 1. **Bearer-Token** – `AWS_BEARER_TOKEN_BEDROCK`-Umgebungsvariable oder Token aus dem `/connect`-Befehl + 2. **AWS Anmeldeinformationskette** – Profil, Zugriffsschlüssel, gemeinsame Anmeldeinformationen, IAM Rollen, Web-Identitätstoken (EKS IRSA), Instanzmetadaten + + :::note + Wenn ein Inhabertoken festgelegt ist (über `/connect` oder `AWS_BEARER_TOKEN_BEDROCK`), hat es Vorrang vor allen AWS-Anmeldeinformationsmethoden, einschließlich konfigurierter Profile. + ::: + +3. Führen Sie den Befehl `/models` aus, um das gewünschte Modell auszuwählen. + + ```txt + /models + ``` + +:::note +Verwenden Sie für benutzerdefinierte Inferenzprofile den Modell- und Anbieternamen im Schlüssel und legen Sie die Eigenschaft `id` auf den Arn fest. Dadurch wird ein korrektes Caching sichergestellt: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### Anthropic + +1. Sobald Sie sich angemeldet haben, führen Sie den Befehl `/connect` aus und wählen Sie Anthropic aus. + + ```txt + /connect + ``` + +2. Hier können Sie die Option **Claude Pro/Max** auswählen und Ihr Browser wird geöffnet + und bitten Sie, sich zu authentifizieren. + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. Jetzt sollten alle Anthropic-Modelle verfügbar sein, wenn Sie den Befehl `/models` verwenden. + + ```txt + /models + ``` + +:::info +Die Verwendung Ihres Claude Pro/Max-Abonnements in OpenCode wird von [Anthropic](https://anthropic.com) nicht offiziell unterstützt. +::: + +##### Verwendung von API-Tasten + +Sie können auch **Erstellen eines API-Schlüssels** auswählen, wenn Sie kein Pro/Max-Abonnement haben. Außerdem wird Ihr Browser geöffnet, Sie werden aufgefordert, sich bei Anthropic anzumelden, und Sie erhalten einen Code, den Sie in Ihr Terminal einfügen können. + +Wenn Sie bereits über einen API-Schlüssel verfügen, können Sie **API-Schlüssel manuell eingeben** auswählen und ihn in Ihr Terminal einfügen. + +--- + +### Azure OpenAI + +:::note +Wenn Sie auf die Fehlermeldung „Es tut mir leid, aber ich kann Ihnen bei dieser Anfrage nicht weiterhelfen“ stoßen, versuchen Sie, den Inhaltsfilter in Ihrer Azure-Ressource von **DefaultV2** in **Default** zu ändern. +::: + +1. Gehen Sie zu [Azure portal](https://portal.azure.com/) und erstellen Sie eine **Azure OpenAI**-Ressource. Sie benötigen: + - **Ressourcenname**: Dies wird Teil Ihres API-Endpunkts (`https://RESOURCE_NAME.openai.azure.com/`) + - **API-Schlüssel**: Entweder `KEY 1` oder `KEY 2` aus Ihrer Ressource + +2. Gehen Sie zu [Azure AI Foundry](https://ai.azure.com/) und stellen Sie ein Modell bereit. + + :::note + Der Bereitstellungsname muss mit dem Modellnamen übereinstimmen, damit Opencode ordnungsgemäß funktioniert. + ::: + +3. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Azure**. + + ```txt + /connect + ``` + +4. Geben Sie Ihren API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Legen Sie Ihren Ressourcennamen als Umgebungsvariable fest: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + Oder fügen Sie es Ihrem Bash-Profil hinzu: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. Führen Sie den Befehl `/models` aus, um Ihr bereitgestelltes Modell auszuwählen. + + ```txt + /models + ``` + +--- + +### Azure Cognitive Services + +1. Gehen Sie zu [Azure portal](https://portal.azure.com/) und erstellen Sie eine **Azure OpenAI**-Ressource. Sie benötigen: + - **Ressourcenname**: Dies wird Teil Ihres API-Endpunkts (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) + - **API-Schlüssel**: Entweder `KEY 1` oder `KEY 2` aus Ihrer Ressource + +2. Gehen Sie zu [Azure AI Foundry](https://ai.azure.com/) und stellen Sie ein Modell bereit. + + :::note + Der Bereitstellungsname muss mit dem Modellnamen übereinstimmen, damit Opencode ordnungsgemäß funktioniert. + ::: + +3. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Azure Cognitive Services**. + + ```txt + /connect + ``` + +4. Geben Sie Ihren API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Legen Sie Ihren Ressourcennamen als Umgebungsvariable fest: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + Oder fügen Sie es Ihrem Bash-Profil hinzu: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. Führen Sie den Befehl `/models` aus, um Ihr bereitgestelltes Modell auszuwählen. + + ```txt + /models + ``` + +--- + +### Baseten + +1. Gehen Sie zu [Baseten](https://app.baseten.co/), erstellen Sie ein Konto und generieren Sie einen API-Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Baseten**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Baseten API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell auszuwählen. + + ```txt + /models + ``` + +--- + +### Cerebras + +1. Gehen Sie zu [Cerebras console](https://inference.cerebras.ai/), erstellen Sie ein Konto und generieren Sie einen API-Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Cerebras**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Cerebras-API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _Qwen 3 Coder 480B_ auszuwählen. + + ```txt + /models + ``` + +--- + +### Cloudflare AI Gateway + +Mit dem Cloudflare AI Gateway können Sie über einen einheitlichen Endpunkt auf Modelle von OpenAI, Anthropic, Workers AI und mehr zugreifen. Mit [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) benötigen Sie nicht für jeden Anbieter separate API-Schlüssel. + +1. Gehen Sie zu [Cloudflare dashboard](https://dash.cloudflare.com/), navigieren Sie zu **AI** > **AI Gateway** und erstellen Sie ein neues Gateway. + +2. Legen Sie Ihr Konto ID und Ihr Gateway ID als Umgebungsvariablen fest. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Cloudflare AI Gateway**. + + ```txt + /connect + ``` + +4. Geben Sie Ihr Cloudflare-API-Token ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + Oder legen Sie es als Umgebungsvariable fest. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. Führen Sie den Befehl `/models` aus, um ein Modell auszuwählen. + + ```txt + /models + ``` + + Sie können Modelle auch über Ihre Opencode-Konfiguration hinzufügen. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### Cortecs + +1. Gehen Sie zu [Cortecs console](https://cortecs.ai/), erstellen Sie ein Konto und generieren Sie einen API-Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Cortecs**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Cortecs-API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _Kimi K2 Instruct_ auszuwählen. + + ```txt + /models + ``` + +--- + +### DeepSeek + +1. Gehen Sie zu [DeepSeek console](https://platform.deepseek.com/), erstellen Sie ein Konto und klicken Sie auf **Neuen API-Schlüssel erstellen**. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **DeepSeek**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren DeepSeek API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein DeepSeek-Modell wie _DeepSeek Reasoner_ auszuwählen. + + ```txt + /models + ``` + +--- + +### Tiefe Infrarot + +1. Gehen Sie zu [Deep Infra dashboard](https://deepinfra.com/dash), erstellen Sie ein Konto und generieren Sie einen API-Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Deep Infra**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Deep Infra API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell auszuwählen. + + ```txt + /models + ``` + +--- + +### Firmware + +1. Gehen Sie zu [Firmware dashboard](https://app.firmware.ai/signup), erstellen Sie ein Konto und generieren Sie einen API-Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Firmware**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Firmware-Schlüssel API ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell auszuwählen. + + ```txt + /models + ``` + +--- + +### Feuerwerk AI + +1. Gehen Sie zu [Fireworks AI console](https://app.fireworks.ai/), erstellen Sie ein Konto und klicken Sie auf **API-Schlüssel erstellen**. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Fireworks AI**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Fireworks-Schlüssel AI API ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _Kimi K2 Instruct_ auszuwählen. + + ```txt + /models + ``` + +--- + +### GitLab Duo + +GitLab Duo bietet AI-gestützten Agenten-Chat mit nativen Tool-Aufruffunktionen über den Anthropic-Proxy von GitLab. + +1. Führen Sie den Befehl `/connect` aus und wählen Sie GitLab aus. + + ```txt + /connect + ``` + +2. Wählen Sie Ihre Authentifizierungsmethode: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### Verwendung von OAuth (empfohlen) + + Wählen Sie **OAuth** und Ihr Browser wird zur Autorisierung geöffnet. + + #### Verwendung eines persönlichen Zugriffstokens + 1. Gehe zu [GitLab User Settings > Access Tokens](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. Klicken Sie auf **Neues Token hinzufügen** + 3. Name: `OpenCode`, Bereiche: `api` + 4. Kopieren Sie das Token (beginnt mit `glpat-`) + 5. Geben Sie es im Terminal ein + +3. Führen Sie den Befehl `/models` aus, um verfügbare Modelle anzuzeigen. + + ```txt + /models + ``` + + Es stehen drei Claude-basierte Modelle zur Verfügung: + - **duo-chat-haiku-4-5** (Standard) – Schnelle Antworten für schnelle Aufgaben + - **duo-chat-sonnet-4-5** – Ausgewogene Leistung für die meisten Arbeitsabläufe + - **duo-chat-opus-4-5** – Am besten geeignet für komplexe Analysen + +:::note +Sie können auch die Umgebungsvariable „GITLAB_TOKEN“ angeben, wenn Sie dies nicht möchten +um das Token im Opencode-Authentifizierungsspeicher zu speichern. +::: + +##### Selbstgehostetes GitLab + +:::note[compliance note] +OpenCode verwendet ein kleines Modell für einige AI-Aufgaben wie das Generieren des Sitzungstitels. +Es ist standardmäßig für die Verwendung von gpt-5-nano konfiguriert und wird von Zen gehostet. Zum Sperren von OpenCode +Um nur Ihre eigene von GitLab gehostete Instanz zu verwenden, fügen Sie Folgendes zu Ihrer hinzu +`opencode.json`-Datei. Es wird außerdem empfohlen, die Sitzungsfreigabe zu deaktivieren. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +Für selbstgehostete GitLab-Instanzen: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +Wenn Ihre Instanz ein benutzerdefiniertes AI-Gateway ausführt: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +Oder fügen Sie zu Ihrem Bash-Profil hinzu: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +Ihr GitLab-Administrator muss Folgendes aktivieren: + +1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) für den Benutzer, die Gruppe oder die Instanz +2. Feature-Flags (über die Rails-Konsole): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### OAuth für selbstgehostete Instanzen + +Damit OAuth für Ihre selbst gehostete Instanz funktioniert, müssen Sie eine erstellen +eine neue Anwendung (Einstellungen → Anwendungen) mit dem +Rückruf URL `http://127.0.0.1:8080/callback` und folgende Bereiche: + +- API (Greifen Sie in Ihrem Namen auf API zu) +- read_user (Lesen Sie Ihre persönlichen Daten) +- read_repository (Ermöglicht schreibgeschützten Zugriff auf das Repository) + +Stellen Sie dann die Anwendung ID als Umgebungsvariable bereit: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +Weitere Dokumentation auf der [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth)-Homepage. + +##### Configuration + +Anpassen über `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API Tools (Optional, aber dringend empfohlen) + +So greifen Sie auf GitLab-Tools zu (Zusammenführungsanfragen, Probleme, Pipelines, CI/CD usw.): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +Dieses Plugin bietet umfassende GitLab-Repository-Verwaltungsfunktionen, einschließlich MR-Überprüfungen, Problemverfolgung, Pipeline-Überwachung und mehr. + +--- + +### GitHub-Copilot + +So verwenden Sie Ihr GitHub Copilot-Abonnement mit Opencode: + +:::note +Einige Modelle benötigen möglicherweise ein [Pro+ +Abonnement](https://github.com/features/copilot/plans) zur Verwendung. + +Einige Modelle müssen in Ihrem [GitHub Copilot settings](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use) manuell aktiviert werden. +::: + +1. Führen Sie den Befehl `/connect` aus und suchen Sie nach GitHub Copilot. + + ```txt + /connect + ``` + +2. Navigieren Sie zu [github.com/login/device](https://github.com/login/device) und geben Sie den Code ein. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. Führen Sie nun den Befehl `/models` aus, um das gewünschte Modell auszuwählen. + + ```txt + /models + ``` + +--- + +### Google Vertex AI + +So verwenden Sie Google Vertex AI mit OpenCode: + +1. Gehen Sie zum **Model Garden** in der Google Cloud Console und überprüfen Sie die + Modelle, die in Ihrer Region verfügbar sind. + + :::note + Sie benötigen ein Google Cloud-Projekt mit aktiviertem Vertex AI API. + ::: + +2. Legen Sie die erforderlichen Umgebungsvariablen fest: + - `GOOGLE_CLOUD_PROJECT`: Ihr Google Cloud-Projekt ID + - `VERTEX_LOCATION` (optional): Die Region für Vertex AI (standardmäßig `global`) + - Authentifizierung (wählen Sie eine aus): + - `GOOGLE_APPLICATION_CREDENTIALS`: Pfad zur Schlüsseldatei Ihres Dienstkontos JSON + - Authentifizieren Sie sich mit gcloud CLI: `gcloud auth application-default login` + + Legen Sie sie fest, während Sie Opencode ausführen. + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + Oder fügen Sie sie Ihrem Bash-Profil hinzu. + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::tip +Die Region `global` verbessert die Verfügbarkeit und reduziert Fehler ohne zusätzliche Kosten. Verwenden Sie regionale Endpunkte (e.g., `us-central1`) für Datenresidenzanforderungen. [Learn more](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. Führen Sie den Befehl `/models` aus, um das gewünschte Modell auszuwählen. + + ```txt + /models + ``` + +--- + +### Groq + +1. Gehen Sie zu [Groq console](https://console.groq.com/), klicken Sie auf **Create API Key** und kopieren Sie den Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach Groq. + + ```txt + /connect + ``` + +3. Geben Sie den Schlüssel API für den Anbieter ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um das gewünschte auszuwählen. + + ```txt + /models + ``` + +--- + +### Umarmendes Gesicht + +[Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers) bietet Zugriff auf offene Modelle, die von 17+-Anbietern unterstützt werden. + +1. Gehen Sie zu [Hugging Face settings](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained), um ein Token mit der Berechtigung zum Aufrufen von Inferenzanbietern zu erstellen. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Hugging Face**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Hugging Face-Token ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _Kimi-K2-Instruct_ oder _GLM-4.6_ auszuwählen. + + ```txt + /models + ``` + +--- + +### Helicone + +[Helicone](https://helicone.ai) ist eine LLM-Beobachtbarkeitsplattform, die Protokollierung, Überwachung und Analyse für Ihre AI-Anwendungen bietet. Das Helicone AI Gateway leitet Ihre Anfragen basierend auf dem Modell automatisch an den entsprechenden Anbieter weiter. + +1. Gehen Sie zu [Helicone](https://helicone.ai), erstellen Sie ein Konto und generieren Sie einen API-Schlüssel über Ihr Dashboard. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Helicone**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Helicone-API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell auszuwählen. + + ```txt + /models + ``` + +Weitere Anbieter und erweiterte Funktionen wie Caching und Ratenbegrenzung finden Sie unter [Helicone documentation](https://docs.helicone.ai). + +#### Optionale Konfigurationen + +Falls Sie eine Funktion oder ein Modell von Helicone sehen, das nicht automatisch über Opencode konfiguriert wird, können Sie es jederzeit selbst konfigurieren. + +Hier ist [Helicone's Model Directory](https://helicone.ai/models). Sie benötigen dies, um die IDs der Modelle abzurufen, die Sie hinzufügen möchten. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### Benutzerdefinierte Header + +Helicone unterstützt benutzerdefinierte Header für Funktionen wie Caching, Benutzerverfolgung und Sitzungsverwaltung. Fügen Sie sie mit `options.headers` zu Ihrer Anbieterkonfiguration hinzu: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### Sitzungsverfolgung + +Mit der [Sessions](https://docs.helicone.ai/features/sessions)-Funktion von Helicone können Sie zusammengehörige LLM-Anfragen gruppieren. Verwenden Sie das [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session)-Plugin, um jede OpenCode-Konversation automatisch als Sitzung in Helicone zu protokollieren. + +```bash +npm install -g opencode-helicone-session +``` + +Fügen Sie es Ihrer Konfiguration hinzu. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +Das Plugin fügt `Helicone-Session-Id`- und `Helicone-Session-Name`-Header in Ihre Anfragen ein. Auf der Seite „Sitzungen“ von Helicone wird jede OpenCode-Konversation als separate Sitzung aufgeführt. + +##### Gängige Helicone-Header + +| Kopfzeile | Beschreibung | +| -------------------------- | ------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | Antwort-Caching aktivieren (`true`/`false`) | +| `Helicone-User-Id` | Verfolgen Sie Metriken nach Benutzer | +| `Helicone-Property-[Name]` | Benutzerdefinierte Eigenschaften hinzufügen (e.g., `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | Anfragen mit Eingabeaufforderungsversionen verknüpfen | + +Alle verfügbaren Header finden Sie unter [Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory). + +--- + +### llama.cpp + +Sie können Opencode für die Verwendung lokaler Modelle über das Dienstprogramm [llama.cpp's](https://github.com/ggml-org/llama.cpp) llama-server konfigurieren + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +In diesem Beispiel: + +- `llama.cpp` ist der benutzerdefinierte Anbieter ID. Dies kann eine beliebige Zeichenfolge sein. +- `npm` gibt das Paket an, das für diesen Anbieter verwendet werden soll. Hier wird `@ai-sdk/openai-compatible` für jeden OpenAI-kompatiblen API verwendet. +- `name` ist der Anzeigename für den Anbieter im UI. +- `options.baseURL` ist der Endpunkt für den lokalen Server. +- `models` ist eine Zuordnung von Modell-IDs zu ihren Konfigurationen. Der Modellname wird in der Modellauswahlliste angezeigt. + +--- + +### IO.NET + +IO.NET bietet 17-Modelle, die für verschiedene Anwendungsfälle optimiert sind: + +1. Gehen Sie zu [IO.NET console](https://ai.io.net/), erstellen Sie ein Konto und generieren Sie einen API-Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **IO.NET**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Schlüssel IO.NET API ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell auszuwählen. + + ```txt + /models + ``` + +--- + +### LM Studio + +Sie können Opencode über LM Studio für die Verwendung lokaler Modelle konfigurieren. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +In diesem Beispiel: + +- `lmstudio` ist der benutzerdefinierte Anbieter ID. Dies kann eine beliebige Zeichenfolge sein. +- `npm` gibt das Paket an, das für diesen Anbieter verwendet werden soll. Hier wird `@ai-sdk/openai-compatible` für jeden OpenAI-kompatiblen API verwendet. +- `name` ist der Anzeigename für den Anbieter im UI. +- `options.baseURL` ist der Endpunkt für den lokalen Server. +- `models` ist eine Zuordnung von Modell-IDs zu ihren Konfigurationen. Der Modellname wird in der Modellauswahlliste angezeigt. + +--- + +### Mondschuss AI + +So verwenden Sie Kimi K2 von Moonshot AI: + +1. Gehen Sie zu [Moonshot AI console](https://platform.moonshot.ai/console), erstellen Sie ein Konto und klicken Sie auf **Schlüssel API erstellen**. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Moonshot AI**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Moonshot API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um _Kimi K2_ auszuwählen. + + ```txt + /models + ``` + +--- + +### MiniMax + +1. Gehen Sie zu [MiniMax API Console](https://platform.minimax.io/login), erstellen Sie ein Konto und generieren Sie einen API-Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **MiniMax**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren MiniMax-Schlüssel API ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _M2.1_ auszuwählen. + + ```txt + /models + ``` + +--- + +### Nebius-Token-Fabrik + +1. Gehen Sie zu [Nebius Token Factory console](https://tokenfactory.nebius.com/), erstellen Sie ein Konto und klicken Sie auf **Schlüssel hinzufügen**. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Nebius Token Factory**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Nebius Token Factory API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _Kimi K2 Instruct_ auszuwählen. + + ```txt + /models + ``` + +--- + +### Ollama + +Sie können Opencode über Ollama für die Verwendung lokaler Modelle konfigurieren. + +:::tip +Ollama kann sich automatisch für OpenCode konfigurieren. Weitere Informationen finden Sie unter [Ollama integration docs](https://docs.ollama.com/integrations/opencode). +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +In diesem Beispiel: + +- `ollama` ist der benutzerdefinierte Anbieter ID. Dies kann eine beliebige Zeichenfolge sein. +- `npm` gibt das Paket an, das für diesen Anbieter verwendet werden soll. Hier wird `@ai-sdk/openai-compatible` für jeden OpenAI-kompatiblen API verwendet. +- `name` ist der Anzeigename für den Anbieter im UI. +- `options.baseURL` ist der Endpunkt für den lokalen Server. +- `models` ist eine Zuordnung von Modell-IDs zu ihren Konfigurationen. Der Modellname wird in der Modellauswahlliste angezeigt. + +:::tip +Wenn Toolaufrufe nicht funktionieren, versuchen Sie, `num_ctx` in Ollama zu erhöhen. Beginnen Sie bei ca. 16.000 – 32.000 km. +::: + +--- + +### Ollama-Wolke + +So verwenden Sie Ollama Cloud mit OpenCode: + +1. Gehen Sie zu [https://ollama.com/](https://ollama.com/) und melden Sie sich an oder erstellen Sie ein Konto. + +2. Navigieren Sie zu **Einstellungen** > **Schlüssel** und klicken Sie auf **Add API Key**, um einen neuen API-Schlüssel zu generieren. + +3. Kopieren Sie den Schlüssel API zur Verwendung in OpenCode. + +4. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Ollama Cloud**. + + ```txt + /connect + ``` + +5. Geben Sie Ihren Ollama Cloud API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **Wichtig**: Bevor Sie Cloud-Modelle in OpenCode verwenden, müssen Sie die Modellinformationen lokal abrufen: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. Führen Sie den Befehl `/models` aus, um Ihr Ollama Cloud-Modell auszuwählen. + + ```txt + /models + ``` + +--- + +### OpenAI + +Wir empfehlen, sich für [ChatGPT Plus or Pro](https://chatgpt.com/pricing) anzumelden. + +1. Führen Sie nach der Anmeldung den Befehl `/connect` aus und wählen Sie OpenAI aus. + + ```txt + /connect + ``` + +2. Hier können Sie die Option **ChatGPT Plus/Pro** auswählen und Ihr Browser wird geöffnet + und bitten Sie, sich zu authentifizieren. + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. Jetzt sollten alle OpenAI-Modelle verfügbar sein, wenn Sie den Befehl `/models` verwenden. + + ```txt + /models + ``` + +##### Verwendung von API-Tasten + +Wenn Sie bereits über einen API-Schlüssel verfügen, können Sie **API-Schlüssel manuell eingeben** auswählen und ihn in Ihr Terminal einfügen. + +--- + +### OpenCode Zen + +OpenCode Zen ist eine Liste getesteter und verifizierter Modelle, die vom OpenCode-Team bereitgestellt werden. [Learn more](/docs/zen). + +1. Melden Sie sich bei **OpenCode Zen** an und klicken Sie auf **Create API Key**. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **OpenCode Zen**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren OpenCode-Schlüssel API ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _Qwen 3 Coder 480B_ auszuwählen. + + ```txt + /models + ``` + +--- + +### OpenRouter + +1. Gehen Sie zu [OpenRouter dashboard](https://openrouter.ai/settings/keys), klicken Sie auf **Create API Key** und kopieren Sie den Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach OpenRouter. + + ```txt + /connect + ``` + +3. Geben Sie den Schlüssel API für den Anbieter ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Viele OpenRouter-Modelle sind standardmäßig vorinstalliert. Führen Sie den Befehl `/models` aus, um das gewünschte Modell auszuwählen. + + ```txt + /models + ``` + + Sie können auch zusätzliche Modelle über Ihre Opencode-Konfiguration hinzufügen. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. Sie können sie auch über Ihre Opencode-Konfiguration anpassen. Hier ist ein Beispiel für die Angabe eines Anbieters + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP AI Kern + +SAP AI Core bietet Zugriff auf 40+ Modelle von OpenAI, Anthropic, Google, Amazon, Meta, Mistral und AI21 über eine einheitliche Plattform. + +1. Gehen Sie zu Ihrem [SAP BTP Cockpit](https://account.hana.ondemand.com/), navigieren Sie zu Ihrer SAP AI Core-Dienstinstanz und erstellen Sie einen Dienstschlüssel. + + :::tip + Der Dienstschlüssel ist ein JSON-Objekt, das `clientid`, `clientsecret`, `url` und `serviceurls.AI_API_URL` enthält. Sie finden Ihre AI Core-Instanz unter **Dienste** > **Instanzen und Abonnements** im BTP Cockpit. + ::: + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **SAP AI Core**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Serviceschlüssel JSON ein. + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + Oder legen Sie die Umgebungsvariable `AICORE_SERVICE_KEY` fest: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + Oder fügen Sie es Ihrem Bash-Profil hinzu: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. Legen Sie optional die Bereitstellung ID und die Ressourcengruppe fest: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::note + Diese Einstellungen sind optional und sollten entsprechend Ihrem SAP AI Core-Setup konfiguriert werden. + ::: + +5. Führen Sie den Befehl `/models` aus, um aus 40+ verfügbaren Modellen auszuwählen. + + ```txt + /models + ``` + +--- + +### OVHcloud AI Endpunkte + +1. Gehen Sie zum [OVHcloud panel](https://ovh.com/manager). Navigieren Sie zum Abschnitt `Public Cloud`, `AI & Machine Learning` > `AI Endpoints` und klicken Sie auf der Registerkarte `API Keys` auf **Neuen API-Schlüssel erstellen**. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **OVHcloud AI Endpoints**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren OVHcloud AI Endpoints API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _gpt-oss-120b_ auszuwählen. + + ```txt + /models + ``` + +--- + +### Scaleway + +So verwenden Sie [Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/) mit Opencode: + +1. Gehen Sie zu [Scaleway Console IAM settings](https://console.scaleway.com/iam/api-keys), um einen neuen API-Schlüssel zu generieren. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Scaleway**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Scaleway-API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _devstral-2-123b-instruct-2512_ oder _gpt-oss-120b_ auszuwählen. + + ```txt + /models + ``` + +--- + +### Zusammen AI + +1. Gehen Sie zu [Together AI console](https://api.together.ai), erstellen Sie ein Konto und klicken Sie auf **Schlüssel hinzufügen**. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Together AI**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Together-Schlüssel AI API ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _Kimi K2 Instruct_ auszuwählen. + + ```txt + /models + ``` + +--- + +### Venedig AI + +1. Gehen Sie zu [Venice AI console](https://venice.ai), erstellen Sie ein Konto und generieren Sie einen API-Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Venedig AI**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Venedig-Schlüssel AI API ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _Llama 3.3 70B_ auszuwählen. + + ```txt + /models + ``` + +--- + +### Vercel AI Gateway + +Mit dem Vercel AI Gateway können Sie über einen einheitlichen Endpunkt auf Modelle von OpenAI, Anthropic, Google, xAI und mehr zugreifen. Die Modelle werden zum Listenpreis ohne Aufschlag angeboten. + +1. Gehen Sie zum [Vercel dashboard](https://vercel.com/), navigieren Sie zur Registerkarte **AI Gateway** und klicken Sie auf **API-Schlüssel**, um einen neuen API-Schlüssel zu erstellen. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Vercel AI Gateway**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren Vercel AI Gateway API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell auszuwählen. + + ```txt + /models + ``` + +Sie können Modelle auch über Ihre Opencode-Konfiguration anpassen. Hier ist ein Beispiel für die Angabe der Provider-Routing-Reihenfolge. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +Einige nützliche Routing-Optionen: + +| Option | Beschreibung | +| ------------------- | ---------------------------------------------------- | +| `order` | Anbietersequenz zum Ausprobieren | +| `only` | Auf bestimmte Anbieter beschränken | +| `zeroDataRetention` | Verwenden Sie nur Anbieter mit Null-Datenaufbewahrungsrichtlinien | + +--- + +### xAI + +1. Gehen Sie zu [xAI console](https://console.x.ai/), erstellen Sie ein Konto und generieren Sie einen API-Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **xAI**. + + ```txt + /connect + ``` + +3. Geben Sie Ihren xAI API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _Grok Beta_ auszuwählen. + + ```txt + /models + ``` + +--- + +### Z.AI + +1. Gehen Sie zu [Z.AI API console](https://z.ai/manage-apikey/apikey-list), erstellen Sie ein Konto und klicken Sie auf **Neuen API-Schlüssel erstellen**. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach **Z.AI**. + + ```txt + /connect + ``` + + Wenn Sie den **GLM Coding Plan** abonniert haben, wählen Sie **Z.AI Coding Plan**. + +3. Geben Sie Ihren Z.AI API-Schlüssel ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Führen Sie den Befehl `/models` aus, um ein Modell wie _GLM-4.7_ auszuwählen. + + ```txt + /models + ``` + +--- + +### ZenMux + +1. Gehen Sie zu [ZenMux dashboard](https://zenmux.ai/settings/keys), klicken Sie auf **Create API Key** und kopieren Sie den Schlüssel. + +2. Führen Sie den Befehl `/connect` aus und suchen Sie nach ZenMux. + + ```txt + /connect + ``` + +3. Geben Sie den Schlüssel API für den Anbieter ein. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Viele ZenMux-Modelle sind standardmäßig vorinstalliert. Führen Sie den Befehl `/models` aus, um das gewünschte Modell auszuwählen. + + ```txt + /models + ``` + + Sie können auch zusätzliche Modelle über Ihre Opencode-Konfiguration hinzufügen. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## Benutzerdefinierter Anbieter + +So fügen Sie einen **OpenAI-kompatiblen** Anbieter hinzu, der nicht im Befehl `/connect` aufgeführt ist: + +:::tip +Sie können jeden OpenAI-kompatiblen Anbieter mit Opencode verwenden. Die meisten modernen AI-Anbieter bieten OpenAI-kompatible APIs an. +::: + +1. Führen Sie den Befehl `/connect` aus und scrollen Sie nach unten zu **Andere**. + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. Geben Sie einen eindeutigen ID für den Anbieter ein. + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note + Wählen Sie einen einprägsamen ID, den Sie in Ihrer Konfigurationsdatei verwenden. + ::: + +3. Geben Sie Ihren API-Schlüssel für den Anbieter ein. + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. Erstellen oder aktualisieren Sie Ihre `opencode.json`-Datei in Ihrem Projektverzeichnis: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + Hier sind die Konfigurationsmöglichkeiten: + - **npm**: AI SDK zu verwendendes Paket, `@ai-sdk/openai-compatible` für OpenAI-kompatible Anbieter + - **Name**: Anzeigename in UI. + - **Modelle**: Verfügbare Modelle. + - **options.baseURL**: API endpoint URL. + - **Optionen.apiKey**: Legen Sie optional den Schlüssel API fest, wenn Sie keine Authentifizierung verwenden. + - **options.headers**: Optional benutzerdefinierte Header festlegen. + + Mehr zu den erweiterten Optionen im Beispiel unten. + +5. Führen Sie den Befehl `/models` aus und Ihr benutzerdefinierter Anbieter und Ihre Modelle werden in der Auswahlliste angezeigt. + +--- + +##### Example + +Hier ist ein Beispiel für die Einstellung der Optionen `apiKey`, `headers` und Modell `limit`. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +Konfigurationsdetails: + +- **apiKey**: Wird mit der Variablensyntax `env`, [learn more](/docs/config#env-vars), festgelegt. +- **Header**: Benutzerdefinierte Header, die mit jeder Anfrage gesendet werden. +- **limit.context**: Maximale Eingabetokens, die das Modell akzeptiert. +- **limit.output**: Maximale Token, die das Modell generieren kann. + +Mithilfe der `limit`-Felder kann OpenCode erkennen, wie viel Kontext Sie noch haben. Standardanbieter beziehen diese automatisch von models.dev. + +--- + +## Troubleshooting + +Wenn Sie Probleme beim Konfigurieren eines Anbieters haben, überprüfen Sie Folgendes: + +1. **Überprüfen Sie die Authentifizierungseinrichtung**: Führen Sie `opencode auth list` aus, um zu sehen, ob die Anmeldeinformationen vorhanden sind + für den Anbieter werden Ihrer Konfiguration hinzugefügt. + + Dies gilt nicht für Anbieter wie Amazon Bedrock, die für ihre Authentifizierung auf Umgebungsvariablen angewiesen sind. + +2. Überprüfen Sie bei benutzerdefinierten Anbietern die Opencode-Konfiguration und: + - Stellen Sie sicher, dass der im Befehl `/connect` verwendete Anbieter ID mit dem ID in Ihrer Opencode-Konfiguration übereinstimmt. + - Für den Anbieter wird das richtige npm-Paket verwendet. Verwenden Sie beispielsweise `@ai-sdk/cerebras` für Cerebras. Und für alle anderen OpenAI-kompatiblen Anbieter verwenden Sie `@ai-sdk/openai-compatible`. + - Überprüfen Sie, ob im Feld `options.baseURL` der richtige Endpunkt API verwendet wird. diff --git a/packages/web/src/content/docs/de/rules.mdx b/packages/web/src/content/docs/de/rules.mdx new file mode 100644 index 000000000..1bce9ffd3 --- /dev/null +++ b/packages/web/src/content/docs/de/rules.mdx @@ -0,0 +1,190 @@ +--- +title: Rules +description: Lege eigene Anweisungen fuer opencode fest. +--- + +Du kannst opencode ueber eine `AGENTS.md`-Datei mit eigenen Anweisungen steuern. +Das ist aehnlich zu den Regeln in Cursor und wird direkt in den LLM-Kontext geladen. + +--- + +## Initialisieren + +Um eine neue `AGENTS.md` zu erstellen, fuehre in opencode den Befehl `/init` aus. + +:::tip +Du solltest die `AGENTS.md` deines Projekts in Git committen. +::: + +Der Befehl scannt dein Projekt und erzeugt daraus eine passende `AGENTS.md`. +So kann opencode sich in deinem Code besser orientieren. + +Wenn bereits eine `AGENTS.md` existiert, versucht opencode sie zu erweitern. + +--- + +## Example + +Du kannst die Datei auch manuell anlegen. +Hier ist ein Beispiel, was in einer `AGENTS.md` stehen kann. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +Hier hinterlegst du projektspezifische Regeln, die dein Team gemeinsam nutzt. + +--- + +## Typen + +opencode kann `AGENTS.md` aus mehreren Orten lesen. +Die Orte haben unterschiedliche Zwecke. + +### Project + +Lege eine `AGENTS.md` im Projekt-Root ab, um projektspezifische Regeln zu definieren. +Diese gelten nur in diesem Verzeichnis und seinen Unterordnern. + +### Global + +Du kannst auch globale Regeln in `~/.config/opencode/AGENTS.md` speichern. +Diese gelten in allen opencode-Sitzungen. + +Da diese Datei nicht in Git landet und nicht mit dem Team geteilt wird, eignet sie sich fuer persoenliche Regeln. + +### Claude Code Compatibility + +Wenn du von Claude Code kommst, unterstuetzt OpenCode dessen Dateikonventionen als Fallback: + +- **Projektregeln**: `CLAUDE.md` im Projekt (wenn keine `AGENTS.md` existiert) +- **Globale Regeln**: `~/.claude/CLAUDE.md` (wenn keine `~/.config/opencode/AGENTS.md` existiert) +- **Skills**: `~/.claude/skills/` - siehe [Agent Skills](/docs/skills/) fuer Details + +Um die Claude-Code-Kompatibilitaet zu deaktivieren, setze eine dieser Umgebungsvariablen: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## Precedence + +Beim Start sucht opencode in dieser Reihenfolge nach Regeldateien: + +1. **Lokale Dateien** beim Hochlaufen ab dem aktuellen Verzeichnis (`AGENTS.md`, `CLAUDE.md`) +2. **Globale Datei** unter `~/.config/opencode/AGENTS.md` +3. **Claude-Code-Datei** unter `~/.claude/CLAUDE.md` (falls nicht deaktiviert) + +Pro Kategorie gewinnt die zuerst passende Datei. +Wenn sowohl `AGENTS.md` als auch `CLAUDE.md` existieren, wird nur `AGENTS.md` verwendet. + +--- + +## Eigene Anweisungen + +Du kannst zusaetzliche Anweisungsdateien in deiner `opencode.json` oder in `~/.config/opencode/opencode.json` angeben. +So kann dein Team bestehende Regeln wiederverwenden, statt Inhalte in `AGENTS.md` zu duplizieren. + +Beispiel: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Du kannst auch Remote-URLs nutzen, um Regeln aus dem Web zu laden. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +Remote-Anweisungen werden mit 5 Sekunden Timeout geladen. + +Alle Anweisungsdateien werden mit deinen `AGENTS.md`-Dateien kombiniert. + +--- + +## Externe Dateien referenzieren + +opencode parst Datei-Referenzen in `AGENTS.md` nicht automatisch. +Du erreichst aehnliches Verhalten auf zwei Wegen. + +### Mit opencode.json + +Empfohlen ist das `instructions`-Feld in der `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Manuelle Anweisungen in AGENTS.md + +Du kannst opencode explizit anweisen, externe Dateien zu lesen. +Hier ein praxisnahes Beispiel: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +Damit kannst du: + +- Modulare, wiederverwendbare Regeldateien erstellen +- Regeln projektuebergreifend per Symlink oder Git-Submodule teilen +- `AGENTS.md` kurz halten und auf Detailregeln verweisen +- Sicherstellen, dass Dateien nur bei Bedarf geladen werden + +:::tip +Fuer Monorepos oder gemeinsame Standards ist `opencode.json` mit Glob-Mustern (z. B. `packages/*/AGENTS.md`) oft wartbarer als manuelle Anweisungen. +::: diff --git a/packages/web/src/content/docs/de/sdk.mdx b/packages/web/src/content/docs/de/sdk.mdx new file mode 100644 index 000000000..9610cdf2b --- /dev/null +++ b/packages/web/src/content/docs/de/sdk.mdx @@ -0,0 +1,393 @@ +--- +title: SDK +description: Typsicherer JS-Client fuer den opencode-Server. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Das opencode JS/TS SDK bietet einen typsicheren Client fuer die Server-API. +Damit kannst du Integrationen bauen und opencode programmatisch steuern. + +[Mehr zum Server](/docs/server). Beispiele findest du in den [Community-Projekten](/docs/ecosystem#projects). + +--- + +## Install + +Installiere das SDK ueber npm: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## Client erstellen + +Erstelle eine opencode-Instanz: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +Das startet Server und Client. + +#### Optionen + +| Option | Type | Description | Default | +| ---------- | ------------- | ------------------------------ | ----------- | +| `hostname` | `string` | Server hostname | `127.0.0.1` | +| `port` | `number` | Server port | `4096` | +| `signal` | `AbortSignal` | Abort signal for cancellation | `undefined` | +| `timeout` | `number` | Timeout in ms for server start | `5000` | +| `config` | `Config` | Configuration object | `{}` | + +--- + +## Config + +Du kannst ein Konfigurationsobjekt uebergeben, um das Verhalten anzupassen. +`opencode.json` wird weiterhin geladen, kann aber inline ueberschrieben oder erweitert werden: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## Nur Client + +Wenn opencode bereits laeuft, kannst du nur einen Client erstellen und verbinden: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### Options + +| Option | Type | Description | Default | +| --------------- | ---------- | -------------------------------- | ----------------------- | +| `baseUrl` | `string` | URL of the server | `http://localhost:4096` | +| `fetch` | `function` | Custom fetch implementation | `globalThis.fetch` | +| `parseAs` | `string` | Response parsing method | `auto` | +| `responseStyle` | `string` | Return style: `data` or `fields` | `fields` | +| `throwOnError` | `boolean` | Throw errors instead of return | `false` | + +--- + +## Typen + +Das SDK bringt TypeScript-Definitionen fuer alle API-Typen mit. +Du kannst sie direkt importieren: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +Alle Typen werden aus der OpenAPI-Spezifikation des Servers generiert und sind in der Typdatei verfuegbar. + +--- + +## Errors + +Das SDK kann Fehler werfen, die du abfangen und behandeln kannst: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## APIs + +Das SDK stellt alle Server-APIs ueber einen typsicheren Client bereit. + +--- + +### Global + +| Method | Description | Response | +| ----------------- | ------------------------------- | ------------------------------------ | +| `global.health()` | Check server health and version | `{ healthy: true, version: string }` | + +--- + +#### Examples + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### App + +| Method | Description | Response | +| -------------- | ------------------------- | ------------------------------------------- | +| `app.log()` | Write a log entry | `boolean` | +| `app.agents()` | List all available agents | Agent[] | + +--- + +#### Examples + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### Project + +| Method | Description | Response | +| ------------------- | ------------------- | --------------------------------------------- | +| `project.list()` | List all projects | Project[] | +| `project.current()` | Get current project | Project | + +--- + +#### Examples + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### Path + +| Method | Description | Response | +| ------------ | ---------------- | ---------------------------------------- | +| `path.get()` | Get current path | Path | + +--- + +#### Examples + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### Config + +| Method | Description | Response | +| -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` | Get config info | Config | +| `config.providers()` | List providers and default models | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +#### Examples + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### Sessions + +| Method | Description | Notes | +| ---------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` | List sessions | Returns Session[] | +| `session.get({ path })` | Get session | Returns Session | +| `session.children({ path })` | List child sessions | Returns Session[] | +| `session.create({ body })` | Create session | Returns Session | +| `session.delete({ path })` | Delete session | Returns `boolean` | +| `session.update({ path, body })` | Update session properties | Returns Session | +| `session.init({ path, body })` | Analyze app and create `AGENTS.md` | Returns `boolean` | +| `session.abort({ path })` | Abort a running session | Returns `boolean` | +| `session.share({ path })` | Share session | Returns Session | +| `session.unshare({ path })` | Unshare session | Returns Session | +| `session.summarize({ path, body })` | Summarize session | Returns `boolean` | +| `session.messages({ path })` | List messages in a session | Returns `{ info: `Message`, parts: `Part[]`}[]` | +| `session.message({ path })` | Get message details | Returns `{ info: `Message`, parts: `Part[]`}` | +| `session.prompt({ path, body })` | Send prompt message | `body.noReply: true` returns UserMessage (context only). Default returns AssistantMessage with AI response | +| `session.command({ path, body })` | Send command to session | Returns `{ info: `AssistantMessage`, parts: `Part[]`}` | +| `session.shell({ path, body })` | Run a shell command | Returns AssistantMessage | +| `session.revert({ path, body })` | Revert a message | Returns Session | +| `session.unrevert({ path })` | Restore reverted messages | Returns Session | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | Respond to a permission request | Returns `boolean` | + +--- + +#### Examples + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### Files + +| Method | Description | Response | +| ------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `find.text({ query })` | Search for text in files | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `find.files({ query })` | Find files and directories by name | `string[]` (paths) | +| `find.symbols({ query })` | Find workspace symbols | Symbol[] | +| `file.read({ query })` | Read a file | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | Get status for tracked files | File[] | + +`find.files` supports a few optional query fields: + +- `type`: `"file"` or `"directory"` +- `directory`: override the project root for the search +- `limit`: max results (1–200) + +--- + +#### Examples + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +| Method | Description | Response | +| ------------------------------ | ------------------------- | --------- | +| `tui.appendPrompt({ body })` | Append text to the prompt | `boolean` | +| `tui.openHelp()` | Open the help dialog | `boolean` | +| `tui.openSessions()` | Open the session selector | `boolean` | +| `tui.openThemes()` | Open the theme selector | `boolean` | +| `tui.openModels()` | Open the model selector | `boolean` | +| `tui.submitPrompt()` | Submit the current prompt | `boolean` | +| `tui.clearPrompt()` | Clear the prompt | `boolean` | +| `tui.executeCommand({ body })` | Execute a command | `boolean` | +| `tui.showToast({ body })` | Show toast notification | `boolean` | + +--- + +#### Examples + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### Auth + +| Method | Description | Response | +| ------------------- | ------------------------------ | --------- | +| `auth.set({ ... })` | Set authentication credentials | `boolean` | + +--- + +#### Examples + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### Events + +| Method | Description | Response | +| ------------------- | ------------------------- | ------------------------- | +| `event.subscribe()` | Server-sent events stream | Server-sent events stream | + +--- + +#### Examples + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/de/server.mdx b/packages/web/src/content/docs/de/server.mdx new file mode 100644 index 000000000..a8a3112c6 --- /dev/null +++ b/packages/web/src/content/docs/de/server.mdx @@ -0,0 +1,291 @@ +--- +title: Server +description: Nutze den opencode-Server ueber HTTP. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Der Befehl `opencode serve` startet einen headless HTTP-Server. +Er stellt einen OpenAPI-Endpunkt bereit, den ein opencode-Client nutzen kann. + +--- + +### Nutzung + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### Optionen + +| Flag | Description | Default | +| --------------- | ----------------------------------- | ---------------- | +| `--port` | Port to listen on | `4096` | +| `--hostname` | Hostname to listen on | `127.0.0.1` | +| `--mdns` | Enable mDNS discovery | `false` | +| `--mdns-domain` | Custom domain name for mDNS service | `opencode.local` | +| `--cors` | Additional browser origins to allow | `[]` | + +`--cors` kann mehrfach angegeben werden: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### Authentifizierung + +Setze `OPENCODE_SERVER_PASSWORD`, um den Server mit HTTP Basic Auth zu schuetzen. +Der Benutzername ist standardmaessig `opencode`, kann aber mit `OPENCODE_SERVER_USERNAME` ueberschrieben werden. Das gilt fuer `opencode serve` und `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### Funktionsweise + +Wenn du `opencode` startest, werden TUI und Server gestartet. +Die TUI ist dabei der Client, der mit dem Server spricht; dessen OpenAPI-3.1-Endpunkt dient auch zur Generierung des [SDK](/docs/sdk). + +:::tip +Nutze den opencode-Server, um opencode programmatisch anzusteuern. +::: + +Diese Architektur erlaubt mehrere Clients und programmatische Nutzung. + +Mit `opencode serve` startest du einen eigenstaendigen Server. +Laeuft bereits eine TUI, startet `opencode serve` trotzdem eine neue Serverinstanz. + +--- + +#### Mit bestehendem Server verbinden + +Beim TUI-Start werden Port und Hostname zufaellig gewaehlt. +Alternativ gibst du `--hostname` und `--port` als [Flags](/docs/cli) vor und verbindest dich dann gezielt damit. + +Der Endpunkt [`/tui`](#tui) kann die TUI ueber den Server steuern, etwa zum Vorbelegen oder Abschicken von Prompts. +Dieses Muster nutzen auch die OpenCode-[IDE](/docs/ide)-Plugins. + +--- + +## Spec + +Der Server veroeffentlicht eine OpenAPI-3.1-Spezifikation unter: + +``` +http://:/doc +``` + +Zum Beispiel `http://localhost:4096/doc`. +Nutze die Spec zum Generieren von Clients, zum Pruefen von Request/Response-Typen oder in einem Swagger-Explorer. + +--- + +## APIs + +Der opencode-Server stellt folgende APIs bereit. + +--- + +### Global + +| Method | Path | Description | Response | +| ------ | ---------------- | ------------------------------ | ------------------------------------ | +| `GET` | `/global/health` | Get server health and version | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | Get global events (SSE stream) | Event stream | + +--- + +### Project + +| Method | Path | Description | Response | +| ------ | ------------------ | ----------------------- | --------------------------------------------- | +| `GET` | `/project` | List all projects | Project[] | +| `GET` | `/project/current` | Get the current project | Project | + +--- + +### Path & VCS + +| Method | Path | Description | Response | +| ------ | ------- | ------------------------------------ | ------------------------------------------- | +| `GET` | `/path` | Get the current path | Path | +| `GET` | `/vcs` | Get VCS info for the current project | VcsInfo | + +--- + +### Instance + +| Method | Path | Description | Response | +| ------ | ------------------- | ---------------------------- | --------- | +| `POST` | `/instance/dispose` | Dispose the current instance | `boolean` | + +--- + +### Config + +| Method | Path | Description | Response | +| ------- | ------------------- | --------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` | Get config info | Config | +| `PATCH` | `/config` | Update config | Config | +| `GET` | `/config/providers` | List providers and default models | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +### Provider + +| Method | Path | Description | Response | +| ------ | -------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` | List all providers | `{ all: `Provider[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | Get provider authentication methods | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | Authorize a provider using OAuth | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | Handle OAuth callback for a provider | `boolean` | + +--- + +### Sessions + +| Method | Path | Description | Notes | +| -------- | ---------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------- | +| `GET` | `/session` | List all sessions | Returns Session[] | +| `POST` | `/session` | Create a new session | body: `{ parentID?, title? }`, returns Session | +| `GET` | `/session/status` | Get session status for all sessions | Returns `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | Get session details | Returns Session | +| `DELETE` | `/session/:id` | Delete a session and all its data | Returns `boolean` | +| `PATCH` | `/session/:id` | Update session properties | body: `{ title? }`, returns Session | +| `GET` | `/session/:id/children` | Get a session's child sessions | Returns Session[] | +| `GET` | `/session/:id/todo` | Get the todo list for a session | Returns Todo[] | +| `POST` | `/session/:id/init` | Analyze app and create `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returns `boolean` | +| `POST` | `/session/:id/fork` | Fork an existing session at a message | body: `{ messageID? }`, returns Session | +| `POST` | `/session/:id/abort` | Abort a running session | Returns `boolean` | +| `POST` | `/session/:id/share` | Share a session | Returns Session | +| `DELETE` | `/session/:id/share` | Unshare a session | Returns Session | +| `GET` | `/session/:id/diff` | Get the diff for this session | query: `messageID?`, returns FileDiff[] | +| `POST` | `/session/:id/summarize` | Summarize the session | body: `{ providerID, modelID }`, returns `boolean` | +| `POST` | `/session/:id/revert` | Revert a message | body: `{ messageID, partID? }`, returns `boolean` | +| `POST` | `/session/:id/unrevert` | Restore all reverted messages | Returns `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | Respond to a permission request | body: `{ response, remember? }`, returns `boolean` | + +--- + +### Messages + +| Method | Path | Description | Notes | +| ------ | --------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` | List messages in a session | query: `limit?`, returns `{ info: `Message`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` | Send a message and wait for response | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, returns `{ info: `Message`, parts: `Part[]`}` | +| `GET` | `/session/:id/message/:messageID` | Get message details | Returns `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/prompt_async` | Send a message asynchronously (no wait) | body: same as `/session/:id/message`, returns `204 No Content` | +| `POST` | `/session/:id/command` | Execute a slash command | body: `{ messageID?, agent?, model?, command, arguments }`, returns `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/shell` | Run a shell command | body: `{ agent, model?, command }`, returns `{ info: `Message`, parts: `Part[]`}` | + +--- + +### Commands + +| Method | Path | Description | Response | +| ------ | ---------- | ----------------- | --------------------------------------------- | +| `GET` | `/command` | List all commands | Command[] | + +--- + +### Files + +| Method | Path | Description | Response | +| ------ | ------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | Search for text in files | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | Find files and directories by name | `string[]` (paths) | +| `GET` | `/find/symbol?query=` | Find workspace symbols | Symbol[] | +| `GET` | `/file?path=` | List files and directories | FileNode[] | +| `GET` | `/file/content?path=

` | Read a file | FileContent | +| `GET` | `/file/status` | Get status for tracked files | File[] | + +#### `/find/file` query parameters + +- `query` (required) — search string (fuzzy match) +- `type` (optional) — limit results to `"file"` or `"directory"` +- `directory` (optional) — override the project root for the search +- `limit` (optional) — max results (1–200) +- `dirs` (optional) — legacy flag (`"false"` returns only files) + +--- + +### Tools (Experimental) + +| Method | Path | Description | Response | +| ------ | ------------------------------------------- | ---------------------------------------- | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` | List all tool IDs | ToolIDs | +| `GET` | `/experimental/tool?provider=

&model=` | List tools with JSON schemas for a model | ToolList | + +--- + +### LSP, Formatters & MCP + +| Method | Path | Description | Response | +| ------ | ------------ | -------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | Get LSP server status | LSPStatus[] | +| `GET` | `/formatter` | Get formatter status | FormatterStatus[] | +| `GET` | `/mcp` | Get MCP server status | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | Add MCP server dynamically | body: `{ name, config }`, returns MCP status object | + +--- + +### Agents + +| Method | Path | Description | Response | +| ------ | -------- | ------------------------- | ------------------------------------------- | +| `GET` | `/agent` | List all available agents | Agent[] | + +--- + +### Logging + +| Method | Path | Description | Response | +| ------ | ------ | ------------------------------------------------------------ | --------- | +| `POST` | `/log` | Write log entry. Body: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| Method | Path | Description | Response | +| ------ | ----------------------- | ------------------------------------------- | ---------------------- | +| `POST` | `/tui/append-prompt` | Append text to the prompt | `boolean` | +| `POST` | `/tui/open-help` | Open the help dialog | `boolean` | +| `POST` | `/tui/open-sessions` | Open the session selector | `boolean` | +| `POST` | `/tui/open-themes` | Open the theme selector | `boolean` | +| `POST` | `/tui/open-models` | Open the model selector | `boolean` | +| `POST` | `/tui/submit-prompt` | Submit the current prompt | `boolean` | +| `POST` | `/tui/clear-prompt` | Clear the prompt | `boolean` | +| `POST` | `/tui/execute-command` | Execute a command (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | Show toast (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | Wait for the next control request | Control request object | +| `POST` | `/tui/control/response` | Respond to a control request (`{ body }`) | `boolean` | + +--- + +### Auth + +| Method | Path | Description | Response | +| ------ | ----------- | --------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | Set authentication credentials. Body must match provider schema | `boolean` | + +--- + +### Events + +| Method | Path | Description | Response | +| ------ | -------- | ----------------------------------------------------------------------------- | ------------------------- | +| `GET` | `/event` | Server-sent events stream. First event is `server.connected`, then bus events | Server-sent events stream | + +--- + +### Docs + +| Method | Path | Description | Response | +| ------ | ------ | ------------------------- | --------------------------- | +| `GET` | `/doc` | OpenAPI 3.1 specification | HTML page with OpenAPI spec | diff --git a/packages/web/src/content/docs/de/share.mdx b/packages/web/src/content/docs/de/share.mdx new file mode 100644 index 000000000..fe95a2bed --- /dev/null +++ b/packages/web/src/content/docs/de/share.mdx @@ -0,0 +1,130 @@ +--- +title: Share +description: Teile OpenCode-Unterhaltungen per oeffentlichem Link. +--- + +Mit der Share-Funktion erstellst du oeffentliche Links zu OpenCode-Unterhaltungen. +So kannst du einfacher mit dem Team zusammenarbeiten oder Hilfe einholen. + +:::note +Geteilte Unterhaltungen sind fuer alle mit dem Link oeffentlich zugaenglich. +::: + +--- + +## How it works + +Wenn du eine Unterhaltung teilst, macht OpenCode Folgendes: + +1. Erstellt eine eindeutige oeffentliche URL fuer deine Sitzung +2. Synchronisiert den Verlauf auf unsere Server +3. Stellt die Unterhaltung unter `opncd.ai/s/` bereit + +--- + +## Sharing + +OpenCode hat drei Modi, die das Teilen steuern: + +--- + +### Manual (default) + +Standardmaessig nutzt OpenCode den manuellen Modus. +Sitzungen werden nicht automatisch geteilt, du kannst sie aber mit `/share` veroeffentlichen: + +``` +/share +``` + +Dabei wird eine eindeutige URL erzeugt und in die Zwischenablage kopiert. + +Um den manuellen Modus explizit in der [Konfiguration](/docs/config) zu setzen: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### Auto-share + +Du kannst automatisches Teilen fuer neue Unterhaltungen aktivieren, indem du in der [Konfiguration](/docs/config) `share` auf `"auto"` setzt: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +Mit aktiviertem Auto-Share wird jede neue Unterhaltung automatisch geteilt und ein Link erstellt. + +--- + +### Disabled + +Du kannst Teilen komplett deaktivieren, indem du in der [Konfiguration](/docs/config) `share` auf `"disabled"` setzt: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +Wenn das fuer ein Projekt teamweit gelten soll, lege es in der Projekt-`opencode.json` fest und committe die Datei. + +--- + +## Teilen aufheben + +Um das Teilen zu beenden und den oeffentlichen Zugriff zu entfernen: + +``` +/unshare +``` + +Dadurch wird der Share-Link entfernt und die zugehoerigen Daten werden geloescht. + +--- + +## Privacy + +Beim Teilen solltest du ein paar Punkte beachten. + +--- + +### Data retention + +Geteilte Unterhaltungen bleiben veroeffentlicht, bis du sie explizit aufhebst. +Das umfasst: + +- Vollstaendigen Unterhaltungsverlauf +- Alle Nachrichten und Antworten +- Sitzungsmetadaten + +--- + +### Recommendations + +- Teile nur Unterhaltungen ohne sensible Informationen. +- Pruefe Inhalte vor dem Teilen. +- Hebe das Teilen wieder auf, wenn die Zusammenarbeit beendet ist. +- Teile keine proprietaeren Codes oder vertraulichen Daten. +- Deaktiviere Teilen komplett bei sensiblen Projekten. + +--- + +## For enterprises + +In Enterprise-Umgebungen kann die Share-Funktion: + +- **Deaktiviert** werden, um Compliance-Vorgaben einzuhalten +- Auf **SSO-authentifizierte** Nutzer eingeschraenkt werden +- **Self-hosted** auf eigener Infrastruktur betrieben werden + +[Mehr dazu](/docs/enterprise), wie du opencode in deiner Organisation einsetzt. diff --git a/packages/web/src/content/docs/de/skills.mdx b/packages/web/src/content/docs/de/skills.mdx new file mode 100644 index 000000000..ec36837a1 --- /dev/null +++ b/packages/web/src/content/docs/de/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "Agent Skills" +description: "Definiere wiederverwendbares Verhalten ueber SKILL.md" +--- + +Agent Skills erlauben OpenCode, wiederverwendbare Anweisungen aus deinem Repo oder Home-Verzeichnis zu finden. +Sie werden bei Bedarf ueber das native `skill`-Tool geladen, wenn ein Agent sie wirklich braucht. + +--- + +## Place files + +Erstelle pro Skill-Namen einen Ordner und lege dort eine `SKILL.md` ab. +OpenCode sucht in folgenden Pfaden: + +- Project config: `.opencode/skills//SKILL.md` +- Global config: `~/.config/opencode/skills//SKILL.md` +- Project Claude-compatible: `.claude/skills//SKILL.md` +- Global Claude-compatible: `~/.claude/skills//SKILL.md` +- Project agent-compatible: `.agents/skills//SKILL.md` +- Global agent-compatible: `~/.agents/skills//SKILL.md` + +--- + +## Understand discovery + +Bei projektlokalen Pfaden laeuft OpenCode vom aktuellen Verzeichnis nach oben bis zum Git-Worktree. +Dabei werden passende `skills/*/SKILL.md` in `.opencode/` sowie passende Dateien unter `.claude/skills/*/SKILL.md` und `.agents/skills/*/SKILL.md` geladen. + +Globale Definitionen kommen zusaetzlich aus `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` und `~/.agents/skills/*/SKILL.md`. + +--- + +## Write frontmatter + +Jede `SKILL.md` muss mit YAML-Frontmatter beginnen. +Nur diese Felder werden ausgewertet: + +- `name` (required) +- `description` (required) +- `license` (optional) +- `compatibility` (optional) +- `metadata` (optional, string-to-string map) + +Unbekannte Frontmatter-Felder werden ignoriert. + +--- + +## Validate names + +`name` muss: + +- 1-64 Zeichen lang sein +- nur Kleinbuchstaben und Ziffern mit einzelnen Bindestrichen enthalten +- nicht mit `-` beginnen oder enden +- kein `--` enthalten +- zum Verzeichnisnamen passen, in dem `SKILL.md` liegt + +Entsprechender Regex: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## Follow length rules + +`description` muss 1-1024 Zeichen lang sein. +Formuliere sie so konkret, dass Agenten den Skill eindeutig auswaehlen koennen. + +--- + +## Use an example + +Erstelle `.opencode/skills/git-release/SKILL.md` zum Beispiel so: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## Recognize tool description + +OpenCode listet verfuegbare Skills in der Beschreibung des `skill`-Tools. +Jeder Eintrag enthaelt Namen und Beschreibung: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +Der Agent laedt einen Skill per Tool-Aufruf: + +``` +skill({ name: "git-release" }) +``` + +--- + +## Configure permissions + +Steuere in `opencode.json` per Muster, auf welche Skills Agenten zugreifen duerfen: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Berechtigung | Verhalten | +| ------------ | ---------------------------------------- | +| `allow` | Skill wird sofort geladen | +| `deny` | Skill ist fuer Agenten versteckt | +| `ask` | Vor dem Laden wird nach Freigabe gefragt | + +Muster unterstuetzen Wildcards: `internal-*` passt z. B. auf `internal-docs` oder `internal-tools`. + +--- + +## Override per agent + +Du kannst einzelnen Agenten andere Berechtigungen als die globalen Defaults geben. + +**Fuer benutzerdefinierte Agenten** (im Frontmatter): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**Fuer eingebaute Agenten** (in `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## Disable the skill tool + +Deaktiviere Skills komplett fuer Agenten, die sie nicht nutzen sollen: + +**Fuer benutzerdefinierte Agenten**: + +```yaml +--- +tools: + skill: false +--- +``` + +**Fuer eingebaute Agenten**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +Wenn deaktiviert, wird der Abschnitt `` komplett weggelassen. + +--- + +## Troubleshoot loading + +Wenn ein Skill nicht auftaucht: + +1. Pruefe, ob `SKILL.md` exakt in Grossbuchstaben geschrieben ist +2. Pruefe, ob Frontmatter `name` und `description` enthaelt +3. Stelle sicher, dass Skill-Namen ueber alle Orte hinweg eindeutig sind +4. Pruefe Berechtigungen - Skills mit `deny` sind fuer Agenten unsichtbar diff --git a/packages/web/src/content/docs/de/themes.mdx b/packages/web/src/content/docs/de/themes.mdx new file mode 100644 index 000000000..8681caa76 --- /dev/null +++ b/packages/web/src/content/docs/de/themes.mdx @@ -0,0 +1,372 @@ +--- +title: Themes +description: Waehle ein eingebautes Theme oder erstelle eins. +--- + +Mit OpenCode kannst du ein eingebautes Theme waehlen, ein an dein Terminal angepasstes Theme nutzen oder ein eigenes Theme definieren. + +Standardmaessig verwendet OpenCode das `opencode`-Theme. + +--- + +## Terminal-Anforderungen + +Damit Themes mit voller Farbpalette korrekt angezeigt werden, muss dein Terminal **truecolor** (24-Bit-Farben) unterstuetzen. +Die meisten modernen Terminals koennen das bereits, eventuell musst du es aber aktivieren: + +- **Support pruefen**: Fuehre `echo $COLORTERM` aus - erwartet ist `truecolor` oder `24bit` +- **Truecolor aktivieren**: Setze in deinem Shell-Profil `COLORTERM=truecolor` +- **Terminal-Kompatibilitaet**: Stelle sicher, dass dein Terminal-Emulator 24-Bit-Farben unterstuetzt + +Ohne truecolor werden Farben weniger exakt dargestellt oder auf eine 256-Farben-Naeherung reduziert. + +--- + +## Eingebaute Themes + +OpenCode liefert mehrere eingebaute Themes mit. + +| Name | Description | +| ---------------------- | ---------------------------------------------------------------------------- | +| `system` | Adapts to your terminal’s background color | +| `tokyonight` | Based on the [Tokyonight](https://github.com/folke/tokyonight.nvim) theme | +| `everforest` | Based on the [Everforest](https://github.com/sainnhe/everforest) theme | +| `ayu` | Based on the [Ayu](https://github.com/ayu-theme) dark theme | +| `catppuccin` | Based on the [Catppuccin](https://github.com/catppuccin) theme | +| `catppuccin-macchiato` | Based on the [Catppuccin](https://github.com/catppuccin) theme | +| `gruvbox` | Based on the [Gruvbox](https://github.com/morhetz/gruvbox) theme | +| `kanagawa` | Based on the [Kanagawa](https://github.com/rebelot/kanagawa.nvim) theme | +| `nord` | Based on the [Nord](https://github.com/nordtheme/nord) theme | +| `matrix` | Hacker-style green on black theme | +| `one-dark` | Based on the [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) Dark theme | + +Und es kommen laufend weitere dazu. + +--- + +## System-Theme + +Das `system`-Theme passt sich automatisch an das Farbschema deines Terminals an. +Im Gegensatz zu Themes mit festen Farben gilt beim _system_-Theme: + +- **Generiert Graustufen**: Basierend auf deiner Terminal-Hintergrundfarbe fuer guten Kontrast +- **Nutzt ANSI-Farben**: Verwendet Standardfarben (0-15), die dein Terminalschema respektieren +- **Behaelt Terminal-Defaults**: Verwendet `none` fuer Text und Hintergruende + +Das System-Theme ist ideal fuer Nutzer, die: + +- OpenCode optisch ans Terminal anpassen wollen +- eigene Terminal-Farbschemata nutzen +- ein konsistentes Erscheinungsbild in Terminal-Apps bevorzugen + +--- + +## Theme verwenden + +Du kannst ein Theme ueber `/theme` auswaehlen oder direkt in der [Konfiguration](/docs/config) setzen. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Eigene Themes + +OpenCode unterstuetzt ein flexibles JSON-basiertes Theme-System. +Damit lassen sich Themes einfach erstellen und anpassen. + +--- + +### Hierarchy + +Themes are loaded from multiple directories in the following order where later directories override earlier ones: + +1. **Built-in themes** - These are embedded in the binary +2. **User config directory** - Defined in `~/.config/opencode/themes/*.json` or `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Project root directory** - Defined in the `/.opencode/themes/*.json` +4. **Current working directory** - Defined in `./.opencode/themes/*.json` + +If multiple directories contain a theme with the same name, the theme from the directory with higher priority will be used. + +--- + +### Creating a theme + +To create a custom theme, create a JSON file in one of the theme directories. + +For user-wide themes: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +And for project-specific themes. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON format + +Themes use a flexible JSON format with support for: + +- **Hex colors**: `"#ffffff"` +- **ANSI colors**: `3` (0-255) +- **Color references**: `"primary"` or custom definitions +- **Dark/light variants**: `{"dark": "#000", "light": "#fff"}` +- **No color**: `"none"` - Uses the terminal's default color or transparent + +--- + +### Color definitions + +The `defs` section is optional and it allows you to define reusable colors that can be referenced in the theme. + +--- + +### Terminal defaults + +The special value `"none"` can be used for any color to inherit the terminal's default color. This is particularly useful for creating themes that blend seamlessly with your terminal's color scheme: + +- `"text": "none"` - Uses terminal's default foreground color +- `"background": "none"` - Uses terminal's default background color + +--- + +### Example + +Here's an example of a custom theme: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/de/tools.mdx b/packages/web/src/content/docs/de/tools.mdx new file mode 100644 index 000000000..33ebb72b8 --- /dev/null +++ b/packages/web/src/content/docs/de/tools.mdx @@ -0,0 +1,390 @@ +--- +title: Tools +description: Verwalte, welche Tools ein LLM nutzen darf. +--- + +Tools erlauben dem LLM Aktionen in deiner Codebasis. +OpenCode bringt eingebaute Tools mit und laesst sich ueber [Custom Tools](/docs/custom-tools) oder [MCP-Server](/docs/mcp-servers) erweitern. + +Standardmaessig sind alle Tools **aktiviert** und brauchen keine Freigabe. +Das Verhalten steuerst du ueber [Berechtigungen](/docs/permissions). + +--- + +## Configure + +Nutze das Feld `permission`, um Tool-Verhalten zu steuern. +Pro Tool kannst du erlauben, verbieten oder eine Rueckfrage verlangen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +Mit Wildcards kannst du mehrere Tools auf einmal steuern. +Zum Beispiel, um fuer alle Tools eines MCP-Servers eine Freigabe zu verlangen: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[Mehr dazu](/docs/permissions), wie du Berechtigungen konfigurierst. + +--- + +## Built-in + +Hier sind alle in OpenCode verfuegbaren eingebauten Tools. + +--- + +### bash + +Fuehrt Shell-Befehle in deiner Projektumgebung aus. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +Damit kann das LLM Terminal-Befehle wie `npm install`, `git status` oder andere Shell-Kommandos ausfuehren. + +--- + +### edit + +Bearbeitet bestehende Dateien ueber exakte String-Ersetzungen. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Dieses Tool fuehrt praezise Aenderungen per exakter Textsuche aus. +Es ist der zentrale Weg, wie das LLM Code aendert. + +--- + +### write + +Erstellt neue Dateien oder ueberschreibt bestehende Dateien. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Damit erlaubst du dem LLM, neue Dateien anzulegen. +Bestehende Dateien werden dabei ueberschrieben. + +:::note +Das Tool `write` wird ueber die Berechtigung `edit` gesteuert. +`edit` gilt fuer alle Datei-Aenderungen (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### read + +Read file contents from your codebase. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +This tool reads files and returns their contents. It supports reading specific line ranges for large files. + +--- + +### grep + +Search file contents using regular expressions. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Fast content search across your codebase. Supports full regex syntax and file pattern filtering. + +--- + +### glob + +Find files by pattern matching. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +Search for files using glob patterns like `**/*.js` or `src/**/*.ts`. Returns matching file paths sorted by modification time. + +--- + +### list + +List files and directories in a given path. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +This tool lists directory contents. It accepts glob patterns to filter results. + +--- + +### lsp (experimental) + +Interact with your configured LSP servers to get code intelligence features like definitions, references, hover info, and call hierarchy. + +:::note +This tool is only available when `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (or `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +Supported operations include `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls`, and `outgoingCalls`. + +To configure which LSP servers are available for your project, see [LSP Servers](/docs/lsp). + +--- + +### patch + +Apply patches to files. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +This tool applies patch files to your codebase. Useful for applying diffs and patches from various sources. + +:::note +The `patch` tool is controlled by the `edit` permission, which covers all file modifications (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### skill + +Load a [skill](/docs/skills) (a `SKILL.md` file) and return its content in the conversation. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todowrite + +Manage todo lists during coding sessions. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +Creates and updates task lists to track progress during complex operations. The LLM uses this to organize multi-step tasks. + +:::note +This tool is disabled for subagents by default, but you can enable it manually. [Learn more](/docs/agents/#permissions) +::: + +--- + +### todoread + +Read existing todo lists. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +Reads the current todo list state. Used by the LLM to track what tasks are pending or completed. + +:::note +This tool is disabled for subagents by default, but you can enable it manually. [Learn more](/docs/agents/#permissions) +::: + +--- + +### webfetch + +Fetch web content. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +Allows the LLM to fetch and read web pages. Useful for looking up documentation or researching online resources. + +--- + +### websearch + +Search the web for information. + +:::note +This tool is only available when using the OpenCode provider or when the `OPENCODE_ENABLE_EXA` environment variable is set to any truthy value (e.g., `true` or `1`). + +To enable when launching OpenCode: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Performs web searches using Exa AI to find relevant information online. Useful for researching topics, finding current events, or gathering information beyond the training data cutoff. + +No API key is required — the tool connects directly to Exa AI's hosted MCP service without authentication. + +:::tip +Use `websearch` when you need to find information (discovery), and `webfetch` when you need to retrieve content from a specific URL (retrieval). +::: + +--- + +### question + +Ask the user questions during execution. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +This tool allows the LLM to ask the user questions during a task. It's useful for: + +- Gathering user preferences or requirements +- Clarifying ambiguous instructions +- Getting decisions on implementation choices +- Offering choices about what direction to take + +Each question includes a header, the question text, and a list of options. Users can select from the provided options or type a custom answer. When there are multiple questions, users can navigate between them before submitting all answers. + +--- + +## Custom tools + +Mit Custom Tools definierst du eigene Funktionen, die das LLM aufrufen kann. +Sie werden in der Konfigurationsdatei definiert und koennen beliebigen Code ausfuehren. + +[Mehr dazu](/docs/custom-tools), wie du Custom Tools erstellst. + +--- + +## MCP servers + +MCP-Server (Model Context Protocol) binden externe Tools und Dienste ein. +Dazu gehoeren Datenbanken, API-Integrationen und Drittanbieter-Services. + +[Mehr dazu](/docs/mcp-servers), wie du MCP-Server konfigurierst. + +--- + +## Internals + +Intern verwenden Tools wie `grep`, `glob` und `list` [ripgrep](https://github.com/BurntSushi/ripgrep). +Standardmaessig beachtet ripgrep `.gitignore`, daher werden dort aufgefuehrte Dateien und Ordner nicht durchsucht. + +--- + +### Ignore patterns + +Wenn du normalerweise ignorierte Dateien einschliessen willst, lege im Projekt-Root eine `.ignore`-Datei an. +Dort kannst du Pfade explizit erlauben. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +Dieses Beispiel erlaubt ripgrep, in `node_modules/`, `dist/` und `build/` zu suchen, auch wenn sie in `.gitignore` stehen. diff --git a/packages/web/src/content/docs/de/troubleshooting.mdx b/packages/web/src/content/docs/de/troubleshooting.mdx new file mode 100644 index 000000000..3bca3a35d --- /dev/null +++ b/packages/web/src/content/docs/de/troubleshooting.mdx @@ -0,0 +1,301 @@ +--- +title: Troubleshooting +description: Haeufige Probleme und schnelle Loesungen. +--- + +Wenn OpenCode Probleme macht, starte mit Logs und lokal gespeicherten Daten auf der Festplatte. + +--- + +## Logs + +Logdateien werden hier gespeichert: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.local\share\opencode\log` + +Dateinamen enthalten Zeitstempel (z. B. `2025-01-09T123456.log`) und es bleiben die letzten 10 Logs erhalten. + +Mit `--log-level` bekommst du detailliertere Diagnoseinfos, z. B. `opencode --log-level DEBUG`. + +--- + +## Storage + +opencode speichert Sitzungs- und App-Daten auf der Festplatte unter: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.local\share\opencode` + +Dieses Verzeichnis enthaelt: + +- `auth.json` - Authentifizierungsdaten wie API-Keys und OAuth-Tokens +- `log/` - Anwendungslogs +- `project/` - Projektspezifische Daten wie Sitzungen und Nachrichten + - In Git-Repositories unter `.//storage/` + - Ohne Git unter `./global/storage/` + +--- + +## Desktop app + +OpenCode Desktop startet im Hintergrund einen lokalen OpenCode-Server (`opencode-cli`-Sidecar). +Viele Probleme kommen von fehlerhaften Plugins, kaputtem Cache oder falschen Server-Einstellungen. + +### Quick checks + +- App komplett beenden und neu starten +- Bei Fehlerbildschirm **Restart** klicken und Details kopieren +- Nur macOS: `OpenCode`-Menue -> **Reload Webview** (hilft bei leerer/eingefrorener UI) + +--- + +### Disable plugins + +If the desktop app is crashing on launch, hanging, or behaving strangely, start by disabling plugins. + +#### Check the global config + +Open your global config file and look for a `plugin` key. + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (or `~/.config/opencode/opencode.json`) +- **macOS/Linux** (older installs): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.config\opencode\opencode.jsonc` + +If you have plugins configured, temporarily disable them by removing the key or setting it to an empty array: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### Check plugin directories + +OpenCode can also load local plugins from disk. Temporarily move these out of the way (or rename the folder) and restart the desktop app: + +- **Global plugins** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.config\opencode\plugins` +- **Project plugins** (only if you use per-project config) + - `/.opencode/plugins/` + +If the app starts working again, re-enable plugins one at a time to find which one is causing the issue. + +--- + +### Clear the cache + +If disabling plugins doesn't help (or a plugin install is stuck), clear the cache so OpenCode can rebuild it. + +1. Quit OpenCode Desktop completely. +2. Delete the cache directory: + +- **macOS**: Finder -> `Cmd+Shift+G` -> paste `~/.cache/opencode` +- **Linux**: delete `~/.cache/opencode` (or run `rm -rf ~/.cache/opencode`) +- **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.cache\opencode` + +3. Restart OpenCode Desktop. + +--- + +### Fix server connection issues + +OpenCode Desktop can either start its own local server (default) or connect to a server URL you configured. + +If you see a **"Connection Failed"** dialog (or the app never gets past the splash screen), check for a custom server URL. + +#### Clear the desktop default server URL + +From the Home screen, click the server name (with the status dot) to open the Server picker. In the **Default server** section, click **Clear**. + +#### Remove `server.port` / `server.hostname` from your config + +If your `opencode.json(c)` contains a `server` section, temporarily remove it and restart the desktop app. + +#### Check environment variables + +If you have `OPENCODE_PORT` set in your environment, the desktop app will try to use that port for the local server. + +- Unset `OPENCODE_PORT` (or pick a free port) and restart. + +--- + +### Linux: Wayland / X11 issues + +On Linux, some Wayland setups can cause blank windows or compositor errors. + +- If you're on Wayland and the app is blank/crashing, try launching with `OC_ALLOW_WAYLAND=1`. +- If that makes things worse, remove it and try launching under an X11 session instead. + +--- + +### Windows: WebView2 runtime + +On Windows, OpenCode Desktop requires the Microsoft Edge **WebView2 Runtime**. If the app opens to a blank window or won't start, install/update WebView2 and try again. + +--- + +### Windows: General performance issues + +If you're experiencing slow performance, file access issues, or terminal problems on Windows, try using [WSL (Windows Subsystem for Linux)](/docs/windows-wsl). WSL provides a Linux environment that works more seamlessly with OpenCode's features. + +--- + +### Notifications not showing + +OpenCode Desktop only shows system notifications when: + +- notifications are enabled for OpenCode in your OS settings, and +- the app window is not focused. + +--- + +### Reset desktop app storage (last resort) + +If the app won't start and you can't clear settings from inside the UI, reset the desktop app's saved state. + +1. Quit OpenCode Desktop. +2. Find and delete these files (they live in the OpenCode Desktop app data directory): + +- `opencode.settings.dat` (desktop default server URL) +- `opencode.global.dat` and `opencode.workspace.*.dat` (UI state like recent servers/projects) + +To find the directory quickly: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (then search for the filenames above) +- **Linux**: search under `~/.local/share` for the filenames above +- **Windows**: Press `WIN+R` -> `%APPDATA%` (then search for the filenames above) + +--- + +## Hilfe bekommen + +Wenn du Probleme mit OpenCode hast: + +1. **Probleme auf GitHub melden** + + Bugs und Feature-Wuensche meldest du am besten im GitHub-Repository: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + Suche vor dem Erstellen nach bestehenden Issues, damit Duplikate vermieden werden. + +2. **Unserem Discord beitreten** + + Fuer schnelle Hilfe und Austausch in der Community: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Haeufige Probleme + +Hier sind typische Fehlerbilder und wie du sie loest. + +--- + +### 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 the `/connect` command in the TUI +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 + +If you encounter `ProviderModelNotFoundError` you are most likely incorrectly +referencing a model somewhere. +Models should be referenced like so: `/` + +Examples: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +To figure out what models you have access to, run `opencode models` + +--- + +### ProviderInitError + +If you encounter a ProviderInitError, you likely have an invalid or corrupted configuration. + +To resolve this: + +1. First, verify your provider is set up correctly by following the [providers guide](/docs/providers) +2. If the issue persists, try clearing your stored configuration: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + On Windows, press `WIN+R` and delete: `%USERPROFILE%\.local\share\opencode` + +3. Re-authenticate with your provider using the `/connect` command in the TUI. + +--- + +### AI_APICallError and provider package issues + +If you encounter API call errors, this may be due to outdated provider packages. opencode dynamically installs provider packages (OpenAI, Anthropic, Google, etc.) as needed and caches them locally. + +To resolve provider package issues: + +1. Clear the provider package cache: + + ```bash + rm -rf ~/.cache/opencode + ``` + + On Windows, press `WIN+R` and delete: `%USERPROFILE%\.cache\opencode` + +2. Restart opencode to reinstall the latest provider packages + +This will force opencode to download the most recent versions of provider packages, which often resolves compatibility issues with model parameters and API changes. + +--- + +### Copy/paste not working on Linux + +Linux users need to have one of the following clipboard utilities installed for copy/paste functionality to work: + +**For X11 systems:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**For Wayland systems:** + +```bash +apt install -y wl-clipboard +``` + +**For headless environments:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode will detect if you're using Wayland and prefer `wl-clipboard`, otherwise it will try to find clipboard tools in order of: `xclip` and `xsel`. diff --git a/packages/web/src/content/docs/de/tui.mdx b/packages/web/src/content/docs/de/tui.mdx new file mode 100644 index 000000000..7f3c69a50 --- /dev/null +++ b/packages/web/src/content/docs/de/tui.mdx @@ -0,0 +1,393 @@ +--- +title: TUI +description: Arbeite mit OpenCode in der Terminal-Oberflaeche. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode bietet eine interaktive Terminaloberflaeche (TUI), um mit einem LLM an deinen Projekten zu arbeiten. + +Ohne weitere Argumente startet OpenCode die TUI im aktuellen Verzeichnis. + +```bash +opencode +``` + +Oder du startest sie fuer ein bestimmtes Arbeitsverzeichnis. + +```bash +opencode /path/to/project +``` + +In der TUI kannst du direkt mit einer Nachricht prompten. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## Datei-Referenzen + +Mit `@` kannst du Dateien in Nachrichten referenzieren. +Dabei wird im aktuellen Verzeichnis eine unscharfe Dateisuche genutzt. + +:::tip +Du kannst `@` in Nachrichten fuer Datei-Referenzen verwenden. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +Der Dateiinhalt wird automatisch zur Unterhaltung hinzugefuegt. + +--- + +## Bash commands + +Beginne eine Nachricht mit `!`, um einen Shell-Befehl auszufuehren. + +```bash frame="none" +!ls -la +``` + +Die Ausgabe landet als Tool-Ergebnis in der Unterhaltung. + +--- + +## Commands + +In der OpenCode-TUI kannst du `/` plus Befehlsnamen eingeben, um Aktionen schnell auszufuehren. +Zum Beispiel: + +```bash frame="none" +/help +``` + +Viele Befehle haben auch Tastenkombinationen mit `ctrl+x` als Leader-Key. +[Mehr dazu](/docs/keybinds). + +Hier sind alle verfuegbaren Slash-Commands: + +--- + +### connect + +Add a provider to OpenCode. Allows you to select from available providers and add their API keys. + +```bash frame="none" +/connect +``` + +--- + +### compact + +Compact the current session. _Alias_: `/summarize` + +```bash frame="none" +/compact +``` + +**Keybind:** `ctrl+x c` + +--- + +### details + +Toggle tool execution details. + +```bash frame="none" +/details +``` + +**Keybind:** `ctrl+x d` + +--- + +### editor + +Open external editor for composing messages. Uses the editor set in your `EDITOR` environment variable. [Learn more](#editor-setup). + +```bash frame="none" +/editor +``` + +**Keybind:** `ctrl+x e` + +--- + +### exit + +Exit OpenCode. _Aliases_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Keybind:** `ctrl+x q` + +--- + +### export + +Export current conversation to Markdown and open in your default editor. Uses the editor set in your `EDITOR` environment variable. [Learn more](#editor-setup). + +```bash frame="none" +/export +``` + +**Keybind:** `ctrl+x x` + +--- + +### help + +Show the help dialog. + +```bash frame="none" +/help +``` + +**Keybind:** `ctrl+x h` + +--- + +### init + +Create or update `AGENTS.md` file. [Learn more](/docs/rules). + +```bash frame="none" +/init +``` + +**Keybind:** `ctrl+x i` + +--- + +### models + +List available models. + +```bash frame="none" +/models +``` + +**Keybind:** `ctrl+x m` + +--- + +### new + +Start a new session. _Alias_: `/clear` + +```bash frame="none" +/new +``` + +**Keybind:** `ctrl+x n` + +--- + +### redo + +Redo a previously undone message. Only available after using `/undo`. + +:::tip +Any file changes will also be restored. +::: + +Internally, this uses Git to manage the file changes. So your project **needs to +be a Git repository**. + +```bash frame="none" +/redo +``` + +**Keybind:** `ctrl+x r` + +--- + +### sessions + +List and switch between sessions. _Aliases_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Keybind:** `ctrl+x l` + +--- + +### share + +Share current session. [Learn more](/docs/share). + +```bash frame="none" +/share +``` + +**Keybind:** `ctrl+x s` + +--- + +### themes + +List available themes. + +```bash frame="none" +/theme +``` + +**Keybind:** `ctrl+x t` + +--- + +### thinking + +Toggle the visibility of thinking/reasoning blocks in the conversation. When enabled, you can see the model's reasoning process for models that support extended thinking. + +:::note +This command only controls whether thinking blocks are **displayed** - it does not enable or disable the model's reasoning capabilities. To toggle actual reasoning capabilities, use `ctrl+t` to cycle through model variants. +::: + +```bash frame="none" +/thinking +``` + +--- + +### undo + +Undo last message in the conversation. Removes the most recent user message, all subsequent responses, and any file changes. + +:::tip +Any file changes made will also be reverted. +::: + +Internally, this uses Git to manage the file changes. So your project **needs to +be a Git repository**. + +```bash frame="none" +/undo +``` + +**Keybind:** `ctrl+x u` + +--- + +### unshare + +Unshare current session. [Learn more](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## Editor setup + +Both the `/editor` and `/export` commands use the editor specified in your `EDITOR` environment variable. + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + + To make it permanent, add this to your shell profile; + `~/.bashrc`, `~/.zshrc`, etc. + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + + To make it permanent, use **System Properties** > **Environment + Variables**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + + To make it permanent, add this to your PowerShell profile. + + + + +Popular editor options include: + +- `code` - Visual Studio Code +- `cursor` - Cursor +- `windsurf` - Windsurf +- `nvim` - Neovim editor +- `vim` - Vim editor +- `nano` - Nano editor +- `notepad` - Windows Notepad +- `subl` - Sublime Text + +:::note +Some editors like VS Code need to be started with the `--wait` flag. +::: + +Some editors need command-line arguments to run in blocking mode. The `--wait` flag makes the editor process block until closed. + +--- + +## Configure + +You can customize TUI behavior through your OpenCode config file. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### Options + +- `scroll_acceleration` - Enable macOS-style scroll acceleration for smooth, natural scrolling. When enabled, scroll speed increases with rapid scrolling gestures and stays precise for slower movements. **This setting takes precedence over `scroll_speed` and overrides it when enabled.** +- `scroll_speed` - Controls how fast the TUI scrolls when using scroll commands (minimum: `1`). Defaults to `3`. **Note: This is ignored if `scroll_acceleration.enabled` is set to `true`.** + +--- + +## Customization + +You can customize various aspects of the TUI view using the command palette (`ctrl+x h` or `/help`). These settings persist across restarts. + +--- + +#### Username display + +Toggle whether your username appears in chat messages. Access this through: + +- Command palette: Search for "username" or "hide username" +- The setting persists automatically and will be remembered across TUI sessions diff --git a/packages/web/src/content/docs/de/web.mdx b/packages/web/src/content/docs/de/web.mdx new file mode 100644 index 000000000..1dc75a083 --- /dev/null +++ b/packages/web/src/content/docs/de/web.mdx @@ -0,0 +1,142 @@ +--- +title: Web +description: Verwenden Sie OpenCode in Ihrem Browser. +--- + +OpenCode kann als Webanwendung in Ihrem Browser ausgeführt werden und bietet das gleiche leistungsstarke KI-Codierungserlebnis, ohne dass ein Terminal erforderlich ist. + +![OpenCode Web – Neue Sitzung](../../../assets/web/web-homepage-new-session.png) + +## Erste Schritte + +Starten Sie die Weboberfläche, indem Sie Folgendes ausführen: + +```bash +opencode web +``` + +Dadurch wird ein lokaler Server auf `127.0.0.1` mit einem zufällig verfügbaren Port gestartet und OpenCode automatisch in Ihrem Standardbrowser geöffnet. + +:::caution +Wenn `OPENCODE_SERVER_PASSWORD` nicht gesetzt ist, ist der Server ungesichert. Dies ist für den lokalen Gebrauch in Ordnung, sollte aber für den Netzwerkzugriff eingestellt werden. +::: + +:::tip[Windows Users] +Um die beste Erfahrung zu erzielen, führen Sie `opencode web` über [WSL](/docs/windows-wsl) und nicht über PowerShell aus. Dies gewährleistet den ordnungsgemäßen Zugriff auf das Dateisystem und die Terminalintegration. +::: + +--- + +## Konfiguration + +Sie können den Webserver mithilfe von Befehlszeilen-Flags oder in Ihrer [Konfigurationsdatei](/docs/config) konfigurieren. + +### Port + +Standardmäßig wählt OpenCode einen verfügbaren Port aus. Sie können einen Port angeben: + +```bash +opencode web --port 4096 +``` + +### Hostname + +Standardmäßig bindet der Server an `127.0.0.1` (nur localhost). So machen Sie OpenCode in Ihrem Netzwerk zugänglich: + +```bash +opencode web --hostname 0.0.0.0 +``` + +Bei Verwendung von `0.0.0.0` zeigt OpenCode sowohl lokale als auch Netzwerkadressen an: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### mDNS-Erkennung + +Aktivieren Sie mDNS, um Ihren Server im lokalen Netzwerk erkennbar zu machen: + +```bash +opencode web --mdns +``` + +Dadurch wird der Hostname automatisch auf `0.0.0.0` gesetzt und der Server als `opencode.local` angekündigt. + +Sie können den mDNS-Domänennamen anpassen, um mehrere Instanzen im selben Netzwerk auszuführen: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +So erlauben Sie zusätzliche Domänen für CORS (nützlich für benutzerdefinierte Frontends): + +```bash +opencode web --cors https://example.com +``` + +### Authentifizierung + +Um den Zugriff zu schützen, legen Sie mithilfe der Umgebungsvariablen `OPENCODE_SERVER_PASSWORD` ein Passwort fest: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +Der Benutzername ist standardmäßig `opencode`, kann aber mit `OPENCODE_SERVER_USERNAME` geändert werden. + +--- + +## Verwenden der Weboberfläche + +Nach dem Start bietet die Weboberfläche Zugriff auf Ihre OpenCode-Sitzungen. + +### Sitzungen + +Zeigen Sie Ihre Sitzungen auf der Startseite an und verwalten Sie sie. Sie können aktive Sitzungen sehen und neue starten. + +![OpenCode Web – Aktive Sitzung](../../../assets/web/web-homepage-active-session.png) + +### Serverstatus + +Klicken Sie auf „Server anzeigen“, um verbundene Server und deren Status anzuzeigen. + +![OpenCode Web – Siehe Server](../../../assets/web/web-homepage-see-servers.png) + +--- + +## Anschließen eines Terminals + +Sie können eine Terminal-TUI an einen laufenden Webserver anschließen: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +Dadurch können Sie sowohl die Weboberfläche als auch das Terminal gleichzeitig verwenden und dieselben Sitzungen und denselben Status teilen. + +--- + +## Konfigurationsdatei + +Sie können Servereinstellungen auch in Ihrer `opencode.json`-Konfigurationsdatei konfigurieren: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +Befehlszeilenflags haben Vorrang vor Konfigurationsdateieinstellungen. diff --git a/packages/web/src/content/docs/de/windows-wsl.mdx b/packages/web/src/content/docs/de/windows-wsl.mdx new file mode 100644 index 000000000..cc701947a --- /dev/null +++ b/packages/web/src/content/docs/de/windows-wsl.mdx @@ -0,0 +1,115 @@ +--- +title: Windows (WSL) +description: Nutze OpenCode unter Windows am besten mit WSL. +--- + +import { Steps } from "@astrojs/starlight/components" + +OpenCode laeuft zwar direkt unter Windows, die beste Erfahrung bekommst du aber mit [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install). +WSL bietet eine Linux-Umgebung, die mit den OpenCode-Features nahtlos funktioniert. + +:::tip[Why WSL?] +WSL bietet bessere Dateisystem-Performance, vollstaendige Terminal-Unterstuetzung und hohe Kompatibilitaet mit den Entwicklungswerkzeugen, die OpenCode nutzt. +::: + +--- + +## Setup + + + +1. **Install WSL** + + Falls noch nicht geschehen, installiere [WSL](https://learn.microsoft.com/en-us/windows/wsl/install) mit der offiziellen Microsoft-Anleitung. + +2. **Install OpenCode in WSL** + + Wenn WSL eingerichtet ist, oeffne dein WSL-Terminal und installiere OpenCode mit einer der [Installationsmethoden](/docs/). + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **Use OpenCode from WSL** + + Wechsle in dein Projektverzeichnis (Windows-Dateien erreichst du ueber `/mnt/c/`, `/mnt/d/` usw.) und starte OpenCode. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## Desktop App + WSL Server + +Wenn du die OpenCode-Desktop-App nutzen willst, den Server aber in WSL betreiben moechtest: + +1. **Starte den Server in WSL** mit `--hostname 0.0.0.0`, damit externe Verbindungen moeglich sind: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Verbinde die Desktop-App** mit `http://localhost:4096` + +:::note +Wenn `localhost` in deiner Umgebung nicht funktioniert, nutze stattdessen die WSL-IP-Adresse (in WSL: `hostname -I`) und verbinde dich mit `http://:4096`. +::: + +:::caution +Wenn du `--hostname 0.0.0.0` verwendest, setze `OPENCODE_SERVER_PASSWORD`, um den Server zu schuetzen. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Web Client + WSL + +Fuer die beste Web-Erfahrung unter Windows: + +1. **Fuehre `opencode web` im WSL-Terminal aus**, nicht in PowerShell: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Rufe die URL im Windows-Browser auf** unter `http://localhost:` (OpenCode zeigt die URL an) + +Wenn du `opencode web` aus WSL startest, bleiben Dateizugriff und Terminal-Integration sauber. +Gleichzeitig ist die Weboberflaeche weiterhin im Windows-Browser erreichbar. + +--- + +## Accessing Windows Files + +WSL kann ueber das Verzeichnis `/mnt/` auf alle Windows-Dateien zugreifen: + +- Laufwerk `C:` -> `/mnt/c/` +- Laufwerk `D:` -> `/mnt/d/` +- usw. + +Example: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +Fuer die beste Performance kannst du dein Repo direkt in das WSL-Dateisystem klonen/kopieren (z. B. nach `~/code/`) und OpenCode dort starten. +::: + +--- + +## Tips + +- Lass OpenCode in WSL laufen, auch wenn das Projekt auf einem Windows-Laufwerk liegt +- Nutze die [WSL-Extension](https://code.visualstudio.com/docs/remote/wsl) von VS Code fuer einen integrierten Workflow +- OpenCode-Konfiguration und Sitzungen liegen in WSL unter `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/de/zen.mdx b/packages/web/src/content/docs/de/zen.mdx new file mode 100644 index 000000000..a12239ecf --- /dev/null +++ b/packages/web/src/content/docs/de/zen.mdx @@ -0,0 +1,247 @@ +--- +title: Zen +description: Kuratierte Modellliste direkt von OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen ist eine vom OpenCode-Team getestete und verifizierte Modellliste. + +:::note +OpenCode Zen befindet sich aktuell in der Beta. +::: + +Zen funktioniert wie jeder andere Provider in OpenCode. +Du meldest dich bei OpenCode Zen an, holst dir deinen API-Key und nutzt ihn optional. + +--- + +## Background + +Es gibt sehr viele Modelle, aber nur ein Teil davon eignet sich wirklich gut als Coding-Agent. +Ausserdem konfigurieren Provider Modelle sehr unterschiedlich, was die Qualitaet stark beeinflusst. + +:::tip +Wir haben eine Auswahl aus Modellen und Providern getestet, die gut mit OpenCode funktionieren. +::: + +Wenn du Modelle ueber Gateways wie OpenRouter nutzt, ist oft unklar, ob du die beste Ausfuehrung eines Modells bekommst. + +Um das zu verbessern, haben wir: + +1. Eine Auswahl an Modellen getestet und mit den Teams ueber optimale Laufzeit-Setups gesprochen +2. Mit Providern zusammengearbeitet, damit diese Modelle korrekt ausgeliefert werden +3. Modell/Provider-Kombinationen gebenchmarkt und eine empfehlenswerte Liste erstellt + +OpenCode Zen ist ein AI-Gateway, das dir Zugriff auf genau diese Modelle gibt. + +--- + +## How it works + +OpenCode Zen funktioniert wie jeder andere Provider in OpenCode. + +1. Melde dich bei **OpenCode Zen** an, hinterlege Zahlungsdaten und kopiere deinen API-Key. +2. Fuehre in der TUI `/connect` aus, waehle OpenCode Zen und fuege den API-Key ein. +3. Starte `/models` in der TUI, um empfohlene Modelle zu sehen. + +Abgerechnet wird pro Anfrage, Guthaben kannst du jederzeit aufladen. + +--- + +## Endpoints + +Du kannst unsere Modelle auch ueber die folgenden API-Endpunkte aufrufen. + +| Model | Model ID | Endpoint | AI SDK Package | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Free | minimax-m2.1-free | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Free | glm-4.7-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Free | kimi-k2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +Die [Model-ID](/docs/config/#models) in deiner OpenCode-Konfiguration hat das Format `opencode/`. +Fuer GPT 5.2 Codex verwendest du zum Beispiel `opencode/gpt-5.2-codex`. + +--- + +### Models + +Die komplette Liste verfuegbarer Modelle inklusive Metadaten findest du unter: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## Pricing + +Wir nutzen ein Pay-as-you-go-Modell. +Unten siehst du die Preise **pro 1 Mio. Tokens**. + +| Model | Input | Output | Cached Read | Cached Write | +| --------------------------------- | ------ | ------ | ----------- | ------------ | +| Big Pickle | Free | Free | Free | - | +| MiniMax M2.1 Free | Free | Free | Free | - | +| MiniMax M2.1 | $0.30 | $1.20 | $0.10 | - | +| GLM 4.7 Free | Free | Free | Free | - | +| GLM 4.7 | $0.60 | $2.20 | $0.10 | - | +| GLM 4.6 | $0.60 | $2.20 | $0.10 | - | +| Kimi K2.5 Free | Free | Free | Free | - | +| Kimi K2.5 | $0.60 | $3.00 | $0.08 | - | +| Kimi K2 Thinking | $0.40 | $2.50 | - | - | +| Kimi K2 | $0.40 | $2.50 | - | - | +| Qwen3 Coder 480B | $0.45 | $1.50 | - | - | +| Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | +| Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | +| Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | +| Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | +| Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | - | +| Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | - | +| Gemini 3 Flash | $0.50 | $3.00 | $0.05 | - | +| GPT 5.2 | $1.75 | $14.00 | $0.175 | - | +| GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | - | +| GPT 5.1 | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | - | +| GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | - | +| GPT 5 | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Nano | Free | Free | Free | - | + +In deinem Verlauf siehst du eventuell _Claude Haiku 3.5_. +Das ist ein [guenstiges Modell](/docs/config/#models), das fuer Session-Titel verwendet wird. + +:::note +Kreditkartengebuehren geben wir zum Selbstkostenpreis weiter (4,4 % + $0.30 pro Transaktion), ohne Aufschlag. +::: + +Die kostenlosen Modelle: + +- GLM 4.7 Free ist fuer begrenzte Zeit verfuegbar, um Feedback zu sammeln und das Modell zu verbessern. +- Kimi K2.5 Free ist fuer begrenzte Zeit verfuegbar, um Feedback zu sammeln und das Modell zu verbessern. +- MiniMax M2.1 Free ist fuer begrenzte Zeit verfuegbar, um Feedback zu sammeln und das Modell zu verbessern. +- Big Pickle ist ein Stealth-Modell und ebenfalls zeitlich begrenzt kostenlos verfuegbar. + +Wenn du Fragen hast, kontaktiere uns. + +--- + +### Auto-reload + +Wenn dein Guthaben unter $5 faellt, laedt Zen automatisch $20 nach. + +Du kannst den Betrag anpassen oder Auto-Reload komplett deaktivieren. + +--- + +### Monthly limits + +Du kannst monatliche Limits fuer den gesamten Workspace und pro Teammitglied festlegen. + +Wenn du z. B. ein Monatslimit von $20 setzt, verbraucht Zen nicht mehr als $20 pro Monat. +Mit aktiviertem Auto-Reload kann die Abrechnung dennoch darueber liegen, falls das Guthaben unter $5 sinkt. + +--- + +## Privacy + +Alle Modelle werden in den USA gehostet. +Unsere Provider arbeiten grundsaetzlich mit Zero-Retention und nutzen deine Daten nicht zum Training, mit folgenden Ausnahmen: + +- Big Pickle: During its free period, collected data may be used to improve the model. +- GLM 4.7 Free: During its free period, collected data may be used to improve the model. +- Kimi K2.5 Free: During its free period, collected data may be used to improve the model. +- MiniMax M2.1 Free: During its free period, collected data may be used to improve the model. +- OpenAI APIs: Requests are retained for 30 days in accordance with [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data). +- Anthropic APIs: Requests are retained for 30 days in accordance with [Anthropic's Data Policies](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## For Teams + +Zen eignet sich auch gut fuer Teams. +Du kannst Mitglieder einladen, Rollen vergeben und den Modellzugriff fuer dein Team steuern. + +:::note +Workspaces sind fuer Teams waehrend der Beta derzeit kostenlos. +::: + +Workspace-Verwaltung ist in der Beta kostenlos. +Details zur spaeteren Preisgestaltung folgen. + +--- + +### Roles + +Du kannst Teammitglieder einladen und Rollen vergeben: + +- **Admin**: Verwalten Modelle, Mitglieder, API-Keys und Abrechnung +- **Member**: Verwalten nur eigene API-Keys + +Admins koennen zusaetzlich monatliche Ausgabenlimits pro Mitglied setzen. + +--- + +### Model access + +Admins koennen einzelne Modelle fuer den Workspace aktivieren oder deaktivieren. +Anfragen an deaktivierte Modelle liefern einen Fehler. + +Das ist hilfreich, wenn bestimmte datenverarbeitende Modelle ausgeschlossen werden sollen. + +--- + +### Bring your own key + +Du kannst eigene OpenAI- oder Anthropic-API-Keys verwenden und trotzdem andere Zen-Modelle nutzen. + +Bei eigenen Keys erfolgt die Token-Abrechnung direkt ueber den Provider, nicht ueber Zen. + +For example, your organization might already have a key for OpenAI or Anthropic +and you want to use that instead of the one that Zen provides. + +--- + +## Goals + +Wir haben OpenCode Zen entwickelt, um: + +1. Die besten Modell/Provider-Kombinationen fuer Coding-Agenten zu **benchmarken** +2. Stets **hohe Qualitaet** ohne Downgrades oder versteckte Umleitungen auf billigere Provider zu liefern +3. **Preissenkungen** zum Selbstkostenpreis weiterzugeben, mit Aufschlag nur fuer Zahlungsgebuehren +4. **Kein Lock-in** zu erzwingen, damit du Zen mit anderen Coding-Agents und OpenCode weiter mit anderen Providern nutzen kannst diff --git a/packages/web/src/content/docs/es/1-0.mdx b/packages/web/src/content/docs/es/1-0.mdx new file mode 100644 index 000000000..12b7e6bba --- /dev/null +++ b/packages/web/src/content/docs/es/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: Migrando a 1.0 +description: Novedades de OpenCode 1.0. +--- + +OpenCode 1.0 es una reescritura completa de TUI. + +Pasamos del TUI basado en go+bubbletea que tenía problemas de rendimiento y capacidad a un marco interno (OpenTUI) escrito en zig+solidjs. + +El nuevo TUI funciona como el anterior ya que se conecta al mismo servidor opencode. + +--- + +## Actualización + +No deberías realizar la actualización automática a 1.0 si actualmente estás utilizando una versión anterior. +versión. Sin embargo, algunas versiones anteriores de OpenCode siempre obtienen la última versión. + +Para actualizar manualmente, ejecute + +```bash +$ opencode upgrade 1.0.0 +``` + +Para volver a bajar a 0.x, ejecute + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## cambios de experiencia de usuario + +El historial de sesiones está más comprimido y solo muestra detalles completos de la herramienta de edición y bash. + +Agregamos una barra de comandos por la que fluye casi todo. Presione Ctrl+p para que aparezca en cualquier contexto y vea todo lo que puede hacer. + +Se agregó una barra lateral de sesión (se puede alternar) con información útil. + +Eliminamos algunas funciones que no estábamos seguros de que alguien realmente usara. Si falta algo importante, abra un problema y lo volveremos a agregar rápidamente. + +--- + +## Cambios importantes + +### Combinaciones de teclas renombradas + +- mensajes_revertir -> mensajes_undo +- switch_agent -> agente_ciclo +- switch_agent_reverse -> agente_cycle_reverse +- switch_mode -> agente_ciclo +- switch_mode_reverse -> agente_cycle_reverse + +### Combinaciones de teclas eliminadas + +- mensajes_layout_toggle +- mensajes_siguiente +- mensajes_anteriores +- file_diff_toggle +- búsqueda_archivo +- archivo_cerrar +- lista_archivo +- aplicación_ayuda +- proyecto_init +- detalles_herramienta +- bloques_pensamiento diff --git a/packages/web/src/content/docs/es/acp.mdx b/packages/web/src/content/docs/es/acp.mdx new file mode 100644 index 000000000..0cdc44513 --- /dev/null +++ b/packages/web/src/content/docs/es/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACP Soporte +description: Utilice OpenCode en cualquier editor compatible con ACP. +--- + +OpenCode admite el [Protocolo de cliente de agente](https://agentclientprotocol.com) o (ACP), lo que le permite usarlo directamente en editores e IDE compatibles. + +:::consejo +Para obtener una lista de editores y herramientas compatibles con ACP, consulte el [informe de progreso de ACP](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP es un protocolo abierto que estandariza la comunicación entre editores de código y agentes de codificación de IA. + +--- + +## Configurar + +Para usar OpenCode a través de ACP, configure su editor para ejecutar el comando `opencode acp`. + +El comando inicia OpenCode como un subproceso compatible con ACP que se comunica con su editor a través de JSON-RPC a través de stdio. + +A continuación se muestran ejemplos de editores populares que admiten ACP. + +--- + +### Zed + +Agregue a su configuración [Zed](https://zed.dev) (`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +Para abrirlo, use la acción `agent: new thread` en la **Paleta de comandos**. + +También puedes vincular un atajo de teclado editando tu `keymap.json`: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### IDE de JetBrains + +Agregue a su [JetBrains IDE](https://www.jetbrains.com/) acp.json de acuerdo con la [documentación](https://www.jetbrains.com/help/ai-assistant/acp.html): + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +Para abrirlo, use el nuevo agente 'OpenCode' en el selector de agentes de AI Chat. + +--- + +### Avante.nvim + +Agregue a su configuración [Avante.nvim](https://github.com/yetone/avante.nvim): + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +Si necesita pasar variables de entorno: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CódigoCompanion.nvim + +Para usar OpenCode como agente ACP en [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim), agregue lo siguiente a su configuración de Neovim: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +Esta configuración configura CodeCompanion para usar OpenCode como agente ACP para el chat. + +Si necesita pasar variables de entorno (como `OPENCODE_API_KEY`), consulte [Configuración de adaptadores: variables de entorno](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) en la documentación de CodeCompanion.nvim para obtener detalles completos. + +## Apoyo + +OpenCode funciona igual a través de ACP que en la terminal. Todas las funciones son compatibles: + +:::nota +Algunos comandos de barra integrados como `/undo` y `/redo` no son compatibles actualmente. +::: + +- Herramientas integradas (operaciones de archivos, comandos de terminal, etc.) +- Herramientas personalizadas y comandos de barra +- Servidores MCP configurados en su configuración OpenCode +- Reglas específicas del proyecto de `AGENTS.md` +- Formateadores y linters personalizados +- Sistema de agentes y permisos. diff --git a/packages/web/src/content/docs/es/agents.mdx b/packages/web/src/content/docs/es/agents.mdx new file mode 100644 index 000000000..03d9853ea --- /dev/null +++ b/packages/web/src/content/docs/es/agents.mdx @@ -0,0 +1,747 @@ +--- +title: Agentes +description: Configurar y utilizar agentes especializados. +--- + +Los agentes son asistentes de IA especializados que se pueden configurar para tareas y flujos de trabajo específicos. Le permiten crear herramientas enfocadas con indicaciones, modelos y acceso a herramientas personalizados. + +:::consejo +Utilice el agente del plan para analizar el código y revisar sugerencias sin realizar ningún cambio en el código. +::: + +Puede cambiar entre agentes durante una sesión o invocarlos con la mención `@`. + +--- + +## Tipos + +Hay dos tipos de agentes en OpenCode; agentes primarios y subagentes. + +--- + +### Agentes primarios + +Los agentes primarios son los asistentes principales con los que interactúas directamente. Puede recorrerlos usando la tecla **Tab** o la combinación de teclas `switch_agent` configurada. Estos agentes manejan su conversación principal. El acceso a las herramientas se configura mediante permisos; por ejemplo, Build tiene todas las herramientas habilitadas mientras que Plan está restringido. + +:::consejo +Puede utilizar la tecla **Tab** para cambiar entre agentes principales durante una sesión. +::: + +OpenCode viene con dos agentes principales integrados, **Construir** y **Planificar**. Bien +mira estos a continuación. + +--- + +### Subagentes + +Los subagentes son asistentes especializados que los agentes principales pueden invocar para tareas específicas. También puedes invocarlos manualmente **@ mencionándolos** en tus mensajes. + +OpenCode viene con dos subagentes integrados, **General** y **Explorar**. Veremos esto a continuación. + +--- + +## Incorporado + +OpenCode viene con dos agentes primarios integrados y dos subagentes integrados. + +--- + +### Usar compilación + +_Modo_: `primary` + +Build es el agente principal **predeterminado** con todas las herramientas habilitadas. Este es el agente estándar para trabajos de desarrollo en los que necesita acceso completo a las operaciones de archivos y comandos del sistema. + +--- + +### Plan de uso + +_Modo_: `primary` + +Un agente restringido diseñado para la planificación y el análisis. Utilizamos un sistema de permisos para brindarle más control y evitar cambios no deseados. +De forma predeterminada, todo lo siguiente está configurado en `ask`: + +- `file edits`: todas las escrituras, parches y ediciones. +- `bash`: Todos los comandos bash + +Este agente es útil cuando desea que LLM analice código, sugiera cambios o cree planes sin realizar modificaciones reales a su base de código. + +--- + +### Uso general + +_Modo_: `subagent` + +Un agente de uso general para investigar preguntas complejas y ejecutar tareas de varios pasos. Tiene acceso completo a las herramientas (excepto tareas pendientes), por lo que puede realizar cambios en los archivos cuando sea necesario. Utilícelo para ejecutar varias unidades de trabajo en paralelo. + +--- + +### Usar explorar + +_Modo_: `subagent` + +Un agente rápido y de solo lectura para explorar bases de código. No se pueden modificar archivos. Úselo cuando necesite buscar rápidamente archivos por patrones, buscar palabras clave en el código o responder preguntas sobre el código base. + +--- + +### Utilice compactación + +_Modo_: `primary` + +Agente de sistema oculto que compacta un contexto largo en un resumen más pequeño. Se ejecuta automáticamente cuando es necesario y no se puede seleccionar en la interfaz de usuario. + +--- + +### Usar título + +_Modo_: `primary` + +Agente del sistema oculto que genera títulos de sesión cortos. Se ejecuta automáticamente y no se puede seleccionar en la interfaz de usuario. + +--- + +### Usar resumen + +_Modo_: `primary` + +Agente del sistema oculto que crea resúmenes de sesiones. Se ejecuta automáticamente y no se puede seleccionar en la interfaz de usuario. + +--- + +## Uso + +1. Para los agentes principales, use la tecla **Tab** para recorrerlos durante una sesión. También puede utilizar su combinación de teclas `switch_agent` configurada. + +2. Se pueden invocar subagentes: + - **Automáticamente** por agentes principales para tareas especializadas según sus descripciones. + - Manualmente **@ mencionando** un subagente en tu mensaje. Por ejemplo. + + ```txt frame="none" + @general help me search for this function + ``` + +3. **Navegación entre sesiones**: cuando los subagentes crean sus propias sesiones secundarias, puede navegar entre la sesión principal y todas las sesiones secundarias usando: + - **\+Derecha** (o su combinación de teclas `session_child_cycle` configurada) para avanzar a través de padre → hijo1 → hijo2 → ... → padre + - **\+Izquierda** (o su combinación de teclas `session_child_cycle_reverse` configurada) para retroceder entre padre ← hijo1 ← hijo2 ← ... ← padre + + Esto le permite cambiar sin problemas entre la conversación principal y el trabajo de subagente especializado. + +--- + +## Configurar + +Puede personalizar los agentes integrados o crear los suyos propios mediante la configuración. Los agentes se pueden configurar de dos maneras: + +--- + +### JSON + +Configure agentes en su archivo de configuración `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Rebaja + +También puede definir agentes utilizando archivos de rebajas. Colócalos en: + +- Global: `~/.config/opencode/agents/` +- Por proyecto: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +El nombre del archivo de rebajas se convierte en el nombre del agente. Por ejemplo, `review.md` crea un agente `review`. + +--- + +## Opciones + +Veamos estas opciones de configuración en detalle. + +--- + +### Descripción + +Utilice la opción `description` para proporcionar una breve descripción de lo que hace el agente y cuándo usarlo. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +Esta es una opción de configuración **obligatoria**. + +--- + +### Temperatura + +Controle la aleatoriedad y la creatividad de las respuestas de LLM con la configuración `temperature`. + +Los valores más bajos hacen que las respuestas sean más centradas y deterministas, mientras que los valores más altos aumentan la creatividad y la variabilidad. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Los valores de temperatura suelen oscilar entre 0,0 y 1,0: + +- **0.0-0.2**: Respuestas muy enfocadas y deterministas, ideales para análisis y planificación de código. +- **0,3-0,5**: respuestas equilibradas con algo de creatividad, buenas para tareas de desarrollo general. +- **0.6-1.0**: respuestas más creativas y variadas, útiles para la lluvia de ideas y la exploración. + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Si no se especifica ninguna temperatura, OpenCode utiliza valores predeterminados específicos del modelo; normalmente 0 para la mayoría de los modelos, 0,55 para los modelos Qwen. + +--- + +### Pasos máximos + +Controle la cantidad máxima de iteraciones agentes que un agente puede realizar antes de verse obligado a responder solo con texto. Esto permite a los usuarios que desean controlar los costos establecer un límite a las acciones de agencia. + +Si no se establece esto, el agente continuará iterando hasta que el modelo decida detenerse o el usuario interrumpa la sesión. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +Cuando se alcanza el límite, el agente recibe un mensaje especial del sistema que le indica que responda con un resumen de su trabajo y las tareas restantes recomendadas. + +:::precaución +El campo heredado `maxSteps` está en desuso. Utilice `steps` en su lugar. +::: + +--- + +### Desactivar + +Establezca en `true` para deshabilitar el agente. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Inmediato + +Especifique un archivo de aviso del sistema personalizado para este agente con la configuración `prompt`. El archivo de aviso debe contener instrucciones específicas para el propósito del agente. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Esta ruta es relativa a donde se encuentra el archivo de configuración. Entonces esto funciona tanto para la configuración global OpenCode como para la configuración específica del proyecto. + +--- + +### Modelo + +Utilice la configuración `model` para anular el modelo de este agente. Útil para utilizar diferentes modelos optimizados para diferentes tareas. Por ejemplo, un modelo más rápido de planificación, un modelo más capaz de implementación. + +:::consejo +Si no especifica un modelo, los agentes primarios usarán el [modelo configurado globalmente](/docs/config#models), mientras que los subagentes usarán el modelo del agente primario que invocó al subagente. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +El ID del modelo en su configuración OpenCode usa el formato `provider/model-id`. Por ejemplo, si usa [OpenCode Zen](/docs/zen), usaría `opencode/gpt-5.1-codex` para GPT 5.1 Codex. + +--- + +### Herramientas + +Controle qué herramientas están disponibles en este agente con la configuración `tools`. Puede habilitar o deshabilitar herramientas específicas configurándolas en `true` o `false`. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::nota +La configuración específica del agente anula la configuración global. +::: + +También puedes utilizar comodines para controlar varias herramientas a la vez. Por ejemplo, para desactivar todas las herramientas de un servidor MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[Más información sobre herramientas](/docs/tools). + +--- + +### Permisos + +Puede configurar permisos para administrar qué acciones puede realizar un agente. Actualmente, los permisos para las herramientas `edit`, `bash` y `webfetch` se pueden configurar para: + +- `"ask"`: solicitar aprobación antes de ejecutar la herramienta +- `"allow"` — Permitir todas las operaciones sin aprobación +- `"deny"` — Desactiva la herramienta + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +Puede anular estos permisos por agente. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +También puede establecer permisos en los agentes de Markdown. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +Puede establecer permisos para comandos bash específicos. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +Esto puede tomar un patrón global. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +Y también puedes usar el comodín `*` para administrar los permisos de todos los comandos. +Dado que la última regla de coincidencia tiene prioridad, coloque el comodín `*` primero y las reglas específicas después. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[Más información sobre permisos](/docs/permissions). + +--- + +### Modo + +Controle el modo del agente con la configuración `mode`. La opción `mode` se utiliza para determinar cómo se puede utilizar el agente. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +La opción `mode` se puede configurar en `primary`, `subagent` o `all`. Si no se especifica `mode`, el valor predeterminado es `all`. + +--- + +### Oculto + +Oculte un subagente del menú de autocompletar `@` con `hidden: true`. Útil para subagentes internos que solo deben ser invocados mediante programación por otros agentes a través de la herramienta Tarea. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +Esto sólo afecta la visibilidad del usuario en el menú de autocompletar. El modelo aún puede invocar agentes ocultos a través de la herramienta Tarea si los permisos lo permiten. + +:::nota +Sólo aplica para agentes `mode: subagent`. +::: + +--- + +### Permisos de tareas + +Controle qué subagentes puede invocar un agente a través de la herramienta Tarea con `permission.task`. Utiliza patrones globales para una combinación flexible. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +Cuando se establece en `deny`, el subagente se elimina por completo de la descripción de la herramienta Tarea, por lo que el modelo no intentará invocarlo. + +:::consejo +Las reglas se evalúan en orden y la **última regla coincidente gana**. En el ejemplo anterior, `orchestrator-planner` coincide con `*` (denegar) y `orchestrator-*` (permitir), pero como `orchestrator-*` viene después de `*`, el resultado es `allow`. +::: + +:::consejo +Los usuarios siempre pueden invocar cualquier subagente directamente a través del menú de autocompletar `@`, incluso si los permisos de tarea del agente lo niegan. +::: + +--- + +### Color + +Personalice la apariencia visual del agente en la interfaz de usuario con la opción `color`. Esto afecta la forma en que aparece el agente en la interfaz. + +Utilice un color hexadecimal válido (por ejemplo, `#FF5733`) o un color de tema: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### P superior + +Controle la diversidad de respuestas con la opción `top_p`. Alternativa a la temperatura para controlar la aleatoriedad. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +Los valores oscilan entre 0,0 y 1,0. Los valores más bajos están más enfocados, los valores más altos son más diversos. + +--- + +### Adicional + +Cualquier otra opción que especifique en la configuración de su agente se **pasará directamente** al proveedor como opciones de modelo. Esto le permite utilizar funciones y parámetros específicos del proveedor. + +Por ejemplo, con los modelos de razonamiento de OpenAI, puedes controlar el esfuerzo de razonamiento: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +Estas opciones adicionales son específicas del modelo y del proveedor. Consulte la documentación de su proveedor para conocer los parámetros disponibles. + +:::consejo +Ejecute `opencode models` para ver una lista de los modelos disponibles. +::: + +--- + +## Crear agentes + +Puede crear nuevos agentes usando el siguiente comando: + +```bash +opencode agent create +``` + +Este comando interactivo: + +1. Preguntar dónde guardar al agente; global o específico del proyecto. +2. Descripción de lo que debe hacer el agente. +3. Genere un indicador y un identificador del sistema adecuados. +4. Le permite seleccionar a qué herramientas puede acceder el agente. +5. Finalmente, cree un archivo Markdown con la configuración del agente. + +--- + +## Casos de uso + +A continuación se muestran algunos casos de uso comunes para diferentes agentes. + +- **Agente de compilación**: trabajo de desarrollo completo con todas las herramientas habilitadas +- **Plan agente**: Análisis y planificación sin realizar cambios +- **Agente de revisión**: revisión de código con acceso de solo lectura más herramientas de documentación +- **Agente de depuración**: centrado en la investigación con bash y herramientas de lectura habilitadas +- **Agente de documentos**: escritura de documentación con operaciones de archivos pero sin comandos del sistema. + +--- + +## Ejemplos + +A continuación se muestran algunos agentes de ejemplo que pueden resultarle útiles. + +:::consejo +¿Tiene un agente que le gustaría compartir? [Enviar un PR](https://github.com/anomalyco/opencode). +::: + +--- + +### Agente de documentación + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### Auditor de seguridad + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/es/cli.mdx b/packages/web/src/content/docs/es/cli.mdx new file mode 100644 index 000000000..6face3684 --- /dev/null +++ b/packages/web/src/content/docs/es/cli.mdx @@ -0,0 +1,601 @@ +--- +title: CLI +description: OpenCode CLI opciones y comandos. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +El OpenCode CLI de forma predeterminada inicia el [TUI](/docs/tui) cuando se ejecuta sin ningún argumento. + +```bash +opencode +``` + +Pero también acepta comandos como se documenta en esta página. Esto le permite interactuar con OpenCode mediante programación. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui + +Inicie la interfaz de usuario del terminal OpenCode. + +```bash +opencode [project] +``` + +#### Banderas + +| Bandera | Corto | Descripción | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | Continuar la última sesión | +| `--session` | `-s` | ID de sesión para continuar | +| `--prompt` | | Aviso de uso | +| `--model` | `-m` | Modelo a utilizar en forma de proveedor/modelo | +| `--agent` | | Agente a utilizar | +| `--port` | | Puerto para escuchar | +| `--hostname` | | Nombre de host para escuchar | + +--- + +## Comandos + +El OpenCode CLI también tiene los siguientes comandos. + +--- + +### agente + +Administrar agentes para OpenCode. + +```bash +opencode agent [command] +``` + +--- + +### adjuntar + +Conecte una terminal a un servidor backend OpenCode que ya se esté ejecutando y iniciado mediante los comandos `serve` o `web`. + +```bash +opencode attach [url] +``` + +Esto permite usar TUI con un backend remoto OpenCode. Por ejemplo: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### Banderas + +| Bandera | Corto | Descripción | +| ----------- | ----- | --------------------------------- | +| `--dir` | | Directorio de trabajo para iniciar TUI en | +| `--session` | `-s` | ID de sesión para continuar | + +--- + +#### crear + +Cree un nuevo agente con configuración personalizada. + +```bash +opencode agent create +``` + +Este comando lo guiará en la creación de un nuevo agente con un mensaje del sistema personalizado y una configuración de herramientas. + +--- + +#### lista + +Enumere todos los agentes disponibles. + +```bash +opencode agent list +``` + +--- + +### autenticación + +Comando para administrar credenciales e iniciar sesión para proveedores. + +```bash +opencode auth [command] +``` + +--- + +#### acceso + +OpenCode funciona con la lista de proveedores en [Models.dev](https://models.dev), por lo que puede usar `opencode auth login` para configurar las claves API para cualquier proveedor que desee utilizar. Esto se almacena en `~/.local/share/opencode/auth.json`. + +```bash +opencode auth login +``` + +Cuando se inicia OpenCode, carga los proveedores desde el archivo de credenciales. Y si hay claves definidas en sus entornos o un archivo `.env` en su proyecto. + +--- + +#### lista + +Enumera todos los proveedores autenticados tal como están almacenados en el archivo de credenciales. + +```bash +opencode auth list +``` + +O la versión corta. + +```bash +opencode auth ls +``` + +--- + +#### cerrar sesión + +Cierra tu sesión de un proveedor eliminándolo del archivo de credenciales. + +```bash +opencode auth logout +``` + +--- + +### github + +Administre el agente GitHub para la automatización del repositorio. + +```bash +opencode github [command] +``` + +--- + +#### instalar + +Instale el agente GitHub en su repositorio. + +```bash +opencode github install +``` + +Esto configura el flujo de trabajo de acciones GitHub necesario y lo guía a través del proceso de configuración. [Más información](/docs/github). + +--- + +#### correr + +Ejecute el agente GitHub. Esto se usa normalmente en acciones GitHub. + +```bash +opencode github run +``` + +##### Banderas + +| Bandera | Descripción | +| --------- | -------------------------------------- | +| `--event` | GitHub evento simulado para ejecutar el agente | +| `--token` | GitHub token de acceso personal | + +--- + +### mcp + +Administrar servidores de protocolo de contexto modelo. + +```bash +opencode mcp [command] +``` + +--- + +#### agregar + +Agregue un servidor MCP a su configuración. + +```bash +opencode mcp add +``` + +Este comando lo guiará para agregar un servidor MCP local o remoto. + +--- + +#### lista + +Enumere todos los servidores MCP configurados y su estado de conexión. + +```bash +opencode mcp list +``` + +O utilice la versión corta. + +```bash +opencode mcp ls +``` + +--- + +#### autenticación + +Autentíquese con un servidor MCP habilitado para OAuth. + +```bash +opencode mcp auth [name] +``` + +Si no proporciona un nombre de servidor, se le pedirá que seleccione entre los servidores compatibles con OAuth disponibles. + +También puede enumerar los servidores compatibles con OAuth y su estado de autenticación. + +```bash +opencode mcp auth list +``` + +O utilice la versión corta. + +```bash +opencode mcp auth ls +``` + +--- + +#### cerrar sesión + +Elimine las credenciales OAuth para un servidor MCP. + +```bash +opencode mcp logout [name] +``` + +--- + +#### depurar + +Depurar problemas de conexión OAuth para un servidor MCP. + +```bash +opencode mcp debug +``` + +--- + +### modelos + +Enumere todos los modelos disponibles de los proveedores configurados. + +```bash +opencode models [provider] +``` + +Este comando muestra todos los modelos disponibles en sus proveedores configurados en el formato `provider/model`. + +Esto es útil para determinar el nombre exacto del modelo que se usará en [su configuración](/docs/config/). + +Opcionalmente, puede pasar un ID de proveedor para filtrar modelos por ese proveedor. + +```bash +opencode models anthropic +``` + +#### Banderas + +| Bandera | Descripción | +| ----------- | ------------------------------------------------------------ | +| `--refresh` | Actualizar la caché de modelos desde models.dev | +| `--verbose` | Utilice una salida del modelo más detallada (incluye metadatos como costos) | + +Utilice el indicador `--refresh` para actualizar la lista de modelos almacenados en caché. Esto es útil cuando se han agregado nuevos modelos a un proveedor y desea verlos en OpenCode. + +```bash +opencode models --refresh +``` + +--- + +### correr + +Ejecute opencode en modo no interactivo pasando un mensaje directamente. + +```bash +opencode run [message..] +``` + +Esto es útil para secuencias de comandos, automatización o cuando desea una respuesta rápida sin iniciar el TUI completo. Por ejemplo. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +También puede conectarse a una instancia `opencode serve` en ejecución para evitar tiempos de arranque en frío del servidor MCP en cada ejecución: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### Banderas + +| Bandera | Corto | Descripción | +| ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | | El comando a ejecutar, use mensaje para args | +| `--continue` | `-c` | Continuar la última sesión | +| `--session` | `-s` | ID de sesión para continuar | +| `--share` | | Comparte la sesión | +| `--model` | `-m` | Modelo a utilizar en forma de proveedor/modelo | +| `--agent` | | Agente a utilizar | +| `--file` | `-f` | Archivo(s) para adjuntar al mensaje | +| `--format` | | Formato: predeterminado (formateado) o json (eventos JSON sin formato) | +| `--title` | | Título de la sesión (utiliza un mensaje truncado si no se proporciona ningún valor) | +| `--attach` | | Adjuntar a un servidor opencode en ejecución (por ejemplo, http://localhost:4096) | +| `--port` | | Puerto para el servidor local (el puerto predeterminado es aleatorio) | + +--- + +### atender + +Inicie un servidor OpenCode sin cabeza para acceso API. Consulte los [documentos del servidor](/docs/server) para conocer la interfaz HTTP completa. + +```bash +opencode serve +``` + +Esto inicia un servidor HTTP que proporciona acceso API a la funcionalidad opencode sin la interfaz TUI. Configure `OPENCODE_SERVER_PASSWORD` para habilitar la autenticación básica HTTP (el nombre de usuario predeterminado es `opencode`). + +#### Banderas + +| Bandera | Descripción | +| ------------ | ------------------------------------------ | +| `--port` | Puerto para escuchar | +| `--hostname` | Nombre de host para escuchar | +| `--mdns` | Habilitar el descubrimiento de mDNS | +| `--cors` | Orígenes de navegador adicionales para permitir CORS | + +--- + +### sesión + +Administrar OpenCode sesiones. + +```bash +opencode session [command] +``` + +--- + +#### lista + +Enumere todas las sesiones OpenCode. + +```bash +opencode session list +``` + +##### Banderas + +| Bandera | Corto | Descripción | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` | Limitar a N sesiones más recientes | +| `--format` | | Formato de salida: tabla o json (tabla) | + +--- + +### estadísticas + +Muestre el uso de tokens y las estadísticas de costos para sus sesiones OpenCode. + +```bash +opencode stats +``` + +#### Banderas + +| Bandera | Descripción | +| ----------- | --------------------------------------------------------------------------- | +| `--days` | Mostrar estadísticas de los últimos N días (todo el tiempo) | +| `--tools` | Número de herramientas para mostrar (todas) | +| `--models` | Mostrar el desglose del uso del modelo (oculto de forma predeterminada). Pase un número para mostrar la parte superior N | +| `--project` | Filtrar por proyecto (todos los proyectos, cadena vacía: proyecto actual) | + +--- + +### exportar + +Exportar datos de la sesión como JSON. + +```bash +opencode export [sessionID] +``` + +Si no proporciona una ID de sesión, se le pedirá que seleccione entre las sesiones disponibles. + +--- + +### importar + +Importe datos de sesión desde un archivo JSON o una URL compartida OpenCode. + +```bash +opencode import +``` + +Puede importar desde un archivo local o una URL compartida OpenCode. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### web + +Inicie un servidor OpenCode sin cabeza con una interfaz web. + +```bash +opencode web +``` + +Esto inicia un servidor HTTP y abre un navegador web para acceder a OpenCode a través de una interfaz web. Configure `OPENCODE_SERVER_PASSWORD` para habilitar la autenticación básica HTTP (el nombre de usuario predeterminado es `opencode`). + +#### Banderas + +| Bandera | Descripción | +| ------------ | ------------------------------------------ | +| `--port` | Puerto para escuchar | +| `--hostname` | Nombre de host para escuchar | +| `--mdns` | Habilitar el descubrimiento de mDNS | +| `--cors` | Orígenes de navegador adicionales para permitir CORS | + +--- + +### acp + +Inicie un servidor ACP (Protocolo de cliente de agente). + +```bash +opencode acp +``` + +Este comando inicia un servidor ACP que se comunica a través de stdin/stdout usando nd-JSON. + +#### Banderas + +| Bandera | Descripción | +| ------------ | --------------------- | +| `--cwd` | Directorio de trabajo | +| `--port` | Puerto para escuchar | +| `--hostname` | Nombre de host para escuchar | + +--- + +### desinstalar + +Desinstale OpenCode y elimine todos los archivos relacionados. + +```bash +opencode uninstall +``` + +#### Banderas + +| Bandera | Corto | Descripción | +| --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` | Mantener archivos de configuración | +| `--keep-data` | `-d` | Conservar datos de sesión e instantáneas | +| `--dry-run` | | Mostrar lo que se eliminaría sin eliminar | +| `--force` | `-f` | Saltar mensajes de confirmación | + +--- + +### mejora + +Actualiza opencode a la última versión o a una versión específica. + +```bash +opencode upgrade [target] +``` + +Para actualizar a la última versión. + +```bash +opencode upgrade +``` + +Para actualizar a una versión específica. + +```bash +opencode upgrade v0.1.48 +``` + +#### Banderas + +| Bandera | Corto | Descripción | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` | El método de instalación que se utilizó; rizo, npm, pnpm, bollo, preparación | + +--- + +## Banderas globales + +El opencode CLI toma las siguientes banderas globales. + +| Bandera | Corto | Descripción | +| -------------- | ----- | ------------------------------------ | +| `--help` | `-h` | Mostrar ayuda | +| `--version` | `-v` | Número de versión de impresión | +| `--print-logs` | | Imprimir registros en stderr | +| `--log-level` | | Nivel de registro (DEPURACIÓN, INFORMACIÓN, ADVERTENCIA, ERROR) | + +--- + +## Variables de entorno + +OpenCode se puede configurar mediante variables de entorno. + +| Variables | Tipo | Descripción | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | booleano | Compartir sesiones automáticamente | +| `OPENCODE_GIT_BASH_PATH` | cadena | Ruta al ejecutable de Git Bash en Windows | +| `OPENCODE_CONFIG` | cadena | Ruta al archivo de configuración | +| `OPENCODE_CONFIG_DIR` | cadena | Ruta al directorio de configuración | +| `OPENCODE_CONFIG_CONTENT` | cadena | Contenido de configuración json en línea | +| `OPENCODE_DISABLE_AUTOUPDATE` | booleano | Deshabilitar las comprobaciones automáticas de actualizaciones | +| `OPENCODE_DISABLE_PRUNE` | booleano | Deshabilitar la poda de datos antiguos | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | booleano | Deshabilitar las actualizaciones automáticas de títulos de terminal | +| `OPENCODE_PERMISSION` | cadena | Configuración de permisos json incorporados | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | booleano | Deshabilitar complementos predeterminados | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | booleano | Deshabilitar las descargas automáticas del servidor LSP | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | booleano | Habilitar modelos experimentales | +| `OPENCODE_DISABLE_AUTOCOMPACT` | booleano | Deshabilitar la compactación automática de contexto | +| `OPENCODE_DISABLE_CLAUDE_CODE` | booleano | Deshabilitar la lectura desde `.claude` (mensaje + habilidades) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | booleano | Desactivar lectura `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | booleano | Deshabilitar la carga `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | booleano | Deshabilitar la recuperación de modelos desde fuentes remotas | +| `OPENCODE_FAKE_VCS` | cadena | Proveedor de VCS falso para fines de prueba | +| `OPENCODE_DISABLE_FILETIME_CHECK` | booleano | Deshabilite la verificación del tiempo del archivo para optimizarlo | +| `OPENCODE_CLIENT` | cadena | Identificador de cliente (por defecto `cli`) | +| `OPENCODE_ENABLE_EXA` | booleano | Habilitar las herramientas de búsqueda web de Exa | +| `OPENCODE_SERVER_PASSWORD` | cadena | Habilite la autenticación básica para `serve`/`web` | +| `OPENCODE_SERVER_USERNAME` | cadena | Anular el nombre de usuario de autenticación básica (predeterminado `opencode`) | +| `OPENCODE_MODELS_URL` | cadena | URL personalizada para buscar la configuración de modelos | + +--- + +### Experimental + +Estas variables de entorno habilitan funciones experimentales que pueden cambiar o eliminarse. + +| Variables | Tipo | Descripción | +| ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | booleano | Habilitar todas las funciones experimentales | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | booleano | Habilitar descubrimiento de íconos | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | booleano | Deshabilitar copia al seleccionar en TUI | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | número | Tiempo de espera predeterminado para comandos bash en ms | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | número | Tokens de salida máximos para respuestas LLM | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | booleano | Habilite el observador de archivos para todo el directorio | +| `OPENCODE_EXPERIMENTAL_OXFMT` | booleano | Habilitar el formateador oxfmt | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | booleano | Habilitar herramienta experimental LSP | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | booleano | Deshabilitar el observador de archivos | +| `OPENCODE_EXPERIMENTAL_EXA` | booleano | Habilitar funciones experimentales de Exa | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | booleano | Habilitar la verificación de tipo experimental LSP | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | booleano | Habilitar funciones de rebajas experimentales | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | booleano | Habilitar modo de plan | diff --git a/packages/web/src/content/docs/es/commands.mdx b/packages/web/src/content/docs/es/commands.mdx new file mode 100644 index 000000000..9d8d72b31 --- /dev/null +++ b/packages/web/src/content/docs/es/commands.mdx @@ -0,0 +1,323 @@ +--- +title: Comandos +description: Cree comandos personalizados para tareas repetitivas. +--- + +Los comandos personalizados le permiten especificar un mensaje que desea ejecutar cuando ese comando se ejecuta en TUI. + +```bash frame="none" +/my-command +``` + +Los comandos personalizados se suman a los comandos integrados como `/init`, `/undo`, `/redo`, `/share`, `/help`. [Más información](/docs/tui#commands). + +--- + +## Crear archivos de comando + +Cree archivos de rebajas en el directorio `commands/` para definir comandos personalizados. + +Crear `.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +El frontmatter define las propiedades del comando. El contenido se convierte en la plantilla. + +Utilice el comando escribiendo `/` seguido del nombre del comando. + +```bash frame="none" +"/test" +``` + +--- + +## Configurar + +Puede agregar comandos personalizados a través de la configuración OpenCode o creando archivos de rebajas en el directorio `commands/`. + +--- + +### JSON + +Utilice la opción `command` en su OpenCode [config](/docs/config): + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Ahora puedes ejecutar este comando en TUI: + +```bash frame="none" +/test +``` + +--- + +### Rebaja + +También puede definir comandos utilizando archivos de rebajas. Colócalos en: + +- Global: `~/.config/opencode/commands/` +- Por proyecto: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +El nombre del archivo de rebajas se convierte en el nombre del comando. Por ejemplo, `test.md` permite +tu corres: + +```bash frame="none" +/test +``` + +--- + +## Configuración rápida + +Las indicaciones para los comandos personalizados admiten varios marcadores de posición y sintaxis especiales. + +--- + +### Argumentos + +Pase argumentos a comandos usando el marcador de posición `$ARGUMENTS`. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +Ejecute el comando con argumentos: + +```bash frame="none" +/component Button +``` + +Y `$ARGUMENTS` será reemplazado por `Button`. + +También puede acceder a argumentos individuales utilizando parámetros posicionales: + +- `$1` - Primer argumento +- `$2` - Segundo argumento +- `$3` - Tercer argumento +- Etcétera... + +Por ejemplo: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +Ejecute el comando: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +Esto reemplaza: + +- `$1` con `config.json` +- `$2` con `src` +- `$3` con `{ "key": "value" }` + +--- + +### Salida del shell + +Utilice _!`command`_ para inyectar la salida de [comando bash](/docs/tui#bash-commands) en su mensaje. + +Por ejemplo, para crear un comando personalizado que analice la cobertura de la prueba: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +O para revisar cambios recientes: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +Los comandos se ejecutan en el directorio raíz de su proyecto y su salida pasa a formar parte del mensaje. + +--- + +### Referencias de archivos + +Incluya archivos en su comando usando `@` seguido del nombre del archivo. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +El contenido del archivo se incluye automáticamente en el mensaje. + +--- + +## Opciones + +Veamos las opciones de configuración en detalle. + +--- + +### Plantilla + +La opción `template` define el mensaje que se enviará al LLM cuando se ejecute el comando. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +Esta es una opción de configuración **obligatoria**. + +--- + +### Descripción + +Utilice la opción `description` para proporcionar una breve descripción de lo que hace el comando. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +Esto se muestra como descripción en TUI cuando escribe el comando. + +--- + +### Agente + +Utilice la configuración `agent` para especificar opcionalmente qué [agente](/docs/agents) debe ejecutar este comando. +Si se trata de un [subagente](/docs/agents/#subagents), el comando activará una invocación de subagente de forma predeterminada. +Para desactivar este comportamiento, establezca `subtask` en `false`. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +Esta es una opción de configuración **opcional**. Si no se especifica, el valor predeterminado es su agente actual. + +--- + +### Subtarea + +Utilice el booleano `subtask` para forzar que el comando active una invocación de [subagente](/docs/agents/#subagents). +Esto es útil si desea que el comando no contamine su contexto principal y **obligue** al agente a actuar como subagente. +incluso si `mode` está configurado en `primary` en la configuración de [agente](/docs/agents). + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +Esta es una opción de configuración **opcional**. + +--- + +### Modelo + +Utilice la configuración `model` para anular el modelo predeterminado para este comando. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Esta es una opción de configuración **opcional**. + +--- + +## Incorporado + +opencode incluye varios comandos integrados como `/init`, `/undo`, `/redo`, `/share`, `/help`; [más información](/docs/tui#commands). + +:::nota +Los comandos personalizados pueden anular los comandos integrados. +::: + +Si define un comando personalizado con el mismo nombre, anulará el comando integrado. diff --git a/packages/web/src/content/docs/es/config.mdx b/packages/web/src/content/docs/es/config.mdx new file mode 100644 index 000000000..a2c278b33 --- /dev/null +++ b/packages/web/src/content/docs/es/config.mdx @@ -0,0 +1,685 @@ +--- +title: configuración +description: Usando la configuración OpenCode JSON. +--- + +Puede configurar OpenCode usando un archivo de configuración JSON. + +--- + +## Formato + +OpenCode admite los formatos **JSON** y **JSONC** (JSON con comentarios). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## Ubicaciones + +Puedes colocar tu configuración en un par de ubicaciones diferentes y tienen un +diferente orden de precedencia. + +:::nota +Los archivos de configuración se **fusionan**, no se reemplazan. +::: + +Los archivos de configuración se fusionan, no se reemplazan. Se combinan las configuraciones de las siguientes ubicaciones de configuración. Las configuraciones posteriores anulan las anteriores solo para claves en conflicto. Se conservan las configuraciones no conflictivas de todas las configuraciones. + +Por ejemplo, si su configuración global establece `theme: "opencode"` y `autoupdate: true`, y la configuración de su proyecto establece `model: "anthropic/claude-sonnet-4-5"`, la configuración final incluirá las tres configuraciones. + +--- + +### Orden de precedencia + +Las fuentes de configuración se cargan en este orden (las fuentes posteriores anulan las anteriores): + +1. **Configuración remota** (de `.well-known/opencode`): valores predeterminados de la organización +2. **Configuración global** (`~/.config/opencode/opencode.json`) - preferencias del usuario +3. **Configuración personalizada** (`OPENCODE_CONFIG` env var): anulaciones personalizadas +4. **Configuración del proyecto** (`opencode.json` en el proyecto): configuración específica del proyecto +5. Directorios **`.opencode`** - agentes, comandos, complementos +6. **Configuración en línea** (`OPENCODE_CONFIG_CONTENT` env var): anulaciones del tiempo de ejecución + +Esto significa que las configuraciones del proyecto pueden anular los valores predeterminados globales y las configuraciones globales pueden anular los valores predeterminados de la organización remota. + +:::nota +Los directorios `.opencode` y `~/.config/opencode` usan **nombres en plural** para los subdirectorios: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/` y `themes/`. También se admiten nombres singulares (por ejemplo, `agent/`) para compatibilidad con versiones anteriores. +::: + +--- + +### Remoto + +Las organizaciones pueden proporcionar una configuración predeterminada a través del punto final `.well-known/opencode`. Esto se obtiene automáticamente cuando se autentica con un proveedor que lo admita. + +La configuración remota se carga primero y sirve como capa base. Todas las demás fuentes de configuración (global, proyecto) pueden anular estos valores predeterminados. + +Por ejemplo, si su organización proporciona servidores MCP que están deshabilitados de forma predeterminada: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +Puede habilitar servidores específicos en su configuración local: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### Global + +Coloque su configuración global OpenCode en `~/.config/opencode/opencode.json`. Utilice la configuración global para las preferencias de todo el usuario, como temas, proveedores o combinaciones de teclas. + +La configuración global anula los valores predeterminados de la organización remota. + +--- + +### Por proyecto + +Agregue `opencode.json` en la raíz de su proyecto. La configuración del proyecto tiene la mayor prioridad entre los archivos de configuración estándar: anula las configuraciones globales y remotas. + +:::consejo +Coloque la configuración específica del proyecto en la raíz de su proyecto. +::: + +Cuando se inicia OpenCode, busca un archivo de configuración en el directorio actual o recorre hasta el directorio Git más cercano. + +Esto también es seguro para registrarlo en Git y utiliza el mismo esquema que el global. + +--- + +### Ruta personalizada + +Especifique una ruta de archivo de configuración personalizada utilizando la variable de entorno `OPENCODE_CONFIG`. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +La configuración personalizada se carga entre las configuraciones globales y del proyecto en orden de prioridad. + +--- + +### Directorio personalizado + +Especifique un directorio de configuración personalizado usando `OPENCODE_CONFIG_DIR` +variable de entorno. En este directorio se buscarán agentes, comandos, +modos y complementos como el directorio estándar `.opencode`, y debería +Sigue la misma estructura. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +El directorio personalizado se carga después de los directorios global config y `.opencode`, por lo que **puede anular** su configuración. + +--- + +## Esquema + +El archivo de configuración tiene un esquema definido en [**`opencode.ai/config.json`**](https://opencode.ai/config.json). + +Su editor debería poder validar y autocompletar según el esquema. + +--- + +### TUI + +Puede configurar ajustes específicos de TUI a través de la opción `tui`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +Opciones disponibles: + +- `scroll_acceleration.enabled` - Habilita la aceleración de desplazamiento estilo macOS. **Tiene prioridad sobre `scroll_speed`.** +- `scroll_speed` - Multiplicador de velocidad de desplazamiento personalizado (predeterminado: `3`, mínimo: `1`). Se ignora si `scroll_acceleration.enabled` es `true`. +- `diff_style` - Controla la representación de diferencias. `"auto"` se adapta al ancho del terminal, `"stacked"` siempre muestra una sola columna. + +[Obtenga más información sobre el uso de TUI aquí](/docs/tui). + +--- + +### Servidor + +Puede configurar los ajustes del servidor para los comandos `opencode serve` y `opencode web` a través de la opción `server`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +Opciones disponibles: + +- `port` - Puerto para escuchar. +- `hostname`: nombre de host para escuchar. Cuando `mdns` está habilitado y no se establece ningún nombre de host, el valor predeterminado es `0.0.0.0`. +- `mdns`: habilita el descubrimiento de servicios mDNS. Esto permite que otros dispositivos en la red descubran su servidor OpenCode. +- `mdnsDomain` - Nombre de dominio personalizado para el servicio mDNS. El valor predeterminado es `opencode.local`. Útil para ejecutar múltiples instancias en la misma red. +- `cors`: orígenes adicionales para permitir CORS cuando se utiliza el servidor HTTP desde un cliente basado en navegador. Los valores deben ser orígenes completos (esquema + host + puerto opcional), por ejemplo, `https://app.example.com`. + +[Obtenga más información sobre el servidor aquí](/docs/server). + +--- + +### Herramientas + +Puede administrar las herramientas que un LLM puede usar a través de la opción `tools`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[Obtenga más información sobre las herramientas aquí](/docs/tools). + +--- + +### Modelos + +Puede configurar los proveedores y modelos que desea utilizar en su configuración OpenCode a través de las opciones `provider`, `model` y `small_model`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +La opción `small_model` configura un modelo separado para tareas livianas como la generación de títulos. De forma predeterminada, OpenCode intenta utilizar un modelo más económico si su proveedor tiene uno disponible; de ​​lo contrario, recurre a su modelo principal. + +Las opciones de proveedores pueden incluir `timeout` y `setCacheKey`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout`: tiempo de espera de solicitud en milisegundos (predeterminado: 300000). Establezca en `false` para desactivar. +- `setCacheKey`: asegúrese de que siempre haya una clave de caché configurada para el proveedor designado. + +También puede configurar [modelos locales](/docs/models#local). [Más información](/docs/models). + +--- + +#### Opciones específicas del proveedor + +Algunos proveedores admiten opciones de configuración adicionales más allá de las configuraciones genéricas `timeout` y `apiKey`. + +##### Amazon Bedrock + +Amazon Bedrock admite la configuración específica de AWS: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - AWS región para Bedrock (el valor predeterminado es `AWS_REGION` env var o `us-east-1`) +- `profile` - AWS perfil con nombre de `~/.aws/credentials` (el valor predeterminado es `AWS_PROFILE` var env) +- `endpoint`: URL de punto de enlace personalizada para puntos de enlace de VPC. Este es un alias para la opción genérica `baseURL` que utiliza terminología específica de AWS. Si se especifican ambos, `endpoint` tiene prioridad. + +:::nota +Los tokens de portador (`AWS_BEARER_TOKEN_BEDROCK` o `/connect`) tienen prioridad sobre la autenticación basada en perfil. Consulte [precedencia de autenticación](/docs/providers#authentication-precedence) para obtener más detalles. +::: + +[Obtenga más información sobre la configuración de Amazon Bedrock](/docs/providers#amazon-bedrock). + +--- + +### Temas + +Puede configurar el tema que desea usar en su configuración OpenCode a través de la opción `theme`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[Más información aquí](/docs/themes). + +--- + +### Agentes + +Puedes configurar agentes especializados para tareas específicas a través de la opción `agent`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +También puede definir agentes utilizando archivos de rebajas en `~/.config/opencode/agents/` o `.opencode/agents/`. [Más información aquí](/docs/agents). + +--- + +### Agente predeterminado + +Puede configurar el agente predeterminado usando la opción `default_agent`. Esto determina qué agente se utiliza cuando no se especifica ninguno explícitamente. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +El agente predeterminado debe ser un agente principal (no un subagente). Puede ser un agente integrado como `"build"` o `"plan"`, o un [agente personalizado](/docs/agents) que haya definido. Si el agente especificado no existe o es un subagente, OpenCode recurrirá a `"build"` con una advertencia. + +Esta configuración se aplica en todas las interfaces: TUI, CLI (`opencode run`), aplicación de escritorio y GitHub Acción. + +--- + +### Intercambio + +Puede configurar la función [compartir](/docs/share) a través de la opción `share`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +Esto requiere: + +- `"manual"` - Permitir compartir manualmente mediante comandos (predeterminado) +- `"auto"` - Comparte automáticamente nuevas conversaciones +- `"disabled"` - Deshabilitar el uso compartido por completo + +De forma predeterminada, el uso compartido está configurado en modo manual, donde debe compartir conversaciones explícitamente usando el comando `/share`. + +--- + +### Comandos + +Puede configurar comandos personalizados para tareas repetitivas a través de la opción `command`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +También puede definir comandos utilizando archivos de rebajas en `~/.config/opencode/commands/` o `.opencode/commands/`. [Más información aquí](/docs/commands). + +--- + +### combinaciones de teclas + +Puede personalizar sus combinaciones de teclas a través de la opción `keybinds`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[Más información aquí](/docs/keybinds). + +--- + +### Actualización automática + +OpenCode descargará automáticamente cualquier actualización nueva cuando se inicie. Puede desactivar esto con la opción `autoupdate`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +Si no desea actualizaciones pero desea recibir una notificación cuando haya una nueva versión disponible, configure `autoupdate` en `"notify"`. +Tenga en cuenta que esto sólo funciona si no se instaló mediante un administrador de paquetes como Homebrew. + +--- + +### Formateadores + +Puede configurar formateadores de código a través de la opción `formatter`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[Obtenga más información sobre los formateadores aquí](/docs/formatters). + +--- + +### Permisos + +De forma predeterminada, opencode **permite todas las operaciones** sin requerir aprobación explícita. Puede cambiar esto usando la opción `permission`. + +Por ejemplo, para garantizar que las herramientas `edit` y `bash` requieran la aprobación del usuario: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[Obtenga más información sobre los permisos aquí](/docs/permissions). + +--- + +### Compactación + +Puede controlar el comportamiento de compactación del contexto a través de la opción `compaction`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto`: compacta automáticamente la sesión cuando el contexto está lleno (predeterminado: `true`). +- `prune`: elimina las salidas de herramientas antiguas para guardar tokens (predeterminado: `true`). + +--- + +### Vigilante + +Puede configurar patrones de ignorancia del observador de archivos a través de la opción `watcher`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +Los patrones siguen la sintaxis global. Utilice esto para excluir directorios ruidosos de la visualización de archivos. + +--- + +### MCP servidores + +Puede configurar los servidores MCP que desee utilizar a través de la opción `mcp`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[Más información aquí](/docs/mcp-servers). + +--- + +### Complementos + +Los [complementos](/docs/plugins) amplían OpenCode con herramientas, enlaces e integraciones personalizados. + +Coloque los archivos de complemento en `.opencode/plugins/` o `~/.config/opencode/plugins/`. También puedes cargar complementos desde npm a través de la opción `plugin`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[Más información aquí](/docs/plugins). + +--- + +### Instrucciones + +Puedes configurar las instrucciones para el modelo que estás usando a través de la opción `instructions`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Esto requiere una variedad de rutas y patrones globales para archivos de instrucciones. [Más información +sobre las reglas aquí](/docs/rules). + +--- + +### Proveedores deshabilitados + +Puede deshabilitar proveedores que se cargan automáticamente a través de la opción `disabled_providers`. Esto es útil cuando desea evitar que se carguen ciertos proveedores incluso si sus credenciales están disponibles. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::nota +El `disabled_providers` tiene prioridad sobre `enabled_providers`. +::: + +La opción `disabled_providers` acepta una variedad de ID de proveedores. Cuando un proveedor está deshabilitado: + +- No se cargará incluso si se establecen variables de entorno. +- No se cargará incluso si las teclas API están configuradas mediante el comando `/connect`. +- Los modelos del proveedor no aparecerán en la lista de selección de modelos. + +--- + +### Proveedores habilitados + +Puede especificar una lista de proveedores permitidos a través de la opción `enabled_providers`. Cuando se establece, solo se habilitarán los proveedores especificados y se ignorarán todos los demás. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +Esto es útil cuando desea restringir OpenCode para que utilice únicamente proveedores específicos en lugar de deshabilitarlos uno por uno. + +:::nota +El `disabled_providers` tiene prioridad sobre `enabled_providers`. +::: + +Si un proveedor aparece tanto en `enabled_providers` como en `disabled_providers`, el `disabled_providers` tiene prioridad para la compatibilidad con versiones anteriores. + +--- + +### Experimental + +La clave `experimental` contiene opciones que se encuentran en desarrollo activo. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::precaución +Las opciones experimentales no son estables. Pueden cambiar o eliminarse sin previo aviso. +::: + +--- + +##Variables + +Puede utilizar la sustitución de variables en sus archivos de configuración para hacer referencia a variables de entorno y contenidos de archivos. + +--- + +### Variables ambientales + +Utilice `{env:VARIABLE_NAME}` para sustituir variables de entorno: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +Si la variable de entorno no está configurada, se reemplazará con una cadena vacía. + +--- + +### Archivos + +Utilice `{file:path/to/file}` para sustituir el contenido de un archivo: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +Las rutas de los archivos pueden ser: + +- Relativo al directorio del archivo de configuración +- O rutas absolutas que comienzan con `/` o `~` + +Estos son útiles para: + +- Mantener datos confidenciales como claves API en archivos separados. +- Incluye archivos de instrucciones grandes sin saturar tu configuración. +- Compartir fragmentos de configuración comunes en múltiples archivos de configuración. diff --git a/packages/web/src/content/docs/es/custom-tools.mdx b/packages/web/src/content/docs/es/custom-tools.mdx new file mode 100644 index 000000000..17c1e368e --- /dev/null +++ b/packages/web/src/content/docs/es/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: Herramientas personalizadas +description: Cree herramientas que LLM pueda llamar en opencode. +--- + +Las herramientas personalizadas son funciones que usted crea y que el LLM puede llamar durante las conversaciones. Trabajan junto con las [herramientas integradas] (./tools) de opencode como `read`, `write` y `bash`. + +--- + +## Creando una herramienta + +Las herramientas se definen como archivos **TypeScript** o **JavaScript**. Sin embargo, la definición de la herramienta puede invocar secuencias de comandos escritas en **cualquier idioma**: TypeScript o JavaScript solo se utilizan para la definición de la herramienta en sí. + +--- + +### Ubicación + +Se pueden definir: + +- Localmente colocándolos en el directorio `.opencode/tools/` de tu proyecto. +- O de forma global, colocándolos en `~/.config/opencode/tools/`. + +--- + +### Estructura + +La forma más sencilla de crear herramientas es utilizar el asistente `tool()` que proporciona seguridad de tipos y validación. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +El **nombre de archivo** se convierte en el **nombre de la herramienta**. Lo anterior crea una herramienta `database`. + +--- + +#### Múltiples herramientas por archivo + +También puede exportar varias herramientas desde un solo archivo. Cada exportación se convierte en **una herramienta independiente** con el nombre **`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +Esto crea dos herramientas: `math_add` y `math_multiply`. + +--- + +### Argumentos + +Puedes usar `tool.schema`, que es simplemente [Zod](/docs/tools), para definir tipos de argumentos. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +También puedes importar [Zod](https://zod.dev) directamente y devolver un objeto simple: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### Contexto + +Las herramientas reciben contexto sobre la sesión actual: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +Utilice `context.directory` para el directorio de trabajo de la sesión. +Utilice `context.worktree` para la raíz del árbol de trabajo de git. + +--- + +## Ejemplos + +### Escribir una herramienta en Python + +Puede escribir sus herramientas en cualquier idioma que desee. Aquí hay un ejemplo que suma dos números usando Python. + +Primero, cree la herramienta como un script de Python: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +Luego cree la definición de herramienta que la invoca: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +Aquí estamos usando la utilidad [`Bun.$`](https://zod.dev) para ejecutar el script Python. diff --git a/packages/web/src/content/docs/es/ecosystem.mdx b/packages/web/src/content/docs/es/ecosystem.mdx new file mode 100644 index 000000000..1888dddc1 --- /dev/null +++ b/packages/web/src/content/docs/es/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: Ecosistema +description: Proyectos e integraciones construidas con OpenCode. +--- + +Una colección de proyectos comunitarios construidos en OpenCode. + +:::nota +¿Quieres agregar tu proyecto relacionado con OpenCode a esta lista? Envíe un PR. +::: + +También puedes consultar [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) y [opencode.cafe](https://opencode.cafe), una comunidad que agrega el ecosistema y la comunidad. + +--- + +## Complementos + +| Nombre | Descripción | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | Ejecute automáticamente sesiones OpenCode en entornos sandbox aislados de Daytona con git sync y vistas previas en vivo | +| [opencode-sesión-helicona](https://github.com/H2Shami/opencode-helicone-session) | Inyecte automáticamente encabezados de sesión de Helicone para agrupación de solicitudes | +| [opencode-tipo-inyección](https://github.com/nick-vi/opencode-type-inject) | Inyecte automáticamente tipos TypeScript/Svelte en lecturas de archivos con herramientas de búsqueda | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Utilice su suscripción ChatGPT Plus/Pro en lugar de créditos API | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Utilice su plan Gemini existente en lugar de la facturación API | +| [opencode-autenticación antigravedad](https://github.com/NoeFabris/opencode-antigravity-auth) | Utilice los modelos gratuitos de Antigravity en lugar de la facturación API | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Aislamiento de contenedores de desarrollo de múltiples ramas con clones superficiales y puertos asignados automáticamente | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Complemento Google Antigravity OAuth, compatible con la Búsqueda de Google y manejo más sólido de API | +| [opencode-poda-de-contexto-dinámico](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Optimice el uso de tokens eliminando los resultados de herramientas obsoletas | +| [opencode-búsqueda web-citada](https://github.com/ghoulr/opencode-websearch-cited.git) | Agregue soporte de búsqueda web nativa para proveedores compatibles con el estilo basado en Google | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Permite a los agentes de IA ejecutar procesos en segundo plano en un PTY y enviarles información interactiva. | +| [opencode-estrategia-shell](https://github.com/JRedeker/opencode-shell-strategy) | Instrucciones para comandos de shell no interactivos: evita bloqueos de operaciones dependientes de TTY | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Seguimiento del uso de OpenCode con Wakatime | +| [opencode-md-formateador de tabla](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Limpiar tablas de rebajas producidas por LLMs | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | Edición de código 10 veces más rápida con Morph Fast Apply API y marcadores de edición diferidos | +| [oh-mi-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Agentes en segundo plano, herramientas LSP/AST/MCP prediseñadas, agentes seleccionados, compatible con Claude Code | +| [opencode-notificador](https://github.com/panta82/opencode-notificator) | Notificaciones de escritorio y alertas sonoras para sesiones OpenCode | +| [opencode-notificador](https://github.com/mohak34/opencode-notifier) | Notificaciones de escritorio y alertas sonoras para eventos de permiso, finalización y error | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | Nomenclatura automática de sesiones Zellij impulsada por IA basada en el contexto OpenCode | +| [opencode-hábil](https://github.com/zenobi-us/opencode-skillful) | Permitir que los agentes OpenCode carguen mensajes de forma diferida a pedido con descubrimiento e inyección de habilidades | +| [opencode-supermemoria](https://github.com/supermemoryai/opencode-supermemory) | Memoria persistente entre sesiones utilizando Supermemoria | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Revisión interactiva del plan con anotaciones visuales y uso compartido privado/sin conexión | +| [@openspoon/subtarea2](https://github.com/spoons-and-mirrors/subtask2) | Amplíe opencode /commands a un potente sistema de orquestación con control de flujo granular | +| [opencode-programador](https://github.com/different-ai/opencode-scheduler) | Programe trabajos recurrentes usando launchd (Mac) o systemd (Linux) con sintaxis cron | +| [micocódigo](https://github.com/vtemian/micode) | Lluvia de ideas estructurada → Planificar → Implementar flujo de trabajo con continuidad de sesión | +| [octto](https://github.com/vtemian/octto) | Interfaz de usuario interactiva del navegador para lluvia de ideas de IA con formularios de preguntas múltiples | +| [opencode-agentes-de-fondo](https://github.com/kdcokenny/opencode-background-agents) | Agentes en segundo plano estilo Claude Code con delegación asíncrona y persistencia de contexto | +| [opencode-notificar](https://github.com/kdcokenny/opencode-notify) | Notificaciones nativas del sistema operativo para OpenCode: sepa cuándo se completan las tareas | +| [opencode-espacio de trabajo](https://github.com/kdcokenny/opencode-workspace) | Arnés de orquestación multiagente incluido: 16 componentes, una instalación | +| [opencode-árbol de trabajo](https://github.com/kdcokenny/opencode-worktree) | Árboles de trabajo de Git de fricción cero para OpenCode | + +--- + +## Proyectos + +| Nombre | Descripción | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | Bot de Discord para controlar sesiones OpenCode, basado en el SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Complemento Neovim para avisos compatibles con el editor, creado en API | +| [portal](https://github.com/hosenur/portal) | Interfaz de usuario web móvil para OpenCode a través de Tailscale/VPN | +| [Plantilla de complemento opencode](https://github.com/zenobi-us/opencode-plugin-template/) | Plantilla para crear complementos OpenCode | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Interfaz de Neovim para opencode: un agente de codificación de IA basado en terminal | +| [ai-sdk-proveedor-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Proveedor Vercel AI SDK para usar OpenCode a través de @opencode-ai/sdk | +| [Cámara Abierta](https://github.com/btriapitsyn/openchamber) | Aplicación web/de escritorio y extensión VS Code para OpenCode | +| [OpenCode-Obsidiana](https://github.com/mtymek/opencode-obsidian) | Complemento de Obsidian que incorpora OpenCode en la interfaz de usuario de Obsidian | +| [OpenWork](https://github.com/different-ai/openwork) | Una alternativa de código abierto a Claude Cowork, impulsada por OpenCode | +| [ocx](https://github.com/kdcokenny/ocx) | Administrador de extensiones OpenCode con perfiles portátiles y aislados. | +| [CódigoNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Aplicación de escritorio, web, móvil y de cliente remoto para OpenCode | + +--- + +## Agentes + +| Nombre | Descripción | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [Agente](https://github.com/Cluster444/agentic) | Agentes y comandos modulares de IA para un desarrollo estructurado | +| [opencode-agentes](https://github.com/darrenhinde/opencode-agents) | Configuraciones, avisos, agentes y complementos para flujos de trabajo mejorados | diff --git a/packages/web/src/content/docs/es/enterprise.mdx b/packages/web/src/content/docs/es/enterprise.mdx new file mode 100644 index 000000000..6850f3899 --- /dev/null +++ b/packages/web/src/content/docs/es/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: Empresa +description: Usar OpenCode de forma segura en su organización. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise es para organizaciones que desean garantizar que su código y sus datos nunca abandonen su infraestructura. Puede hacerlo mediante el uso de una configuración centralizada que se integra con su SSO y su puerta de enlace AI interna. + +:::nota +OpenCode no almacena ningún código ni datos de contexto. +::: + +Para comenzar con OpenCode Enterprise: + +1. Haz una prueba interna con tu equipo. +2. **Contáctenos** para analizar los precios y las opciones de implementación. + +--- + +## Ensayo + +OpenCode es de código abierto y no almacena ningún código ni datos de contexto, por lo que sus desarrolladores pueden simplemente [comenzar](/docs/) y realizar una prueba. + +--- + +### Manejo de datos + +**OpenCode no almacena su código ni datos de contexto.** Todo el procesamiento se realiza localmente o mediante llamadas directas API a su proveedor de IA. + +Esto significa que siempre que utilice un proveedor de confianza o un proveedor interno +Puerta de enlace AI, puede usar OpenCode de forma segura. + +La única advertencia aquí es la característica opcional `/share`. + +--- + +#### Compartir conversaciones + +Si un usuario habilita la función `/share`, la conversación y los datos asociados con ella se envían al servicio que utilizamos para alojar estas páginas compartidas en opencode.ai. + +Actualmente, los datos se entregan a través de la red perimetral de nuestra CDN y se almacenan en caché en el perímetro cerca de sus usuarios. + +Le recomendamos que desactive esto para su prueba. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[Más información sobre cómo compartir](/docs/share). + +--- + +### Propiedad del código + +**Eres propietario de todo el código producido por OpenCode.** No existen restricciones de licencia ni reclamaciones de propiedad. + +--- + +## Precios + +Usamos un modelo por puesto para OpenCode Enterprise. Si tiene su propia puerta de enlace LLM, no cobramos por los tokens utilizados. Para obtener más detalles sobre precios y opciones de implementación, **contáctenos**. + +--- + +## Implementación + +Una vez que haya completado su prueba y esté listo para usar OpenCode en +su organización, puede **contáctenos** para discutir +opciones de fijación de precios y de implementación. + +--- + +### Configuración central + +Podemos configurar OpenCode para usar una única configuración central para toda su organización. + +Esta configuración centralizada puede integrarse con su proveedor de SSO y garantiza que todos los usuarios accedan únicamente a su puerta de enlace de IA interna. + +--- + +### Integración SSO + +A través de la configuración central, OpenCode puede integrarse con el proveedor de SSO de su organización para la autenticación. + +Esto permite a OpenCode obtener credenciales para su puerta de enlace interna de IA a través de su sistema de gestión de identidad existente. + +--- + +### Puerta de enlace interna de IA + +Con la configuración central, OpenCode también se puede configurar para usar solo su puerta de enlace AI interna. + +También puede desactivar todos los demás proveedores de IA, asegurándose de que todas las solicitudes pasen por la infraestructura aprobada de su organización. + +--- + +### Autohospedaje + +Si bien recomendamos desactivar las páginas para compartir para garantizar que sus datos nunca abandonen +su organización, también podemos ayudarle a autohospedarlos en su infraestructura. + +Esto se encuentra actualmente en nuestra hoja de ruta. Si está interesado, **háganoslo saber**. + +--- + +## Preguntas frecuentes + +

+¿Qué es OpenCode Enterprise? + +OpenCode Enterprise es para organizaciones que desean garantizar que su código y sus datos nunca abandonen su infraestructura. Puede hacerlo mediante el uso de una configuración centralizada que se integra con su SSO y su puerta de enlace AI interna. + +
+ +
+¿Cómo empiezo con OpenCode Enterprise? + +Simplemente comience con una prueba interna con su equipo. OpenCode de forma predeterminada no almacena su código ni datos de contexto, lo que facilita el inicio. + +Luego **contáctenos** para analizar los precios y las opciones de implementación. + +
+ +
+¿Cómo funcionan los precios empresariales? + +Ofrecemos precios empresariales por asiento. Si tiene su propia puerta de enlace LLM, no cobramos por los tokens utilizados. Para obtener más detalles, **contáctenos** para obtener una cotización personalizada basada en las necesidades de su organización. + +
+ +
+¿Están mis datos seguros con OpenCode Enterprise? + +Sí. OpenCode no almacena su código ni datos de contexto. Todo el procesamiento se realiza localmente o mediante llamadas directas API a su proveedor de IA. Con la configuración central y la integración de SSO, sus datos permanecen seguros dentro de la infraestructura de su organización. + +
+ +
+¿Podemos utilizar nuestro propio registro privado de NPM? + +OpenCode admite registros privados npm a través del soporte de archivos `.npmrc` nativo de Bun. Si su organización utiliza un registro privado, como JFrog Artifactory, Nexus o similar, asegúrese de que los desarrolladores estén autenticados antes de ejecutar OpenCode. + +Para configurar la autenticación con su registro privado: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +Esto crea `~/.npmrc` con detalles de autenticación. OpenCode automáticamente +recoge esto. + +:::precaución +Debe iniciar sesión en el registro privado antes de ejecutar OpenCode. +::: + +Alternativamente, puede configurar manualmente un archivo `.npmrc`: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Los desarrolladores deben iniciar sesión en el registro privado antes de ejecutar OpenCode para garantizar que los paquetes se puedan instalar desde su registro empresarial. + +
diff --git a/packages/web/src/content/docs/es/formatters.mdx b/packages/web/src/content/docs/es/formatters.mdx new file mode 100644 index 000000000..36550fb2e --- /dev/null +++ b/packages/web/src/content/docs/es/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: Formateadores +description: OpenCode utiliza formateadores específicos del idioma. +--- + +OpenCode formatea automáticamente los archivos después de escribirlos o editarlos utilizando formateadores específicos del idioma. Esto garantiza que el código generado siga los estilos de código de su proyecto. + +--- + +## Incorporado + +OpenCode viene con varios formateadores integrados para lenguajes y marcos populares. A continuación se muestra una lista de los formateadores, las extensiones de archivo compatibles y los comandos u opciones de configuración que necesita. + +| Formateador | Extensiones | Requisitos | +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| gobierno | .ir | Comando `gofmt` disponible | +| mezclar | .ex, .exs, .eex, .heex, .leex, .neex, .sface | Comando `mix` disponible | +| más bonita | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml y [más](https://prettier.io/docs/en/index.html) | dependencia `prettier` en `package.json` | +| bioma | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml y [más](https://biomejs.dev/) | `biome.json(c)` archivo de configuración | +| zigzag | .zig, .zon | Comando `zig` disponible | +| formato clang | .c, .cpp, .h, .hpp, .ino y [más](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` archivo de configuración | +| klint | .kt, .kts | Comando `ktlint` disponible | +| gorguera | .py, .pyi | Comando `ruff` disponible con configuración | +| óxido | .rs | Comando `rustfmt` disponible | +| cargafmt | .rs | Comando `cargo fmt` disponible | +| ultravioleta | .py, .pyi | Comando `uv` disponible | +| rubocop | .rb, .rake, .gemspec, .ru | Comando `rubocop` disponible | +| estándarrb | .rb, .rake, .gemspec, .ru | Comando `standardrb` disponible | +| embellecedor html | .erb, .html.erb | Comando `htmlbeautifier` disponible | +| aire | .R | Comando `air` disponible | +| dardo | .dardo | Comando `dart` disponible | +| formato ocaml | .ml, .mli | Comando `ocamlformat` disponible y archivo de configuración `.ocamlformat` | +| terraformar | .tf, .tfvars | Comando `terraform` disponible | +| brillo | .brillo | Comando `gleam` disponible | +| nixfmt | .nix | Comando `nixfmt` disponible | +| shfmt | .sh, .bash | Comando `shfmt` disponible | +| pinta | .php | dependencia `laravel/pint` en `composer.json` | +| oxfmt (Experimental) | .js, .jsx, .ts, .tsx | Dependencia de `oxfmt` en `package.json` y un [indicador de variable de entorno experimental](/docs/cli/#experimental) | +| ormolu | .hs | Comando `ormolu` disponible | + +Entonces, si su proyecto tiene `prettier` en su `package.json`, OpenCode lo usará automáticamente. + +--- + +## Cómo funciona + +Cuando OpenCode escribe o edita un archivo,: + +1. Comprueba la extensión del archivo con todos los formateadores habilitados. +2. Ejecuta el comando de formateo apropiado en el archivo. +3. Aplica los cambios de formato automáticamente. + +Este proceso ocurre en segundo plano, lo que garantiza que los estilos de su código se mantengan sin ningún paso manual. + +--- + +## Configurar + +Puede personalizar los formateadores a través de la sección `formatter` en su configuración OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +Cada configuración del formateador admite lo siguiente: + +| Propiedad | Tipo | Descripción | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` | booleano | Establezca esto en `true` para deshabilitar el formateador | +| `command` | cadena[] | El comando a ejecutar para formatear | +| `environment` | objeto | Variables de entorno para configurar al ejecutar el formateador | +| `extensions` | cadena[] | Extensiones de archivo que este formateador debería manejar | + +Veamos algunos ejemplos. + +--- + +### Deshabilitar formateadores + +Para deshabilitar **todos** los formateadores globalmente, configure `formatter` en `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +Para deshabilitar un formateador **específico**, establezca `disabled` en `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Formateadores personalizados + +Puede anular los formateadores integrados o agregar otros nuevos especificando el comando, las variables de entorno y las extensiones de archivo: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +El marcador de posición **`$FILE`** en el comando se reemplazará con la ruta al archivo que se está formateando. diff --git a/packages/web/src/content/docs/es/github.mdx b/packages/web/src/content/docs/es/github.mdx new file mode 100644 index 000000000..9358f98f4 --- /dev/null +++ b/packages/web/src/content/docs/es/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: Utilice OpenCode en problemas y solicitudes de extracción de GitHub. +--- + +OpenCode se integra con su flujo de trabajo GitHub. Mencione `/opencode` o `/oc` en su comentario y OpenCode ejecutará tareas dentro de su corredor de acciones GitHub. + +--- + +## Características + +- **Problemas de clasificación**: Pídele a OpenCode que investigue un problema y te lo explique. +- **Reparar e implementar**: pídale a OpenCode que solucione un problema o implemente una función. Y funcionará en una nueva sucursal y enviará un PR con todos los cambios. +- **Seguro**: OpenCode se ejecuta dentro de los corredores de tu GitHub. + +--- + +## Instalación + +Ejecute el siguiente comando en un proyecto que se encuentra en un repositorio GitHub: + +```bash +opencode github install +``` + +Esto lo guiará a través de la instalación de la aplicación GitHub, la creación del flujo de trabajo y la configuración de secretos. + +--- + +### Configuración manual + +O puede configurarlo manualmente. + +1. **Instale la aplicación GitHub** + + Dirígete a [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). Asegúrese de que esté instalado en el repositorio de destino. + +2. **Agregar el flujo de trabajo** + + Agregue el siguiente archivo de flujo de trabajo a `.github/workflows/opencode.yml` en su repositorio. Asegúrese de configurar las claves `model` apropiadas y API requeridas en `env`. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **Guarda las claves API en secretos** + + En la **configuración** de tu organización o proyecto, expande **Secretos y variables** a la izquierda y selecciona **Acciones**. Y agregue las claves API requeridas. + +--- + +## Configuración + +- `model`: El modelo a usar con OpenCode. Toma el formato de `provider/model`. Esto es **obligatorio**. +- `agent`: El agente a utilizar. Debe ser un agente primario. Vuelve a `default_agent` desde la configuración o `"build"` si no se encuentra. +- `share`: si se comparte la sesión OpenCode. El valor predeterminado es **verdadero** para repositorios públicos. +- `prompt`: mensaje personalizado opcional para anular el comportamiento predeterminado. Utilice esto para personalizar cómo OpenCode procesa las solicitudes. +- `token`: token de acceso GitHub opcional para realizar operaciones como crear comentarios, confirmar cambios y abrir solicitudes de extracción. De forma predeterminada, OpenCode usa el token de acceso a la instalación de la aplicación OpenCode GitHub, por lo que las confirmaciones, los comentarios y las solicitudes de extracción aparecen como provenientes de la aplicación. + + Alternativamente, puede usar el GitHub Action Runner [`GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) incorporado sin instalar la aplicación OpenCode GitHub. Solo asegúrese de otorgar los permisos necesarios en su flujo de trabajo: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + También puede utilizar [tokens de acceso personal](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) si lo prefiere. + +--- + +## Eventos admitidos + +OpenCode puede desencadenarse por los siguientes eventos GitHub: + +| Tipo de evento | Activado por | Detalles | +| ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | Comentar sobre un tema o PR | Mencione `/opencode` o `/oc` en su comentario. OpenCode lee el contexto y puede crear ramas, abrir relaciones públicas o responder. | +| `pull_request_review_comment` | Comente líneas de código específicas en un PR | Mencione `/opencode` o `/oc` mientras revisa el código. OpenCode recibe la ruta del archivo, los números de línea y el contexto de diferencias. | +| `issues` | Número abierto o editado | Activa automáticamente OpenCode cuando se crean o modifican problemas. Requiere entrada `prompt`. | +| `pull_request` | PR abierto o actualizado | Activa automáticamente OpenCode cuando los PR se abren, sincronizan o vuelven a abrir. Útil para revisiones automatizadas. | +| `schedule` | Programación basada en cron | Ejecute OpenCode según una programación. Requiere entrada `prompt`. La salida va a registros y relaciones públicas (no hay temas que comentar). | +| `workflow_dispatch` | Activador manual desde GitHub UI | Active OpenCode a pedido a través de la pestaña Acciones. Requiere entrada `prompt`. La salida va a registros y relaciones públicas. | + +### Ejemplo de programación + +Ejecute OpenCode según una programación para realizar tareas automatizadas: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +Para eventos programados, la entrada `prompt` es **obligatoria** ya que no hay comentarios del que extraer instrucciones. Los flujos de trabajo programados se ejecutan sin un contexto de usuario para verificar los permisos, por lo que el flujo de trabajo debe otorgar `contents: write` y `pull-requests: write` si espera que OpenCode cree ramas o PR. + +--- + +### Ejemplo de solicitud de extracción + +Revisar automáticamente los PR cuando se abren o actualizan: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Para los eventos `pull_request`, si no se proporciona `prompt`, OpenCode revisa de forma predeterminada la solicitud de extracción. + +--- + +### Ejemplo de clasificación de problemas + +Clasifique automáticamente nuevos problemas. Este ejemplo filtra cuentas con más de 30 días para reducir el spam: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +Para eventos `issues`, la entrada `prompt` es **obligatoria** ya que no hay ningún comentario del que extraer instrucciones. + +--- + +## Avisos personalizados + +Anule el mensaje predeterminado para personalizar el comportamiento de OpenCode para su flujo de trabajo. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Esto es útil para hacer cumplir criterios de revisión específicos, estándares de codificación o áreas de enfoque relevantes para su proyecto. + +--- + +## Ejemplos + +A continuación se muestran algunos ejemplos de cómo puede utilizar OpenCode en GitHub. + +- **Explica un problema** + + Agregue este comentario en una edición GitHub. + + ``` + /opencode explain this issue + ``` + + OpenCode leerá el hilo completo, incluidos todos los comentarios, y responderá con una explicación clara. + +- **Solucionar un problema** + + En un problema GitHub, diga: + + ``` + /opencode fix this + ``` + + Y OpenCode creará una nueva rama, implementará los cambios y abrirá un PR con los cambios. + +- **Revisar relaciones públicas y realizar cambios** + + Deja el siguiente comentario en un GitHub PR. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + OpenCode implementará el cambio solicitado y lo comprometerá con el mismo PR. + +- **Revisar líneas de código específicas** + + Deje un comentario directamente en las líneas de código en la pestaña "Archivos" del PR. OpenCode detecta automáticamente el archivo, los números de línea y el contexto de diferencias para proporcionar respuestas precisas. + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + Al comentar líneas específicas, OpenCode recibe: + - El archivo exacto que se está revisando. + - Las líneas de código específicas. + - El contexto diferencial circundante. + - Información del número de línea + + Esto permite solicitudes más específicas sin necesidad de especificar rutas de archivo o números de línea manualmente. diff --git a/packages/web/src/content/docs/es/gitlab.mdx b/packages/web/src/content/docs/es/gitlab.mdx new file mode 100644 index 000000000..b53ca9cc1 --- /dev/null +++ b/packages/web/src/content/docs/es/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: Utilice OpenCode en problemas GitLab y solicitudes de fusión. +--- + +OpenCode se integra con su flujo de trabajo GitLab a través de su canal de CI/CD GitLab o con GitLab Duo. + +En ambos casos, OpenCode se ejecutará en tus corredores GitLab. + +--- + +## GitLab CI + +OpenCode funciona en una tubería GitLab normal. Puede integrarlo en una canalización como un [componente de CI](https://docs.gitlab.com/ee/ci/components/) + +Aquí estamos utilizando un componente CI/CD creado por la comunidad para OpenCode — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### Características + +- **Usar configuración personalizada por trabajo**: configure OpenCode con un directorio de configuración personalizado, por ejemplo `./config/#custom-directory` para habilitar o deshabilitar la funcionalidad por invocación de OpenCode. +- **Configuración mínima**: el componente CI configura OpenCode en segundo plano, solo necesita crear la configuración OpenCode y el mensaje inicial. +- **Flexible**: el componente CI admite varias entradas para personalizar su comportamiento + +--- + +### Configuración + +1. Guarde su OpenCode autenticación JSON como variables de entorno de CI de tipo de archivo en **Configuración** > **CI/CD** > **Variables**. Asegúrate de marcarlos como "Enmascarados y ocultos". +2. Agregue lo siguiente a su archivo `.gitlab-ci.yml`. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +Para obtener más entradas y casos de uso, [consulte los documentos](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) de este componente. + +--- + +## GitLab Dúo + +OpenCode se integra con su flujo de trabajo GitLab. +Mencione `@opencode` en un comentario y OpenCode ejecutará tareas dentro de su canal de CI GitLab. + +--- + +### Características + +- **Problemas de clasificación**: Pídele a OpenCode que investigue un problema y te lo explique. +- **Reparar e implementar**: pídale a OpenCode que solucione un problema o implemente una función. + Creará una nueva rama y generará una solicitud de fusión con los cambios. +- **Seguro**: OpenCode se ejecuta en tus corredores GitLab. + +--- + +### Configuración + +OpenCode se ejecuta en su canalización de CI/CD GitLab. Esto es lo que necesitará para configurarlo: + +:::consejo +Consulte los [**GitLab documentos**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) para obtener instrucciones actualizadas. +::: + +1. Configure su entorno GitLab +2. Configurar CI/CD +3. Obtenga una clave API de proveedor de modelo de IA +4. Crea una cuenta de servicio +5. Configurar variables CI/CD +6. Cree un archivo de configuración de flujo, aquí hay un ejemplo: + +
+ + Configuración de flujo + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +Puede consultar los [GitLab CLI documentos de los agentes](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) para obtener instrucciones detalladas. + +--- + +### Ejemplos + +A continuación se muestran algunos ejemplos de cómo puede utilizar OpenCode en GitLab. + +:::consejo +Puede configurarlo para utilizar una frase de activación diferente a `@opencode`. +::: + +- **Explica un problema** + + Agregue este comentario en una edición GitLab. + + ``` + @opencode explain this issue + ``` + + OpenCode leerá el problema y responderá con una explicación clara. + +- **Solucionar un problema** + + En un problema GitLab, diga: + + ``` + @opencode fix this + ``` + + OpenCode creará una nueva rama, implementará los cambios y abrirá una solicitud de fusión con los cambios. + +- **Revisar solicitudes de fusión** + + Deje el siguiente comentario sobre una solicitud de fusión GitLab. + + ``` + @opencode review this merge request + ``` + + OpenCode revisará la solicitud de fusión y brindará comentarios. diff --git a/packages/web/src/content/docs/es/ide.mdx b/packages/web/src/content/docs/es/ide.mdx new file mode 100644 index 000000000..1568ec617 --- /dev/null +++ b/packages/web/src/content/docs/es/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: La extensión OpenCode para VS Code, Cursor y otros IDE +--- + +OpenCode se integra con VS Code, Cursor o cualquier IDE que admita un terminal. Simplemente ejecute `opencode` en la terminal para comenzar. + +--- + +## Uso + +- **Inicio rápido**: use `Cmd+Esc` (Mac) o `Ctrl+Esc` (Windows/Linux) para abrir OpenCode en una vista de terminal dividida, o enfoque una sesión de terminal existente si ya se está ejecutando una. +- **Nueva sesión**: use `Cmd+Shift+Esc` (Mac) o `Ctrl+Shift+Esc` (Windows/Linux) para iniciar una nueva sesión de terminal OpenCode, incluso si ya hay una abierta. También puede hacer clic en el botón OpenCode en la interfaz de usuario. +- **Conciencia del contexto**: comparte automáticamente tu selección o pestaña actual con OpenCode. +- **Atajos de referencia de archivos**: utilice `Cmd+Option+K` (Mac) o `Alt+Ctrl+K` (Linux/Windows) para insertar referencias de archivos. Por ejemplo, `@File#L37-42`. + +--- + +## Instalación + +Para instalar OpenCode en VS Code y bifurcaciones populares como Cursor, Windsurf, VSCodium: + +1. Abra VS Code +2. Abra el terminal integrado +3. Ejecute `opencode`: la extensión se instala automáticamente + +Si, por otro lado, desea utilizar su propio IDE cuando ejecuta `/editor` o `/export` desde TUI, deberá configurar `export EDITOR="code --wait"`. [Más información](/docs/tui/#editor-setup). + +--- + +### Instalación manual + +Busque **OpenCode** en Extension Marketplace y haga clic en **Instalar**. + +--- + +### Solución de problemas + +Si la extensión no se instala automáticamente: + +- Asegúrese de estar ejecutando `opencode` en el terminal integrado. +- Confirme que el CLI para su IDE esté instalado: + - Para VS Code: comando `code` + - Para cursor: comando `cursor` + - Para Windsurf: comando `windsurf` + - Para VSCodium: comando `codium` + - Si no, ejecute `Cmd+Shift+P` (Mac) o `Ctrl+Shift+P` (Windows/Linux) y busque "Comando Shell: Instalar comando 'código' en RUTA" (o el equivalente para su IDE) +- Asegúrese de que VS Code tenga permiso para instalar extensiones. diff --git a/packages/web/src/content/docs/es/index.mdx b/packages/web/src/content/docs/es/index.mdx new file mode 100644 index 000000000..bca0c7b82 --- /dev/null +++ b/packages/web/src/content/docs/es/index.mdx @@ -0,0 +1,359 @@ +--- +title: Introducción +description: Comience con OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) es un agente de codificación de IA de código abierto. Está disponible como interfaz basada en terminal, aplicación de escritorio o extensión IDE. + +![OpenCode TUI con el tema opencode](../../../assets/lander/screenshot.png) + +Empecemos. + +--- + +#### Requisitos previos + +Para usar OpenCode en su terminal, necesitará: + +1. Un emulador de terminal moderno como: + - [WezTerm](https://wezterm.org), multiplataforma + - [Alacritty](https://alacritty.org), multiplataforma + - [Fantasmal](https://ghostty.org), Linux y macOS + - [Gatito](https://sw.kovidgoyal.net/kitty/), Linux y macOS + +2. API claves para los LLM proveedores que desea utilizar. + +--- + +## Instalar + +La forma más sencilla de instalar OpenCode es mediante el script de instalación. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +También puedes instalarlo con los siguientes comandos: + +- **Usando Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **Usando Homebrew en macOS y Linux** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > Recomendamos utilizar el grifo OpenCode para las versiones más actualizadas. La fórmula oficial `brew install opencode` la mantiene el equipo Homebrew y se actualiza con menos frecuencia. + +- **Usando Paru en Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### Windows + +:::tip[Recomendado: Usar WSL] +Para obtener la mejor experiencia en Windows, recomendamos utilizar [Subsistema Windows para Linux (WSL)](/docs/windows-wsl). Proporciona un mejor rendimiento y compatibilidad total con las funciones de OpenCode. +::: + +- **Usando Chocolatey** + + ```bash + choco install opencode + ``` + +- **Usando Scoop** + + ```bash + scoop install opencode + ``` + +- **Usando NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **Usando Mise** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **Usando Docker** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +Actualmente se encuentra en progreso el soporte para instalar OpenCode en Windows usando Bun. + +También puede obtener el binario de [Versiones](https://github.com/anomalyco/opencode/releases). + +--- + +## Configurar + +Con OpenCode puedes usar cualquier proveedor LLM configurando sus claves API. + +Si es nuevo en el uso de proveedores LLM, le recomendamos usar [OpenCode Zen](/docs/zen). +Es una lista seleccionada de modelos que han sido probados y verificados por OpenCode +equipo. + +1. Ejecute el comando `/connect` en TUI, seleccione opencode y diríjase a [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Inicie sesión, agregue sus datos de facturación y copie su clave API. + +3. Pega tu clave API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +Alternativamente, puede seleccionar uno de los otros proveedores. [Más información](/docs/providers#directory). + +--- + +## Inicializar + +Ahora que ha configurado un proveedor, puede navegar a un proyecto que +quieres trabajar. + +```bash +cd /path/to/project +``` + +Y ejecute OpenCode. + +```bash +opencode +``` + +A continuación, inicialice OpenCode para el proyecto ejecutando el siguiente comando. + +```bash frame="none" +/init +``` + +Esto hará que OpenCode analice su proyecto y cree un archivo `AGENTS.md` en +la raíz del proyecto. + +:::consejo +Debes enviar el archivo `AGENTS.md` de tu proyecto a Git. +::: + +Esto ayuda a OpenCode a comprender la estructura del proyecto y los patrones de codificación. +usado. + +--- + +## Uso + +Ahora está listo para usar OpenCode para trabajar en su proyecto. No dudes en preguntarlo +¡cualquier cosa! + +Si es nuevo en el uso de un agente de codificación de IA, aquí hay algunos ejemplos que podrían +ayuda. + +--- + +### Hacer preguntas + +Puede pedirle a OpenCode que le explique el código base. + +:::consejo +Utilice la tecla `@` para realizar una búsqueda aproximada de archivos en el proyecto. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +Esto es útil si hay una parte del código base en la que no trabajaste. + +--- + +### Agregar funciones + +Puede pedirle a OpenCode que agregue nuevas funciones a su proyecto. Aunque primero recomendamos pedirle que cree un plan. + +1. **Crea un plan** + + OpenCode tiene un _modo Plan_ que desactiva su capacidad para realizar cambios y + en su lugar, sugiera _cómo_ implementará la función. + + Cambie a él usando la tecla **Tab**. Verás un indicador para esto en la esquina inferior derecha. + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + Ahora describamos lo que queremos que haga. + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + Quiere darle a OpenCode suficientes detalles para entender lo que quiere. ayuda + hablar con él como si estuviera hablando con un desarrollador junior de su equipo. + + :::consejo + Dale a OpenCode mucho contexto y ejemplos para ayudarlo a comprender lo que + desear. + ::: + +2. **Repetir el plan** + + Una vez que le proporcione un plan, puede enviarle comentarios o agregar más detalles. + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::consejo + Arrastre y suelte imágenes en la terminal para agregarlas al mensaje. + ::: + + OpenCode puede escanear cualquier imagen que le proporcione y agregarla al mensaje. Puede + Haga esto arrastrando y soltando una imagen en la terminal. + +3. **Crea la función** + + Una vez que se sienta cómodo con el plan, vuelva al _modo de construcción_ + presionando la tecla **Tab** nuevamente. + + ```bash frame="none" + + ``` + + Y pidiéndole que haga los cambios. + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### Realizar cambios + +Para cambios más sencillos, puede pedirle a OpenCode que lo construya directamente. +sin tener que revisar el plan primero. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +Desea asegurarse de proporcionar una buena cantidad de detalles para que OpenCode tome la decisión correcta. +cambios. + +--- + +### Deshacer cambios + +Digamos que le pides a OpenCode que haga algunos cambios. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Pero te das cuenta de que no es lo que querías. Puedes **deshacer** los cambios +usando el comando `/undo`. + +```bash frame="none" +/undo +``` + +OpenCode ahora revertirá los cambios que realizó y mostrará su mensaje original +de nuevo. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Desde aquí puedes modificar el mensaje y pedirle a OpenCode que vuelva a intentarlo. + +:::consejo +Puede ejecutar `/undo` varias veces para deshacer varios cambios. +::: + +O **puedes rehacer** los cambios usando el comando `/redo`. + +```bash frame="none" +/redo +``` + +--- + +## Compartir + +Las conversaciones que tengas con OpenCode pueden ser [compartidas con tu +equipo](/docs/compartir). + +```bash frame="none" +/share +``` + +Esto creará un enlace a la conversación actual y lo copiará en su portapapeles. + +:::nota +Las conversaciones no se comparten de forma predeterminada. +::: + +Aquí hay una [conversación de ejemplo](https://opencode.ai/s/4XP1fce5) con OpenCode. + +--- + +## Personalizar + +¡Y eso es todo! Ahora eres un profesional en el uso de OpenCode. + +Para personalizarlo, recomendamos [elegir un tema](/docs/themes), [personalizar las combinaciones de teclas](/docs/keybinds), [configurar formateadores de código](/docs/formatters), [crear comandos personalizados](/docs/commands) o jugar con la [configuración OpenCode](/docs/config). diff --git a/packages/web/src/content/docs/es/keybinds.mdx b/packages/web/src/content/docs/es/keybinds.mdx new file mode 100644 index 000000000..688553157 --- /dev/null +++ b/packages/web/src/content/docs/es/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: combinaciones de teclas +description: Personaliza tus combinaciones de teclas. +--- + +OpenCode tiene una lista de combinaciones de teclas que puede personalizar a través de la configuración OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## Tecla de líder + +OpenCode usa una tecla `leader` para la mayoría de las combinaciones de teclas. Esto evita conflictos en tu terminal. + +De forma predeterminada, `ctrl+x` es la tecla principal y la mayoría de las acciones requieren que primero presione la tecla principal y luego el acceso directo. Por ejemplo, para iniciar una nueva sesión, primero presione `ctrl+x` y luego presione `n`. + +No es necesario utilizar una tecla líder para las combinaciones de teclas, pero le recomendamos que lo haga. + +--- + +## Desactivar combinación de teclas + +Puede deshabilitar una combinación de teclas agregando la clave a su configuración con un valor de "ninguno". + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## Atajos de mensajes de escritorio + +La entrada de solicitud de la aplicación de escritorio OpenCode admite atajos comunes de estilo Readline/Emacs para editar texto. Estos están integrados y actualmente no se pueden configurar a través de `opencode.json`. + +| Atajo | Acción | +| -------- | ---------------------------------------- | +| `ctrl+a` | Mover al inicio de la línea actual | +| `ctrl+e` | Mover al final de la línea actual | +| `ctrl+b` | Mover el cursor hacia atrás un carácter | +| `ctrl+f` | Mover el cursor hacia adelante un carácter | +| `alt+b` | Mover el cursor hacia atrás una palabra | +| `alt+f` | Mover el cursor hacia adelante una palabra | +| `ctrl+d` | Eliminar carácter debajo del cursor | +| `ctrl+k` | Matar hasta el final de la línea | +| `ctrl+u` | Matar al inicio de la línea | +| `ctrl+w` | Matar palabra anterior | +| `alt+d` | Mata la siguiente palabra | +| `ctrl+t` | Transponer caracteres | +| `ctrl+g` | Cancelar ventanas emergentes/abortar la respuesta en ejecución | + +--- + +## Mayús+Entrar + +Algunos terminales no envían teclas modificadoras con Enter de forma predeterminada. Es posible que necesite configurar su terminal para enviar `Shift+Enter` como secuencia de escape. + +### Windows Terminal + +Abra su `settings.json` en: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +Agregue esto a la matriz `actions` de nivel raíz: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Agregue esto a la matriz `keybindings` de nivel raíz: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Guarde el archivo y reinicie Windows Terminal o abra una nueva pestaña. diff --git a/packages/web/src/content/docs/es/lsp.mdx b/packages/web/src/content/docs/es/lsp.mdx new file mode 100644 index 000000000..24b79fd1e --- /dev/null +++ b/packages/web/src/content/docs/es/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: LSP Servidores +description: OpenCode se integra con sus servidores LSP. +--- + +OpenCode se integra con su protocolo de servidor de idiomas (LSP) para ayudar a LLM a interactuar con su código base. Utiliza diagnósticos para proporcionar retroalimentación al LLM. + +--- + +## Incorporado + +OpenCode viene con varios servidores LSP integrados para idiomas populares: + +| LSP Servidor | Extensiones | Requisitos | +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +| astro | .astro | Autoinstalaciones para proyectos Astro | +| fiesta | .sh, .bash, .zsh, .ksh | Autoinstala el servidor en lenguaje bash | +| sonido metálico | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Instalaciones automáticas para proyectos C/C++ | +| csostenido | .cs | `.NET SDK` instalado | +| clojure-lsp | .clj, .cljs, .cljc, .edn | Comando `clojure-lsp` disponible | +| dardo | .dardo | Comando `dart` disponible | +| deno | .ts, .tsx, .js, .jsx, .mjs | Comando `deno` disponible (detecta automáticamente deno.json/deno.jsonc) | +| elixir-ls | .ex, .exs | Comando `elixir` disponible | +| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` dependencia en proyecto | +| f sostenido | .fs, .fsi, .fsx, .fsscript | `.NET SDK` instalado | +| brillo | .brillo | Comando `gleam` disponible | +| gopls | .ir | Comando `go` disponible | +| hls | .hs, .lhs | Comando `haskell-language-server-wrapper` disponible | +| jdtls | .java | `Java SDK (version 21+)` instalado | +| kotlin-ls | .kt, .kts | Autoinstalaciones para proyectos Kotlin | +| lua-ls | .lua | Autoinstalaciones para proyectos Lua | +| nada | .nix | Comando `nixd` disponible | +| ocaml-lsp | .ml, .mli | Comando `ocamllsp` disponible | +| oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | `oxlint` dependencia en proyecto | +| php intelefense | .php | Autoinstalaciones para proyectos PHP | +| prisma | .prisma | Comando `prisma` disponible | +| derechos de autor | .py, .pyi | Dependencia `pyright` instalada | +| rubí-lsp (rubocop) | .rb, .rake, .gemspec, .ru | Comandos `ruby` y `gem` disponibles | +| óxido | .rs | Comando `rust-analyzer` disponible | +| kit de fuente-lsp | .swift, .objc, .objcpp | `swift` instalado (`xcode` en macOS) | +| esbelto | .esbelto | Autoinstalaciones para proyectos Svelte | +| terraformar | .tf, .tfvars | Instalaciones automáticas desde versiones GitHub | +| diminuto | .tipo, .tipo | Instalaciones automáticas desde versiones GitHub | +| mecanografiado | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` dependencia en proyecto | +| vista | .vue | Autoinstalaciones para proyectos Vue | +| yaml-ls | .yaml, .yml | Autoinstala Red Hat yaml-language-server | +| zls | .zig, .zon | Comando `zig` disponible | + +Los servidores LSP se habilitan automáticamente cuando se detecta una de las extensiones de archivo anteriores y se cumplen los requisitos. + +:::nota +Puede deshabilitar las descargas automáticas del servidor LSP configurando la variable de entorno `OPENCODE_DISABLE_LSP_DOWNLOAD` en `true`. +::: + +--- + +## Cómo funciona + +Cuando opencode abre un archivo,: + +1. Comprueba la extensión del archivo con todos los servidores LSP habilitados. +2. Inicia el servidor LSP apropiado si aún no se está ejecutando. + +--- + +## Configurar + +Puede personalizar los servidores LSP a través de la sección `lsp` en su configuración opencode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Cada servidor LSP admite lo siguiente: + +| Propiedad | Tipo | Descripción | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` | booleano | Establezca esto en `true` para deshabilitar el servidor LSP | +| `command` | cadena[] | El comando para iniciar el servidor LSP | +| `extensions` | cadena[] | Extensiones de archivo que este servidor LSP debería manejar | +| `env` | objeto | Variables de entorno para configurar al iniciar el servidor | +| `initialization` | objeto | Opciones de inicialización para enviar al servidor LSP | + +Veamos algunos ejemplos. + +--- + +### Variables de entorno + +Utilice la propiedad `env` para establecer variables de entorno al iniciar el servidor LSP: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### Opciones de inicialización + +Utilice la propiedad `initialization` para pasar opciones de inicialización al servidor LSP. Estas son configuraciones específicas del servidor enviadas durante la solicitud LSP `initialize`: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::nota +Las opciones de inicialización varían según el servidor LSP. Consulte la documentación de su servidor LSP para conocer las opciones disponibles. +::: + +--- + +### Deshabilitar servidores LSP + +Para deshabilitar **todos** los servidores LSP globalmente, configure `lsp` en `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +Para deshabilitar un servidor LSP **específico**, configure `disabled` en `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Servidores LSP personalizados + +Puede agregar servidores LSP personalizados especificando el comando y las extensiones de archivo: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## Información adicional + +### PHP Intelefense + +PHP Intelephense ofrece funciones premium a través de una clave de licencia. Puede proporcionar una clave de licencia colocando (únicamente) la clave en un archivo de texto en: + +- El macOS/Linux: `$HOME/intelephense/licence.txt` +- El Windows: `%USERPROFILE%/intelephense/licence.txt` + +El archivo debe contener sólo la clave de licencia sin contenido adicional. diff --git a/packages/web/src/content/docs/es/mcp-servers.mdx b/packages/web/src/content/docs/es/mcp-servers.mdx new file mode 100644 index 000000000..e32c98efe --- /dev/null +++ b/packages/web/src/content/docs/es/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: MCP servidores +description: Agregue herramientas MCP locales y remotas. +--- + +Puede agregar herramientas externas a OpenCode utilizando el _Model Context Protocol_ o MCP. OpenCode admite servidores locales y remotos. + +Una vez agregadas, las herramientas MCP están disponibles automáticamente para LLM junto con las herramientas integradas. + +--- + +#### Advertencias + +Cuando utiliza un servidor MCP, se suma al contexto. Esto puede acumularse rápidamente si tiene muchas herramientas. Por lo que recomendamos tener cuidado con qué servidores MCP utiliza. + +:::consejo +Los servidores MCP se agregan a su contexto, por lo que debe tener cuidado con cuáles habilita. +::: + +Ciertos servidores MCP, como el servidor GitHub MCP, tienden a agregar muchos tokens y pueden exceder fácilmente el límite de contexto. + +--- + +## Permitir + +Puede definir servidores MCP en su [OpenCode Config](https://opencode.ai/docs/config/) en `mcp`. Agregue cada MCP con un nombre único. Puede referirse a ese MCP por su nombre cuando solicite el LLM. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +También puede desactivar un servidor configurando `enabled` en `false`. Esto es útil si desea desactivar temporalmente un servidor sin eliminarlo de su configuración. + +--- + +### Anulación de los valores predeterminados remotos + +Las organizaciones pueden proporcionar servidores MCP predeterminados a través de su punto final `.well-known/opencode`. Estos servidores pueden estar deshabilitados de forma predeterminada, lo que permite a los usuarios optar por los que necesitan. + +Para habilitar un servidor específico desde la configuración remota de su organización, agréguelo a su configuración local con `enabled: true`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +Los valores de configuración local anulan los valores predeterminados remotos. Consulte [precedencia de configuración](/docs/config#precedence-order) para obtener más detalles. + +--- + +## Local + +Agregue servidores MCP locales usando `type` a `"local"` dentro del objeto MCP. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +El comando es cómo se inicia el servidor MCP local. También puede pasar una lista de variables de entorno. + +Por ejemplo, así es como puede agregar el servidor de prueba [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +Y para usarlo puedo agregar `use the mcp_everything tool` a mis indicaciones. + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### Opciones + +Aquí están todas las opciones para configurar un servidor MCP local. + +| Opción | Tipo | Requerido | Descripción | +| ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | Cadena | Y | El tipo de conexión del servidor MCP debe ser `"local"`. | +| `command` | Matriz | Y | Comando y argumentos para ejecutar el servidor MCP. | +| `environment` | Objeto | | Variables de entorno para configurar al ejecutar el servidor. | +| `enabled` | booleano | | Habilite o deshabilite el servidor MCP al inicio. | +| `timeout` | Número | | Tiempo de espera en ms para recuperar herramientas del servidor MCP. El valor predeterminado es 5000 (5 segundos). | + +--- + +## Remoto + +Agregue servidores MCP remotos configurando `type` en `"remote"`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` es la URL del servidor MCP remoto y con la opción `headers` puede pasar una lista de encabezados. + +--- + +#### Opciones + +| Opción | Tipo | Requerido | Descripción | +| --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | Cadena | Y | El tipo de conexión del servidor MCP debe ser `"remote"`. | +| `url` | Cadena | Y | URL del servidor MCP remoto. | +| `enabled` | booleano | | Habilite o deshabilite el servidor MCP al inicio. | +| `headers` | Objeto | | Encabezados para enviar con la solicitud. | +| `oauth` | Objeto | | OAuth configuración de autenticación. Consulte la sección [OAuth](#oauth) a continuación. | +| `timeout` | Número | | Tiempo de espera en ms para recuperar herramientas del servidor MCP. El valor predeterminado es 5000 (5 segundos). | + +--- + +## OAuth + +OpenCode maneja automáticamente la autenticación OAuth para servidores MCP remotos. Cuando un servidor requiere autenticación, OpenCode: + +1. Detectar la respuesta 401 e iniciar el flujo OAuth +2. Utilice **Registro dinámico de cliente (RFC 7591)** si el servidor lo admite. +3. Almacene tokens de forma segura para futuras solicitudes + +--- + +### Automático + +Para la mayoría de los servidores MCP habilitados para OAuth, no se necesita ninguna configuración especial. Simplemente configure el servidor remoto: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +Si el servidor requiere autenticación, OpenCode le pedirá que se autentique cuando intente usarlo por primera vez. De lo contrario, puede [activar manualmente el flujo](#authenticating) con `opencode mcp auth `. + +--- + +### Preinscrito + +Si tiene credenciales de cliente del proveedor del servidor MCP, puede configurarlas: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### Autenticación + +Puede activar manualmente la autenticación o administrar las credenciales. + +Autenticar con un servidor MCP específico: + +```bash +opencode mcp auth my-oauth-server +``` + +Enumere todos los servidores MCP y su estado de autenticación: + +```bash +opencode mcp list +``` + +Eliminar las credenciales almacenadas: + +```bash +opencode mcp logout my-oauth-server +``` + +El comando `mcp auth` abrirá su navegador para obtener autorización. Después de su autorización, OpenCode almacenará los tokens de forma segura en `~/.local/share/opencode/mcp-auth.json`. + +--- + +#### Deshabilitando OAuth + +Si desea deshabilitar el OAuth automático para un servidor (por ejemplo, para servidores que usan claves API), configure `oauth` en `false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### OAuth Opciones + +| Opción | Tipo | Descripción | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` | Objeto \| falso | OAuth objeto de configuración, o `false` para deshabilitar la detección automática de OAuth. | +| `clientId` | Cadena | OAuth ID de cliente. Si no se proporciona, se intentará el registro dinámico del cliente. | +| `clientSecret` | Cadena | OAuth secreto del cliente, si lo requiere el servidor de autorización. | +| `scope` | Cadena | OAuth alcances para solicitar durante la autorización. | + +#### Depuración + +Si un servidor MCP remoto no puede autenticarse, puede diagnosticar problemas con: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +El comando `mcp debug` muestra el estado de autenticación actual, prueba la conectividad HTTP e intenta el flujo de descubrimiento OAuth. + +--- + +## Administrar + +Sus MCP están disponibles como herramientas en OpenCode, junto con herramientas integradas. Para que puedas administrarlos a través de la configuración OpenCode como cualquier otra herramienta. + +--- + +### Global + +Esto significa que puede habilitarlos o deshabilitarlos globalmente. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +También podemos usar un patrón global para deshabilitar todos los MCP coincidentes. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +Aquí estamos usando el patrón global `my-mcp*` para deshabilitar todos los MCP. + +--- + +### Por agente + +Si tiene una gran cantidad de servidores MCP, es posible que desee habilitarlos solo por agente y deshabilitarlos globalmente. Para hacer esto: + +1. Desactívelo como herramienta a nivel global. +2. En su [configuración del agente](/docs/agents#tools), habilite el servidor MCP como herramienta. + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### Patrones globales + +El patrón global utiliza patrones globales simples de expresiones regulares: + +- `*` coincide con cero o más de cualquier carácter (por ejemplo, `"my-mcp*"` coincide con `my-mcp_search`, `my-mcp_list`, etc.) +- `?` coincide exactamente con un carácter +- Todos los demás caracteres coinciden literalmente + +:::nota +Las herramientas del servidor MCP están registradas con el nombre del servidor como prefijo, por lo que para deshabilitar todas las herramientas para un servidor simplemente use: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## Ejemplos + +A continuación se muestran ejemplos de algunos servidores MCP comunes. Puede enviar un PR si desea documentar otros servidores. + +--- + +### centinela + +Agregue el [servidor Sentry MCP](https://mcp.sentry.dev) para interactuar con sus proyectos y problemas Sentry. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +Después de agregar la configuración, autentíquese con Sentry: + +```bash +opencode mcp auth sentry +``` + +Esto abrirá una ventana del navegador para completar el flujo OAuth y conectar OpenCode a su cuenta Sentry. + +Una vez autenticado, puede utilizar las herramientas Sentry en sus indicaciones para consultar problemas, proyectos y datos de errores. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Contexto7 + +Agregue el [servidor Context7 MCP](https://github.com/upstash/context7) para buscar en los documentos. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +Si se ha registrado para obtener una cuenta gratuita, puede usar su clave API y obtener límites de tarifas más altos. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +Aquí asumimos que tiene configurada la variable de entorno `CONTEXT7_API_KEY`. + +Agregue `use context7` a sus indicaciones para usar el servidor Context7 MCP. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +Alternativamente, puede agregar algo como esto a su [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep de Vercel + +Agregue el servidor [Grep by Vercel](https://grep.app) MCP para buscar fragmentos de código en GitHub. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +Dado que llamamos a nuestro servidor MCP `gh_grep`, puede agregar `use the gh_grep tool` a sus indicaciones para que el agente lo use. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +Alternativamente, puede agregar algo como esto a su [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/es/models.mdx b/packages/web/src/content/docs/es/models.mdx new file mode 100644 index 000000000..67d284cc9 --- /dev/null +++ b/packages/web/src/content/docs/es/models.mdx @@ -0,0 +1,223 @@ +--- +title: Modelos +description: Configuración de un proveedor y modelo LLM. +--- + +OpenCode usa el [AI SDK](https://ai-sdk.dev/) y [Models.dev](https://models.dev) para admitir **75+ proveedores LLM** y admite la ejecución de modelos locales. + +--- + +## Proveedores + +Los proveedores más populares están precargados de forma predeterminada. Si agregó las credenciales de un proveedor mediante el comando `/connect`, estarán disponibles cuando inicie OpenCode. + +Obtenga más información sobre [proveedores](/docs/providers). + +--- + +## Selecciona un modelo + +Una vez que hayas configurado tu proveedor podrás seleccionar el modelo que desees escribiendo: + +```bash frame="none" +/models +``` + +--- + +## Modelos recomendados + +Hay muchos modelos disponibles y cada semana salen nuevos modelos. + +:::consejo +Considere utilizar uno de los modelos que recomendamos. +::: + +Sin embargo, sólo unos pocos de ellos son buenos tanto para generar código como para llamar a herramientas. + +Aquí hay varios modelos que funcionan bien con OpenCode, sin ningún orden en particular. (Esta no es una lista exhaustiva ni necesariamente actualizada): + +-GPT 5.2 +- Códice GPT 5.1 +- Claude Opus 4.5 +- Claude Soneto 4.5 +-Minimax M2.1 +- Géminis 3 Pro + +--- + +## Establecer un valor predeterminado + +Para configurar uno de estos como modelo predeterminado, puede configurar la tecla `model` en su +OpenCode configuración. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Aquí el ID completo es `provider_id/model_id`. Por ejemplo, si usa [OpenCode Zen](/docs/zen), usaría `opencode/gpt-5.1-codex` para GPT 5.1 Codex. + +Si ha configurado un [proveedor personalizado](/docs/providers#custom), `provider_id` es la clave de la parte `provider` de su configuración y `model_id` es la clave de `provider.models`. + +--- + +## Configurar modelos + +Puede configurar globalmente las opciones de un modelo a través de la configuración. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Aquí estamos configurando ajustes globales para dos modelos integrados: `gpt-5` cuando se accede a través del proveedor `openai` y `claude-sonnet-4-20250514` cuando se accede a través del proveedor `anthropic`. +Los nombres de modelo y proveedor integrados se pueden encontrar en [Models.dev](https://models.dev). + +También puede configurar estas opciones para cualquier agente que esté utilizando. La configuración del agente anula cualquier opción global aquí. [Más información](/docs/agents/#additional). + +También puede definir variantes personalizadas que amplíen las integradas. Las variantes le permiten configurar diferentes ajustes para el mismo modelo sin crear entradas duplicadas: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## Variantes + +Muchos modelos admiten múltiples variantes con diferentes configuraciones. OpenCode se envía con variantes predeterminadas integradas para proveedores populares. + +### Variantes integradas + +OpenCode se envía con variantes predeterminadas para muchos proveedores: + +**Anthropic**: + +- `high` - Presupuesto de pensamiento alto (predeterminado) +- `max` - Presupuesto de pensamiento máximo + +**OpenAI**: + +Varía según el modelo, pero aproximadamente: + +- `none` - Sin razonamiento +- `minimal` - Mínimo esfuerzo de razonamiento +- `low` - Bajo esfuerzo de razonamiento +- `medium` - Esfuerzo de razonamiento medio +- `high` - Alto esfuerzo de razonamiento +- `xhigh` - Esfuerzo de razonamiento extra alto + +**Google**: + +- `low` - Menor esfuerzo/presupuesto simbólico +- `high` - Mayor esfuerzo/presupuesto simbólico + +:::consejo +Esta lista no es exhaustiva. Muchos otros proveedores también tienen valores predeterminados integrados. +::: + +### Variantes personalizadas + +Puede anular las variantes existentes o agregar las suyas propias: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### Variantes de ciclo + +Utilice la combinación de teclas `variant_cycle` para cambiar rápidamente entre variantes. [Más información](/docs/keybinds). + +--- + +## Cargando modelos + +Cuando se inicia OpenCode, busca modelos en el siguiente orden de prioridad: + +1. El indicador de línea de comando `--model` o `-m`. El formato es el mismo que en el archivo de configuración: `provider_id/model_id`. + +2. La lista de modelos en la configuración OpenCode. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + El formato aquí es `provider/model`. + +3. El último modelo utilizado. + +4. El primer modelo que utiliza una prioridad interna. diff --git a/packages/web/src/content/docs/es/modes.mdx b/packages/web/src/content/docs/es/modes.mdx new file mode 100644 index 000000000..b5cf1eed4 --- /dev/null +++ b/packages/web/src/content/docs/es/modes.mdx @@ -0,0 +1,331 @@ +--- +title: Modos +description: Diferentes modos para diferentes casos de uso. +--- + +:::precaución +Los modos ahora se configuran a través de la opción `agent` en la configuración opencode. El +La opción `mode` ahora está en desuso. [Más información](/docs/agents). +::: + +Los modos en opencode le permiten personalizar el comportamiento, las herramientas y las indicaciones para diferentes casos de uso. + +Viene con dos modos integrados: **construir** y **planificar**. Puedes personalizar +estos o configure el suyo propio a través de la configuración opencode. + +Puede cambiar entre modos durante una sesión o configurarlos en su archivo de configuración. + +--- + +## Incorporado + +opencode viene con dos modos integrados. + +--- + +### Construir + +Build es el modo **predeterminado** con todas las herramientas habilitadas. Este es el modo estándar para el trabajo de desarrollo en el que necesita acceso completo a las operaciones de archivos y a los comandos del sistema. + +--- + +### Plan + +Un modo restringido diseñado para la planificación y el análisis. En el modo de plan, las siguientes herramientas están deshabilitadas de forma predeterminada: + +- `write` - No se pueden crear archivos nuevos +- `edit` - No se pueden modificar archivos existentes, excepto los archivos ubicados en `.opencode/plans/*.md` para detallar el plan en sí. +- `patch` - No se pueden aplicar parches +- `bash` - No se pueden ejecutar comandos de shell + +Este modo es útil cuando desea que la IA analice código, sugiera cambios o cree planes sin realizar modificaciones reales en su base de código. + +--- + +## Cambio + +Puede cambiar entre modos durante una sesión usando la tecla _Tab_. O su combinación de teclas `switch_mode` configurada. + +Consulte también: [Formateadores](/docs/formatters) para obtener información sobre la configuración de formato de código. + +--- + +## Configurar + +Puede personalizar los modos integrados o crear los suyos propios mediante la configuración. Los modos se pueden configurar de dos maneras: + +### JSON Configuración + +Configure los modos en su archivo de configuración `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Configuración de rebajas + +También puede definir modos utilizando archivos de rebajas. Colócalos en: + +- Global: `~/.config/opencode/modes/` +- Proyecto: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +El nombre del archivo de rebajas se convierte en el nombre del modo (por ejemplo, `review.md` crea un modo `review`). + +Veamos estas opciones de configuración en detalle. + +--- + +### Modelo + +Utilice la configuración `model` para anular el modelo predeterminado para este modo. Útil para utilizar diferentes modelos optimizados para diferentes tareas. Por ejemplo, un modelo más rápido de planificación, un modelo más capaz de implementación. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Temperatura + +Controle la aleatoriedad y la creatividad de las respuestas de la IA con la configuración `temperature`. Los valores más bajos hacen que las respuestas sean más centradas y deterministas, mientras que los valores más altos aumentan la creatividad y la variabilidad. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Los valores de temperatura suelen oscilar entre 0,0 y 1,0: + +- **0.0-0.2**: Respuestas muy enfocadas y deterministas, ideales para análisis y planificación de código. +- **0,3-0,5**: respuestas equilibradas con algo de creatividad, buenas para tareas de desarrollo general. +- **0.6-1.0**: respuestas más creativas y variadas, útiles para la lluvia de ideas y la exploración. + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Si no se especifica ninguna temperatura, opencode utiliza valores predeterminados específicos del modelo (normalmente 0 para la mayoría de los modelos, 0,55 para los modelos Qwen). + +--- + +### Inmediato + +Especifique un archivo de aviso del sistema personalizado para este modo con la configuración `prompt`. El archivo de aviso debe contener instrucciones específicas para el propósito del modo. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Esta ruta es relativa a donde se encuentra el archivo de configuración. Entonces esto funciona para +tanto la configuración global opencode como la configuración específica del proyecto. + +--- + +### Herramientas + +Controle qué herramientas están disponibles en este modo con la configuración `tools`. Puede habilitar o deshabilitar herramientas específicas configurándolas en `true` o `false`. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +Si no se especifica ninguna herramienta, todas las herramientas están habilitadas de forma predeterminada. + +--- + +#### Herramientas disponibles + +Aquí están todas las herramientas que se pueden controlar a través del modo de configuración. + +| Herramienta | Descripción | +| ----------- | ----------------------- | +| `bash` | Ejecutar comandos de shell | +| `edit` | Modificar archivos existentes | +| `write` | Crear nuevos archivos | +| `read` | Leer el contenido del archivo | +| `grep` | Buscar contenido del archivo | +| `glob` | Buscar archivos por patrón | +| `list` | Listar el contenido del directorio | +| `patch` | Aplicar parches a archivos | +| `todowrite` | Administrar listas de tareas pendientes | +| `todoread` | Leer listas de tareas pendientes | +| `webfetch` | Obtener contenido web | + +--- + +## Modos personalizados + +Puede crear sus propios modos personalizados agregándolos a la configuración. A continuación se muestran ejemplos que utilizan ambos enfoques: + +### Usando la configuración JSON + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Usando archivos de rebajas + +Cree archivos de modo en `.opencode/modes/` para modos específicos del proyecto o `~/.config/opencode/modes/` para modos globales: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### Casos de uso + +A continuación se muestran algunos casos de uso comunes para diferentes modos. + +- **Modo de compilación**: trabajo de desarrollo completo con todas las herramientas habilitadas +- **Modo Planificación**: Análisis y planificación sin realizar cambios +- **Modo de revisión**: revisión de código con acceso de solo lectura más herramientas de documentación +- **Modo de depuración**: centrado en la investigación con bash y herramientas de lectura habilitadas +- **Modo Documentos**: escritura de documentación con operaciones de archivos pero sin comandos del sistema + +También puede encontrar que diferentes modelos son buenos para diferentes casos de uso. diff --git a/packages/web/src/content/docs/es/network.mdx b/packages/web/src/content/docs/es/network.mdx new file mode 100644 index 000000000..e3599cfbe --- /dev/null +++ b/packages/web/src/content/docs/es/network.mdx @@ -0,0 +1,57 @@ +--- +title: Red +description: Configure proxies y certificados personalizados. +--- + +OpenCode admite variables de entorno de proxy estándar y certificados personalizados para entornos de red empresarial. + +--- + +## apoderado + +OpenCode respeta las variables de entorno de proxy estándar. + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::precaución +El TUI se comunica con un servidor HTTP local. Debe omitir el proxy para esta conexión para evitar bucles de enrutamiento. +::: + +Puede configurar el puerto y el nombre de host del servidor usando [CLI flags](/docs/cli#run). + +--- + +### Autenticar + +Si su proxy requiere autenticación básica, incluya las credenciales en la URL. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::precaución +Evite codificar contraseñas. Utilice variables de entorno o almacenamiento seguro de credenciales. +::: + +Para servidores proxy que requieren autenticación avanzada como NTLM o Kerberos, considere usar una puerta de enlace LLM que admita su método de autenticación. + +--- + +## Certificados personalizados + +Si su empresa utiliza CA personalizadas para conexiones HTTPS, configure OpenCode para confiar en ellas. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +Esto funciona tanto para conexiones proxy como para acceso directo a API. diff --git a/packages/web/src/content/docs/es/permissions.mdx b/packages/web/src/content/docs/es/permissions.mdx new file mode 100644 index 000000000..c77f6443f --- /dev/null +++ b/packages/web/src/content/docs/es/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: Permisos +description: Controle qué acciones requieren aprobación para ejecutarse. +--- + +OpenCode usa la configuración `permission` para decidir si una acción determinada debe ejecutarse automáticamente, avisarle o bloquearse. + +A partir de `v1.1.1`, la configuración booleana heredada `tools` está obsoleta y se ha fusionado en `permission`. La antigua configuración `tools` todavía se admite por compatibilidad con versiones anteriores. + +--- + +## Acciones + +Cada regla de permiso se resuelve en una de: + +- `"allow"` — ejecutar sin aprobación +- `"ask"` — solicitar aprobación +- `"deny"` — bloquea la acción + +--- + +## Configuración + +Puede establecer permisos globalmente (con `*`) y anular herramientas específicas. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +También puedes configurar todos los permisos a la vez: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## Reglas granulares (sintaxis de objeto) + +Para la mayoría de los permisos, puede utilizar un objeto para aplicar diferentes acciones según la entrada de la herramienta. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +Las reglas se evalúan según la coincidencia de patrones, y la **última regla coincidente gana**. Un patrón común es poner primero la regla general `"*"` y después reglas más específicas. + +### Comodines + +Los patrones de permisos utilizan una simple coincidencia de comodines: + +- `*` coincide con cero o más de cualquier carácter +- `?` coincide exactamente con un carácter +- Todos los demás caracteres coinciden literalmente + +### Expansión del directorio de inicio + +Puede usar `~` o `$HOME` al comienzo de un patrón para hacer referencia a su directorio de inicio. Esto es particularmente útil para las reglas [`external_directory`](#external-directories). + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### Directorios externos + +Utilice `external_directory` para permitir llamadas a herramientas que toquen rutas fuera del directorio de trabajo donde se inició OpenCode. Esto se aplica a cualquier herramienta que tome una ruta como entrada (por ejemplo, `read`, `edit`, `list`, `glob`, `grep` y muchos comandos `bash`). + +La expansión del hogar (como `~/...`) solo afecta la forma en que se escribe un patrón. No hace que una ruta externa forme parte del espacio de trabajo actual, por lo que las rutas fuera del directorio de trabajo aún deben permitirse a través de `external_directory`. + +Por ejemplo, esto permite el acceso a todo lo que se encuentra en `~/projects/personal/`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +Cualquier directorio permitido aquí hereda los mismos valores predeterminados que el espacio de trabajo actual. Dado que [`read` tiene por defecto `allow`](#defaults), también se permiten lecturas para entradas bajo `external_directory` a menos que se anulen. Agregue reglas explícitas cuando una herramienta deba restringirse en estas rutas, como bloquear ediciones mientras se mantienen las lecturas: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +Mantenga la lista centrada en rutas confiables y aplique reglas adicionales de permitir o denegar según sea necesario para otras herramientas (por ejemplo, `bash`). + +--- + +## Permisos disponibles + +Los permisos OpenCode están codificados por el nombre de la herramienta, además de un par de medidas de seguridad: + +- `read` — leer un archivo (coincide con la ruta del archivo) +- `edit` — todas las modificaciones de archivos (cubre `edit`, `write`, `patch`, `multiedit`) +- `glob` — globalización de archivos (coincide con el patrón global) +- `grep` — búsqueda de contenido (coincide con el patrón de expresiones regulares) +- `list` — enumerar archivos en un directorio (coincide con la ruta del directorio) +- `bash`: ejecuta comandos de shell (coincide con comandos analizados como `git status --porcelain`) +- `task` — lanzamiento de subagentes (coincide con el tipo de subagente) +- `skill` — cargar una habilidad (coincide con el nombre de la habilidad) +- `lsp`: ejecución de consultas LSP (actualmente no granulares) +- `todoread`, `todowrite` — leer/actualizar la lista de tareas pendientes +- `webfetch` — obteniendo una URL (coincide con la URL) +- `websearch`, `codesearch` — búsqueda web/código (coincide con la consulta) +- `external_directory`: se activa cuando una herramienta toca rutas fuera del directorio de trabajo del proyecto. +- `doom_loop`: se activa cuando la misma llamada de herramienta se repite 3 veces con entrada idéntica + +--- + +## Valores predeterminados + +Si no especifica nada, OpenCode comienza desde valores predeterminados permisivos: + +- La mayoría de los permisos están predeterminados en `"allow"`. +- `doom_loop` y `external_directory` por defecto son `"ask"`. +- `read` es `"allow"`, pero los archivos `.env` están denegados de forma predeterminada: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## ¿Qué significa "preguntar"? + +Cuando OpenCode solicita aprobación, la interfaz de usuario ofrece tres resultados: + +- `once` — aprobar solo esta solicitud +- `always`: aprueba solicitudes futuras que coincidan con los patrones sugeridos (para el resto de la sesión actual OpenCode) +- `reject` — rechazar la solicitud + +La herramienta proporciona el conjunto de patrones que `always` aprobaría (por ejemplo, las aprobaciones de bash generalmente incluyen en la lista blanca un prefijo de comando seguro como `git status*`). + +--- + +## Agentes + +Puede anular los permisos por agente. Los permisos del agente se combinan con la configuración global y las reglas del agente tienen prioridad. [Más información](/docs/agents#permissions) sobre los permisos de los agentes. + +:::nota +Consulte la sección [Reglas granulares (sintaxis de objeto)](#granular-rules-object-syntax) anterior para obtener ejemplos de coincidencia de patrones más detallados. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +También puede configurar los permisos del agente en Markdown: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::consejo +Utilice la coincidencia de patrones para comandos con argumentos. `"grep *"` permite `grep pattern file.txt`, mientras que `"grep"` solo lo bloquearía. Los comandos como `git status` funcionan para el comportamiento predeterminado pero requieren permiso explícito (como `"git status *"`) cuando se pasan argumentos. +::: diff --git a/packages/web/src/content/docs/es/plugins.mdx b/packages/web/src/content/docs/es/plugins.mdx new file mode 100644 index 000000000..7a0ac780a --- /dev/null +++ b/packages/web/src/content/docs/es/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: Complementos +description: Escriba sus propios complementos para extender OpenCode. +--- + +Los complementos le permiten extender OpenCode al conectarse a varios eventos y personalizar el comportamiento. Puede crear complementos para agregar nuevas funciones, integrarlos con servicios externos o modificar el comportamiento predeterminado de OpenCode. + +Para ver ejemplos, consulte los [complementos](/docs/ecosystem#plugins) creados por la comunidad. + +--- + +## Usa un complemento + +Hay dos formas de cargar complementos. + +--- + +### De archivos locales + +Coloque los archivos JavaScript o TypeScript en el directorio del complemento. + +- `.opencode/plugins/` - Complementos a nivel de proyecto +- `~/.config/opencode/plugins/` - Complementos globales + +Los archivos en estos directorios se cargan automáticamente al inicio. + +--- + +### De npm + +Especifique paquetes npm en su archivo de configuración. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +Se admiten paquetes npm regulares y de alcance. + +Explore los complementos disponibles en el [ecosistema](/docs/ecosystem#plugins). + +--- + +### Cómo se instalan los complementos + +Los **complementos npm** se instalan automáticamente usando Bun al inicio. Los paquetes y sus dependencias se almacenan en caché en `~/.cache/opencode/node_modules/`. + +**Los complementos locales** se cargan directamente desde el directorio de complementos. Para usar paquetes externos, debe crear un `package.json` dentro de su directorio de configuración (consulte [Dependencias](#dependencies)), o publicar el complemento en npm y [agregarlo a su configuración](/docs/config#plugins). + +--- + +### Cargar orden + +Los complementos se cargan desde todas las fuentes y todos los enlaces se ejecutan en secuencia. El orden de carga es: + +1. Configuración global (`~/.config/opencode/opencode.json`) +2. Configuración del proyecto (`opencode.json`) +3. Directorio global de complementos (`~/.config/opencode/plugins/`) +4. Directorio de complementos del proyecto (`.opencode/plugins/`) + +Los paquetes npm duplicados con el mismo nombre y versión se cargan una vez. Sin embargo, un complemento local y un complemento npm con nombres similares se cargan por separado. + +--- + +## Crear un complemento + +Un complemento es un módulo **JavaScript/TypeScript** que exporta uno o más complementos. +funciones. Cada función recibe un objeto de contexto y devuelve un objeto de enlace. + +--- + +### Dependencias + +Los complementos locales y las herramientas personalizadas pueden utilizar paquetes npm externos. Agregue un `package.json` a su directorio de configuración con las dependencias que necesita. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode ejecuta `bun install` al inicio para instalarlos. Luego, sus complementos y herramientas pueden importarlos. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### Estructura básica + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +La función del complemento recibe: + +- `project`: La información actual del proyecto. +- `directory`: El directorio de trabajo actual. +- `worktree`: La ruta del árbol de trabajo de git. +- `client`: Un cliente SDK opencode para interactuar con la IA. +- `$`: [shell API](https://bun.com/docs/runtime/shell) de Bun para ejecutar comandos. + +--- + +### TypeScript soporte + +Para los complementos TypeScript, puede importar tipos desde el paquete de complementos: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### Eventos + +Los complementos pueden suscribirse a eventos como se ve a continuación en la sección Ejemplos. Aquí hay una lista de los diferentes eventos disponibles. + +#### Eventos de comando + +- `command.executed` + +#### Eventos de archivo + +- `file.edited` +- `file.watcher.updated` + +#### Eventos de instalación + +- `installation.updated` + +#### LSP Eventos + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### Eventos de mensajes + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### Eventos de permiso + +- `permission.asked` +- `permission.replied` + +#### Eventos del servidor + +- `server.connected` + +#### Eventos de sesión + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### Todo Eventos + +- `todo.updated` + +#### Eventos Shell + +- `shell.env` + +#### Eventos de herramientas + +- `tool.execute.after` +- `tool.execute.before` + +#### TUI Eventos + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## Ejemplos + +A continuación se muestran algunos ejemplos de complementos que puede utilizar para ampliar opencode. + +--- + +### Enviar notificaciones + +Enviar notificaciones cuando ocurran ciertos eventos: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +Estamos usando `osascript` para ejecutar AppleScript en macOS. Aquí lo estamos usando para enviar notificaciones. + +:::nota +Si está utilizando la aplicación de escritorio OpenCode, puede enviar notificaciones del sistema automáticamente cuando una respuesta esté lista o cuando se produzca un error en una sesión. +::: + +--- + +### protección .env + +Evite que opencode lea archivos `.env`: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### Inyectar variables de entorno + +Inyecte variables de entorno en toda la ejecución del shell (herramientas de inteligencia artificial y terminales de usuario): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### Herramientas personalizadas + +Los complementos también pueden agregar herramientas personalizadas a opencode: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +El ayudante `tool` crea una herramienta personalizada a la que opencode puede llamar. Toma una función de esquema Zod y devuelve una definición de herramienta con: + +- `description`: Qué hace la herramienta +- `args`: Esquema Zod para los argumentos de la herramienta. +- `execute`: Función que se ejecuta cuando se llama a la herramienta + +Sus herramientas personalizadas estarán disponibles para opencode junto con las herramientas integradas. + +--- + +### Registro + +Utilice `client.app.log()` en lugar de `console.log` para el registro estructurado: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +Niveles: `debug`, `info`, `warn`, `error`. Consulte la [documentación del SDK](https://opencode.ai/docs/sdk) para obtener más detalles. + +--- + +### Ganchos de compactación + +Personalice el contexto incluido cuando se compacta una sesión: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +El gancho `experimental.session.compacting` se activa antes de que LLM genere un resumen de continuación. Úselo para inyectar contexto específico del dominio que el mensaje de compactación predeterminado omitiría. + +También puede reemplazar completamente el mensaje de compactación configurando `output.prompt`: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +Cuando se configura `output.prompt`, reemplaza completamente el mensaje de compactación predeterminado. En este caso, se ignora la matriz `output.context`. diff --git a/packages/web/src/content/docs/es/providers.mdx b/packages/web/src/content/docs/es/providers.mdx new file mode 100644 index 000000000..fd83a55ec --- /dev/null +++ b/packages/web/src/content/docs/es/providers.mdx @@ -0,0 +1,1889 @@ +--- +title: Proveedores +description: Usando cualquier proveedor LLM en OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode usa el [AI SDK](https://ai-sdk.dev/) y [Models.dev](https://models.dev) para admitir **75+ proveedores LLM** y admite la ejecución de modelos locales. + +Para agregar un proveedor necesita: + +1. Agregue las claves API para el proveedor usando el comando `/connect`. +2. Configure el proveedor en su configuración OpenCode. + +--- + +### Credenciales + +Cuando agrega las claves API de un proveedor con el comando `/connect`, se almacenan +en `~/.local/share/opencode/auth.json`. + +--- + +### Configuración + +Puedes personalizar los proveedores a través de la sección `provider` en tu OpenCode +configuración. + +--- + +#### URL base + +Puede personalizar la URL base para cualquier proveedor configurando la opción `baseURL`. Esto resulta útil cuando se utilizan servicios proxy o puntos finales personalizados. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen es una lista de modelos proporcionados por el equipo OpenCode que han sido +probado y verificado para funcionar bien con OpenCode. [Más información](/docs/zen). + +:::consejo +Si eres nuevo, te recomendamos comenzar con OpenCode Zen. +::: + +1. Ejecute el comando `/connect` en TUI, seleccione opencode y diríjase a [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Inicie sesión, agregue sus datos de facturación y copie su clave API. + +3. Pega tu clave API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute `/models` en TUI para ver la lista de modelos que recomendamos. + + ```txt + /models + ``` + +Funciona como cualquier otro proveedor en OpenCode y su uso es completamente opcional. + +--- + +## Directorio + +Veamos algunos de los proveedores en detalle. Si desea agregar un proveedor a la +lista, no dude en abrir un PR. + +:::nota +¿No ves un proveedor aquí? Envíe un PR. +::: + +--- + +### 302.AI + +1. Dirígete a la [consola 302.AI](https://302.ai/), crea una cuenta y genera una clave API. + +2. Ejecute el comando `/connect` y busque **302.AI**. + + ```txt + /connect + ``` + +3. Ingrese su clave 302.AI API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo. + + ```txt + /models + ``` + +--- + +### Amazon Bedrock + +Para usar Amazon Bedrock con OpenCode: + +1. Dirígete al **Catálogo de modelos** en la consola Amazon Bedrock y solicita + Accede a los modelos que desees. + + :::consejo + Necesita tener acceso al modelo que desea en Amazon Bedrock. + ::: + +2. **Configure la autenticación** utilizando uno de los siguientes métodos: + + #### Variables de entorno (Inicio rápido) + + Establezca una de estas variables de entorno mientras ejecuta opencode: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + O agrégalos a tu perfil de bash: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### Archivo de configuración (recomendado) + + Para una configuración persistente o específica del proyecto, utilice `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **Opciones disponibles:** + - `region` - AWS región (p. ej., `us-east-1`, `eu-west-1`) + - `profile` - AWS perfil con nombre de `~/.aws/credentials` + - `endpoint`: URL de punto de enlace personalizada para puntos de enlace de la VPC (alias para la opción genérica `baseURL`) + + :::consejo + Las opciones del archivo de configuración tienen prioridad sobre las variables de entorno. + ::: + + #### Avanzado: puntos finales de la VPC + + Si utiliza puntos de enlace de VPC para Bedrock: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::nota + La opción `endpoint` es un alias para la opción genérica `baseURL`, que utiliza terminología específica de AWS. Si se especifican `endpoint` y `baseURL`, `endpoint` tiene prioridad. + ::: + + #### Métodos de autenticación + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: Crear un usuario de IAM y generar claves de acceso en la Consola AWS + - **`AWS_PROFILE`**: Utilice perfiles con nombre de `~/.aws/credentials`. Primero configure con `aws configure --profile my-profile` o `aws sso login` + - **`AWS_BEARER_TOKEN_BEDROCK`**: Genera claves API a largo plazo desde la consola Amazon Bedrock + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: Para EKS IRSA (Roles IAM para Cuentas de Servicio) u otros entornos de Kubernetes con federación OIDC. Kubernetes inyecta automáticamente estas variables de entorno cuando se utilizan anotaciones de cuentas de servicio. + + #### Prioridad de autenticación + + Amazon Bedrock utiliza la siguiente prioridad de autenticación: + 1. **Token de portador** - `AWS_BEARER_TOKEN_BEDROCK` variable de entorno o token del comando `/connect` + 2. **AWS Cadena de credenciales**: perfil, claves de acceso, credenciales compartidas, roles de IAM, tokens de identidad web (EKS IRSA), metadatos de instancia + + :::nota + Cuando se establece un token de portador (a través de `/connect` o `AWS_BEARER_TOKEN_BEDROCK`), tiene prioridad sobre todos los métodos de credenciales AWS, incluidos los perfiles configurados. + ::: + +3. Ejecute el comando `/models` para seleccionar el modelo que desee. + + ```txt + /models + ``` + +:::nota +Para perfiles de inferencia personalizados, utilice el modelo y el nombre del proveedor en la clave y establezca la propiedad `id` en arn. Esto garantiza un almacenamiento en caché correcto: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### Anthropic + +1. Una vez que se haya registrado, ejecute el comando `/connect` y seleccione Anthropic. + + ```txt + /connect + ``` + +2. Aquí puedes seleccionar la opción **Claude Pro/Max** y se abrirá tu navegador. + y pedirle que se autentique. + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. Ahora todos los modelos Anthropic deberían estar disponibles cuando use el comando `/models`. + + ```txt + /models + ``` + +:::información +El uso de su suscripción Claude Pro/Max en OpenCode no está oficialmente respaldado por [Anthropic](https://anthropic.com). +::: + +##### Usando las teclas API + +También puede seleccionar **Crear una clave API** si no tiene una suscripción Pro/Max. También abrirá su navegador y le pedirá que inicie sesión en Anthropic y le dará un código que puede pegar en su terminal. + +O si ya tienes una clave API, puedes seleccionar **Ingresar manualmente la clave API** y pegarla en tu terminal. + +--- + +### Azul OpenAI + +:::nota +Si encuentra errores del tipo "Lo siento, pero no puedo ayudar con esa solicitud", intente cambiar el filtro de contenido de **DefaultV2** a **Default** en su recurso de Azure. +::: + +1. Diríjase al [portal de Azure](https://portal.azure.com/) y cree un recurso **Azure OpenAI**. Necesitarás: + - **Nombre del recurso**: esto pasa a formar parte de su punto final API (`https://RESOURCE_NAME.openai.azure.com/`) + - **Clave API**: `KEY 1` o `KEY 2` de su recurso + +2. Vaya a [Azure AI Foundry](https://ai.azure.com/) e implemente un modelo. + + :::nota + El nombre de la implementación debe coincidir con el nombre del modelo para que opencode funcione correctamente. + ::: + +3. Ejecute el comando `/connect` y busque **Azure**. + + ```txt + /connect + ``` + +4. Ingrese su clave API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Configure el nombre de su recurso como una variable de entorno: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + O agrégalo a tu perfil de bash: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. Ejecute el comando `/models` para seleccionar su modelo implementado. + + ```txt + /models + ``` + +--- + +### Servicios cognitivos de Azure + +1. Diríjase al [portal de Azure](https://portal.azure.com/) y cree un recurso **Azure OpenAI**. Necesitarás: + - **Nombre del recurso**: esto pasa a formar parte de su punto final API (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) + - **Clave API**: `KEY 1` o `KEY 2` de su recurso + +2. Vaya a [Azure AI Foundry](https://ai.azure.com/) e implemente un modelo. + + :::nota + El nombre de la implementación debe coincidir con el nombre del modelo para que opencode funcione correctamente. + ::: + +3. Ejecute el comando `/connect` y busque **Azure Cognitive Services**. + + ```txt + /connect + ``` + +4. Ingrese su clave API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Configure el nombre de su recurso como una variable de entorno: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + O agrégalo a tu perfil de bash: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. Ejecute el comando `/models` para seleccionar su modelo implementado. + + ```txt + /models + ``` + +--- + +### Baseten + +1. Dirígete a [Baseten](https://app.baseten.co/), crea una cuenta y genera una clave API. + +2. Ejecute el comando `/connect` y busque **Baseten**. + + ```txt + /connect + ``` + +3. Ingrese su clave Baseten API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo. + + ```txt + /models + ``` + +--- + +### Cerebras + +1. Dirígete a la [consola Cerebras](https://inference.cerebras.ai/), crea una cuenta y genera una clave API. + +2. Ejecute el comando `/connect` y busque **Cerebras**. + + ```txt + /connect + ``` + +3. Ingrese su clave Cerebras API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### Puerta de enlace de IA de Cloudflare + +Cloudflare AI Gateway le permite acceder a modelos de OpenAI, Anthropic, Workers AI y más a través de un punto final unificado. Con [Facturación unificada](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) no necesita claves API independientes para cada proveedor. + +1. Dirígete al [panel de Cloudflare](https://dash.cloudflare.com/), navega hasta **AI** > **AI Gateway** y crea una nueva puerta de enlace. + +2. Configure su ID de cuenta y su ID de puerta de enlace como variables de entorno. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. Ejecute el comando `/connect` y busque **Cloudflare AI Gateway**. + + ```txt + /connect + ``` + +4. Ingrese su token API de Cloudflare. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + O configúrelo como una variable de entorno. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. Ejecute el comando `/models` para seleccionar un modelo. + + ```txt + /models + ``` + + También puede agregar modelos a través de su configuración opencode. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### Córtecs + +1. Dirígete a la [consola de Cortecs](https://cortecs.ai/), crea una cuenta y genera una clave API. + +2. Ejecute el comando `/connect` y busque **Cortecs**. + + ```txt + /connect + ``` + +3. Ingrese su clave Cortecs API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Búsqueda profunda + +1. Dirígete a la [consola de DeepSeek](https://platform.deepseek.com/), crea una cuenta y haz clic en **Crear nueva clave API**. + +2. Ejecute el comando `/connect` y busque **DeepSeek**. + + ```txt + /connect + ``` + +3. Ingrese su clave DeepSeek API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo de DeepSeek como _DeepSeek Reasoner_. + + ```txt + /models + ``` + +--- + +### Infraestructura profunda + +1. Dirígete al [panel de Deep Infra] (https://deepinfra.com/dash), crea una cuenta y genera una clave API. + +2. Ejecute el comando `/connect` y busque **Deep Infra**. + + ```txt + /connect + ``` + +3. Ingrese su clave Deep Infra API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo. + + ```txt + /models + ``` + +--- + +### Firmware + +1. Dirígete al [Panel de firmware](https://app.firmware.ai/signup), crea una cuenta y genera una clave API. + +2. Ejecute el comando `/connect` y busque **Firmware**. + + ```txt + /connect + ``` + +3. Ingrese su clave de firmware API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo. + + ```txt + /models + ``` + +--- + +### Fuegos artificiales AI + +1. Dirígete a la [Consola de Fireworks AI](https://app.fireworks.ai/), crea una cuenta y haz clic en **Crear clave API**. + +2. Ejecute el comando `/connect` y busque **Fireworks AI**. + + ```txt + /connect + ``` + +3. Ingrese su clave API de AI de Fireworks. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### GitLab Dúo + +GitLab Duo proporciona chat agente basado en IA con capacidades de llamada de herramientas nativas a través del proxy Anthropic de GitLab. + +1. Ejecute el comando `/connect` y seleccione GitLab. + + ```txt + /connect + ``` + +2. Elija su método de autenticación: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### Usando OAuth (recomendado) + + Seleccione **OAuth** y su navegador se abrirá para autorización. + + #### Uso del token de acceso personal + 1. Vaya a [GitLab Configuración de usuario > Tokens de acceso](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. Haga clic en **Agregar nuevo token** + 3. Nombre: `OpenCode`, Alcances: `api` + 4. Copie el token (comienza con `glpat-`) + 5. Introdúcelo en la terminal. + +3. Ejecute el comando `/models` para ver los modelos disponibles. + + ```txt + /models + ``` + + Hay tres modelos basados ​​en Claude disponibles: + - **duo-chat-haiku-4-5** (predeterminado) - Respuestas rápidas para tareas rápidas + - **duo-chat-sonnet-4-5** - Rendimiento equilibrado para la mayoría de los flujos de trabajo + - **duo-chat-opus-4-5** - Más capaz para análisis complejos + +:::nota +También puede especificar la variable de entorno 'GITLAB_TOKEN' si no desea +para almacenar el token en el almacenamiento de autenticación opencode. +::: + +##### Autohospedado GitLab + +:::note[nota de cumplimiento] +OpenCode utiliza un modelo pequeño para algunas tareas de IA, como generar el título de la sesión. +Está configurado para usar gpt-5-nano de forma predeterminada, alojado por Zen. Para bloquear OpenCode +Para usar solo su propia instancia alojada en GitLab, agregue lo siguiente a su +Archivo `opencode.json`. También se recomienda desactivar el uso compartido de sesiones. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +Para instancias GitLab autohospedadas: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +Si su instancia ejecuta una puerta de enlace AI personalizada: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +O agregue a su perfil de bash: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::nota +Su administrador GitLab debe habilitar lo siguiente: + +1. [Plataforma de agente Duo](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) para el usuario, grupo o instancia +2. Indicadores de funciones (a través de la consola Rails): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### OAuth para instancias autohospedadas + +Para que Oauth funcione para su instancia autohospedada, debe crear +una nueva aplicación (Configuración → Aplicaciones) con el +URL de devolución de llamada `http://127.0.0.1:8080/callback` y siguientes ámbitos: + +- api (Acceda al API en su nombre) +- read_user (Lee tu información personal) +- read_repository (Permite acceso de solo lectura al repositorio) + +Luego exponga el ID de la aplicación como variable de entorno: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +Más documentación en la página de inicio de [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth). + +##### Configuración + +Personalizar a través de `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API Herramientas (opcionales, pero muy recomendables) + +Para acceder a herramientas GitLab (solicitudes de fusión, problemas, canalizaciones, CI/CD, etc.): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +Este complemento proporciona capacidades integrales de administración del repositorio GitLab que incluyen revisiones de MR, seguimiento de problemas, monitoreo de canalizaciones y más. + +--- + +### GitHub Copiloto + +Para utilizar su suscripción GitHub Copilot con opencode: + +:::nota +Algunos modelos pueden necesitar un [Pro+ +suscripción](https://github.com/features/copilot/plans) para usar. + +Algunos modelos deben habilitarse manualmente en su [GitHub configuración del copiloto](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. Ejecute el comando `/connect` y busque GitHub Copilot. + + ```txt + /connect + ``` + +2. Navegue hasta [github.com/login/device](https://github.com/login/device) e ingrese el código. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. Ahora ejecute el comando `/models` para seleccionar el modelo que desea. + + ```txt + /models + ``` + +--- + +### IA de vértice de Google + +Para utilizar Google Vertex AI con OpenCode: + +1. Dirígete a **Model Garden** en Google Cloud Console y verifica el + Modelos disponibles en su región. + + :::nota + Debes tener un proyecto de Google Cloud con Vertex AI API habilitado. + ::: + +2. Establezca las variables de entorno requeridas: + - `GOOGLE_CLOUD_PROJECT`: tu ID de proyecto de Google Cloud + - `VERTEX_LOCATION` (opcional): la región para Vertex AI (por defecto es `global`) + - Autenticación (elija una): + - `GOOGLE_APPLICATION_CREDENTIALS`: ruta al archivo clave JSON de su cuenta de servicio + - Autenticar usando gcloud CLI: `gcloud auth application-default login` + + Configúrelos mientras ejecuta opencode. + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + O agréguelos a su perfil de bash. + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::consejo +La región `global` mejora la disponibilidad y reduce los errores sin costo adicional. Utilice puntos finales regionales (por ejemplo, `us-central1`) para los requisitos de residencia de datos. [Más información](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. Ejecute el comando `/models` para seleccionar el modelo que desee. + + ```txt + /models + ``` + +--- + +### Groq + +1. Dirígete a la [consola Groq](https://console.groq.com/), haz clic en **Crear clave API** y copia la clave. + +2. Ejecute el comando `/connect` y busque Groq. + + ```txt + /connect + ``` + +3. Ingrese la clave API para el proveedor. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar el que desee. + + ```txt + /models + ``` + +--- + +### Abrazando la cara + +[Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers) proporciona acceso a modelos abiertos compatibles con más de 17 proveedores. + +1. Dirígete a [Configuración de cara de abrazo](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) para crear un token con permiso para realizar llamadas a proveedores de inferencia. + +2. Ejecute el comando `/connect` y busque **Hugging Face**. + + ```txt + /connect + ``` + +3. Ingresa tu token de Hugging Face. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _Kimi-K2-Instruct_ o _GLM-4.6_. + + ```txt + /models + ``` + +--- + +### Helicón + +[Helicone](https://helicone.ai) es una plataforma de observabilidad LLM que proporciona registro, monitoreo y análisis para sus aplicaciones de IA. Helicone AI Gateway enruta sus solicitudes al proveedor apropiado automáticamente según el modelo. + +1. Dirígete a [Helicone](https://helicone.ai), crea una cuenta y genera una clave API desde tu panel. + +2. Ejecute el comando `/connect` y busque **Helicone**. + + ```txt + /connect + ``` + +3. Ingrese su clave Helicone API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo. + + ```txt + /models + ``` + +Para obtener más proveedores y funciones avanzadas como almacenamiento en caché y limitación de velocidad, consulte la [documentación de Helicone](https://docs.helicone.ai). + +#### Configuraciones opcionales + +En caso de que vea una característica o modelo de Helicone que no esté configurado automáticamente a través de opencode, siempre podrá configurarlo usted mismo. + +Aquí está el [Directorio de modelos de Helicone](https://helicone.ai/models), lo necesitará para obtener las ID de los modelos que desea agregar. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### Encabezados personalizados + +Helicone admite encabezados personalizados para funciones como almacenamiento en caché, seguimiento de usuarios y gestión de sesiones. Agréguelos a la configuración de su proveedor usando `options.headers`: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### Seguimiento de sesión + +La función [Sesiones](https://docs.helicone.ai/features/sessions) de Helicone le permite agrupar solicitudes LLM relacionadas. Utilice el complemento [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) para registrar automáticamente cada conversación OpenCode como una sesión en Helicone. + +```bash +npm install -g opencode-helicone-session +``` + +Agréguelo a su configuración. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +El complemento inyecta encabezados `Helicone-Session-Id` y `Helicone-Session-Name` en sus solicitudes. En la página Sesiones de Helicone, verá cada conversación OpenCode enumerada como una sesión separada. + +##### Cabeceras comunes de Helicone + +| Encabezado | Descripción | +| -------------------------- | ------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | Habilitar el almacenamiento en caché de respuestas (`true`/`false`) | +| `Helicone-User-Id` | Seguimiento de métricas por usuario | +| `Helicone-Property-[Name]` | Agregar propiedades personalizadas (por ejemplo, `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | Solicitudes asociadas con versiones rápidas | + +Consulte el [Directorio de encabezados de Helicone](https://docs.helicone.ai/helicone-headers/header-directory) para conocer todos los encabezados disponibles. + +--- + +### llama.cpp + +Puede configurar opencode para usar modelos locales a través de la utilidad llama-server de [llama.cpp](https://github.com/ggml-org/llama.cpp) + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +En este ejemplo: + +- `llama.cpp` es el ID del proveedor personalizado. Puede ser cualquier cadena que desees. +- `npm` especifica el paquete que se utilizará para este proveedor. Aquí, `@ai-sdk/openai-compatible` se utiliza para cualquier OpenAI compatible con API. +- `name` es el nombre para mostrar del proveedor en la interfaz de usuario. +- `options.baseURL` es el punto final del servidor local. +- `models` es un mapa de ID de modelo para sus configuraciones. El nombre del modelo se mostrará en la lista de selección de modelos. + +--- + +### IO.NET + +IO.NET ofrece 17 modelos optimizados para varios casos de uso: + +1. Dirígete a la [consola IO.NET](https://ai.io.net/), crea una cuenta y genera una clave API. + +2. Ejecute el comando `/connect` y busque **IO.NET**. + + ```txt + /connect + ``` + +3. Ingrese su clave IO.NET API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo. + + ```txt + /models + ``` + +--- + +### Estudio LM + +Puede configurar opencode para usar modelos locales a través de LM Studio. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +En este ejemplo: + +- `lmstudio` es el ID del proveedor personalizado. Puede ser cualquier cadena que desees. +- `npm` especifica el paquete que se utilizará para este proveedor. Aquí, `@ai-sdk/openai-compatible` se utiliza para cualquier OpenAI compatible con API. +- `name` es el nombre para mostrar del proveedor en la interfaz de usuario. +- `options.baseURL` es el punto final del servidor local. +- `models` es un mapa de ID de modelo para sus configuraciones. El nombre del modelo se mostrará en la lista de selección de modelos. + +--- + +### IA disparada a la luna + +Para usar Kimi K2 de Moonshot AI: + +1. Dirígete a la [consola Moonshot AI](https://platform.moonshot.ai/console), crea una cuenta y haz clic en **Crear clave API**. + +2. Ejecute el comando `/connect` y busque **Moonshot AI**. + + ```txt + /connect + ``` + +3. Ingrese su clave Moonshot API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar _Kimi K2_. + + ```txt + /models + ``` + +--- + +### Minimáx. + +1. Dirígete a la [Consola MiniMax API](https://platform.minimax.io/login), crea una cuenta y genera una clave API. + +2. Ejecute el comando `/connect` y busque **MiniMax**. + + ```txt + /connect + ``` + +3. Ingrese su clave MiniMax API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _M2.1_. + + ```txt + /models + ``` + +--- + +### Fábrica de tokens Nebius + +1. Dirígete a la [consola de Nebius Token Factory](https://tokenfactory.nebius.com/), crea una cuenta y haz clic en **Agregar clave**. + +2. Ejecute el comando `/connect` y busque **Nebius Token Factory**. + + ```txt + /connect + ``` + +3. Ingrese su clave API de Nebius Token Factory. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Ollama + +Puedes configurar opencode para usar modelos locales a través de Ollama. + +:::consejo +Ollama puede configurarse automáticamente para OpenCode. Consulte los [documentos de integración de Ollama](https://docs.ollama.com/integrations/opencode) para obtener más detalles. +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +En este ejemplo: + +- `ollama` es el ID del proveedor personalizado. Puede ser cualquier cadena que desees. +- `npm` especifica el paquete que se utilizará para este proveedor. Aquí, `@ai-sdk/openai-compatible` se utiliza para cualquier OpenAI compatible con API. +- `name` es el nombre para mostrar del proveedor en la interfaz de usuario. +- `options.baseURL` es el punto final del servidor local. +- `models` es un mapa de ID de modelo para sus configuraciones. El nombre del modelo se mostrará en la lista de selección de modelos. + +:::consejo +Si las llamadas a herramientas no funcionan, intente aumentar `num_ctx` en Ollama. Comience alrededor de 16k - 32k. +::: + +--- + +### Nube de Ollama + +Para usar Ollama Cloud con OpenCode: + +1. Dirígete a [https://ollama.com/](https://ollama.com/) e inicia sesión o crea una cuenta. + +2. Vaya a **Configuración** > **Claves** y haga clic en **Agregar clave API** para generar una nueva clave API. + +3. Copie la clave API para usarla en OpenCode. + +4. Ejecute el comando `/connect` y busque **Ollama Cloud**. + + ```txt + /connect + ``` + +5. Ingrese su clave Ollama Cloud API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **Importante**: Antes de usar modelos en la nube en OpenCode, debe obtener la información del modelo localmente: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. Ejecute el comando `/models` para seleccionar su modelo de Ollama Cloud. + + ```txt + /models + ``` + +--- + +### OpenAI + +Recomendamos registrarse en [ChatGPT Plus o Pro](https://chatgpt.com/pricing). + +1. Una vez que se haya registrado, ejecute el comando `/connect` y seleccione OpenAI. + + ```txt + /connect + ``` + +2. Aquí puedes seleccionar la opción **ChatGPT Plus/Pro** y se abrirá tu navegador. + y pedirle que se autentique. + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. Ahora todos los modelos OpenAI deberían estar disponibles cuando use el comando `/models`. + + ```txt + /models + ``` + +##### Usando las teclas API + +Si ya tiene una clave API, puede seleccionar **Ingresar manualmente la clave API** y pegarla en su terminal. + +--- + +### OpenCode Zen + +OpenCode Zen es una lista de modelos probados y verificados proporcionada por el equipo OpenCode. [Más información](/docs/zen). + +1. Inicie sesión en **OpenCode Zen** y haga clic en **Crear API clave**. + +2. Ejecute el comando `/connect` y busque **OpenCode Zen**. + + ```txt + /connect + ``` + +3. Ingrese su clave OpenCode API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### Enrutador abierto + +1. Dirígete al [panel de OpenRouter](https://openrouter.ai/settings/keys), haz clic en **Crear clave API** y copia la clave. + +2. Ejecute el comando `/connect` y busque OpenRouter. + + ```txt + /connect + ``` + +3. Ingrese la clave API para el proveedor. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Muchos modelos de OpenRouter están precargados de forma predeterminada, ejecute el comando `/models` para seleccionar el que desee. + + ```txt + /models + ``` + + También puede agregar modelos adicionales a través de su configuración opencode. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. También puedes personalizarlos a través de tu configuración opencode. A continuación se muestra un ejemplo de cómo especificar un proveedor. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### Núcleo de IA de SAP + +SAP AI Core brinda acceso a más de 40 modelos de OpenAI, Anthropic, Google, Amazon, Meta, Mistral y AI21 a través de una plataforma unificada. + +1. Vaya a su [SAP BTP Cockpit](https://account.hana.ondemand.com/), navegue hasta su instancia de servicio SAP AI Core y cree una clave de servicio. + + :::consejo + La clave de servicio es un objeto JSON que contiene `clientid`, `clientsecret`, `url` y `serviceurls.AI_API_URL`. Puede encontrar su instancia de AI Core en **Servicios** > **Instancias y suscripciones** en BTP Cockpit. + ::: + +2. Ejecute el comando `/connect` y busque **SAP AI Core**. + + ```txt + /connect + ``` + +3. Ingrese su clave de servicio JSON. + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + O configure la variable de entorno `AICORE_SERVICE_KEY`: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + O agrégalo a tu perfil de bash: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. Opcionalmente, configure el ID de implementación y el grupo de recursos: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::nota + Estas configuraciones son opcionales y deben configurarse de acuerdo con su configuración de SAP AI Core. + ::: + +5. Ejecute el comando `/models` para seleccionar entre más de 40 modelos disponibles. + + ```txt + /models + ``` + +--- + +### Puntos finales de IA de OVHcloud + +1. Dirígete al [panel de OVHcloud](https://ovh.com/manager). Navegue a la sección `Public Cloud`, `AI & Machine Learning` > `AI Endpoints` y en la pestaña `API Keys`, haga clic en **Crear una nueva clave API**. + +2. Ejecute el comando `/connect` y busque **OVHcloud AI Endpoints**. + + ```txt + /connect + ``` + +3. Introduzca la clave API de sus OVHcloud AI Endpoints. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Escala + +Para utilizar [API generativas de Scaleway](https://www.scaleway.com/en/docs/generative-apis/) con OpenCode: + +1. Dirígete a la [Configuración de IAM de la consola Scaleway](https://console.scaleway.com/iam/api-keys) para generar una nueva clave API. + +2. Ejecute el comando `/connect` y busque **Scaleway**. + + ```txt + /connect + ``` + +3. Ingrese su clave Scaleway API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _devstral-2-123b-instruct-2512_ o _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Juntos IA + +1. Dirígete a la [consola de Together AI](https://api.together.ai), crea una cuenta y haz clic en **Agregar clave**. + +2. Ejecute el comando `/connect` y busque **Together AI**. + + ```txt + /connect + ``` + +3. Ingrese su clave Together AI API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Venecia AI + +1. Dirígete a la [consola de Venice AI](https://venice.ai), crea una cuenta y genera una clave API. + +2. Ejecute el comando `/connect` y busque **Venice AI**. + + ```txt + /connect + ``` + +3. Ingrese su clave Venecia AI API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _Llama 3.3 70B_. + + ```txt + /models + ``` + +--- + +### Puerta de enlace AI de Vercel + +Vercel AI Gateway le permite acceder a modelos de OpenAI, Anthropic, Google, xAI y más a través de un punto final unificado. Los modelos se ofrecen a precio de lista sin margen de beneficio. + +1. Dirígete al [panel de Vercel](https://vercel.com/), navega hasta la pestaña **AI Gateway** y haz clic en **API claves** para crear una nueva clave API. + +2. Ejecute el comando `/connect` y busque **Vercel AI Gateway**. + + ```txt + /connect + ``` + +3. Ingrese su clave Vercel AI Gateway API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo. + + ```txt + /models + ``` + +También puede personalizar modelos a través de su configuración opencode. A continuación se muestra un ejemplo de cómo especificar el orden de enrutamiento del proveedor. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +Algunas opciones de enrutamiento útiles: + +| Opción | Descripción | +| ------------------- | ---------------------------------------------------- | +| `order` | Secuencia de proveedores para probar | +| `only` | Restringir a proveedores específicos | +| `zeroDataRetention` | Utilice únicamente proveedores con políticas de retención de datos cero | + +--- + +### xAI + +1. Dirígete a la [consola xAI](https://console.x.ai/), crea una cuenta y genera una clave API. + +2. Ejecute el comando `/connect` y busque **xAI**. + + ```txt + /connect + ``` + +3. Ingrese su clave xAI API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _Grok Beta_. + + ```txt + /models + ``` + +--- + +### Z.AI + +1. Dirígete a la [consola Z.AI API](https://z.ai/manage-apikey/apikey-list), crea una cuenta y haz clic en **Crear una nueva clave API**. + +2. Ejecute el comando `/connect` y busque **Z.AI**. + + ```txt + /connect + ``` + + Si está suscrito al **Plan de codificación GLM**, seleccione **Plan de codificación Z.AI**. + +3. Ingrese su clave Z.AI API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Ejecute el comando `/models` para seleccionar un modelo como _GLM-4.7_. + + ```txt + /models + ``` + +--- + +### ZenMux + +1. Dirígete al [panel de ZenMux](https://zenmux.ai/settings/keys), haz clic en **Crear clave API** y copia la clave. + +2. Ejecute el comando `/connect` y busque ZenMux. + + ```txt + /connect + ``` + +3. Ingrese la clave API para el proveedor. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Muchos modelos de ZenMux están precargados de forma predeterminada, ejecute el comando `/models` para seleccionar el que desee. + + ```txt + /models + ``` + + También puede agregar modelos adicionales a través de su configuración opencode. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## Proveedor personalizado + +Para agregar cualquier proveedor **compatible con OpenAI** que no aparezca en el comando `/connect`: + +:::consejo +Puede utilizar cualquier proveedor compatible con OpenAI con opencode. La mayoría de los proveedores de IA modernos ofrecen API compatibles con OpenAI. +::: + +1. Ejecute el comando `/connect` y desplácese hacia abajo hasta **Otro**. + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. Ingrese una identificación única para el proveedor. + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::nota + Elija una identificación memorable, la usará en su archivo de configuración. + ::: + +3. Ingrese su clave API para el proveedor. + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. Cree o actualice su archivo `opencode.json` en el directorio de su proyecto: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + Aquí están las opciones de configuración: + - **npm**: paquete AI SDK para usar, `@ai-sdk/openai-compatible` para proveedores compatibles con OpenAI + - **nombre**: nombre para mostrar en la interfaz de usuario. + - **modelos**: Modelos disponibles. + - **options.baseURL**: API URL del punto final. + - **options.apiKey**: Opcionalmente, configure la clave API, si no usa autenticación. + - **options.headers**: Opcionalmente, configure encabezados personalizados. + + Más información sobre las opciones avanzadas en el siguiente ejemplo. + +5. Ejecute el comando `/models` y su proveedor y modelos personalizados aparecerán en la lista de selección. + +--- + +##### Ejemplo + +A continuación se muestra un ejemplo de configuración de las opciones `apiKey`, `headers` y modelo `limit`. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +Detalles de configuración: + +- **apiKey**: se configura usando la sintaxis de la variable `env`, [más información](/docs/config#env-vars). +- **encabezados**: encabezados personalizados enviados con cada solicitud. +- **limit.context**: tokens de entrada máximos que acepta el modelo. +- **limit.output**: tokens máximos que el modelo puede generar. + +Los campos `limit` le permiten a OpenCode comprender cuánto contexto le queda. Los proveedores estándar los extraen de models.dev automáticamente. + +--- + +## Solución de problemas + +Si tiene problemas para configurar un proveedor, verifique lo siguiente: + +1. **Verifique la configuración de autenticación**: Ejecute `opencode auth list` para ver si las credenciales + para el proveedor se agregan a su configuración. + + Esto no se aplica a proveedores como Amazon Bedrock, que dependen de variables de entorno para su autenticación. + +2. Para proveedores personalizados, verifique la configuración opencode y: + - Asegúrese de que el ID del proveedor utilizado en el comando `/connect` coincida con el ID en su configuración opencode. + - Se utiliza el paquete npm correcto para el proveedor. Por ejemplo, utilice `@ai-sdk/cerebras` para Cerebras. Y para todos los demás proveedores compatibles con OpenAI, utilice `@ai-sdk/openai-compatible`. + - Verifique que se utilice el punto final API correcto en el campo `options.baseURL`. diff --git a/packages/web/src/content/docs/es/rules.mdx b/packages/web/src/content/docs/es/rules.mdx new file mode 100644 index 000000000..e4479afdd --- /dev/null +++ b/packages/web/src/content/docs/es/rules.mdx @@ -0,0 +1,180 @@ +--- +title: Normas +description: Establezca instrucciones personalizadas para opencode. +--- + +Puede proporcionar instrucciones personalizadas a opencode creando un archivo `AGENTS.md`. Esto es similar a las reglas del Cursor. Contiene instrucciones que se incluirán en el contexto de LLM para personalizar su comportamiento para su proyecto específico. + +--- + +## Inicializar + +Para crear un nuevo archivo `AGENTS.md`, puede ejecutar el comando `/init` en opencode. + +:::consejo +Debes enviar el archivo `AGENTS.md` de tu proyecto a Git. +::: + +Esto escaneará su proyecto y todo su contenido para comprender de qué se trata y generar un archivo `AGENTS.md` con él. Esto ayuda a opencode a navegar mejor por el proyecto. + +Si tiene un archivo `AGENTS.md` existente, intentará agregarlo. + +--- + +## Ejemplo + +También puedes crear este archivo manualmente. A continuación se muestra un ejemplo de algunas cosas que puede colocar en un archivo `AGENTS.md`. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +Estamos agregando instrucciones específicas del proyecto aquí y esto se compartirá con todo su equipo. + +--- + +## Tipos + +opencode también admite la lectura del archivo `AGENTS.md` desde múltiples ubicaciones. Y esto tiene diferentes propósitos. + +### Proyecto + +Coloque un `AGENTS.md` en la raíz de su proyecto para reglas específicas del proyecto. Estos solo se aplican cuando trabaja en este directorio o sus subdirectorios. + +### Global + +También puedes tener reglas globales en un archivo `~/.config/opencode/AGENTS.md`. Esto se aplica en todas las sesiones opencode. + +Dado que esto no está comprometido con Git ni se comparte con su equipo, recomendamos usarlo para especificar las reglas personales que debe seguir LLM. + +### Compatibilidad del código Claude + +Para los usuarios que migran desde Claude Code, OpenCode admite las convenciones de archivos de Claude Code como alternativas: + +- **Reglas del proyecto**: `CLAUDE.md` en el directorio de tu proyecto (se usa si no existe `AGENTS.md`) +- **Reglas globales**: `~/.claude/CLAUDE.md` (se usa si no existe `~/.config/opencode/AGENTS.md`) +- **Habilidades**: `~/.claude/skills/`; consulte [Habilidades del agente](/docs/skills/) para obtener más detalles. + +Para deshabilitar la compatibilidad de Claude Code, configure una de estas variables de entorno: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## Prioridad + +Cuando se inicia opencode, busca archivos de reglas en este orden: + +1. **Archivos locales** atravesando desde el directorio actual (`AGENTS.md`, `CLAUDE.md`) +2. **Archivo global** en `~/.config/opencode/AGENTS.md` +3. **Archivo de Código Claude** en `~/.claude/CLAUDE.md` (a menos que esté deshabilitado) + +El primer archivo coincidente gana en cada categoría. Por ejemplo, si tiene `AGENTS.md` y `CLAUDE.md`, solo se usa `AGENTS.md`. De manera similar, `~/.config/opencode/AGENTS.md` tiene prioridad sobre `~/.claude/CLAUDE.md`. + +--- + +## Instrucciones personalizadas + +Puede especificar archivos de instrucciones personalizados en su `opencode.json` o el `~/.config/opencode/opencode.json` global. Esto le permite a usted y a su equipo reutilizar las reglas existentes en lugar de tener que duplicarlas en AGENTS.md. + +Ejemplo: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +También puede utilizar URL remotas para cargar instrucciones desde la web. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +Las instrucciones remotas se recuperan con un tiempo de espera de 5 segundos. + +Todos los archivos de instrucciones se combinan con sus archivos `AGENTS.md`. + +--- + +## Hacer referencia a archivos externos + +Si bien opencode no analiza automáticamente las referencias de archivos en `AGENTS.md`, puedes lograr una funcionalidad similar de dos maneras: + +### Usando opencode.json + +El enfoque recomendado es utilizar el campo `instructions` en `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Instrucciones manuales en AGENTS.md + +Puede enseñarle a opencode a leer archivos externos proporcionando instrucciones explícitas en su `AGENTS.md`. He aquí un ejemplo práctico: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +Este enfoque le permite: + +- Crear archivos de reglas modulares y reutilizables +- Compartir reglas entre proyectos a través de enlaces simbólicos o submódulos de git +- Mantenga AGENTS.md conciso mientras hace referencia a pautas detalladas +- Asegúrese de que opencode cargue archivos solo cuando sea necesario para la tarea específica + +:::consejo +Para monorepos o proyectos con estándares compartidos, usar `opencode.json` con patrones globales (como `packages/*/AGENTS.md`) es más fácil de mantener que las instrucciones manuales. +::: diff --git a/packages/web/src/content/docs/es/sdk.mdx b/packages/web/src/content/docs/es/sdk.mdx new file mode 100644 index 000000000..7a55e951e --- /dev/null +++ b/packages/web/src/content/docs/es/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: Cliente JS con seguridad de tipos para el servidor opencode. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +El SDK opencode JS/TS proporciona un cliente con seguridad de tipos para interactuar con el servidor. +Úselo para crear integraciones y controlar opencode mediante programación. + +[Más información](/docs/server) sobre cómo funciona el servidor. Para ver ejemplos, consulte los [proyectos](/docs/ecosystem#projects) creados por la comunidad. + +--- + +## Instalar + +Instale el SDK desde npm: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## Crear cliente + +Cree una instancia de opencode: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +Esto inicia tanto un servidor como un cliente. + +#### Opciones + +| Opción | Tipo | Descripción | Predeterminado | +| ---------- | ------------- | ------------------------------ | ----------- | +| `hostname` | `string` | Nombre de host del servidor | `127.0.0.1` | +| `port` | `number` | Puerto del servidor | `4096` | +| `signal` | `AbortSignal` | Señal de aborto para cancelación | `undefined` | +| `timeout` | `number` | Tiempo de espera en ms para inicio del servidor | `5000` | +| `config` | `Config` | Objeto de configuración | `{}` | + +--- + +## Configuración + +Puede pasar un objeto de configuración para personalizar el comportamiento. La instancia aún recoge su `opencode.json`, pero puede anular o agregar configuración en línea: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## Solo cliente + +Si ya tiene una instancia en ejecución de opencode, puede crear una instancia de cliente para conectarse a ella: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### Opciones + +| Opción | Tipo | Descripción | Predeterminado | +| --------------- | ---------- | -------------------------------- | ----------------------- | +| `baseUrl` | `string` | URL del servidor | `http://localhost:4096` | +| `fetch` | `function` | Implementación de recuperación personalizada | `globalThis.fetch` | +| `parseAs` | `string` | Método de análisis de respuesta | `auto` | +| `responseStyle` | `string` | Estilo de devolución: `data` o `fields` | `fields` | +| `throwOnError` | `boolean` | Lanzar errores en lugar de devolver | `false` | + +--- + +## Tipos + +El SDK incluye definiciones TypeScript para todos los tipos API. Importarlos directamente: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +Todos los tipos se generan a partir de la especificación OpenAPI del servidor y están disponibles en el archivo de tipos. + +--- + +## Errores + +El SDK puede generar errores que puedes detectar y manejar: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## API + +El SDK expone todas las API del servidor a través de un cliente con seguridad de tipos. + +--- + +### Global + +| Método | Descripción | Respuesta | +| ----------------- | ------------------------------- | ------------------------------------ | +| `global.health()` | Verificar el estado y la versión del servidor | `{ healthy: true, version: string }` | + +--- + +#### Ejemplos + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### Aplicación + +| Método | Descripción | Respuesta | +| -------------- | ------------------------- | ------------------------------------------- | +| `app.log()` | Escribe una entrada de registro | `boolean` | +| `app.agents()` | Listar todos los agentes disponibles | Agente[] | + +--- + +#### Ejemplos + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### Proyecto + +| Método | Descripción | Respuesta | +| ------------------- | ------------------- | --------------------------------------------- | +| `project.list()` | Listar todos los proyectos | Proyecto[] | +| `project.current()` | Obtener proyecto actual | Proyecto | + +--- + +#### Ejemplos + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### Camino + +| Método | Descripción | Respuesta | +| ------------ | ---------------- | ---------------------------------------- | +| `path.get()` | Obtener ruta actual | Ruta | + +--- + +#### Ejemplos + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### Configuración + +| Método | Descripción | Respuesta | +| -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` | Obtener información de configuración | Configuración | +| `config.providers()` | Lista de proveedores y modelos predeterminados | `{ providers: `Proveedor[]`, default: { [key: string]: string } }` | + +--- + +#### Ejemplos + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### Sesiones + +| Método | Descripción | Notas | +| ---------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` | Listar sesiones | Devuelve Sesión[] | +| `session.get({ path })` | Obtener sesión | Devuelve Sesión | +| `session.children({ path })` | Listar sesiones infantiles | Devuelve Sesión[] | +| `session.create({ body })` | Crear sesión | Devuelve Sesión | +| `session.delete({ path })` | Eliminar sesión | Devuelve `boolean` | +| `session.update({ path, body })` | Actualizar propiedades de sesión | Devuelve Sesión | +| `session.init({ path, body })` | Analizar aplicación y crear `AGENTS.md` | Devuelve `boolean` | +| `session.abort({ path })` | Cancelar una sesión en ejecución | Devuelve `boolean` | +| `session.share({ path })` | Compartir sesión | Devuelve Sesión | +| `session.unshare({ path })` | Dejar de compartir sesión | Devuelve Sesión | +| `session.summarize({ path, body })` | Resumir sesión | Devuelve `boolean` | +| `session.messages({ path })` | Listar mensajes en una sesión | Devuelve `{ info: `Mensaje`, parts: `Parte[]`}[]` | +| `session.message({ path })` | Obtener detalles del mensaje | Devuelve `{ info: `Mensaje`, parts: `Parte[]`}` | +| `session.prompt({ path, body })` | Enviar mensaje rápido | `body.noReply: true` devuelve UserMessage (solo contexto). El valor predeterminado devuelve AssistantMessage con respuesta de IA | +| `session.command({ path, body })` | Enviar comando a la sesión | Devuelve `{ info: `AssistantMessage`, parts: `Parte[]`}` | +| `session.shell({ path, body })` | Ejecute un comando de shell | Devuelve AssistantMessage | +| `session.revert({ path, body })` | Revertir un mensaje | Devuelve Sesión | +| `session.unrevert({ path })` | Restaurar mensajes revertidos | Devuelve Sesión | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | Responder a una solicitud de permiso | Devuelve `boolean` | + +--- + +#### Ejemplos + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### Archivos + +| Método | Descripción | Respuesta | +| ------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `find.text({ query })` | Buscar texto en archivos | Matriz de objetos coincidentes con `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `find.files({ query })` | Buscar archivos y directorios por nombre | `string[]` (rutas) | +| `find.symbols({ query })` | Buscar símbolos del espacio de trabajo | Símbolo[] | +| `file.read({ query })` | Leer un archivo | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | Obtener el estado de los archivos rastreados | Archivo[] | + +`find.files` admite algunos campos de consulta opcionales: + +- `type`: `"file"` o `"directory"` +- `directory`: anula la raíz del proyecto para la búsqueda. +- `limit`: resultados máximos (1–200) + +--- + +#### Ejemplos + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +| Método | Descripción | Respuesta | +| ------------------------------ | ------------------------- | --------- | +| `tui.appendPrompt({ body })` | Agregar texto al mensaje | `boolean` | +| `tui.openHelp()` | Abra el cuadro de diálogo de ayuda | `boolean` | +| `tui.openSessions()` | Abrir el selector de sesiones | `boolean` | +| `tui.openThemes()` | Abra el selector de temas | `boolean` | +| `tui.openModels()` | Abrir el selector de modelo | `boolean` | +| `tui.submitPrompt()` | Enviar el mensaje actual | `boolean` | +| `tui.clearPrompt()` | Borrar el mensaje | `boolean` | +| `tui.executeCommand({ body })` | Ejecutar un comando | `boolean` | +| `tui.showToast({ body })` | Mostrar notificación del brindis | `boolean` | + +--- + +#### Ejemplos + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### Autenticación + +| Método | Descripción | Respuesta | +| ------------------- | ------------------------------ | --------- | +| `auth.set({ ... })` | Establecer credenciales de autenticación | `boolean` | + +--- + +#### Ejemplos + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### Eventos + +| Método | Descripción | Respuesta | +| ------------------- | ------------------------- | ------------------------- | +| `event.subscribe()` | Transmisión de eventos enviados por el servidor | Transmisión de eventos enviados por el servidor | + +--- + +#### Ejemplos + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/es/server.mdx b/packages/web/src/content/docs/es/server.mdx new file mode 100644 index 000000000..30f637797 --- /dev/null +++ b/packages/web/src/content/docs/es/server.mdx @@ -0,0 +1,287 @@ +--- +title: Servidor +description: Interactuar con el servidor opencode a través de HTTP. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +El comando `opencode serve` ejecuta un servidor HTTP sin cabeza que expone un punto final OpenAPI que un cliente opencode puede usar. + +--- + +### Uso + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### Opciones + +| Bandera | Descripción | Predeterminado | +| --------------- | ----------------------------------- | ---------------- | +| `--port` | Puerto para escuchar | `4096` | +| `--hostname` | Nombre de host para escuchar | `127.0.0.1` | +| `--mdns` | Habilitar el descubrimiento de mDNS | `false` | +| `--mdns-domain` | Nombre de dominio personalizado para el servicio mDNS | `opencode.local` | +| `--cors` | Orígenes de navegador adicionales para permitir | `[]` | + +`--cors` se puede pasar varias veces: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### Autenticación + +Configure `OPENCODE_SERVER_PASSWORD` para proteger el servidor con autenticación básica HTTP. El nombre de usuario predeterminado es `opencode`, o configure `OPENCODE_SERVER_USERNAME` para anularlo. Esto se aplica tanto a `opencode serve` como a `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### Cómo funciona + +Cuando ejecuta `opencode`, inicia un TUI y un servidor. Donde el TUI es el +Cliente que habla con el servidor. El servidor expone una especificación OpenAPI 3.1 +punto final. Este punto final también se utiliza para generar un [SDK](/docs/sdk). + +:::consejo +Utilice el servidor opencode para interactuar con opencode mediante programación. +::: + +Esta arquitectura permite que opencode admita múltiples clientes y le permite interactuar con opencode mediante programación. + +Puede ejecutar `opencode serve` para iniciar un servidor independiente. Si tienes el +opencode TUI ejecutándose, `opencode serve` iniciará un nuevo servidor. + +--- + +#### Conectarse a un servidor existente + +Cuando inicia el TUI, asigna aleatoriamente un puerto y un nombre de host. En su lugar, puede pasar `--hostname` y `--port` [banderas](/docs/cli). Luego use esto para conectarse a su servidor. + +El punto final [`/tui`](#tui) se puede utilizar para conducir el TUI a través del servidor. Por ejemplo, puede completar previamente o ejecutar un mensaje. Esta configuración es utilizada por los complementos OpenCode [IDE](/docs/ide). + +--- + +## Especificaciones + +El servidor publica una especificación OpenAPI 3.1 que se puede ver en: + +``` +http://:/doc +``` + +Por ejemplo, `http://localhost:4096/doc`. Utilice la especificación para generar clientes o inspeccionar tipos de solicitudes y respuestas. O verlo en un explorador Swagger. + +--- + +## API + +El servidor opencode expone las siguientes API. + +--- + +### Global + +| Método | Camino | Descripción | Respuesta | +| ------ | ---------------- | ------------------------------ | ------------------------------------ | +| `GET` | `/global/health` | Obtener el estado y la versión del servidor | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | Obtenga eventos globales (transmisión SSE) | Flujo de eventos | + +--- + +### Proyecto + +| Método | Camino | Descripción | Respuesta | +| ------ | ------------------ | ----------------------- | --------------------------------------------- | +| `GET` | `/project` | Listar todos los proyectos | Proyecto[] | +| `GET` | `/project/current` | Obtener el proyecto actual | Proyecto | + +--- + +### Ruta y VCS + +| Método | Camino | Descripción | Respuesta | +| ------ | ------- | ------------------------------------ | ------------------------------------------- | +| `GET` | `/path` | Obtener la ruta actual | Ruta | +| `GET` | `/vcs` | Obtenga información de VCS para el proyecto actual | VcsInfo | + +--- + +### Instancia + +| Método | Camino | Descripción | Respuesta | +| ------ | ------------------- | ---------------------------- | --------- | +| `POST` | `/instance/dispose` | Eliminar la instancia actual | `boolean` | + +--- + +### Configuración + +| Método | Camino | Descripción | Respuesta | +| ------- | ------------------- | --------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` | Obtener información de configuración | Configuración | +| `PATCH` | `/config` | Actualizar configuración | Configuración | +| `GET` | `/config/providers` | Lista de proveedores y modelos predeterminados | `{ providers: `Proveedor[]`, default: { [key: string]: string } }` | + +--- + +### Proveedor + +| Método | Camino | Descripción | Respuesta | +| ------ | -------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` | Listar todos los proveedores | `{ all: `Proveedor[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | Obtener métodos de autenticación de proveedores | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | Autorizar a un proveedor usando OAuth | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | Manejar la devolución de llamada OAuth para un proveedor | `boolean` | + +--- + +### Sesiones + +| Método | Camino | Descripción | Notas | +| -------- | ---------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------- | +| `GET` | `/session` | Listar todas las sesiones | Devuelve Sesión[] | +| `POST` | `/session` | Crear una nueva sesión | cuerpo: `{ parentID?, title? }`, devuelve Sesión | +| `GET` | `/session/status` | Obtener el estado de la sesión para todas las sesiones | Devuelve `{ [sessionID: string]: `Estado de sesión` }` | +| `GET` | `/session/:id` | Obtener detalles de la sesión | Devuelve Sesión | +| `DELETE` | `/session/:id` | Eliminar una sesión y todos sus datos | Devuelve `boolean` | +| `PATCH` | `/session/:id` | Actualizar propiedades de sesión | cuerpo: `{ title? }`, devuelve Sesión | +| `GET` | `/session/:id/children` | Obtener las sesiones secundarias de una sesión | Devuelve Sesión[] | +| `GET` | `/session/:id/todo` | Obtener la lista de tareas pendientes para una sesión | Devuelve Todo[] | +| `POST` | `/session/:id/init` | Analizar aplicación y crear `AGENTS.md` | cuerpo: `{ messageID, providerID, modelID }`, devuelve `boolean` | +| `POST` | `/session/:id/fork` | Bifurca una sesión existente en un mensaje | cuerpo: `{ messageID? }`, devuelve Sesión | +| `POST` | `/session/:id/abort` | Cancelar una sesión en ejecución | Devuelve `boolean` | +| `POST` | `/session/:id/share` | Compartir una sesión | Devuelve Sesión | +| `DELETE` | `/session/:id/share` | Dejar de compartir una sesión | Devuelve Sesión | +| `GET` | `/session/:id/diff` | Obtenga la diferencia para esta sesión | consulta: `messageID?`, devuelve FileDiff[] | +| `POST` | `/session/:id/summarize` | Resumir la sesión | cuerpo: `{ providerID, modelID }`, devuelve `boolean` | +| `POST` | `/session/:id/revert` | Revertir un mensaje | cuerpo: `{ messageID, partID? }`, devuelve `boolean` | +| `POST` | `/session/:id/unrevert` | Restaurar todos los mensajes revertidos | Devuelve `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | Responder a una solicitud de permiso | cuerpo: `{ response, remember? }`, devuelve `boolean` | + +--- + +### Mensajes + +| Método | Camino | Descripción | Notas | +| ------ | --------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` | Listar mensajes en una sesión | consulta: `limit?`, devuelve `{ info: `Mensaje`, parts: `Parte[]`}[]` | +| `POST` | `/session/:id/message` | Envía un mensaje y espera respuesta | cuerpo: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, devuelve `{ info: `Mensaje`, parts: `Parte[]`}` | +| `GET` | `/session/:id/message/:messageID` | Obtener detalles del mensaje | Devuelve `{ info: `Mensaje`, parts: `Parte[]`}` | +| `POST` | `/session/:id/prompt_async` | Enviar un mensaje de forma asincrónica (sin espera) | cuerpo: igual que `/session/:id/message`, devuelve `204 No Content` | +| `POST` | `/session/:id/command` | Ejecutar un comando de barra diagonal | cuerpo: `{ messageID?, agent?, model?, command, arguments }`, devuelve `{ info: `Mensaje`, parts: `Parte[]`}` | +| `POST` | `/session/:id/shell` | Ejecute un comando de shell | cuerpo: `{ agent, model?, command }`, devuelve `{ info: `Mensaje`, parts: `Parte[]`}` | + +--- + +### Comandos + +| Método | Camino | Descripción | Respuesta | +| ------ | ---------- | ----------------- | --------------------------------------------- | +| `GET` | `/command` | Listar todos los comandos | Comando[] | + +--- + +### Archivos + +| Método | Camino | Descripción | Respuesta | +| ------ | ------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | Buscar texto en archivos | Matriz de objetos coincidentes con `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | Buscar archivos y directorios por nombre | `string[]` (caminos) | +| `GET` | `/find/symbol?query=` | Buscar símbolos del espacio de trabajo | Símbolo[] | +| `GET` | `/file?path=` | Listar archivos y directorios | FileNode[] | +| `GET` | `/file/content?path=

` | Leer un archivo | Contenido del archivo | +| `GET` | `/file/status` | Obtener el estado de los archivos rastreados | Archivo[] | + +#### `/find/file` parámetros de consulta + +- `query` (obligatorio) — cadena de búsqueda (coincidencia aproximada) +- `type` (opcional): limita los resultados a `"file"` o `"directory"` +- `directory` (opcional): anula la raíz del proyecto para la búsqueda. +- `limit` (opcional) — resultados máximos (1–200) +- `dirs` (opcional): indicador heredado (`"false"` devuelve solo archivos) + +--- + +### Herramientas (experimentales) + +| Método | Camino | Descripción | Respuesta | +| ------ | ------------------------------------------- | ---------------------------------------- | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` | Listar todos los ID de herramientas | ID de herramientas | +| `GET` | `/experimental/tool?provider=

&model=` | Listar herramientas con esquemas JSON para un modelo | Lista de herramientas | + +--- + +### LSP, formateadores y MCP + +| Método | Camino | Descripción | Respuesta | +| ------ | ------------ | -------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | Obtener el estado del servidor LSP | LSPStatus[] | +| `GET` | `/formatter` | Obtener estado del formateador | FormatterStatus[] | +| `GET` | `/mcp` | Obtener el estado del servidor MCP | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | Agregue el servidor MCP dinámicamente | cuerpo: `{ name, config }`, devuelve MCP objeto de estado | + +--- + +### Agentes + +| Método | Camino | Descripción | Respuesta | +| ------ | -------- | ------------------------- | ------------------------------------------- | +| `GET` | `/agent` | Listar todos los agentes disponibles | Agente[] | + +--- + +### Registro + +| Método | Camino | Descripción | Respuesta | +| ------ | ------ | ------------------------------------------------------------ | --------- | +| `POST` | `/log` | Escribir entrada de registro. Cuerpo: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| Método | Camino | Descripción | Respuesta | +| ------ | ----------------------- | ------------------------------------------- | ---------------------- | +| `POST` | `/tui/append-prompt` | Agregar texto al mensaje | `boolean` | +| `POST` | `/tui/open-help` | Abra el cuadro de diálogo de ayuda | `boolean` | +| `POST` | `/tui/open-sessions` | Abrir el selector de sesiones | `boolean` | +| `POST` | `/tui/open-themes` | Abra el selector de temas | `boolean` | +| `POST` | `/tui/open-models` | Abrir el selector de modelo | `boolean` | +| `POST` | `/tui/submit-prompt` | Enviar el mensaje actual | `boolean` | +| `POST` | `/tui/clear-prompt` | Borrar el mensaje | `boolean` | +| `POST` | `/tui/execute-command` | Ejecutar un comando (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | Mostrar brindis (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | Espere la próxima solicitud de control | Objeto de solicitud de control | +| `POST` | `/tui/control/response` | Responder a una solicitud de control (`{ body }`) | `boolean` | + +--- + +### Autenticación + +| Método | Camino | Descripción | Respuesta | +| ------ | ----------- | --------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | Establecer credenciales de autenticación. El cuerpo debe coincidir con el esquema del proveedor | `boolean` | + +--- + +### Eventos + +| Método | Camino | Descripción | Respuesta | +| ------ | -------- | ----------------------------------------------------------------------------- | ------------------------- | +| `GET` | `/event` | Transmisión de eventos enviados por el servidor. El primer evento es `server.connected`, luego eventos de bus | Transmisión de eventos enviados por el servidor | + +--- + +### Documentos + +| Método | Camino | Descripción | Respuesta | +| ------ | ------ | ------------------------- | --------------------------- | +| `GET` | `/doc` | Especificación OpenAPI 3.1 | Página HTML con especificación OpenAPI | diff --git a/packages/web/src/content/docs/es/share.mdx b/packages/web/src/content/docs/es/share.mdx new file mode 100644 index 000000000..c9df11712 --- /dev/null +++ b/packages/web/src/content/docs/es/share.mdx @@ -0,0 +1,128 @@ +--- +title: Compartir +description: Comparte tus conversaciones OpenCode. +--- + +La función para compartir de OpenCode te permite crear enlaces públicos a tus conversaciones de OpenCode, para que puedas colaborar con compañeros de equipo u obtener ayuda de otros. + +:::nota +Las conversaciones compartidas son de acceso público para cualquier persona que tenga el enlace. +::: + +--- + +## Cómo funciona + +Cuando compartes una conversación, OpenCode: + +1. Crea una URL pública única para su sesión. +2. Sincroniza tu historial de conversaciones con nuestros servidores +3. Hace que la conversación sea accesible a través del enlace para compartir: `opncd.ai/s/` + +--- + +## Intercambio + +OpenCode admite tres modos de compartir que controlan cómo se comparten las conversaciones: + +--- + +### Manual (predeterminado) + +De forma predeterminada, OpenCode usa el modo de compartir manual. Las sesiones no se comparten automáticamente, pero puedes compartirlas manualmente usando el comando `/share`: + +``` +/share +``` + +Esto generará una URL única que se copiará en su portapapeles. + +Para configurar explícitamente el modo manual en su [archivo de configuración](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### Compartir automáticamente + +Puede habilitar el uso compartido automático para todas las conversaciones nuevas configurando la opción `share` en `"auto"` en su [archivo de configuración](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +Con el uso compartido automático habilitado, cada nueva conversación se compartirá automáticamente y se generará un enlace. + +--- + +### Desactivado + +Puede desactivar el uso compartido por completo configurando la opción `share` en `"disabled"` en su [archivo de configuración](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +Para aplicar esto en todo su equipo para un proyecto determinado, agréguelo al `opencode.json` en su proyecto y regístrelo en Git. + +--- + +## Dejar de compartir + +Para dejar de compartir una conversación y eliminarla del acceso público: + +``` +/unshare +``` + +Esto eliminará el enlace para compartir y eliminará los datos relacionados con la conversación. + +--- + +## Privacidad + +Hay algunas cosas a tener en cuenta al compartir una conversación. + +--- + +### Retención de datos + +Las conversaciones compartidas permanecen accesibles hasta que las dejes de compartir explícitamente. Este +incluye: + +- Historial de conversaciones completo +- Todos los mensajes y respuestas. +- Metadatos de la sesión + +--- + +### Recomendaciones + +- Comparta únicamente conversaciones que no contengan información confidencial. +- Revisar el contenido de la conversación antes de compartir. +- Dejar de compartir conversaciones cuando se complete la colaboración. +- Evite compartir conversaciones con código propietario o datos confidenciales. +- Para proyectos confidenciales, deshabilite el uso compartido por completo. + +--- + +## Para empresas + +Para implementaciones empresariales, la función de compartir puede ser: + +- **Desactivado** completamente por motivos de seguridad. +- **Restringido** solo a usuarios autenticados a través de SSO +- **Autohospedado** en tu propia infraestructura + +[Obtenga más información](/docs/enterprise) sobre el uso de opencode en su organización. diff --git a/packages/web/src/content/docs/es/skills.mdx b/packages/web/src/content/docs/es/skills.mdx new file mode 100644 index 000000000..d6b0699b7 --- /dev/null +++ b/packages/web/src/content/docs/es/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "Habilidades del agente" +description: "Defina el comportamiento reutilizable mediante definiciones de SKILL.md" +--- + +Las habilidades del agente permiten a OpenCode descubrir instrucciones reutilizables de su repositorio o directorio de inicio. +Las habilidades se cargan bajo demanda a través de la herramienta nativa `skill`: los agentes ven las habilidades disponibles y pueden cargar el contenido completo cuando sea necesario. + +--- + +## Colocar archivos + +Cree una carpeta por nombre de habilidad y coloque un `SKILL.md` dentro de ella. +OpenCode busca estas ubicaciones: + +- Configuración del proyecto: `.opencode/skills//SKILL.md` +- Configuración global: `~/.config/opencode/skills//SKILL.md` +- Compatible con Proyecto Claude: `.claude/skills//SKILL.md` +- Compatible con Claude global: `~/.claude/skills//SKILL.md` +- Compatible con agente de proyecto: `.agents/skills//SKILL.md` +- Compatible con agentes globales: `~/.agents/skills//SKILL.md` + +--- + +## Entender el descubrimiento + +Para las rutas locales del proyecto, OpenCode sube desde su directorio de trabajo actual hasta llegar al árbol de trabajo de git. +Carga cualquier `skills/*/SKILL.md` coincidente en `.opencode/` y cualquier `.claude/skills/*/SKILL.md` o `.agents/skills/*/SKILL.md` coincidente a lo largo del camino. + +Las definiciones globales también se cargan desde `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` y `~/.agents/skills/*/SKILL.md`. + +--- + +## Escribe la introducción + +Cada `SKILL.md` debe comenzar con el frontmatter de YAML. +Sólo se reconocen estos campos: + +- `name` (obligatorio) +- `description` (obligatorio) +- `license` (opcional) +- `compatibility` (opcional) +- `metadata` (opcional, mapa de cadena a cadena) + +Los campos desconocidos se ignoran. + +--- + +## Validar nombres + +`name` debe: + +- Tener entre 1 y 64 caracteres. +- Ser alfanuméricos en minúsculas con separadores de guión simple +- No comienza ni termina con `-` +- No contener `--` consecutivos +- Coincide con el nombre del directorio que contiene `SKILL.md` + +expresión regular equivalente: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## Siga las reglas de longitud + +`description` debe tener entre 1 y 1024 caracteres. +Manténgalo lo suficientemente específico para que el agente elija correctamente. + +--- + +## Usa un ejemplo + +Crea `.opencode/skills/git-release/SKILL.md` así: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## Reconocer la descripción de la herramienta + +OpenCode enumera las habilidades disponibles en la descripción de la herramienta `skill`. +Cada entrada incluye el nombre y la descripción de la habilidad: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +El agente carga una habilidad llamando a la herramienta: + +``` +skill({ name: "git-release" }) +``` + +--- + +## Configurar permisos + +Controle a qué agentes de habilidades pueden acceder utilizando permisos basados ​​en patrones en `opencode.json`: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Permiso | Comportamiento | +| ---------- | ----------------------------------------- | +| `allow` | La habilidad se carga inmediatamente | +| `deny` | Habilidad oculta al agente, acceso rechazado | +| `ask` | Se solicita al usuario aprobación antes de cargar | + +Los patrones admiten comodines: `internal-*` coincide con `internal-docs`, `internal-tools`, etc. + +--- + +## Anulación por agente + +Otorgue a agentes específicos permisos diferentes a los predeterminados globales. + +**Para agentes personalizados** (en el frente del agente): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**Para agentes integrados** (en `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## Deshabilitar la herramienta de habilidades + +Deshabilite completamente las habilidades para los agentes que no deberían usarlas: + +**Para agentes personalizados**: + +```yaml +--- +tools: + skill: false +--- +``` + +**Para agentes integrados**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +Cuando está deshabilitada, la sección `` se omite por completo. + +--- + +## Solucionar problemas de carga + +Si una habilidad no aparece: + +1. Verifique que `SKILL.md` esté escrito en mayúsculas. +2. Verifique que el frontmatter incluya `name` y `description` +3. Asegúrese de que los nombres de las habilidades sean únicos en todas las ubicaciones +4. Verifique los permisos: las habilidades con `deny` están ocultas para los agentes diff --git a/packages/web/src/content/docs/es/themes.mdx b/packages/web/src/content/docs/es/themes.mdx new file mode 100644 index 000000000..2465b8698 --- /dev/null +++ b/packages/web/src/content/docs/es/themes.mdx @@ -0,0 +1,369 @@ +--- +title: Temas +description: Seleccione un tema integrado o defina el suyo propio. +--- + +Con OpenCode puede seleccionar uno de varios temas integrados, usar un tema que se adapte al tema de su terminal o definir su propio tema personalizado. + +De forma predeterminada, OpenCode usa nuestro propio tema `opencode`. + +--- + +## Requisitos del terminal + +Para que los temas se muestren correctamente con su paleta de colores completa, su terminal debe admitir **truecolor** (color de 24 bits). La mayoría de los terminales modernos admiten esto de forma predeterminada, pero es posible que debas habilitarlo: + +- **Verificar soporte**: Ejecute `echo $COLORTERM` - debería generar `truecolor` o `24bit` +- **Habilitar color verdadero**: establezca la variable de entorno `COLORTERM=truecolor` en su perfil de shell +- **Compatibilidad de terminal**: asegúrese de que su emulador de terminal admita colores de 24 bits (la mayoría de los terminales modernos como iTerm2, Alacritty, Kitty, Windows Terminal y las versiones recientes de GNOME Terminal lo hacen) + +Sin soporte de color verdadero, los temas pueden aparecer con una precisión de color reducida o retroceder a la aproximación de 256 colores más cercana. + +--- + +## Temas integrados + +OpenCode viene con varios temas integrados. + +| Nombre | Descripción | +| ---------------------- | ---------------------------------------------------------------------------- | +| `system` | Se adapta al color de fondo de tu terminal | +| `tokyonight` | Basado en el tema [Tokyonight](https://github.com/folke/tokyonight.nvim) | +| `everforest` | Basado en el tema [Everforest](https://github.com/sainnhe/everforest) | +| `ayu` | Basado en el tema oscuro de [Ayu](https://github.com/ayu-theme) | +| `catppuccin` | Basado en el tema [Catppuccin](https://github.com/catppuccin) | +| `catppuccin-macchiato` | Basado en el tema [Catppuccin](https://github.com/catppuccin) | +| `gruvbox` | Basado en el tema [Gruvbox](https://github.com/morhetz/gruvbox) | +| `kanagawa` | Basado en el tema [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | +| `nord` | Basado en el tema [Nord](https://github.com/nordtheme/nord) | +| `matrix` | Verde estilo hacker sobre el tema negro | +| `one-dark` | Basado en el tema oscuro [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) | + +Y más, constantemente agregamos nuevos temas. + +--- + +## Tema del sistema + +El tema `system` está diseñado para adaptarse automáticamente a la combinación de colores de su terminal. A diferencia de los temas tradicionales que utilizan colores fijos, el tema _system_: + +- **Genera escala de grises**: Crea una escala de grises personalizada basada en el color de fondo de tu terminal, asegurando un contraste óptimo. +- **Utiliza colores ANSI**: aprovecha los colores ANSI estándar (0-15) para resaltar la sintaxis y los elementos de la interfaz de usuario, que respetan la paleta de colores de su terminal. +- **Conserva los valores predeterminados del terminal**: utiliza `none` para el texto y los colores de fondo para mantener la apariencia nativa de su terminal. + +El tema del sistema es para usuarios que: + +- Quiere que OpenCode coincida con la apariencia de su terminal +- Utilice esquemas de color de terminal personalizados +- Prefiere una apariencia consistente en todas las aplicaciones de terminal + +--- + +## Usando un tema + +Puede seleccionar un tema abriendo la selección de tema con el comando `/theme`. O puede especificarlo en su [config](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Temas personalizados + +OpenCode admite un sistema de temas flexible basado en JSON que permite a los usuarios crear y personalizar temas fácilmente. + +--- + +### Jerarquía + +Los temas se cargan desde varios directorios en el siguiente orden, donde los directorios posteriores anulan los anteriores: + +1. **Temas integrados**: están integrados en el binario +2. **Directorio de configuración de usuario**: definido en `~/.config/opencode/themes/*.json` o `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Directorio raíz del proyecto**: definido en `/.opencode/themes/*.json` +4. **Directorio de trabajo actual** - Definido en `./.opencode/themes/*.json` + +Si varios directorios contienen un tema con el mismo nombre, se utilizará el tema del directorio con mayor prioridad. + +--- + +### Creando un tema + +Para crear un tema personalizado, cree un archivo JSON en uno de los directorios de temas. + +Para temas para todo el usuario: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +Y para temas específicos del proyecto. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### formato JSON + +Los temas utilizan un formato JSON flexible compatible con: + +- **Colores hexadecimales**: `"#ffffff"` +- **Colores ANSI**: `3` (0-255) +- **Referencias de color**: `"primary"` o definiciones personalizadas +- **Variantes oscuras/claras**: `{"dark": "#000", "light": "#fff"}` +- **Sin color**: `"none"` - Utiliza el color predeterminado del terminal o transparente + +--- + +### Definiciones de colores + +La sección `defs` es opcional y le permite definir colores reutilizables a los que se puede hacer referencia en el tema. + +--- + +### Valores predeterminados del terminal + +El valor especial `"none"` se puede utilizar para que cualquier color herede el color predeterminado del terminal. Esto es particularmente útil para crear temas que combinen perfectamente con la combinación de colores de su terminal: + +- `"text": "none"` - Utiliza el color de primer plano predeterminado del terminal +- `"background": "none"` - Utiliza el color de fondo predeterminado del terminal + +--- + +### Ejemplo + +A continuación se muestra un ejemplo de un tema personalizado: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/es/tools.mdx b/packages/web/src/content/docs/es/tools.mdx new file mode 100644 index 000000000..de5553965 --- /dev/null +++ b/packages/web/src/content/docs/es/tools.mdx @@ -0,0 +1,379 @@ +--- +title: Herramientas +description: Administre las herramientas que puede usar un LLM. +--- + +Las herramientas permiten que LLM realice acciones en su código base. OpenCode viene con un conjunto de herramientas integradas, pero puede ampliarlo con [herramientas personalizadas](/docs/custom-tools) o [servidores MCP](/docs/mcp-servers). + +De forma predeterminada, todas las herramientas están **habilitadas** y no necesitan permiso para ejecutarse. Puede controlar el comportamiento de la herramienta a través de [permisos](/docs/permissions). + +--- + +## Configurar + +Utilice el campo `permission` para controlar el comportamiento de la herramienta. Puede permitir, denegar o exigir aprobación para cada herramienta. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +También puedes utilizar comodines para controlar varias herramientas a la vez. Por ejemplo, para solicitar aprobación para todas las herramientas de un servidor MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[Más información](/docs/permissions) sobre la configuración de permisos. + +--- + +## Incorporado + +Aquí están todas las herramientas integradas disponibles en OpenCode. + +--- + +### fiesta + +Ejecute comandos de shell en el entorno de su proyecto. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +Esta herramienta permite que LLM ejecute comandos de terminal como `npm install`, `git status` o cualquier otro comando de shell. + +--- + +### editar + +Modifique archivos existentes utilizando reemplazos de cadenas exactas. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Esta herramienta realiza ediciones precisas de archivos reemplazando coincidencias de texto exactas. Es la forma principal en que LLM modifica el código. + +--- + +### escribir + +Cree nuevos archivos o sobrescriba los existentes. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Utilice esto para permitir que LLM cree nuevos archivos. Sobrescribirá los archivos existentes si ya existen. + +:::nota +La herramienta `write` está controlada por el permiso `edit`, que cubre todas las modificaciones de archivos (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### leer + +Lea el contenido del archivo desde su base de código. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +Esta herramienta lee archivos y devuelve su contenido. Admite la lectura de rangos de líneas específicos para archivos grandes. + +--- + +### grep + +Busque contenidos de archivos utilizando expresiones regulares. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Búsqueda rápida de contenido en su base de código. Admite sintaxis de expresiones regulares completa y filtrado de patrones de archivos. + +--- + +### globo + +Encuentre archivos por coincidencia de patrones. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +Busque archivos usando patrones globales como `**/*.js` o `src/**/*.ts`. Devuelve rutas de archivos coincidentes ordenadas por hora de modificación. + +--- + +### lista + +Enumere archivos y directorios en una ruta determinada. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +Esta herramienta enumera el contenido del directorio. Acepta patrones globales para filtrar resultados. + +--- + +### lsp (experimental) + +Interactúe con sus servidores LSP configurados para obtener funciones de inteligencia de código como definiciones, referencias, información de desplazamiento y jerarquía de llamadas. + +:::nota +Esta herramienta solo está disponible cuando `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (o `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +Las operaciones admitidas incluyen `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` y `outgoingCalls`. + +Para configurar qué servidores LSP están disponibles para su proyecto, consulte [Servidores LSP](/docs/lsp). + +--- + +### parche + +Aplicar parches a los archivos. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Esta herramienta aplica archivos de parche a su código base. Útil para aplicar diferencias y parches de diversas fuentes. + +:::nota +La herramienta `patch` está controlada por el permiso `edit`, que cubre todas las modificaciones de archivos (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### habilidad + +Cargue una [habilidad](/docs/skills) (un archivo `SKILL.md`) y devuelva su contenido en la conversación. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todo escribir + +Administre listas de tareas pendientes durante las sesiones de codificación. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +Crea y actualiza listas de tareas para realizar un seguimiento del progreso durante operaciones complejas. El LLM usa esto para organizar tareas de varios pasos. + +:::nota +Esta herramienta está deshabilitada para los subagentes de forma predeterminada, pero puede habilitarla manualmente. [Más información](/docs/agents/#permissions) +::: + +--- + +### todo leer + +Leer listas de tareas pendientes existentes. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +Lee el estado actual de la lista de tareas pendientes. Utilizado por LLM para rastrear qué tareas están pendientes o completadas. + +:::nota +Esta herramienta está deshabilitada para los subagentes de forma predeterminada, pero puede habilitarla manualmente. [Más información](/docs/agents/#permissions) +::: + +--- + +### búsqueda web + +Obtener contenido web. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +Permite que LLM busque y lea páginas web. Útil para buscar documentación o investigar recursos en línea. + +--- + +### búsqueda web + +Busque información en la web. + +:::nota +Esta herramienta solo está disponible cuando se utiliza el proveedor OpenCode o cuando la variable de entorno `OPENCODE_ENABLE_EXA` está configurada en cualquier valor verdadero (por ejemplo, `true` o `1`). + +Para habilitar al iniciar OpenCode: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Realiza búsquedas web utilizando Exa AI para encontrar información relevante en línea. Útil para investigar temas, encontrar eventos actuales o recopilar información más allá del límite de datos de entrenamiento. + +No se requiere ninguna clave API: la herramienta se conecta directamente al servicio MCP alojado de Exa AI sin autenticación. + +:::consejo +Utilice `websearch` cuando necesite encontrar información (descubrimiento) y `webfetch` cuando necesite recuperar contenido de una URL específica (recuperación). +::: + +--- + +### pregunta + +Haga preguntas al usuario durante la ejecución. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +Esta herramienta permite que LLM haga preguntas al usuario durante una tarea. Es útil para: + +- Recopilar preferencias o requisitos del usuario. +- Aclarar instrucciones ambiguas +- Tomar decisiones sobre las opciones de implementación. +- Ofrecer opciones sobre qué dirección tomar. + +Cada pregunta incluye un encabezado, el texto de la pregunta y una lista de opciones. Los usuarios pueden seleccionar entre las opciones proporcionadas o escribir una respuesta personalizada. Cuando hay varias preguntas, los usuarios pueden navegar entre ellas antes de enviar todas las respuestas. + +--- + +## Herramientas personalizadas + +Las herramientas personalizadas le permiten definir sus propias funciones a las que LLM puede llamar. Estos están definidos en su archivo de configuración y pueden ejecutar código arbitrario. + +[Más información](/docs/custom-tools) sobre la creación de herramientas personalizadas. + +--- + +## MCP servidores + +Los servidores MCP (Protocolo de contexto modelo) le permiten integrar herramientas y servicios externos. Esto incluye acceso a bases de datos, integraciones API y servicios de terceros. + +[Más información](/docs/mcp-servers) sobre la configuración de servidores MCP. + +--- + +## Internos + +Internamente, herramientas como `grep`, `glob` y `list` usan [ripgrep](https://github.com/BurntSushi/ripgrep) bajo el capó. De forma predeterminada, ripgrep respeta los patrones `.gitignore`, lo que significa que los archivos y directorios enumerados en su `.gitignore` se excluirán de las búsquedas y listados. + +--- + +### Ignorar patrones + +Para incluir archivos que normalmente se ignorarían, cree un archivo `.ignore` en la raíz de su proyecto. Este archivo puede permitir explícitamente ciertas rutas. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +Por ejemplo, este archivo `.ignore` permite que ripgrep busque dentro de los directorios `node_modules/`, `dist/` y `build/` incluso si figuran en `.gitignore`. diff --git a/packages/web/src/content/docs/es/troubleshooting.mdx b/packages/web/src/content/docs/es/troubleshooting.mdx new file mode 100644 index 000000000..109f6eba5 --- /dev/null +++ b/packages/web/src/content/docs/es/troubleshooting.mdx @@ -0,0 +1,300 @@ +--- +title: Solución de problemas +description: Problemas comunes y cómo resolverlos. +--- + +Para depurar problemas con OpenCode, comience verificando los registros y los datos locales que almacena en el disco. + +--- + +## Registros + +Los archivos de registro se escriben en: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: Presione `WIN+R` y pegue `%USERPROFILE%\.local\share\opencode\log` + +Los archivos de registro reciben nombres con marcas de tiempo (por ejemplo, `2025-01-09T123456.log`) y se conservan los 10 archivos de registro más recientes. + +Puede configurar el nivel de registro con la opción de línea de comandos `--log-level` para obtener información de depuración más detallada. Por ejemplo, `opencode --log-level DEBUG`. + +--- + +## Almacenamiento + +opencode almacena datos de sesión y otros datos de aplicaciones en el disco en: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: Presione `WIN+R` y pegue `%USERPROFILE%\.local\share\opencode` + +Este directorio contiene: + +- `auth.json` - Datos de autenticación como API claves, OAuth tokens +- `log/` - Registros de aplicaciones +- `project/` - Datos específicos del proyecto, como datos de sesión y mensajes. + - Si el proyecto está dentro de un repositorio de Git, se almacena en `.//storage/` + - Si no es un repositorio de Git, se almacena en `./global/storage/` + +--- + +## Aplicación de escritorio + +OpenCode Desktop ejecuta un servidor OpenCode local (el sidecar `opencode-cli`) en segundo plano. La mayoría de los problemas se deben a un complemento que no funciona correctamente, una memoria caché dañada o una mala configuración del servidor. + +### Comprobaciones rápidas + +- Salga por completo y reinicie la aplicación. +- Si la aplicación muestra una pantalla de error, haga clic en **Reiniciar** y copie los detalles del error. +- Solo macOS: menú `OpenCode` -> **Recargar vista web** (ayuda si la interfaz de usuario está en blanco/congelada). + +--- + +### Deshabilitar complementos + +Si la aplicación de escritorio falla al iniciarse, se bloquea o se comporta de manera extraña, comience por deshabilitar los complementos. + +#### Verifique la configuración global + +Abra su archivo de configuración global y busque una clave `plugin`. + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (o `~/.config/opencode/opencode.json`) +- **macOS/Linux** (instalaciones anteriores): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: Presione `WIN+R` y pegue `%USERPROFILE%\.config\opencode\opencode.jsonc` + +Si tiene complementos configurados, desactívelos temporalmente eliminando la clave o configurándola en una matriz vacía: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### Verificar directorios de complementos + +OpenCode también puede cargar complementos locales desde el disco. Quítelos temporalmente del camino (o cambie el nombre de la carpeta) y reinicie la aplicación de escritorio: + +- **Complementos globales** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: Presione `WIN+R` y pegue `%USERPROFILE%\.config\opencode\plugins` +- **Complementos de proyecto** (solo si usas la configuración por proyecto) + - `/.opencode/plugins/` + +Si la aplicación comienza a funcionar nuevamente, vuelva a habilitar los complementos uno a la vez para encontrar cuál está causando el problema. + +--- + +### Borrar el caché + +Si deshabilitar los complementos no ayuda (o la instalación de un complemento está bloqueada), borre el caché para que OpenCode pueda reconstruirlo. + +1. Salga de OpenCode Desktop por completo. +2. Elimine el directorio de caché: + +- **macOS**: Buscador -> `Cmd+Shift+G` -> pegar `~/.cache/opencode` +- **Linux**: eliminar `~/.cache/opencode` (o ejecutar `rm -rf ~/.cache/opencode`) +- **Windows**: Presione `WIN+R` y pegue `%USERPROFILE%\.cache\opencode` + +3. Reinicie el escritorio OpenCode. + +--- + +### Solucionar problemas de conexión del servidor + +OpenCode Desktop puede iniciar su propio servidor local (predeterminado) o conectarse a la URL de un servidor que haya configurado. + +Si ve un cuadro de diálogo **"Error de conexión"** (o la aplicación nunca pasa de la pantalla de inicio), busque una URL de servidor personalizada. + +#### Borrar la URL del servidor predeterminado del escritorio + +Desde la pantalla de inicio, haga clic en el nombre del servidor (con el punto de estado) para abrir el selector de servidor. En la sección **Servidor predeterminado**, haga clic en **Borrar**. + +#### Elimina `server.port` / `server.hostname` de tu configuración + +Si su `opencode.json(c)` contiene una sección `server`, elimínela temporalmente y reinicie la aplicación de escritorio. + +#### Verificar variables de entorno + +Si tiene `OPENCODE_PORT` configurado en su entorno, la aplicación de escritorio intentará usar ese puerto para el servidor local. + +- Desarme `OPENCODE_PORT` (o elija un puerto libre) y reinicie. + +--- + +### Linux: Problemas con Wayland/X11 + +En Linux, algunas configuraciones de Wayland pueden causar ventanas en blanco o errores de compositor. + +- Si estás en Wayland y la aplicación está en blanco o falla, intenta iniciarla con `OC_ALLOW_WAYLAND=1`. +- Si eso empeora las cosas, elimínelo e intente iniciarlo en una sesión X11. + +--- + +### Windows: tiempo de ejecución de WebView2 + +En Windows, el escritorio OpenCode requiere Microsoft Edge **WebView2 Runtime**. Si la aplicación se abre en una ventana en blanco o no se inicia, instale/actualice WebView2 e inténtelo nuevamente. + +--- + +### Windows: Problemas generales de rendimiento + +Si tiene un rendimiento lento, problemas de acceso a archivos o problemas de terminal en Windows, intente usar [WSL (Windows Subsistema para Linux)](/docs/windows-wsl). WSL proporciona un entorno Linux que funciona de manera más fluida con las funciones de OpenCode. + +--- + +### Notificaciones que no se muestran + +OpenCode Desktop solo muestra notificaciones del sistema cuando: + +- las notificaciones están habilitadas para OpenCode en la configuración de su sistema operativo, y +- la ventana de la aplicación no está enfocada. + +--- + +### Restablecer el almacenamiento de la aplicación de escritorio (último recurso) + +Si la aplicación no se inicia y no puede borrar la configuración desde la interfaz de usuario, restablezca el estado guardado de la aplicación de escritorio. + +1. Salga del escritorio OpenCode. +2. Busque y elimine estos archivos (se encuentran en el directorio de datos de la aplicación de escritorio OpenCode): + +- `opencode.settings.dat` (URL del servidor predeterminado de escritorio) +- `opencode.global.dat` y `opencode.workspace.*.dat` (estado de la interfaz de usuario como servidores/proyectos recientes) + +Para encontrar el directorio rápidamente: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (luego busque los nombres de archivo arriba) +- **Linux**: busque en `~/.local/share` los nombres de archivo anteriores +- **Windows**: Presione `WIN+R` -> `%APPDATA%` (luego busque los nombres de archivo arriba) + +--- + +## Obteniendo ayuda + +Si tiene problemas con OpenCode: + +1. **Informar problemas el GitHub** + + La mejor manera de informar errores o solicitar funciones es a través de nuestro repositorio GitHub: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + Antes de crear un nuevo problema, busque los problemas existentes para ver si su problema ya ha sido informado. + +2. **Únete a nuestro Discord** + + Para obtener ayuda en tiempo real y debates comunitarios, únase a nuestro servidor de Discord: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Problemas comunes + +A continuación se detallan algunos problemas comunes y cómo resolverlos. + +--- + +### OpenCode no se inicia + +1. Verifique los registros en busca de mensajes de error. +2. Intente ejecutar con `--print-logs` para ver el resultado en la terminal. +3. Asegúrese de tener la última versión con `opencode upgrade` + +--- + +### Problemas de autenticación + +1. Intente volver a autenticarse con el comando `/connect` en TUI +2. Verifique que sus claves API sean válidas +3. Asegúrese de que su red permita conexiones al API del proveedor. + +--- + +### Modelo no disponible + +1. Comprueba que te has autenticado con el proveedor. +2. Verifique que el nombre del modelo en su configuración sea correcto +3. Algunos modelos pueden requerir acceso o suscripciones específicas + +Si encuentra `ProviderModelNotFoundError`, lo más probable es que esté equivocado. +haciendo referencia a un modelo en alguna parte. +Se debe hacer referencia a los modelos así: `/` + +Ejemplos: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +Para saber a qué modelos tiene acceso, ejecute `opencode models` + +--- + +### Error de inicio del proveedor + +Si encuentra un ProviderInitError, es probable que tenga una configuración no válida o dañada. + +Para resolver esto: + +1. Primero, verifique que su proveedor esté configurado correctamente siguiendo la [guía de proveedores](/docs/providers) +2. Si el problema persiste, intente borrar la configuración almacenada: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + En Windows, presione `WIN+R` y elimine: `%USERPROFILE%\.local\share\opencode` + +3. Vuelva a autenticarse con su proveedor utilizando el comando `/connect` en TUI. + +--- + +### AI_APICallError y problemas con el paquete del proveedor + +Si encuentra errores de llamada API, esto puede deberse a paquetes de proveedores obsoletos. opencode instala dinámicamente paquetes de proveedores (OpenAI, Anthropic, Google, etc.) según sea necesario y los almacena en caché localmente. + +Para resolver problemas con el paquete del proveedor: + +1. Borre la caché del paquete del proveedor: + + ```bash + rm -rf ~/.cache/opencode + ``` + + En Windows, presione `WIN+R` y elimine: `%USERPROFILE%\.cache\opencode` + +2. Reinicie opencode para reinstalar los paquetes del proveedor más recientes. + +Esto obligará a opencode a descargar las versiones más recientes de los paquetes del proveedor, lo que a menudo resuelve problemas de compatibilidad con los parámetros del modelo y los cambios de API. + +--- + +### Copiar/pegar no funciona en Linux + +Los usuarios de Linux deben tener instalada una de las siguientes utilidades del portapapeles para que funcione la función copiar/pegar: + +**Para sistemas X11:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**Para sistemas Wayland:** + +```bash +apt install -y wl-clipboard +``` + +**Para entornos sin cabeza:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode detectará si estás usando Wayland y prefieres `wl-clipboard`; de lo contrario, intentará encontrar herramientas del portapapeles en el orden de: `xclip` y `xsel`. diff --git a/packages/web/src/content/docs/es/tui.mdx b/packages/web/src/content/docs/es/tui.mdx new file mode 100644 index 000000000..57003807f --- /dev/null +++ b/packages/web/src/content/docs/es/tui.mdx @@ -0,0 +1,390 @@ +--- +title: TUI +description: Usando la interfaz de usuario del terminal OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode proporciona una interfaz de terminal interactiva o TUI para trabajar en sus proyectos con un LLM. + +Al ejecutar OpenCode se inicia TUI para el directorio actual. + +```bash +opencode +``` + +O puede iniciarlo para un directorio de trabajo específico. + +```bash +opencode /path/to/project +``` + +Una vez que esté en TUI, puede indicarlo con un mensaje. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## Referencias de archivos + +Puede hacer referencia a archivos en sus mensajes usando `@`. Esto realiza una búsqueda difusa de archivos en el directorio de trabajo actual. + +:::consejo +También puede utilizar `@` para hacer referencia a archivos en sus mensajes. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +El contenido del archivo se agrega a la conversación automáticamente. + +--- + +## Comandos bash + +Inicie un mensaje con `!` para ejecutar un comando de shell. + +```bash frame="none" +!ls -la +``` + +El resultado del comando se agrega a la conversación como resultado de la herramienta. + +--- + +## Comandos + +Cuando utilice OpenCode TUI, puede escribir `/` seguido de un nombre de comando para ejecutar acciones rápidamente. Por ejemplo: + +```bash frame="none" +/help +``` + +La mayoría de los comandos también tienen una combinación de teclas que utiliza `ctrl+x` como tecla principal, donde `ctrl+x` es la tecla principal predeterminada. [Más información](/docs/keybinds). + +Aquí están todos los comandos de barra diagonal disponibles: + +--- + +### conectar + +Agregue un proveedor a OpenCode. Le permite seleccionar entre proveedores disponibles y agregar sus claves API. + +```bash frame="none" +/connect +``` + +--- + +### compacto + +Compacta la sesión actual. _Alias_: `/summarize` + +```bash frame="none" +/compact +``` + +**Combinación de teclas:** `ctrl+x c` + +--- + +### detalles + +Alternar detalles de ejecución de la herramienta. + +```bash frame="none" +/details +``` + +**Combinación de teclas:** `ctrl+x d` + +--- + +### editor + +Abra un editor externo para redactar mensajes. Utiliza el editor configurado en su variable de entorno `EDITOR`. [Más información](#editor-setup). + +```bash frame="none" +/editor +``` + +**Combinación de teclas:** `ctrl+x e` + +--- + +### salida + +Salga de OpenCode. _Alias_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Combinación de teclas:** `ctrl+x q` + +--- + +### exportar + +Exporte la conversación actual a Markdown y ábrala en su editor predeterminado. Utiliza el editor configurado en su variable de entorno `EDITOR`. [Más información](#editor-setup). + +```bash frame="none" +/export +``` + +**Combinación de teclas:** `ctrl+x x` + +--- + +### ayuda + +Muestra el cuadro de diálogo de ayuda. + +```bash frame="none" +/help +``` + +**Combinación de teclas:** `ctrl+x h` + +--- + +### inicio + +Cree o actualice el archivo `AGENTS.md`. [Más información](/docs/rules). + +```bash frame="none" +/init +``` + +**Combinación de teclas:** `ctrl+x i` + +--- + +### modelos + +Listar modelos disponibles. + +```bash frame="none" +/models +``` + +**Combinación de teclas:** `ctrl+x m` + +--- + +### nuevo + +Iniciar una nueva sesión. _Alias_: `/clear` + +```bash frame="none" +/new +``` + +**Combinación de teclas:** `ctrl+x n` + +--- + +### rehacer + +Rehacer un mensaje previamente deshecho. Solo disponible después de usar `/undo`. + +:::consejo +También se restaurarán todos los cambios en el archivo. +::: + +Internamente, esto utiliza Git para gestionar los cambios de archivos. Entonces tu proyecto **necesita +ser un repositorio Git**. + +```bash frame="none" +/redo +``` + +**Combinación de teclas:** `ctrl+x r` + +--- + +### sesiones + +Enumere y cambie entre sesiones. _Alias_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Combinación de teclas:** `ctrl+x l` + +--- + +### compartir + +Compartir la sesión actual. [Más información](/docs/share). + +```bash frame="none" +/share +``` + +**Combinación de teclas:** `ctrl+x s` + +--- + +### temas + +Listar temas disponibles. + +```bash frame="none" +/theme +``` + +**Combinación de teclas:** `ctrl+x t` + +--- + +### pensamiento + +Alterna la visibilidad de los bloques de pensamiento/razonamiento en la conversación. Cuando está habilitado, puede ver el proceso de razonamiento del modelo para los modelos que admiten el pensamiento extendido. + +:::nota +Este comando solo controla si se **muestran** los bloques de pensamiento; no habilita ni deshabilita las capacidades de razonamiento del modelo. Para alternar las capacidades de razonamiento reales, use `ctrl+t` para recorrer las variantes del modelo. +::: + +```bash frame="none" +/thinking +``` + +--- + +### deshacer + +Deshacer el último mensaje de la conversación. Elimina el mensaje de usuario más reciente, todas las respuestas posteriores y cualquier cambio de archivo. + +:::consejo +Cualquier cambio de archivo realizado también se revertirá. +::: + +Internamente, esto utiliza Git para gestionar los cambios de archivos. Entonces tu proyecto **necesita +ser un repositorio Git**. + +```bash frame="none" +/undo +``` + +**Combinación de teclas:** `ctrl+x u` + +--- + +### dejar de compartir + +Dejar de compartir la sesión actual. [Más información](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## Configuración del editor + +Tanto el comando `/editor` como el `/export` usan el editor especificado en su variable de entorno `EDITOR`. + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + + Para hacerlo permanente, agréguelo a su perfil de shell; + `~/.bashrc`, `~/.zshrc`, etc. + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + + Para hacerlo permanente, use **Propiedades del sistema** > **Entorno + Variables**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + + Para hacerlo permanente, agréguelo a su perfil de PowerShell. + + + + +Las opciones de editor populares incluyen: + +- `code` - Código de Visual Studio +- `cursor` - Cursor +- `windsurf` - Windsurf +- `nvim` - Editor Neovim +- `vim` - Editor Vim +- `nano` - Nanoeditor +- `notepad` - Windows Bloc de notas +- `subl` - Texto sublime + +:::nota +Algunos editores como VS Code deben iniciarse con el indicador `--wait`. +::: + +Algunos editores necesitan argumentos de línea de comandos para ejecutarse en modo de bloqueo. El indicador `--wait` hace que el proceso del editor se bloquee hasta que se cierre. + +--- + +## Configurar + +Puede personalizar el comportamiento de TUI a través de su archivo de configuración OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### Opciones + +- `scroll_acceleration`: habilite la aceleración de desplazamiento estilo macOS para un desplazamiento suave y natural. Cuando está habilitado, la velocidad de desplazamiento aumenta con gestos de desplazamiento rápido y se mantiene precisa para movimientos más lentos. **Esta configuración tiene prioridad sobre `scroll_speed` y la anula cuando está habilitada.** +- `scroll_speed`: controla la rapidez con la que se desplaza el TUI cuando se utilizan comandos de desplazamiento (mínimo: `1`). El valor predeterminado es `3`. **Nota: Esto se ignora si `scroll_acceleration.enabled` está configurado en `true`.** + +--- + +## Personalización + +Puede personalizar varios aspectos de la vista TUI usando la paleta de comandos (`ctrl+x h` o `/help`). Estas configuraciones persisten después de los reinicios. + +--- + +#### Visualización del nombre de usuario + +Alterna si tu nombre de usuario aparece en los mensajes de chat. Accede a este a través de: + +- Paleta de comandos: busque "nombre de usuario" u "ocultar nombre de usuario" +- La configuración persiste automáticamente y se recordará en TUI sesiones diff --git a/packages/web/src/content/docs/es/web.mdx b/packages/web/src/content/docs/es/web.mdx new file mode 100644 index 000000000..fbd4eefe7 --- /dev/null +++ b/packages/web/src/content/docs/es/web.mdx @@ -0,0 +1,142 @@ +--- +title: Web +description: Usando OpenCode en su navegador. +--- + +OpenCode puede ejecutarse como una aplicación web en su navegador, brindando la misma poderosa experiencia de codificación de IA sin necesidad de una terminal. + +![OpenCode Web - Nueva sesión](../../../assets/web/web-homepage-new-session.png) + +## Empezando + +Inicie la interfaz web ejecutando: + +```bash +opencode web +``` + +Esto inicia un servidor local en `127.0.0.1` con un puerto disponible aleatorio y abre automáticamente OpenCode en su navegador predeterminado. + +:::precaución +Si no se establece `OPENCODE_SERVER_PASSWORD`, el servidor no será seguro. Esto está bien para uso local, pero debe configurarse para acceso a la red. +::: + +:::tip[Windows Usuarios] +Para obtener la mejor experiencia, ejecute `opencode web` desde [WSL](/docs/windows-wsl) en lugar de PowerShell. Esto garantiza el acceso adecuado al sistema de archivos y la integración del terminal. +::: + +--- + +## Configuración + +Puede configurar el servidor web usando indicadores de línea de comando o en su [archivo de configuración](/docs/config). + +### Puerto + +De forma predeterminada, OpenCode elige un puerto disponible. Puede especificar un puerto: + +```bash +opencode web --port 4096 +``` + +### Nombre de host + +De forma predeterminada, el servidor se vincula a `127.0.0.1` (solo localhost). Para hacer que OpenCode sea accesible en su red: + +```bash +opencode web --hostname 0.0.0.0 +``` + +Al usar `0.0.0.0`, OpenCode mostrará direcciones locales y de red: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### Descubrimiento de mDNS + +Habilite mDNS para que su servidor sea reconocible en la red local: + +```bash +opencode web --mdns +``` + +Esto establece automáticamente el nombre de host en `0.0.0.0` y anuncia el servidor como `opencode.local`. + +Puede personalizar el nombre de dominio mDNS para ejecutar varias instancias en la misma red: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +Para permitir dominios adicionales para CORS (útil para interfaces personalizadas): + +```bash +opencode web --cors https://example.com +``` + +### Autenticación + +Para proteger el acceso, establezca una contraseña utilizando la variable de entorno `OPENCODE_SERVER_PASSWORD`: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +El nombre de usuario predeterminado es `opencode` pero se puede cambiar con `OPENCODE_SERVER_USERNAME`. + +--- + +## Uso de la interfaz web + +Una vez iniciada, la interfaz web proporciona acceso a sus sesiones OpenCode. + +### Sesiones + +Vea y administre sus sesiones desde la página de inicio. Puedes ver sesiones activas e iniciar otras nuevas. + +![OpenCode Web - Sesión activa](../../../assets/web/web-homepage-active-session.png) + +### Estado del servidor + +Haga clic en "Ver servidores" para ver los servidores conectados y su estado. + +![OpenCode Web - Ver Servidores](../../../assets/web/web-homepage-see-servers.png) + +--- + +## Adjuntar una terminal + +Puede conectar un terminal TUI a un servidor web en ejecución: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +Esto le permite utilizar la interfaz web y el terminal simultáneamente, compartiendo las mismas sesiones y estados. + +--- + +## Archivo de configuración + +También puede configurar los ajustes del servidor en su archivo de configuración `opencode.json`: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +Los indicadores de la línea de comando tienen prioridad sobre la configuración del archivo de configuración. diff --git a/packages/web/src/content/docs/es/windows-wsl.mdx b/packages/web/src/content/docs/es/windows-wsl.mdx new file mode 100644 index 000000000..d2e682798 --- /dev/null +++ b/packages/web/src/content/docs/es/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: Ejecuta OpenCode en Windows con WSL para una mejor experiencia. +--- + +import { Steps } from "@astrojs/starlight/components" + +Aunque OpenCode puede ejecutarse directamente en Windows, recomendamos usar [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) para obtener la mejor experiencia. WSL ofrece un entorno Linux que funciona perfectamente con las funciones de OpenCode. + +:::tip[Por que WSL?] +WSL ofrece mejor rendimiento del sistema de archivos, soporte completo de terminal y compatibilidad con las herramientas de desarrollo de las que depende OpenCode. +::: + +--- + +## Configuracion + + + +1. **Instala WSL** + + Si aun no lo hiciste, [instala WSL](https://learn.microsoft.com/en-us/windows/wsl/install) usando la guia oficial de Microsoft. + +2. **Instala OpenCode en WSL** + + Cuando WSL este listo, abre tu terminal de WSL e instala OpenCode con uno de los [metodos de instalacion](/docs/). + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **Usa OpenCode desde WSL** + + Ve al directorio de tu proyecto (accede a los archivos de Windows desde `/mnt/c/`, `/mnt/d/`, etc.) y ejecuta OpenCode. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## Aplicacion de escritorio + servidor WSL + +Si prefieres usar la app de escritorio de OpenCode pero quieres ejecutar el servidor en WSL: + +1. **Inicia el servidor en WSL** con `--hostname 0.0.0.0` para permitir conexiones externas: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Conecta la app de escritorio** a `http://localhost:4096` + +:::note +Si `localhost` no funciona en tu configuracion, conectate usando la direccion IP de WSL (desde WSL: `hostname -I`) y usa `http://:4096`. +::: + +:::caution +Cuando uses `--hostname 0.0.0.0`, define `OPENCODE_SERVER_PASSWORD` para proteger el servidor. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Cliente web + WSL + +Para obtener la mejor experiencia web en Windows: + +1. **Ejecuta `opencode web` en la terminal de WSL** en lugar de PowerShell: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Accede desde tu navegador de Windows** en `http://localhost:` (OpenCode muestra la URL) + +Ejecutar `opencode web` desde WSL garantiza acceso correcto al sistema de archivos e integracion con la terminal, manteniendolo accesible desde tu navegador de Windows. + +--- + +## Acceso a archivos de Windows + +WSL puede acceder a todos tus archivos de Windows mediante el directorio `/mnt/`: + +- Unidad `C:` → `/mnt/c/` +- Unidad `D:` → `/mnt/d/` +- Y asi sucesivamente... + +Ejemplo: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +Para una experiencia mas fluida, considera clonar o copiar tu repo al sistema de archivos de WSL (por ejemplo en `~/code/`) y ejecutar OpenCode ahi. +::: + +--- + +## Consejos + +- Ejecuta OpenCode en WSL para proyectos guardados en unidades de Windows: el acceso a archivos es transparente +- Usa la [extension WSL de VS Code](https://code.visualstudio.com/docs/remote/wsl) junto con OpenCode para un flujo de desarrollo integrado +- Tu configuracion y tus sesiones de OpenCode se guardan dentro del entorno WSL en `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/es/zen.mdx b/packages/web/src/content/docs/es/zen.mdx new file mode 100644 index 000000000..d81e90248 --- /dev/null +++ b/packages/web/src/content/docs/es/zen.mdx @@ -0,0 +1,254 @@ +--- +title: zen +description: Lista seleccionada de modelos proporcionada por OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen es una lista de modelos probados y verificados proporcionada por el equipo OpenCode. + +:::nota +OpenCode Zen se encuentra actualmente en versión beta. +::: + +Zen funciona como cualquier otro proveedor en OpenCode. Inicia sesión en OpenCode Zen y obtiene +su clave API. Es **completamente opcional** y no necesitas usarlo para usarlo. +OpenCode. + +--- + +## Fondo + +Hay una gran cantidad de modelos, pero solo unos pocos. +Estos modelos funcionan bien como agentes codificadores. Además, la mayoría de los proveedores son +configurado de manera muy diferente; por lo que obtienes un rendimiento y una calidad muy diferentes. + +:::consejo +Probamos un grupo selecto de modelos y proveedores que funcionan bien con OpenCode. +::: + +Entonces, si estás usando un modelo a través de algo como OpenRouter, nunca podrás ser +Asegúrese de obtener la mejor versión del modelo que desea. + +Para solucionar este problema, hicimos un par de cosas: + +1. Probamos un grupo selecto de modelos y hablamos con sus equipos sobre cómo + mejor ejecutarlos. +2. Luego trabajamos con algunos proveedores para asegurarnos de que estuvieran siendo atendidos. + correctamente. +3. Finalmente, comparamos la combinación modelo/proveedor y llegamos + con una lista que nos sentimos bien recomendando. + +OpenCode Zen es una puerta de enlace de IA que le brinda acceso a estos modelos. + +--- + +## Cómo funciona + +OpenCode Zen funciona como cualquier otro proveedor en OpenCode. + +1. Inicias sesión en **OpenCode Zen**, agregas tu facturación + detalles y copie su clave API. +2. Ejecuta el comando `/connect` en TUI, selecciona OpenCode Zen y pega tu clave API. +3. Ejecute `/models` en TUI para ver la lista de modelos que recomendamos. + +Se le cobra por solicitud y puede agregar créditos a su cuenta. + +--- + +## Puntos finales + +También puede acceder a nuestros modelos a través de los siguientes puntos finales API. + +| Modelo | Identificación del modelo | Punto final | Paquete SDK de IA | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Códice GPT 5.2 | gpt-5.2-códice | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Códice GPT 5.1 | gpt-5.1-códice | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Códice Máximo | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Códice Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Códice GPT 5 | gpt-5-códice | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT5Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Soneto 4.5 | soneto-claude-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Soneto 4 | claude-soneto-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Géminis 3 Pro | geminis-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Géminis 3 Flash | geminis-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Gratis | minimax-m2.1-libre | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Gratis | glm-4.7-libre | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Gratis | kimi-k2.5-libre | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Pensamiento Kimi K2 | kimi-k2-pensando | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Codificador Qwen3 480B | codificador qwen3 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Gran pepinillo | gran pepinillo | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +El [ID del modelo](/docs/config/#models) en su configuración OpenCode +utiliza el formato `opencode/`. Por ejemplo, para el Codex GPT 5.2, deberías +use `opencode/gpt-5.2-codex` en su configuración. + +--- + +### Modelos + +Puede obtener la lista completa de modelos disponibles y sus metadatos en: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## Precios + +Apoyamos un modelo de pago por uso. A continuación se muestran los precios **por 1 millón de tokens**. + +| Modelo | Entrada | Salida | Lectura en caché | Escritura en caché | +| --------------------------------- | ------ | ------ | ----------- | ------------ | +| Gran pepinillo | Gratis | Gratis | Gratis | - | +| MiniMax M2.1 Gratis | Gratis | Gratis | Gratis | - | +| MiniMax M2.1 | $0,30 | $1,20 | $0,10 | - | +| GLM 4.7 Gratis | Gratis | Gratis | Gratis | - | +| GLM 4.7 | $0,60 | $2.20 | $0,10 | - | +| GLM 4.6 | $0,60 | $2.20 | $0,10 | - | +| Kimi K2.5 Gratis | Gratis | Gratis | Gratis | - | +| Kimi K2.5 | $0,60 | $3.00 | $0,08 | - | +| Pensamiento Kimi K2 | $0,40 | $2.50 | - | - | +| Kimi K2 | $0,40 | $2.50 | - | - | +| Codificador Qwen3 480B | $0,45 | $1,50 | - | - | +| Claude Sonnet 4.5 (≤ 200.000 tokens) | $3.00 | $15.00 | $0,30 | $3,75 | +| Claude Sonnet 4.5 (> 200.000 tokens) | $6.00 | $22,50 | $0,60 | $7.50 | +| Claude Soneto 4 (≤ 200.000 fichas) | $3.00 | $15.00 | $0,30 | $3,75 | +| Claude Sonnet 4 (> 200.000 fichas) | $6.00 | $22,50 | $0,60 | $7.50 | +| Claude Haiku 4.5 | $1.00 | $5.00 | $0,10 | $1,25 | +| Claude Haiku 3.5 | $0,80 | $4.00 | $0,08 | $1.00 | +| Claude Opus 4.6 (≤ 200.000 tokens) | $5.00 | $25.00 | $0,50 | $6.25 | +| Claude Opus 4.6 (> 200K fichas) | $10.00 | $37,50 | $1.00 | $12,50 | +| Claude Opus 4.5 | $5.00 | $25.00 | $0,50 | $6.25 | +| Claude Opus 4.1 | $15.00 | $75.00 | $1,50 | $18,75 | +| Géminis 3 Pro (≤ 200.000 tokens) | $2.00 | $12.00 | $0,20 | - | +| Géminis 3 Pro (> 200.000 tokens) | $4.00 | $18.00 | $0,40 | - | +| Géminis 3 Flash | $0,50 | $3.00 | $0,05 | - | +| GPT 5.2 | $1,75 | $14.00 | $0,175 | - | +| Códice GPT 5.2 | $1,75 | $14.00 | $0,175 | - | +| GPT 5.1 | $1.07 | $8,50 | $0,107 | - | +| Códice GPT 5.1 | $1.07 | $8,50 | $0,107 | - | +| GPT 5.1 Códice Máximo | $1,25 | $10.00 | $0,125 | - | +| GPT 5.1 Códice Mini | $0,25 | $2.00 | $0,025 | - | +| GPT 5 | $1.07 | $8,50 | $0,107 | - | +| Códice GPT 5 | $1.07 | $8,50 | $0,107 | - | +| GPT5Nano | Gratis | Gratis | Gratis | - | + +Es posible que notes _Claude Haiku 3.5_ en tu historial de uso. Este es un [modelo de bajo costo](/docs/config/#models) que se utiliza para generar los títulos de tus sesiones. + +:::nota +Las tarifas de las tarjetas de crédito se trasladan al costo (4,4% + 0,30 dólares por transacción); No cobramos nada más allá de eso. +::: + +Los modelos gratuitos: + +- GLM 4.7 Free está disponible en OpenCode por tiempo limitado. El equipo está aprovechando este tiempo para recopilar comentarios y mejorar el modelo. +- Kimi K2.5 Free está disponible en OpenCode por tiempo limitado. El equipo está aprovechando este tiempo para recopilar comentarios y mejorar el modelo. +- MiniMax M2.1 Free está disponible en OpenCode por tiempo limitado. El equipo está aprovechando este tiempo para recopilar comentarios y mejorar el modelo. +- Big Pickle es un modelo sigiloso gratuito en OpenCode por tiempo limitado. El equipo está aprovechando este tiempo para recopilar comentarios y mejorar el modelo. + +Contáctenos si tiene alguna pregunta. + +--- + +### Recarga automática + +Si su saldo es inferior a $5, Zen recargará automáticamente $20. + +Puedes cambiar el monto de la recarga automática. También puedes desactivar la recarga automática por completo. + +--- + +### Límites mensuales + +También puede establecer un límite de uso mensual para todo el espacio de trabajo y para cada +miembro de tu equipo. + +Por ejemplo, digamos que establece un límite de uso mensual de $20, Zen no usará +más de $20 en un mes. Pero si tienes habilitada la recarga automática, Zen podría terminar +cobrarle más de $20 si su saldo es inferior a $5. + +--- + +## Privacidad + +Todos nuestros modelos están alojados en los EE. UU. Nuestros proveedores siguen una política de retención cero y no utilizan sus datos para la capacitación de modelos, con las siguientes excepciones: + +- Big Pickle: Durante su periodo gratuito, los datos recopilados podrán utilizarse para mejorar el modelo. +- GLM 4.7 Gratis: Durante su periodo gratuito, los datos recopilados podrán utilizarse para mejorar el modelo. +- Kimi K2.5 Free: Durante su periodo gratuito, los datos recopilados podrán utilizarse para mejorar el modelo. +- MiniMax M2.1 Free: Durante su período gratuito, los datos recopilados podrán utilizarse para mejorar el modelo. +- API de OpenAI: las solicitudes se conservan durante 30 días de acuerdo con las [Políticas de datos de OpenAI](https://platform.openai.com/docs/guides/your-data). +- API de Anthropic: las solicitudes se conservan durante 30 días de acuerdo con las [Políticas de datos de Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## Para equipos + +Zen también funciona muy bien para equipos. Puedes invitar a compañeros de equipo, asignar roles, seleccionar +los modelos que utiliza su equipo y más. + +:::nota +Actualmente, los espacios de trabajo son gratuitos para los equipos como parte de la versión beta. +::: + +Actualmente, administrar su espacio de trabajo es gratuito para equipos como parte de la versión beta. estaremos +compartiremos más detalles sobre los precios pronto. + +--- + +### Roles + +Puedes invitar a compañeros de equipo a tu espacio de trabajo y asignar roles: + +- **Administrador**: administra modelos, miembros, claves API y facturación +- **Miembro**: administra solo sus propias claves API + +Los administradores también pueden establecer límites de gastos mensuales para cada miembro para mantener los costos bajo control. + +--- + +### Acceso al modelo + +Los administradores pueden habilitar o deshabilitar modelos específicos para el espacio de trabajo. Las solicitudes realizadas a un modelo deshabilitado devolverán un error. + +Esto es útil para los casos en los que desea desactivar el uso de un modelo que +recopila datos. + +--- + +### Trae tu propia llave + +Puede utilizar sus propias teclas OpenAI o Anthropic API mientras accede a otros modelos en Zen. + +Cuando utiliza sus propias claves, los tokens los factura directamente el proveedor, no Zen. + +Por ejemplo, es posible que su organización ya tenga una clave para OpenAI o Anthropic. +y quieres usar ese en lugar del que proporciona Zen. + +--- + +## Objetivos + +Creamos OpenCode Zen para: + +1. **Evaluar** los mejores modelos/proveedores de agentes de codificación. +2. Tener acceso a las opciones de **más alta calidad** y no degradar el rendimiento ni recurrir a proveedores más baratos. +3. Transmitir cualquier **bajada de precio** vendiendo al costo; por lo que el único margen de beneficio es para cubrir nuestras tarifas de procesamiento. +4. **No tener ningún bloqueo** al permitirle usarlo con cualquier otro agente de codificación. Y siempre le permitirá utilizar cualquier otro proveedor con OpenCode también. diff --git a/packages/web/src/content/docs/fr/1-0.mdx b/packages/web/src/content/docs/fr/1-0.mdx new file mode 100644 index 000000000..522c221cd --- /dev/null +++ b/packages/web/src/content/docs/fr/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: Migration vers 1.0 +description: Quoi de neuf dans OpenCode 1.0. +--- + +OpenCode 1.0 est une réécriture complète de TUI. + +Nous sommes passés du TUI basé sur go+bubbletea qui présentait des problèmes de performances et de capacités à un framework interne (OpenTUI) écrit en zig+solidjs. + +Le nouveau TUI fonctionne comme l'ancien puisqu'il se connecte au même serveur opencode. + +--- + +## Mise à niveau + +Vous ne devriez pas être automatiquement mis à niveau vers la version 1.0 si vous utilisez actuellement une version précédente +version. Cependant, certaines anciennes versions de OpenCode récupèrent toujours la dernière version. + +Pour mettre à niveau manuellement, exécutez + +```bash +$ opencode upgrade 1.0.0 +``` + +Pour revenir à 0.x, exécutez + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## Changements UX + +L'historique de la session est plus compressé, affichant uniquement tous les détails de l'outil d'édition et de bash. + +Nous avons ajouté une barre de commandes par laquelle presque tout passe. Appuyez sur ctrl+p pour l'afficher dans n'importe quel contexte et voir tout ce que vous pouvez faire. + +Ajout d'une barre latérale de session (peut être basculée) avec des informations utiles. + +Nous avons supprimé certaines fonctionnalités que nous n'étions pas sûrs que quiconque utilisait réellement. S'il manque quelque chose d'important, veuillez ouvrir un problème et nous le rajouterons rapidement. + +--- + +## Modifications radicales + +### Raccourcis clavier renommés + +- messages_revert -> messages_undo +- switch_agent -> agent_cycle +- switch_agent_reverse -> agent_cycle_reverse +- switch_mode -> agent_cycle +- switch_mode_reverse -> agent_cycle_reverse + +### Raccourcis clavier supprimés + +- messages_layout_toggle +- messages_suivant +- messages_précédent +- fichier_diff_toggle +- recherche_fichier +- fichier_fermer +- liste_fichiers +- app_help +- projet_init +- outil_détails +- blocs_de_pensée diff --git a/packages/web/src/content/docs/fr/acp.mdx b/packages/web/src/content/docs/fr/acp.mdx new file mode 100644 index 000000000..bd9b66576 --- /dev/null +++ b/packages/web/src/content/docs/fr/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACP Assistance +description: Utilisez OpenCode dans n’importe quel éditeur compatible ACP. +--- + +OpenCode prend en charge le [Agent Client Protocol](https://agentclientprotocol.com) ou (ACP), vous permettant de l'utiliser directement dans les éditeurs et IDE compatibles. + +:::tip +Pour obtenir une liste des éditeurs et des outils prenant en charge ACP, consultez le [ACP progress report](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP est un protocole ouvert qui standardise la communication entre les éditeurs de code et les agents de codage IA. + +--- + +## Configurer + +Pour utiliser OpenCode via ACP, configurez votre éditeur pour exécuter la commande `opencode acp`. + +La commande démarre OpenCode en tant que sous-processus compatible ACP qui communique avec votre éditeur via JSON-RPC via stdio. + +Vous trouverez ci-dessous des exemples d'éditeurs populaires prenant en charge ACP. + +--- + +### Zed + +Ajoutez à votre configuration [Zed](https://zed.dev) (`~/.config/zed/settings.json`) : + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +Pour l'ouvrir, utilisez l'action `agent: new thread` dans la **Palette de commandes**. + +Vous pouvez également associer un raccourci clavier en modifiant votre `keymap.json` : + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### IDE JetBrains + +Ajoutez à votre [JetBrains IDE](https://www.jetbrains.com/) acp.json conformément à la [documentation](https://www.jetbrains.com/help/ai-assistant/acp.html) : + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +Pour l'ouvrir, utilisez le nouvel agent « OpenCode » dans le sélecteur d'agent AI Chat. + +--- + +### Avante.nvim + +Ajoutez à votre configuration [Avante.nvim](https://github.com/yetone/avante.nvim) : + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +Si vous devez transmettre des variables d'environnement : + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +Pour utiliser OpenCode comme agent ACP dans [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim), ajoutez ce qui suit à votre configuration Neovim : + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +Cette configuration configure CodeCompanion pour utiliser OpenCode comme agent ACP pour le chat. + +Si vous devez transmettre des variables d'environnement (comme `OPENCODE_API_KEY`), reportez-vous à [Configuration des adaptateurs : variables d'environnement ](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) dans la documentation CodeCompanion.nvim pour plus de détails. + +## Soutien + +OpenCode fonctionne de la même manière via ACP que dans le terminal. Toutes les fonctionnalités sont prises en charge : + +:::note +Certaines commandes slash intégrées telles que `/undo` et `/redo` ne sont actuellement pas prises en charge. +::: + +- Outils intégrés (opérations sur les fichiers, commandes de terminal, etc.) +- Outils personnalisés et commandes slash +- Serveurs MCP configurés dans votre configuration OpenCode +- Règles spécifiques au projet à partir de `AGENTS.md` +- Formateurs et linters personnalisés +- Système d'agents et d'autorisations diff --git a/packages/web/src/content/docs/fr/agents.mdx b/packages/web/src/content/docs/fr/agents.mdx new file mode 100644 index 000000000..6bad5d269 --- /dev/null +++ b/packages/web/src/content/docs/fr/agents.mdx @@ -0,0 +1,747 @@ +--- +title: Agents +description: Configurez et utilisez des agents spécialisés. +--- + +Les agents sont des assistants IA spécialisés qui peuvent être configurés pour des tâches et des flux de travail spécifiques. Ils vous permettent de créer des outils ciblés avec des invites, des modèles et un accès aux outils personnalisés. + +:::tip +Utilisez l'agent de plan pour analyser le code et examiner les suggestions sans apporter de modifications au code. +::: + +Vous pouvez basculer entre les agents au cours d'une session ou les appeler avec la mention `@`. + +--- + +## Espèces + +Il existe deux types d'agents dans OpenCode ; agents primaires et sous-agents. + +--- + +### Agents primaires + +Les agents principaux sont les principaux assistants avec lesquels vous interagissez directement. Vous pouvez les parcourir à l'aide de la touche **Tab** ou de votre combinaison de touches `switch_agent` configurée. Ces agents gèrent votre conversation principale. L'accès aux outils est configuré via les autorisations : par exemple, Build a tous les outils activés tandis que Plan est restreint. + +:::tip +Vous pouvez utiliser la touche **Tab** pour basculer entre les agents principaux au cours d'une session. +::: + +OpenCode est livré avec deux agents principaux intégrés, **Build** et **Plan**. Bien +regardez-les ci-dessous. + +--- + +### Sous-agents + +Les sous-agents sont des assistants spécialisés que les agents principaux peuvent appeler pour des tâches spécifiques. Vous pouvez également les invoquer manuellement en **@ les mentionnant** dans vos messages. + +OpenCode est livré avec deux sous-agents intégrés, **Général** et **Explore**. Nous verrons cela ci-dessous. + +--- + +## Intégré + +OpenCode est livré avec deux agents principaux intégrés et deux sous-agents intégrés. + +--- + +### Utiliser la construction + +_Mode_ : `primary` + +Build est l'agent principal **par défaut** avec tous les outils activés. Il s'agit de l'agent standard pour les travaux de développement où vous avez besoin d'un accès complet aux opérations sur les fichiers et aux commandes système. + +--- + +### Utiliser le forfait + +_Mode_ : `primary` + +Un agent restreint conçu pour la planification et l'analyse. Nous utilisons un système d'autorisation pour vous donner plus de contrôle et empêcher toute modification involontaire. +Par défaut, tous les éléments suivants sont définis sur `ask` : + +- `file edits` : toutes les écritures, correctifs et modifications +- `bash` : toutes les commandes bash + +Cet agent est utile lorsque vous souhaitez que LLM analyse le code, suggère des modifications ou crée des plans sans apporter de modifications réelles à votre base de code. + +--- + +### Utiliser général + +_Mode_ : `subagent` + +Un agent polyvalent pour rechercher des questions complexes et exécuter des tâches en plusieurs étapes. Dispose d'un accès complet aux outils (sauf todo), il peut donc apporter des modifications aux fichiers en cas de besoin. Utilisez-le pour exécuter plusieurs unités de travail en parallèle. + +--- + +### Utiliser explorer + +_Mode_ : `subagent` + +Un agent rapide en lecture seule pour explorer les bases de code. Impossible de modifier les fichiers. Utilisez-le lorsque vous avez besoin de rechercher rapidement des fichiers par modèles, de rechercher du code par mots-clés ou de répondre à des questions sur la base de code. + +--- + +### Utiliser le compactage + +_Mode_ : `primary` + +Agent système caché qui compacte un contexte long en un résumé plus petit. Il s'exécute automatiquement en cas de besoin et n'est pas sélectionnable dans l'interface utilisateur. + +--- + +### Utiliser le titre + +_Mode_ : `primary` + +Agent système caché qui génère des titres de session courts. Il s'exécute automatiquement et n'est pas sélectionnable dans l'interface utilisateur. + +--- + +### Utiliser le résumé + +_Mode_ : `primary` + +Agent système caché qui crée des résumés de session. Il s'exécute automatiquement et n'est pas sélectionnable dans l'interface utilisateur. + +--- + +## Usage + +1. Pour les agents principaux, utilisez la touche **Tab** pour les parcourir au cours d'une session. Vous pouvez également utiliser votre raccourci clavier `switch_agent` configuré. + +2. Les sous-agents peuvent être invoqués : + - **Automatiquement** par les agents principaux pour des tâches spécialisées en fonction de leurs descriptions. + - Manuellement en **@ mentionnant** un sous-agent dans votre message. Par exemple. + + ```txt frame="none" + @general help me search for this function + ``` + +3. **Navigation entre les sessions** : lorsque les sous-agents créent leurs propres sessions enfants, vous pouvez naviguer entre la session parent et toutes les sessions enfants en utilisant : + - **\+Right** (ou votre combinaison de touches `session_child_cycle` configurée) pour avancer via parent → enfant1 → enfant2 → ... → parent + - **\+Left** (ou votre combinaison de touches `session_child_cycle_reverse` configurée) pour revenir en arrière dans parent ← enfant1 ← enfant2 ← ... ← parent + +Cela vous permet de basculer en toute transparence entre la conversation principale et le travail spécialisé des sous-agents. + +--- + +## Configurer + +Vous pouvez personnaliser les agents intégrés ou créer les vôtres via la configuration. Les agents peuvent être configurés de deux manières : + +--- + +### JSON + +Configurez les agents dans votre fichier de configuration `opencode.json` : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Réduction + +Vous pouvez également définir des agents à l'aide de fichiers markdown. Placez-les dans : + +- Mondial : `~/.config/opencode/agents/` +- Par projet : `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Le nom du fichier de démarque devient le nom de l'agent. Par exemple, `review.md` crée un agent `review`. + +--- + +## Possibilités + +Examinons ces options de configuration en détail. + +--- + +### Description + +Utilisez l'option `description` pour fournir une brève description de ce que fait l'agent et quand l'utiliser. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +Il s'agit d'une option de configuration **obligatoire**. + +--- + +### Température + +Contrôlez le caractère aléatoire et la créativité des réponses du LLM avec la configuration `temperature`. + +Des valeurs faibles rendent les réponses plus ciblées et déterministes, tandis que des valeurs plus élevées augmentent la créativité et la variabilité. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Les valeurs de température varient généralement de 0,0 à 1,0 : + +- **0,0-0,2** : réponses très ciblées et déterministes, idéales pour l'analyse et la planification du code +- **0,3-0,5** : réponses équilibrées avec une certaine créativité, idéales pour les tâches de développement générales +- **0,6-1,0** : réponses plus créatives et variées, utiles pour le brainstorming et l'exploration + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Si aucune température n'est spécifiée, OpenCode utilise les valeurs par défaut spécifiques au modèle ; généralement 0 pour la plupart des modèles, 0,55 pour les modèles Qwen. + +--- + +### Pas maximum + +Contrôlez le nombre maximum d'itérations agents qu'un agent peut effectuer avant d'être obligé de répondre avec du texte uniquement. Cela permet aux utilisateurs qui souhaitent contrôler les coûts de fixer une limite aux actions agents. + +Si cela n'est pas défini, l'agent continuera à itérer jusqu'à ce que le modèle choisisse de s'arrêter ou que l'utilisateur interrompe la session. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +Lorsque la limite est atteinte, l'agent reçoit une invite système spéciale lui demandant de répondre avec un résumé de son travail et des tâches restantes recommandées. + +:::caution +L’ancien champ `maxSteps` est obsolète. Utilisez plutôt `steps`. +::: + +--- + +### Désactiver + +Définissez sur `true` pour désactiver l'agent. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Rapide + +Spécifiez un fichier d'invite système personnalisé pour cet agent avec la configuration `prompt`. Le fichier d'invite doit contenir des instructions spécifiques à l'objectif de l'agent. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Ce chemin est relatif à l'emplacement du fichier de configuration. Cela fonctionne donc à la fois pour la configuration globale OpenCode et pour la configuration spécifique au projet. + +--- + +### Modèle + +Utilisez la configuration `model` pour remplacer le modèle de cet agent. Utile pour utiliser différents modèles optimisés pour différentes tâches. Par exemple, un modèle de planification plus rapide, un modèle de mise en œuvre plus performant. + +:::tip +Si vous ne spécifiez pas de modèle, les agents principaux utilisent le [modèle globalement configuré](/docs/config#models) tandis que les sous-agents utiliseront le modèle de l'agent principal qui a appelé le sous-agent. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +L'ID de modèle dans votre configuration OpenCode utilise le format `provider/model-id`. Par exemple, si vous utilisez [OpenCode Zen](/docs/zen), vous utiliserez `opencode/gpt-5.1-codex` pour GPT 5.1 Codex. + +--- + +### Outils + +Contrôlez quels outils sont disponibles dans cet agent avec la configuration `tools`. Vous pouvez activer ou désactiver des outils spécifiques en les définissant sur `true` ou `false`. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +La configuration spécifique à l'agent remplace la configuration globale. +::: + +Vous pouvez également utiliser des caractères génériques pour contrôler plusieurs outils à la fois. Par exemple, pour désactiver tous les outils d'un serveur MCP : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[En savoir plus sur les outils](/docs/tools). + +--- + +### Autorisations + +Vous pouvez configurer des autorisations pour gérer les actions qu'un agent peut effectuer. Actuellement, les autorisations pour les outils `edit`, `bash` et `webfetch` peuvent être configurées pour : + +- `"ask"` — Demander l'approbation avant d'exécuter l'outil +- `"allow"` — Autoriser toutes les opérations sans approbation +- `"deny"` – Désactiver l'outil + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +Vous pouvez remplacer ces autorisations par agent. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +Vous pouvez également définir des autorisations dans les agents Markdown. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +Vous pouvez définir des autorisations pour des commandes bash spécifiques. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +Cela peut prendre un modèle global. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +Et vous pouvez également utiliser le caractère générique `*` pour gérer les autorisations pour toutes les commandes. +Puisque la dernière règle correspondante est prioritaire, placez le caractère générique `*` en premier et les règles spécifiques après. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[En savoir plus sur les autorisations](/docs/permissions). + +--- + +### Mode + +Contrôlez le mode de l'agent avec la configuration `mode`. L'option `mode` est utilisée pour déterminer comment l'agent peut être utilisé. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +L'option `mode` peut être définie sur `primary`, `subagent` ou `all`. Si aucun `mode` n’est spécifié, la valeur par défaut est `all`. + +--- + +### Caché + +Masquez un sous-agent du menu de saisie semi-automatique `@` avec `hidden: true`. Utile pour les sous-agents internes qui ne doivent être invoqués que par programme par d'autres agents via l'outil Tâche. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +Cela affecte uniquement la visibilité de l'utilisateur dans le menu de saisie semi-automatique. Les agents masqués peuvent toujours être invoqués par le modèle via l'outil Tâche si les autorisations le permettent. + +:::note +S'applique uniquement aux agents `mode: subagent`. +::: + +--- + +### Autorisations de tâches + +Contrôlez quels sous-agents un agent peut appeler via l'outil Tâche avec `permission.task`. Utilise des modèles globaux pour une correspondance flexible. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +Lorsqu'il est défini sur `deny`, le sous-agent est entièrement supprimé de la description de l'outil Tâche, de sorte que le modèle ne tentera pas de l'invoquer. + +:::tip +Les règles sont évaluées dans l'ordre et la **dernière règle correspondante l'emporte**. Dans l'exemple ci-dessus, `orchestrator-planner` correspond à la fois à `*` (refuser) et à `orchestrator-*` (autoriser), mais comme `orchestrator-*` vient après `*`, le résultat est `allow`. +::: + +:::tip +Les utilisateurs peuvent toujours appeler n'importe quel sous-agent directement via le menu de saisie semi-automatique `@`, même si les autorisations de tâche de l'agent le refuseraient. +::: + +--- + +### Couleur + +Personnalisez l'apparence visuelle de l'agent dans l'interface utilisateur avec l'option `color`. Cela affecte la façon dont l'agent apparaît dans l'interface. + +Utilisez une couleur hexadécimale valide (par exemple, `#FF5733`) ou une couleur de thème : `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### Haut P + +Contrôlez la diversité des réponses avec l’option `top_p`. Alternative à la température pour contrôler le caractère aléatoire. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +Les valeurs vont de 0,0 à 1,0. Les valeurs inférieures sont plus ciblées, les valeurs élevées plus diversifiées. + +--- + +### Supplémentaire + +Toutes les autres options que vous spécifiez dans la configuration de votre agent seront **transmises directement** au fournisseur en tant qu'options de modèle. Cela vous permet d'utiliser des fonctionnalités et des paramètres spécifiques au fournisseur. + +Par exemple, avec les modèles de raisonnement de OpenAI, vous pouvez contrôler l'effort de raisonnement : + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +Ces options supplémentaires sont spécifiques au modèle et au fournisseur. Consultez la documentation de votre fournisseur pour connaître les paramètres disponibles. + +:::tip +Exécutez `opencode models` pour voir une liste des modèles disponibles. +::: + +--- + +## Créer des agents + +Vous pouvez créer de nouveaux agents à l'aide de la commande suivante : + +```bash +opencode agent create +``` + +Cette commande interactive va : + +1. Demandez où enregistrer l'agent ; global ou spécifique à un projet. +2. Description de ce que l'agent doit faire. +3. Générez une invite système et un identifiant appropriés. +4. Vous permet de sélectionner les outils auxquels l'agent peut accéder. +5. Enfin, créez un fichier markdown avec la configuration de l'agent. + +--- + +## Cas d'utilisation + +Voici quelques cas d’utilisation courants pour différents agents. + +- **Agent de build** : travail de développement complet avec tous les outils activés +- **Agent de plan** : analyse et planification sans apporter de modifications +- **Agent de révision** : révision de code avec accès en lecture seule et outils de documentation +- **Agent de débogage** : axé sur l'investigation avec les outils bash et read activés +- **Agent Docs** : écriture de documentation avec des opérations sur les fichiers mais pas de commandes système + +--- + +## Exemples + +Voici quelques exemples d’agents qui pourraient vous être utiles. + +:::tip +Avez-vous un agent que vous aimeriez partager ? [Soumettez un PR](https://github.com/anomalyco/opencode). +::: + +--- + +### Agent de documentation + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### Auditeur de sécurité + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/fr/cli.mdx b/packages/web/src/content/docs/fr/cli.mdx new file mode 100644 index 000000000..e103b35fa --- /dev/null +++ b/packages/web/src/content/docs/fr/cli.mdx @@ -0,0 +1,601 @@ +--- +title: CLI +description: Options et commandes CLI OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +La CLI OpenCode démarre par défaut le [TUI](/docs/tui) lorsqu'il est exécuté sans aucun argument. + +```bash +opencode +``` + +Mais il accepte également les commandes documentées sur cette page. Cela vous permet d'interagir avec OpenCode par programme. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui + +Démarrez l’interface utilisateur du terminal OpenCode. + +```bash +opencode [project] +``` + +#### Drapeaux + +| Drapeau | Court | Descriptif | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | Continuer la dernière séance | +| `--session` | `-s` | ID de session pour continuer | +| `--prompt` | | Invite à utiliser | +| `--model` | `-m` | Modèle à utiliser sous forme de fournisseur/modèle | +| `--agent` | | Agent à utiliser | +| `--port` | | Port à écouter sur | +| `--hostname` | | Nom d'hôte sur lequel écouter | + +--- + +## Commandes + +La CLI OpenCode dispose également des commandes suivantes. + +--- + +### agent + +Gérer les agents pour OpenCode. + +```bash +opencode agent [command] +``` + +--- + +### attacher + +Attachez un terminal à un serveur backend OpenCode déjà en cours d'exécution démarré via les commandes `serve` ou `web`. + +```bash +opencode attach [url] +``` + +Cela permet d'utiliser le TUI avec un backend OpenCode distant. Par exemple: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### Drapeaux + +| Drapeau | Court | Descriptif | +| ----------- | ----- | --------------------------------- | +| `--dir` | | Répertoire de travail dans lequel démarrer TUI | +| `--session` | `-s` | ID de session pour continuer | + +--- + +#### créer + +Créez un nouvel agent avec une configuration personnalisée. + +```bash +opencode agent create +``` + +Cette commande vous guidera dans la création d'un nouvel agent avec une invite système personnalisée et une configuration d'outil. + +--- + +#### liste + +Répertoriez tous les agents disponibles. + +```bash +opencode agent list +``` + +--- + +### authentification + +Commande pour gérer les informations d’identification et la connexion des fournisseurs. + +```bash +opencode auth [command] +``` + +--- + +#### se connecter + +OpenCode est alimenté par la liste des fournisseurs sur [Models.dev](https://models.dev), vous pouvez donc utiliser `opencode auth login` pour configurer les clés API pour tout fournisseur que vous souhaitez utiliser. Ceci est stocké dans `~/.local/share/opencode/auth.json`. + +```bash +opencode auth login +``` + +Lorsque OpenCode démarre, il charge les fournisseurs à partir du fichier d'informations d'identification. Et s'il y a des clés définies dans vos environnements ou un fichier `.env` dans votre projet. + +--- + +#### liste + +Répertorie tous les fournisseurs authentifiés tels qu'ils sont stockés dans le fichier d'informations d'identification. + +```bash +opencode auth list +``` + +Ou la version courte. + +```bash +opencode auth ls +``` + +--- + +#### déconnexion + +Vous déconnecte d'un fournisseur en l'effaçant du fichier d'informations d'identification. + +```bash +opencode auth logout +``` + +--- + +### github + +Gérez l'agent GitHub pour l'automatisation du référentiel. + +```bash +opencode github [command] +``` + +--- + +#### installer + +Installez l'agent GitHub dans votre référentiel. + +```bash +opencode github install +``` + +Cela configure le flux de travail GitHub Actions nécessaire et vous guide tout au long du processus de configuration. [En savoir plus](/docs/github). + +--- + +#### courir + +Exécutez l'agent GitHub. Ceci est généralement utilisé dans les actions GitHub. + +```bash +opencode github run +``` + +##### Drapeaux + +| Drapeau | Descriptif | +| --------- | -------------------------------------- | +| `--event` | Événement simulé GitHub pour lequel exécuter l'agent | +| `--token` | Jeton d'accès personnel GitHub | + +--- + +### MCP + +Gérer les serveurs Model Context Protocol. + +```bash +opencode mcp [command] +``` + +--- + +#### ajouter + +Ajoutez un serveur MCP à votre configuration. + +```bash +opencode mcp add +``` + +Cette commande vous guidera dans l’ajout d’un serveur MCP local ou distant. + +--- + +#### liste + +Répertoriez tous les serveurs MCP configurés et leur état de connexion. + +```bash +opencode mcp list +``` + +Ou utilisez la version courte. + +```bash +opencode mcp ls +``` + +--- + +#### authentification + +Authentifiez-vous auprès d'un serveur MCP compatible OAuth. + +```bash +opencode mcp auth [name] +``` + +Si vous ne fournissez pas de nom de serveur, vous serez invité à sélectionner parmi les serveurs compatibles OAuth disponibles. + +Vous pouvez également répertorier les serveurs compatibles OAuth et leur statut d'authentification. + +```bash +opencode mcp auth list +``` + +Ou utilisez la version courte. + +```bash +opencode mcp auth ls +``` + +--- + +#### déconnexion + +Supprimez les informations d'identification OAuth pour un serveur MCP. + +```bash +opencode mcp logout [name] +``` + +--- + +#### déboguer + +Déboguer les problèmes de connexion OAuth pour un serveur MCP. + +```bash +opencode mcp debug +``` + +--- + +### modèles + +Répertoriez tous les modèles disponibles auprès des fournisseurs configurés. + +```bash +opencode models [provider] +``` + +Cette commande affiche tous les modèles disponibles parmi vos fournisseurs configurés au format `provider/model`. + +Ceci est utile pour déterminer le nom exact du modèle à utiliser dans [votre config](/docs/config/). + +Vous pouvez éventuellement transmettre un ID de fournisseur pour filtrer les modèles en fonction de ce fournisseur. + +```bash +opencode models anthropic +``` + +#### Drapeaux + +| Drapeau | Descriptif | +| ----------- | ------------------------------------------------------------ | +| `--refresh` | Actualisez le cache des modèles à partir de models.dev | +| `--verbose` | Utiliser une sortie de modèle plus détaillée (inclut des métadonnées telles que les coûts) | + +Utilisez l'indicateur `--refresh` pour mettre à jour la liste des modèles mis en cache. Ceci est utile lorsque de nouveaux modèles ont été ajoutés à un fournisseur et que vous souhaitez les voir dans OpenCode. + +```bash +opencode models --refresh +``` + +--- + +### courir + +Exécutez opencode en mode non interactif en transmettant directement une invite. + +```bash +opencode run [message..] +``` + +Ceci est utile pour les scripts, l'automatisation ou lorsque vous souhaitez une réponse rapide sans lancer le TUI complet. Par exemple. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +Vous pouvez également vous connecter à une instance `opencode serve` en cours d'exécution pour éviter les temps de démarrage à froid du serveur MCP à chaque exécution : + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### Drapeaux + +| Drapeau | Court | Descriptif | +| ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | | La commande à exécuter, utilisez message pour args | +| `--continue` | `-c` | Continuer la dernière séance | +| `--session` | `-s` | ID de session pour continuer | +| `--share` | | Partager la séance | +| `--model` | `-m` | Modèle à utiliser sous forme de fournisseur/modèle | +| `--agent` | | Agent à utiliser | +| `--file` | `-f` | Fichier(s) à joindre au message | +| `--format` | | Format : par défaut (formaté) ou json (événements JSON bruts) | +| `--title` | | Titre de la session (utilise une invite tronquée si aucune valeur n'est fournie) | +| `--attach` | | Connectez-vous à un serveur opencode en cours d'exécution (par exemple, http://localhost:4096) | +| `--port` | | Port du serveur local (port aléatoire par défaut) | + +--- + +### servir + +Démarrez un serveur OpenCode sans tête pour un accès API. Consultez le [serveur docs](/docs/server) pour l'interface complète HTTP. + +```bash +opencode serve +``` + +Cela démarre un serveur HTTP qui fournit à API un accès à la fonctionnalité opencode sans l'interface TUI. Définissez `OPENCODE_SERVER_PASSWORD` pour activer l'authentification de base HTTP (le nom d'utilisateur par défaut est `opencode`). + +#### Drapeaux + +| Drapeau | Descriptif | +| ------------ | ------------------------------------------ | +| `--port` | Port à écouter sur | +| `--hostname` | Nom d'hôte sur lequel écouter | +| `--mdns` | Activer la découverte mDNS | +| `--cors` | Origines de navigateur supplémentaires pour autoriser CORS | + +--- + +### session + +Gérer les sessions OpenCode. + +```bash +opencode session [command] +``` + +--- + +#### liste + +Répertoriez toutes les sessions OpenCode. + +```bash +opencode session list +``` + +##### Drapeaux + +| Drapeau | Court | Descriptif | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` | Limiter aux N sessions les plus récentes | +| `--format` | | Format de sortie : tableau ou json (tableau) | + +--- + +### statistiques + +Affichez les statistiques d'utilisation et de coût des jetons pour vos sessions OpenCode. + +```bash +opencode stats +``` + +#### Drapeaux + +| Drapeau | Descriptif | +| ----------- | --------------------------------------------------------------------------- | +| `--days` | Afficher les statistiques des N derniers jours (tous les temps) | +| `--tools` | Nombre d'outils à afficher (tous) | +| `--models` | Afficher la répartition de l'utilisation du modèle (masqué par défaut). Passez un numéro pour afficher le premier N | +| `--project` | Filtrer par projet (tous les projets, chaîne vide : projet en cours) | + +--- + +### exporter + +Exportez les données de session sous JSON. + +```bash +opencode export [sessionID] +``` + +Si vous ne fournissez pas d'ID de session, vous serez invité à sélectionner parmi les sessions disponibles. + +--- + +### importer + +Importez les données de session à partir d'un fichier JSON ou d'un partage OpenCode URL. + +```bash +opencode import +``` + +Vous pouvez importer à partir d'un fichier local ou d'un partage OpenCode URL. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### la toile + +Démarrez un serveur OpenCode sans tête avec une interface Web. + +```bash +opencode web +``` + +Cela démarre un serveur HTTP et ouvre un navigateur Web pour accéder à OpenCode via une interface Web. Définissez `OPENCODE_SERVER_PASSWORD` pour activer l'authentification de base HTTP (le nom d'utilisateur par défaut est `opencode`). + +#### Drapeaux + +| Drapeau | Descriptif | +| ------------ | ------------------------------------------ | +| `--port` | Port à écouter sur | +| `--hostname` | Nom d'hôte sur lequel écouter | +| `--mdns` | Activer la découverte mDNS | +| `--cors` | Origines de navigateur supplémentaires pour autoriser CORS | + +--- + +### acp + +Démarrez un serveur ACP (Agent Client Protocol). + +```bash +opencode acp +``` + +Cette commande démarre un serveur ACP qui communique via stdin/stdout en utilisant nd-JSON. + +#### Drapeaux + +| Drapeau | Descriptif | +| ------------ | --------------------- | +| `--cwd` | Répertoire de travail | +| `--port` | Port à écouter sur | +| `--hostname` | Nom d'hôte sur lequel écouter | + +--- + +### désinstaller + +Désinstallez OpenCode et supprimez tous les fichiers associés. + +```bash +opencode uninstall +``` + +#### Drapeaux + +| Drapeau | Court | Descriptif | +| --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` | Conserver les fichiers de configuration | +| `--keep-data` | `-d` | Conserver les données de session et les instantanés | +| `--dry-run` | | Afficher ce qui serait supprimé sans supprimer | +| `--force` | `-f` | Ignorer les invites de confirmation | + +--- + +### mise à niveau + +Met à jour opencode vers la dernière version ou une version spécifique. + +```bash +opencode upgrade [target] +``` + +Pour mettre à niveau vers la dernière version. + +```bash +opencode upgrade +``` + +Pour passer à une version spécifique. + +```bash +opencode upgrade v0.1.48 +``` + +#### Drapeaux + +| Drapeau | Court | Descriptif | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` | La méthode d'installation utilisée ; curl, npm, pnpm, chignon, infusion | + +--- + +## Drapeaux mondiaux + +La CLI opencode prend les indicateurs globaux suivants. + +| Drapeau | Court | Descriptif | +| -------------- | ----- | ------------------------------------ | +| `--help` | `-h` | Afficher l'aide | +| `--version` | `-v` | Imprimer le numéro de version | +| `--print-logs` | | Imprimer les journaux sur stderr | +| `--log-level` | | Niveau de journalisation (DEBUG, INFO, WARN, ERROR) | + +--- + +## Variables d'environnement + +OpenCode peut être configuré à l'aide de variables d'environnement. + +| Variables | Tapez | Descriptif | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | booléen | Partager automatiquement des sessions | +| `OPENCODE_GIT_BASH_PATH` | chaîne | Chemin vers l'exécutable Git Bash sur Windows | +| `OPENCODE_CONFIG` | chaîne | Chemin d'accès au fichier de configuration | +| `OPENCODE_CONFIG_DIR` | chaîne | Chemin d'accès au répertoire de configuration | +| `OPENCODE_CONFIG_CONTENT` | chaîne | Contenu de configuration JSON en ligne | +| `OPENCODE_DISABLE_AUTOUPDATE` | booléen | Désactiver les vérifications automatiques des mises à jour | +| `OPENCODE_DISABLE_PRUNE` | booléen | Désactiver l'élagage des anciennes données | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | booléen | Désactiver les mises à jour automatiques des titres du terminal | +| `OPENCODE_PERMISSION` | chaîne | Configuration des autorisations JSON intégrées | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | booléen | Désactiver les plugins par défaut | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | booléen | Désactiver les téléchargements automatiques du serveur LSP | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | booléen | Activer les modèles expérimentaux | +| `OPENCODE_DISABLE_AUTOCOMPACT` | booléen | Désactiver le compactage automatique du contexte | +| `OPENCODE_DISABLE_CLAUDE_CODE` | booléen | Désactiver la lecture de `.claude` (invite + compétences) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | booléen | Désactiver la lecture `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | booléen | Désactiver le chargement de `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | booléen | Désactiver la récupération de modèles à partir de sources distantes | +| `OPENCODE_FAKE_VCS` | chaîne | Faux fournisseur VCS à des fins de test | +| `OPENCODE_DISABLE_FILETIME_CHECK` | booléen | Désactiver la vérification de l'heure des fichiers pour l'optimisation | +| `OPENCODE_CLIENT` | chaîne | Identifiant du client (par défaut `cli`) | +| `OPENCODE_ENABLE_EXA` | booléen | Activer les outils de recherche Web Exa | +| `OPENCODE_SERVER_PASSWORD` | chaîne | Activer l'authentification de base pour `serve`/`web` | +| `OPENCODE_SERVER_USERNAME` | chaîne | Remplacer le nom d'utilisateur d'authentification de base (par défaut `opencode`) | +| `OPENCODE_MODELS_URL` | chaîne | URL personnalisé pour récupérer la configuration des modèles | + +--- + +### Expérimental + +Ces variables d'environnement activent des fonctionnalités expérimentales qui peuvent être modifiées ou supprimées. + +| Variables | Tapez | Descriptif | +| ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | booléen | Activer toutes les fonctionnalités expérimentales | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | booléen | Activer la découverte d'icônes | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | booléen | Désactiver la copie lors de la sélection dans TUI | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | numéro | Délai d'expiration par défaut pour les commandes bash dans ms | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | numéro | Nombre maximum de jetons de sortie pour les réponses LLM | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | booléen | Activer l'observateur de fichiers pour l'ensemble du répertoire | +| `OPENCODE_EXPERIMENTAL_OXFMT` | booléen | Activer le formateur oxfmt | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | booléen | Activer l'outil expérimental LSP | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | booléen | Désactiver l'observateur de fichiers | +| `OPENCODE_EXPERIMENTAL_EXA` | booléen | Activer les fonctionnalités Exa expérimentales | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | booléen | Activer la vérification expérimentale du type LSP | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | booléen | Activer les fonctionnalités de démarque expérimentales | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | booléen | Activer le mode plan | diff --git a/packages/web/src/content/docs/fr/commands.mdx b/packages/web/src/content/docs/fr/commands.mdx new file mode 100644 index 000000000..de20cf799 --- /dev/null +++ b/packages/web/src/content/docs/fr/commands.mdx @@ -0,0 +1,323 @@ +--- +title: Commandes +description: Créez des commandes personnalisées pour les tâches répétitives. +--- + +Les commandes personnalisées vous permettent de spécifier une invite que vous souhaitez exécuter lorsque cette commande est exécutée dans TUI. + +```bash frame="none" +/my-command +``` + +Les commandes personnalisées s'ajoutent aux commandes intégrées telles que `/init`, `/undo`, `/redo`, `/share`, `/help`. [En savoir plus](/docs/tui#commands). + +--- + +## Créer des fichiers de commandes + +Créez des fichiers markdown dans le répertoire `commands/` pour définir des commandes personnalisées. + +Créez `.opencode/commands/test.md` : + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Le frontmatter définit les propriétés de la commande. Le contenu devient le modèle. + +Utilisez la commande en tapant `/` suivi du nom de la commande. + +```bash frame="none" +"/test" +``` + +--- + +## Configurer + +Vous pouvez ajouter des commandes personnalisées via la configuration OpenCode ou en créant des fichiers markdown dans le répertoire `commands/`. + +--- + +### JSON + +Utilisez l'option `command` dans votre OpenCode [config](/docs/config) : + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Vous pouvez maintenant exécuter cette commande dans TUI : + +```bash frame="none" +/test +``` + +--- + +### Réduction + +Vous pouvez également définir des commandes à l'aide de fichiers markdown. Placez-les dans : + +- Mondial : `~/.config/opencode/commands/` +- Par projet : `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Le nom du fichier markdown devient le nom de la commande. Par exemple, `test.md` permet +tu cours : + +```bash frame="none" +/test +``` + +--- + +## Configuration rapide + +Les invites pour les commandes personnalisées prennent en charge plusieurs espaces réservés et syntaxes spéciaux. + +--- + +### Arguments + +Transmettez les arguments aux commandes à l’aide de l’espace réservé `$ARGUMENTS`. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +Exécutez la commande avec des arguments : + +```bash frame="none" +/component Button +``` + +Et `$ARGUMENTS` sera remplacé par `Button`. + +Vous pouvez également accéder à des arguments individuels à l'aide de paramètres de position : + +- `$1` - Premier argument +- `$2` - Deuxième argument +- `$3` - Troisième argument +- Et ainsi de suite... + +Par exemple: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +Exécutez la commande : + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +Celui-ci remplace : + +- `$1` avec `config.json` +- `$2` avec `src` +- `$3` avec `{ "key": "value" }` + +--- + +### Sortie du shell + +Utilisez _!`command`_ pour injecter la sortie [bash command](/docs/tui#bash-commands) dans votre invite. + +Par exemple, pour créer une commande personnalisée qui analyse la couverture des tests : + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +Ou pour consulter les modifications récentes : + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +Les commandes s'exécutent dans le répertoire racine de votre projet et leur sortie fait partie de l'invite. + +--- + +### Références de fichiers + +Incluez les fichiers dans votre commande en utilisant `@` suivi du nom du fichier. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +Le contenu du fichier est automatiquement inclus dans l’invite. + +--- + +## Possibilités + +Examinons les options de configuration en détail. + +--- + +### Modèle + +L'option `template` définit l'invite qui sera envoyée au LLM lors de l'exécution de la commande. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +Il s'agit d'une option de configuration **obligatoire**. + +--- + +### Description + +Utilisez l'option `description` pour fournir une brève description de ce que fait la commande. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +Ceci est affiché comme description dans le TUI lorsque vous tapez la commande. + +--- + +### Agent + +Utilisez la configuration `agent` pour spécifier éventuellement quel [agent](/docs/agents) doit exécuter cette commande. +S'il s'agit d'un [subagent](/docs/agents/#subagents), la commande déclenchera un appel de sous-agent par défaut. +Pour désactiver ce comportement, définissez `subtask` sur `false`. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +Il s'agit d'une option de configuration **facultative**. S’il n’est pas spécifié, la valeur par défaut est votre agent actuel. + +--- + +### Sous-tâche + +Utilisez le booléen `subtask` pour forcer la commande à déclencher un invocation de [subagent](/docs/agents/#subagents). +Ceci est utile si vous souhaitez que la commande ne pollue pas votre contexte principal et **force** l'agent à agir en tant que sous-agent, +même si `mode` est défini sur `primary` dans la configuration [agent](/docs/agents). + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +Il s'agit d'une option de configuration **facultative**. + +--- + +### Modèle + +Utilisez la configuration `model` pour remplacer le modèle par défaut pour cette commande. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Il s'agit d'une option de configuration **facultative**. + +--- + +## Intégré + +opencode comprend plusieurs commandes intégrées comme `/init`, `/undo`, `/redo`, `/share`, `/help` ; [en savoir plus](/docs/tui#commands). + +:::note +Les commandes personnalisées peuvent remplacer les commandes intégrées. +::: + +Si vous définissez une commande personnalisée portant le même nom, elle remplacera la commande intégrée. diff --git a/packages/web/src/content/docs/fr/config.mdx b/packages/web/src/content/docs/fr/config.mdx new file mode 100644 index 000000000..07e895de8 --- /dev/null +++ b/packages/web/src/content/docs/fr/config.mdx @@ -0,0 +1,685 @@ +--- +title: Configuration +description: En utilisant la configuration OpenCode JSON. +--- + +Vous pouvez configurer OpenCode à l'aide d'un fichier de configuration JSON. + +--- + +## Format + +OpenCode prend en charge les formats **JSON** et **JSONC** (JSON avec commentaires). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## Emplacements + +Vous pouvez placer votre configuration à plusieurs emplacements différents et ils ont un +ordre de priorité différent. + +:::note +Les fichiers de configuration sont **fusionnés**, pas remplacés. +::: + +Les fichiers de configuration sont fusionnés et non remplacés. Les paramètres des emplacements de configuration suivants sont combinés. Les configurations ultérieures remplacent les précédentes uniquement en cas de clés en conflit. Les paramètres non conflictuels de toutes les configurations sont conservés. + +Par exemple, si votre configuration globale définit `theme: "opencode"` et `autoupdate: true` et que la configuration de votre projet définit `model: "anthropic/claude-sonnet-4-5"`, la configuration finale inclura les trois paramètres. + +--- + +### Ordre de priorité + +Les sources de configuration sont chargées dans cet ordre (les sources ultérieures remplacent les précédentes) : + +1. **Configuration à distance** (à partir de `.well-known/opencode`) - paramètres par défaut de l'organisation +2. **Configuration globale** (`~/.config/opencode/opencode.json`) - préférences utilisateur +3. **Configuration personnalisée** (`OPENCODE_CONFIG` env var) - remplacements personnalisés +4. **Configuration du projet** (`opencode.json` dans le projet) - paramètres spécifiques au projet +5. **`.opencode` répertoires** - agents, commandes, plugins +6. **Configuration en ligne** (`OPENCODE_CONFIG_CONTENT` env var) - remplacements d'exécution + +Cela signifie que les configurations de projet peuvent remplacer les valeurs par défaut globales, et que les configurations globales peuvent remplacer les valeurs par défaut de l'organisation distante. + +:::note +Les répertoires `.opencode` et `~/.config/opencode` utilisent des **noms au pluriel** pour les sous-répertoires : `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/` et `themes/`. Les noms singuliers (par exemple, `agent/`) sont également pris en charge pour une compatibilité ascendante. +::: + +--- + +### Télécommande + +Les organisations peuvent fournir une configuration par défaut via le point de terminaison `.well-known/opencode`. Ceci est récupéré automatiquement lorsque vous vous authentifiez auprès d’un fournisseur qui le prend en charge. + +La configuration distante est chargée en premier, servant de couche de base. Toutes les autres sources de configuration (globales, projet) peuvent remplacer ces valeurs par défaut. + +Par exemple, si votre organisation fournit des serveurs MCP qui sont désactivés par défaut : + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +Vous pouvez activer des serveurs spécifiques dans votre configuration locale : + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### Mondial + +Placez votre configuration globale OpenCode dans `~/.config/opencode/opencode.json`. Utilisez la configuration globale pour les préférences de l'utilisateur telles que les thèmes, les fournisseurs ou les raccourcis clavier. + +La configuration globale remplace les paramètres par défaut de l'organisation distante. + +--- + +### Par projet + +Ajoutez `opencode.json` à la racine de votre projet. La configuration du projet a la priorité la plus élevée parmi les fichiers de configuration standard : elle remplace les configurations globales et distantes. + +:::tip +Placez la configuration spécifique au projet à la racine de votre projet. +::: + +Lorsque OpenCode démarre, il recherche un fichier de configuration dans le répertoire actuel ou remonte jusqu'au répertoire Git le plus proche. + +Il peut également être archivé en toute sécurité dans Git et utilise le même schéma que le schéma global. + +--- + +### Chemin personnalisé + +Spécifiez un chemin de fichier de configuration personnalisé à l'aide de la variable d'environnement `OPENCODE_CONFIG`. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +La configuration personnalisée est chargée entre les configurations globales et celles du projet dans l'ordre de priorité. + +--- + +### Répertoire personnalisé + +Spécifiez un répertoire de configuration personnalisé à l'aide de `OPENCODE_CONFIG_DIR` +variable d'environnement. Ce répertoire sera recherché pour les agents, les commandes, +modes et plugins tout comme le répertoire standard `.opencode`, et devrait +suivent la même structure. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +Le répertoire personnalisé est chargé après les répertoires de configuration globale et `.opencode`, il **peut donc remplacer** leurs paramètres. + +--- + +## Schéma + +Le fichier de configuration a un schéma défini dans [**`opencode.ai/config.json`**](https://opencode.ai/config.json). + +Votre éditeur doit être capable de valider et de compléter automatiquement en fonction du schéma. + +--- + +### TUI + +Vous pouvez configurer les paramètres spécifiques à TUI via l'option `tui`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +Options disponibles : + +- `scroll_acceleration.enabled` - Active l'accélération de défilement de style macOS. **A priorité sur `scroll_speed`.** +- `scroll_speed` - Multiplicateur de vitesse de défilement personnalisé (par défaut : `3`, minimum : `1`). Ignoré si `scroll_acceleration.enabled` est `true`. +- `diff_style` - Contrôle le rendu différentiel. `"auto"` s'adapte à la largeur du terminal, `"stacked"` affiche toujours une seule colonne. + +[En savoir plus sur l'utilisation du TUI ici](/docs/tui). + +--- + +### Serveur + +Vous pouvez configurer les paramètres du serveur pour les commandes `opencode serve` et `opencode web` via l'option `server`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +Options disponibles : + +- `port` - Port sur lequel écouter. +- `hostname` - Nom d'hôte sur lequel écouter. Lorsque `mdns` est activé et qu'aucun nom d'hôte n'est défini, la valeur par défaut est `0.0.0.0`. +- `mdns` - Activer la découverte du service mDNS. Cela permet à d'autres appareils du réseau de découvrir votre serveur OpenCode. +- `mdnsDomain` - Nom de domaine personnalisé pour le service mDNS. La valeur par défaut est `opencode.local`. Utile pour exécuter plusieurs instances sur le même réseau. +- `cors` - Origines supplémentaires pour autoriser CORS lors de l'utilisation du serveur HTTP à partir d'un client basé sur un navigateur. Les valeurs doivent être des origines complètes (schéma + hôte + port facultatif), par exemple `https://app.example.com`. + +[En savoir plus sur le serveur ici](/docs/server). + +--- + +### Outils + +Vous pouvez gérer les outils qu'un LLM peut utiliser via l'option `tools`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[En savoir plus sur les outils ici](/docs/tools). + +--- + +### Modèles + +Vous pouvez configurer les fournisseurs et les modèles que vous souhaitez utiliser dans votre configuration OpenCode via les options `provider`, `model` et `small_model`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +L'option `small_model` configure un modèle distinct pour les tâches légères comme la génération de titres. Par défaut, OpenCode essaie d'utiliser un modèle moins cher s'il est disponible auprès de votre fournisseur, sinon il revient à votre modèle principal. + +Les options du fournisseur peuvent inclure `timeout` et `setCacheKey` : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - Délai d'expiration de la demande en millisecondes (par défaut : 300 000). Réglez sur `false` pour désactiver. +- `setCacheKey` - Assurez-vous qu'une clé de cache est toujours définie pour le fournisseur désigné. + +Vous pouvez également configurer [modèles locaux](/docs/models#local). [En savoir plus](/docs/models). + +--- + +#### Options spécifiques au fournisseur + +Certains fournisseurs prennent en charge des options de configuration supplémentaires au-delà des paramètres génériques `timeout` et `apiKey`. + +##### Socle amazonien + +Amazon Bedrock prend en charge la configuration spécifique à AWS : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - Région AWS pour Bedrock (par défaut : `AWS_REGION` env var ou `us-east-1`) +- `profile` - Profil nommé AWS de `~/.aws/credentials` (par défaut : `AWS_PROFILE` env var) +- `endpoint` - Point de terminaison personnalisé URL pour les points de terminaison d'un VPC. Il s'agit d'un alias pour l'option générique `baseURL` utilisant la terminologie spécifique à AWS. Si les deux sont spécifiés, `endpoint` est prioritaire. + +:::note +Les jetons du porteur (`AWS_BEARER_TOKEN_BEDROCK` ou `/connect`) ont priorité sur l'authentification basée sur le profil. Voir [précédence d'authentification](/docs/providers#authentication-precedence) pour plus de détails. +::: + +[En savoir plus sur la configuration d'Amazon Bedrock](/docs/providers#amazon-bedrock). + +--- + +### Thèmes + +Vous pouvez configurer le thème que vous souhaitez utiliser dans votre configuration OpenCode via l'option `theme`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[En savoir plus ici](/docs/themes). + +--- + +### Agents + +Vous pouvez configurer des agents spécialisés pour des tâches spécifiques via l'option `agent`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +Vous pouvez également définir des agents à l'aide de fichiers markdown dans `~/.config/opencode/agents/` ou `.opencode/agents/`. [En savoir plus ici](/docs/agents). + +--- + +### Agent par défaut + +Vous pouvez définir l'agent par défaut à l'aide de l'option `default_agent`. Ceci détermine quel agent est utilisé lorsqu'aucun n'est explicitement spécifié. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +L'agent par défaut doit être un agent principal (et non un sous-agent). Il peut s'agir d'un agent intégré tel que `"build"` ou `"plan"`, ou d'un [agent personnalisé](/docs/agents) que vous avez défini. Si l'agent spécifié n'existe pas ou est un sous-agent, OpenCode reviendra à `"build"` avec un avertissement. + +Ce paramètre s'applique à toutes les interfaces : TUI, CLI (`opencode run`), application de bureau et GitHub Action. + +--- + +### Partage + +Vous pouvez configurer la fonctionnalité [share](/docs/share) via l'option `share`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +Cela prend : + +- `"manual"` - Autoriser le partage manuel via des commandes (par défaut) +- `"auto"` – Partager automatiquement de nouvelles conversations +- `"disabled"` – Désactiver complètement le partage + +Par défaut, le partage est défini en mode manuel où vous devez partager explicitement les conversations à l'aide de la commande `/share`. + +--- + +### Commandes + +Vous pouvez configurer des commandes personnalisées pour les tâches répétitives via l'option `command`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +Vous pouvez également définir des commandes à l'aide de fichiers markdown dans `~/.config/opencode/commands/` ou `.opencode/commands/`. [En savoir plus ici](/docs/commands). + +--- + +### Raccourcis clavier + +Vous pouvez personnaliser vos raccourcis clavier via l'option `keybinds`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[En savoir plus ici](/docs/keybinds). + +--- + +### Mise à jour automatique + +OpenCode téléchargera automatiquement toutes les nouvelles mises à jour au démarrage. Vous pouvez désactiver cela avec l'option `autoupdate`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +Si vous ne souhaitez pas de mises à jour mais souhaitez être averti lorsqu'une nouvelle version est disponible, définissez `autoupdate` sur `"notify"`. +Notez que cela ne fonctionne que s'il n'a pas été installé à l'aide d'un gestionnaire de packages tel que Homebrew. + +--- + +### Formateurs + +Vous pouvez configurer les formateurs de code via l'option `formatter`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[En savoir plus sur les formateurs ici](/docs/formatters). + +--- + +### Autorisations + +Par défaut, opencode **autorise toutes les opérations** sans nécessiter d'approbation explicite. Vous pouvez modifier cela en utilisant l'option `permission`. + +Par exemple, pour garantir que les outils `edit` et `bash` nécessitent l'approbation de l'utilisateur : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[En savoir plus sur les autorisations ici](/docs/permissions). + +--- + +### Compactage + +Vous pouvez contrôler le comportement de compactage du contexte via l'option `compaction`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - Compacte automatiquement la session lorsque le contexte est plein (par défaut : `true`). +- `prune` - Supprimez les anciennes sorties de l'outil pour enregistrer les jetons (par défaut : `true`). + +--- + +### Observateur + +Vous pouvez configurer les modèles d'ignorance de l'observateur de fichiers via l'option `watcher`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +Les modèles suivent la syntaxe globale. Utilisez ceci pour exclure les répertoires bruyants de la surveillance des fichiers. + +--- + +### Serveurs MCP + +Vous pouvez configurer les serveurs MCP que vous souhaitez utiliser via l'option `mcp`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[En savoir plus ici](/docs/mcp-servers). + +--- + +### Plugins + +[Plugins](/docs/plugins) étendent OpenCode avec des outils, des hooks et des intégrations personnalisés. + +Placez les fichiers du plugin dans `.opencode/plugins/` ou `~/.config/opencode/plugins/`. Vous pouvez également charger des plugins depuis npm via l'option `plugin`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[En savoir plus ici](/docs/plugins). + +--- + +### Instructions + +Vous pouvez configurer les instructions pour le modèle que vous utilisez via l'option `instructions`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Cela prend un tableau de chemins et de modèles globaux vers les fichiers d'instructions. [Apprendre encore plus +à propos des règles ici](/docs/rules). + +--- + +### Fournisseurs handicapés + +Vous pouvez désactiver les fournisseurs chargés automatiquement via l'option `disabled_providers`. Ceci est utile lorsque vous souhaitez empêcher le chargement de certains fournisseurs même si leurs informations d'identification sont disponibles. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +Le `disabled_providers` est prioritaire sur `enabled_providers`. +::: + +L'option `disabled_providers` accepte un tableau d'ID de fournisseur. Lorsqu'un fournisseur est désactivé : + +- Il ne sera pas chargé même si des variables d'environnement sont définies. +- Il ne sera pas chargé même si les clés API sont configurées via la commande `/connect`. +- Les modèles du fournisseur n'apparaîtront pas dans la liste de sélection des modèles. + +--- + +### Fournisseurs activés + +Vous pouvez spécifier une liste autorisée de fournisseurs via l'option `enabled_providers`. Une fois défini, seuls les fournisseurs spécifiés seront activés et tous les autres seront ignorés. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +Ceci est utile lorsque vous souhaitez restreindre OpenCode à l'utilisation de fournisseurs spécifiques plutôt que de les désactiver un par un. + +:::note +Le `disabled_providers` est prioritaire sur `enabled_providers`. +::: + +Si un fournisseur apparaît à la fois dans `enabled_providers` et `disabled_providers`, le `disabled_providers` est prioritaire pour la compatibilité ascendante. + +--- + +### Expérimental + +La clé `experimental` contient des options en cours de développement actif. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::caution +Les options expérimentales ne sont pas stables. Ils peuvent changer ou être supprimés sans préavis. +::: + +--- + +## Variables + +Vous pouvez utiliser la substitution de variables dans vos fichiers de configuration pour référencer les variables d'environnement et le contenu des fichiers. + +--- + +### Vars d'environnement + +Utilisez `{env:VARIABLE_NAME}` pour remplacer les variables d'environnement : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +Si la variable d'environnement n'est pas définie, elle sera remplacée par une chaîne vide. + +--- + +### Fichiers + +Utilisez `{file:path/to/file}` pour remplacer le contenu d'un fichier : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +Les chemins de fichiers peuvent être : + +- Par rapport au répertoire du fichier de configuration +- Ou des chemins absolus commençant par `/` ou `~` + +Ceux-ci sont utiles pour : + +- Conserver les données sensibles telles que les clés API dans des fichiers séparés. +- Y compris de gros fichiers d'instructions sans encombrer votre configuration. +- Partage d'extraits de configuration communs sur plusieurs fichiers de configuration. diff --git a/packages/web/src/content/docs/fr/custom-tools.mdx b/packages/web/src/content/docs/fr/custom-tools.mdx new file mode 100644 index 000000000..c0d63e54d --- /dev/null +++ b/packages/web/src/content/docs/fr/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: Outils personnalisés +description: Créez des outils que LLM peut appeler dans opencode. +--- + +Les outils personnalisés sont des fonctions que vous créez et que le LLM peut appeler pendant les conversations. Ils fonctionnent avec les [outils intégrés](/docs/tools) de opencode comme `read`, `write` et `bash`. + +--- + +## Création d'un outil + +Les outils sont définis sous forme de fichiers **TypeScript** ou **JavaScript**. Cependant, la définition de l'outil peut appeler des scripts écrits dans **n'importe quel langage** : TypeScript ou JavaScript n'est utilisé que pour la définition de l'outil elle-même. + +--- + +### Emplacement + +Ils peuvent être définis : + +- Localement en les plaçant dans le répertoire `.opencode/tools/` de votre projet. +- Ou globalement, en les plaçant dans `~/.config/opencode/tools/`. + +--- + +### Structure + +Le moyen le plus simple de créer des outils consiste à utiliser l'assistant `tool()` qui fournit la sécurité et la validation du type. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +Le **nom de fichier** devient le **nom de l'outil**. Ce qui précède crée un outil `database`. + +--- + +#### Plusieurs outils par fichier + +Vous pouvez également exporter plusieurs outils à partir d'un seul fichier. Chaque exportation devient **un outil distinct** portant le nom **`_`** : + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +Cela crée deux outils : `math_add` et `math_multiply`. + +--- + +### Arguments + +Vous pouvez utiliser `tool.schema`, qui est simplement [Zod](https://zod.dev), pour définir les types d'arguments. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +Vous pouvez également importer [Zod](https://zod.dev) directement et renvoyer un objet simple : + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### Contexte + +Les outils reçoivent du contexte sur la session en cours : + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +Utilisez `context.directory` pour le répertoire de travail de la session. +Utilisez `context.worktree` pour la racine de git worktree. + +--- + +## Exemples + +### Écrire un outil en Python + +Vous pouvez écrire vos outils dans la langue de votre choix. Voici un exemple qui ajoute deux nombres à l'aide de Python. + +Tout d'abord, créez l'outil en tant que script Python : + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +Créez ensuite la définition d'outil qui l'invoque : + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +Ici, nous utilisons l'utilitaire [`Bun.$`](https://bun.com/docs/runtime/shell) pour exécuter le script Python. diff --git a/packages/web/src/content/docs/fr/ecosystem.mdx b/packages/web/src/content/docs/fr/ecosystem.mdx new file mode 100644 index 000000000..8792c25fa --- /dev/null +++ b/packages/web/src/content/docs/fr/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: Écosystème +description: Projets et intégrations construits avec OpenCode. +--- + +Une collection de projets communautaires construits sur OpenCode. + +:::note +Vous souhaitez ajouter votre projet lié à OpenCode à cette liste ? Soumettez un PR. +::: + +Vous pouvez également consulter [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) et [opencode.cafe](https://opencode.cafe), une communauté qui regroupe l'écosystème et la communauté. + +--- + +## Plugins + +| Nom | Descriptif | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | Exécutez automatiquement des sessions OpenCode dans des sandbox Daytona isolés avec synchronisation git et aperçus en direct | +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Injecter automatiquement les en-têtes de session Helicone pour le regroupement des requêtes | +| [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Injectez automatiquement les types TypeScript/Svelte dans les lectures de fichiers avec des outils de recherche | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Utilisez votre abonnement ChatGPT Plus/Pro au lieu de crédits API | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Utilisez votre forfait Gemini existant au lieu de la facturation API | +| [opencode-antigravité-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Utilisez les modèles gratuits d'Antigravity au lieu de la facturation API | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Isolation de conteneur de développement multibranche avec clones superficiels et ports attribués automatiquement | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Plugin Google Antigravity OAuth, avec prise en charge de la recherche Google et gestion API plus robuste | +| [opencode-élagage-de-contexte-dynamique](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Optimisez l'utilisation des jetons en éliminant les sorties d'outils obsolètes | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Ajoutez la prise en charge native de la recherche Web pour les fournisseurs pris en charge avec le style ancré par Google | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Permet aux agents IA d'exécuter des processus en arrière-plan dans un PTY et de leur envoyer des entrées interactives. | +| [opencode-shell-stratégie](https://github.com/JRedeker/opencode-shell-strategy) | Instructions pour les commandes shell non interactives - empêche les blocages des opérations dépendantes du téléscripteur | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Suivez l'utilisation de OpenCode avec Wakatime | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Nettoyer les tableaux de démarques produits par les LLM | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | Édition de code 10 fois plus rapide avec Morph Fast Apply API et les marqueurs d'édition différée | +| [oh-mon-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Agents d'arrière-plan, outils LSP/AST/MCP prédéfinis, agents sélectionnés, compatibles Claude Code | +| [opencode-notificateur](https://github.com/panta82/opencode-notificator) | Notifications de bureau et alertes sonores pour les sessions OpenCode | +| [opencode-notificateur](https://github.com/mohak34/opencode-notifier) | Notifications sur le bureau et alertes sonores pour les événements d'autorisation, d'achèvement et d'erreur | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | Dénomination automatique de session Zellij basée sur l'IA basée sur le contexte OpenCode | +| [opencode-habile](https://github.com/zenobi-us/opencode-skillful) | Autoriser les agents OpenCode à charger paresseusement les invites à la demande grâce à la découverte et à l'injection de compétences | +| [opencode-supermémoire](https://github.com/supermemoryai/opencode-supermemory) | Mémoire persistante entre les sessions utilisant Supermemory | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Révision interactive du plan avec annotation visuelle et partage privé/hors ligne | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Étendez opencode /commands dans un système d'orchestration puissant avec contrôle de flux granulaire | +| [opencode-planificateur](https://github.com/different-ai/opencode-scheduler) | Planifiez des tâches récurrentes à l'aide de launchd (Mac) ou systemd (Linux) avec la syntaxe cron | +| [micode](https://github.com/vtemian/micode) | Brainstorming structuré → Planifier → Mettre en œuvre un workflow avec continuité de session | +| [octo](https://github.com/vtemian/octto) | Interface utilisateur de navigateur interactive pour le brainstorming IA avec des formulaires multi-questions | +| [opencode-agents-de-fond](https://github.com/kdcokenny/opencode-background-agents) | Agents d'arrière-plan de style Claude Code avec délégation asynchrone et persistance du contexte | +| [opencode-notifier](https://github.com/kdcokenny/opencode-notify) | Notifications natives du système d'exploitation pour OpenCode – savoir quand les tâches sont terminées | +| [opencode-espace de travail](https://github.com/kdcokenny/opencode-workspace) | Harnais d'orchestration multi-agents fourni – 16 composants, une installation | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Arbres de travail Git sans friction pour OpenCode | + +--- + +## Projets + +| Nom | Descriptif | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | Bot Discord pour contrôler les sessions OpenCode, construit sur le SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Plugin Neovim pour les invites compatibles avec l'éditeur, construit sur API | +| [portail](https://github.com/hosenur/portal) | Interface utilisateur Web axée sur les mobiles pour OpenCode sur Tailscale/VPN | +| [Modèle de plug-in opencode](https://github.com/zenobi-us/opencode-plugin-template/) | Modèle pour créer des plugins OpenCode | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Frontend Neovim pour opencode - un agent de codage d'IA basé sur un terminal | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Fournisseur Vercel AI SDK pour l'utilisation de OpenCode via @opencode-ai/sdk | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | Application Web/De bureau et extension VS Code pour OpenCode | +| [OpenCode-Obsidienne](https://github.com/mtymek/opencode-obsidian) | Plugin Obsidian qui intègre OpenCode dans l'interface utilisateur d'Obsidian | +| [OpenWork](https://github.com/different-ai/openwork) | Une alternative open source à Claude Cowork, propulsée par OpenCode | +| [ocx](https://github.com/kdcokenny/ocx) | Gestionnaire d'extensions OpenCode avec profils portables et isolés. | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Application client de bureau, Web, mobile et distante pour OpenCode | + +--- + +## Agents + +| Nom | Descriptif | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [Agent](https://github.com/Cluster444/agentic) | Agents et commandes d'IA modulaires pour un développement structuré | +| [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Configurations, invites, agents et plug-ins pour des flux de travail améliorés | diff --git a/packages/web/src/content/docs/fr/enterprise.mdx b/packages/web/src/content/docs/fr/enterprise.mdx new file mode 100644 index 000000000..4121fd304 --- /dev/null +++ b/packages/web/src/content/docs/fr/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: Entreprise +description: Utiliser OpenCode en toute sécurité dans votre organisation. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise est destiné aux organisations qui souhaitent s'assurer que leur code et leurs données ne quittent jamais leur infrastructure. Il peut le faire en utilisant une configuration centralisée qui s'intègre à votre SSO et à votre passerelle IA interne. + +:::note +OpenCode ne stocke aucune de vos données de code ou de contexte. +::: + +Pour démarrer avec OpenCode Enterprise : + +1. Faites un essai en interne avec votre équipe. +2. **Contactez-nous** pour discuter des options de tarification et de mise en œuvre. + +--- + +## Procès + +OpenCode est open source et ne stocke aucune de vos données de code ou de contexte, vos développeurs peuvent donc simplement [commencer ](/docs/) et effectuer un essai. + +--- + +### Traitement des données + +**OpenCode ne stocke pas votre code ni vos données contextuelles.** Tous les traitements s'effectuent localement ou via des appels API directs à votre fournisseur d'IA. + +Cela signifie que tant que vous faites appel à un fournisseur de confiance ou à un +Passerelle AI, vous pouvez utiliser OpenCode en toute sécurité. + +La seule mise en garde ici concerne la fonctionnalité facultative `/share`. + +--- + +#### Partager des conversations + +Si un utilisateur active la fonctionnalité `/share`, la conversation et les données qui y sont associées sont envoyées au service que nous utilisons pour héberger ces pages de partage sur opencode.ai. + +Les données sont actuellement servies via le réseau périphérique de notre CDN et sont mises en cache en périphérie, à proximité de vos utilisateurs. + +Nous vous recommandons de désactiver cette option pour votre essai. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[En savoir plus sur le partage](/docs/share). + +--- + +### Propriété du code + +**Vous possédez tout le code produit par OpenCode.** Il n'y a aucune restriction de licence ni revendication de propriété. + +--- + +## Tarifs + +Nous utilisons un modèle par siège pour OpenCode Enterprise. Si vous disposez de votre propre passerelle LLM, nous ne facturons pas les jetons utilisés. Pour plus de détails sur les options de tarification et de mise en œuvre, **contactez-nous**. + +--- + +## Déploiement + +Une fois que vous avez terminé votre essai et que vous êtes prêt à utiliser OpenCode à +votre organisation, vous pouvez **nous contacter** pour en discuter +options de tarification et de mise en œuvre. + +--- + +### Configuration centrale + +Nous pouvons configurer OpenCode pour utiliser une seule configuration centrale pour l'ensemble de votre organisation. + +Cette configuration centralisée peut s'intégrer à votre fournisseur SSO et garantit que tous les utilisateurs accèdent uniquement à votre passerelle IA interne. + +--- + +### Intégration SSO + +Grâce à la configuration centrale, OpenCode peut s'intégrer au fournisseur SSO de votre organisation pour l'authentification. + +Cela permet à OpenCode d'obtenir les informations d'identification de votre passerelle IA interne via votre système de gestion des identités existant. + +--- + +### Passerelle IA interne + +Avec la configuration centrale, OpenCode peut également être configuré pour utiliser uniquement votre passerelle IA interne. + +Vous pouvez également désactiver tous les autres fournisseurs d'IA, en vous assurant que toutes les demandes transitent par l'infrastructure approuvée de votre organisation. + +--- + +### Auto-hébergement + +Bien que nous vous recommandons de désactiver les pages de partage pour garantir que vos données ne quittent jamais +votre organisation, nous pouvons également vous aider à les auto-héberger sur votre infrastructure. + +Ceci est actuellement sur notre feuille de route. Si vous êtes intéressé, **faites-le-nous savoir**. + +--- + +## FAQ + +

+Qu’est-ce que OpenCode Entreprise ? + +OpenCode Enterprise est destiné aux organisations qui souhaitent s'assurer que leur code et leurs données ne quittent jamais leur infrastructure. Il peut le faire en utilisant une configuration centralisée qui s'intègre à votre SSO et à votre passerelle IA interne. + +
+ +
+Comment démarrer avec OpenCode Enterprise ? + +Commencez simplement par un essai interne avec votre équipe. OpenCode par défaut ne stocke pas votre code ni vos données contextuelles, ce qui facilite le démarrage. + +Ensuite, **contactez-nous** pour discuter des options de tarification et de mise en œuvre. + +
+ +
+Comment fonctionne la tarification d'entreprise ? + +Nous proposons des tarifs d'entreprise par siège. Si vous disposez de votre propre passerelle LLM, nous ne facturons pas les jetons utilisés. Pour plus de détails, **contactez-nous** pour un devis personnalisé basé sur les besoins de votre organisation. + +
+ +
+Mes données sont-elles sécurisées avec OpenCode Enterprise ? + +Oui. OpenCode ne stocke pas votre code ni vos données contextuelles. Tout le traitement s'effectue localement ou via des appels API directs à votre fournisseur d'IA. Grâce à la configuration centrale et à l'intégration SSO, vos données restent sécurisées au sein de l'infrastructure de votre organisation. + +
+ +
+Pouvons-nous utiliser notre propre registre privé NPM ? + +OpenCode prend en charge les registres npm privés via la prise en charge native des fichiers `.npmrc` de Bun. Si votre organisation utilise un registre privé, tel que JFrog Artifactory, Nexus ou similaire, assurez-vous que les développeurs sont authentifiés avant d'exécuter OpenCode. + +Pour configurer l'authentification avec votre registre privé : + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +Cela crée `~/.npmrc` avec les détails d'authentification. OpenCode sera automatiquement +ramasse ça. + +:::caution +Vous devez être connecté au registre privé avant d'exécuter OpenCode. +::: + +Alternativement, vous pouvez configurer manuellement un fichier `.npmrc` : + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Les développeurs doivent être connectés au registre privé avant d'exécuter OpenCode pour garantir que les packages peuvent être installés à partir du registre de votre entreprise. + +
diff --git a/packages/web/src/content/docs/fr/formatters.mdx b/packages/web/src/content/docs/fr/formatters.mdx new file mode 100644 index 000000000..7d7551ffb --- /dev/null +++ b/packages/web/src/content/docs/fr/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: Formateurs +description: OpenCode utilise des formateurs spécifiques à la langue. +--- + +OpenCode formate automatiquement les fichiers après leur écriture ou leur modification à l'aide de formateurs spécifiques à la langue. Cela garantit que le code généré suit les styles de code de votre projet. + +--- + +## Intégré + +OpenCode est livré avec plusieurs formateurs intégrés pour les langages et frameworks populaires. Vous trouverez ci-dessous une liste des formateurs, des extensions de fichiers prises en charge et des commandes ou options de configuration dont il a besoin. + +| Formateur | Rallonges | Exigences | +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| gofmt | .aller | Commande `gofmt` disponible | +| mélanger | .ex, .exs, .eex, .heex, .leex, .neex, .sface | Commande `mix` disponible | +| plus jolie | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml et [plus](https://prettier.io/docs/en/index.html) | Dépendance `prettier` dans `package.json` | +| biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml et [plus](https://biomejs.dev/) | Fichier de configuration `biome.json(c)` | +| zigzag | .zig, .zon | Commande `zig` disponible | +| format clang | .c, .cpp, .h, .hpp, .ino et [plus](https://clang.llvm.org/docs/ClangFormat.html) | Fichier de configuration `.clang-format` | +| klint | .kt, .kts | Commande `ktlint` disponible | +| fraise | .py, .pyi | Commande `ruff` disponible avec config | +| rustfmt | .rs | Commande `rustfmt` disponible | +| fret | .rs | Commande `cargo fmt` disponible | +| UV | .py, .pyi | Commande `uv` disponible | +| rubocop | .rb, .rake, .gemspec, .ru | Commande `rubocop` disponible | +| normerb | .rb, .rake, .gemspec, .ru | Commande `standardrb` disponible | +| htmlbeautifier | .erb, .html.erb | Commande `htmlbeautifier` disponible | +| air | .R | Commande `air` disponible | +| fléchette | .dart | Commande `dart` disponible | +| format ocaml | .ml, .mli | Commande `ocamlformat` disponible et fichier de configuration `.ocamlformat` | +| terraformer | .tf, .tfvars | Commande `terraform` disponible | +| lueur | .lueur | Commande `gleam` disponible | +| nixfmt | .nix | Commande `nixfmt` disponible | +| shfmt | .sh, .bash | Commande `shfmt` disponible | +| pinte | .php | Dépendance `laravel/pint` dans `composer.json` | +| oxfmt (expérimental) | .js, .jsx, .ts, .tsx | Dépendance `oxfmt` dans `package.json` et un [flag de variable d'environnement expérimental](/docs/cli/#experimental) | +| bronze doré | .hs | Commande `ormolu` disponible | + +Ainsi, si votre projet a `prettier` dans votre `package.json`, OpenCode l'utilisera automatiquement. + +--- + +## Comment ça marche + +Lorsque OpenCode écrit ou modifie un fichier, il : + +1. Vérifie l'extension du fichier par rapport à tous les formateurs activés. +2. Exécute la commande de formatage appropriée sur le fichier. +3. Applique automatiquement les modifications de formatage. + +Ce processus se déroule en arrière-plan, garantissant que vos styles de code sont conservés sans aucune étape manuelle. + +--- + +## Configurer + +Vous pouvez personnaliser les formateurs via la section `formatter` de votre configuration OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +Chaque configuration du formateur prend en charge les éléments suivants : + +| Propriété | Tapez | Descriptif | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` | booléen | Définissez ceci sur `true` pour désactiver le formateur | +| `command` | chaîne[] | La commande à exécuter pour le formatage | +| `environment` | objet | Variables d'environnement à définir lors de l'exécution du formateur | +| `extensions` | chaîne[] | Extensions de fichiers que ce formateur doit gérer | + +Regardons quelques exemples. + +--- + +### Désactivation des formateurs + +Pour désactiver **tous** les formateurs globalement, définissez `formatter` sur `false` : + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +Pour désactiver un formateur **spécifique**, définissez `disabled` sur `true` : + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Formateurs personnalisés + +Vous pouvez remplacer les formateurs intégrés ou en ajouter de nouveaux en spécifiant la commande, les variables d'environnement et les extensions de fichier : + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +L'espace réservé **`$FILE`** dans la commande sera remplacé par le chemin d'accès au fichier en cours de formatage. diff --git a/packages/web/src/content/docs/fr/github.mdx b/packages/web/src/content/docs/fr/github.mdx new file mode 100644 index 000000000..90fe3b9c2 --- /dev/null +++ b/packages/web/src/content/docs/fr/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: Utilisez OpenCode dans les problèmes et les pull-requests GitHub. +--- + +OpenCode s'intègre à votre flux de travail GitHub. Mentionnez `/opencode` ou `/oc` dans votre commentaire, et OpenCode exécutera des tâches dans votre coureur d'actions GitHub. + +--- + +## Caractéristiques + +- **Problèmes de triage** : demandez à OpenCode d'examiner un problème et de vous l'expliquer. +- **Réparer et implémenter** : demandez à OpenCode de résoudre un problème ou d'implémenter une fonctionnalité. Et il fonctionnera dans une nouvelle branche et soumettra un PR avec tous les changements. +- **Sécurisé** : OpenCode court à l'intérieur des coureurs de votre GitHub. + +--- + +## Installation + +Exécutez la commande suivante dans un projet qui se trouve dans un dépôt GitHub : + +```bash +opencode github install +``` + +Cela vous guidera dans l'installation de l'application GitHub, la création du flux de travail et la configuration des secrets. + +--- + +### Configuration manuelle + +Ou vous pouvez le configurer manuellement. + +1. **Installez l'application GitHub** + +Rendez-vous sur [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). Assurez-vous qu'il est installé sur le référentiel cible. + +2. **Ajouter le flux de travail** + +Ajoutez le fichier de workflow suivant à `.github/workflows/opencode.yml` dans votre référentiel. Assurez-vous de définir les clés `model` appropriées et API requises dans `env`. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **Stockez les clés API en secret** + +Dans les **paramètres** de votre organisation ou de votre projet, développez **Secrets et variables** sur la gauche et sélectionnez **Actions**. Et ajoutez les clés API requises. + +--- + +## Configuration + +- `model` : Le modèle à utiliser avec OpenCode. Prend le format `provider/model`. Ceci est **obligatoire**. +- `agent` : l'agent à utiliser. Doit être un agent principal. Revient à `default_agent` à partir de la configuration ou à `"build"` s'il n'est pas trouvé. +- `share` : s'il faut partager la session OpenCode. La valeur par défaut est **true** pour les référentiels publics. +- `prompt` : invite personnalisée facultative pour remplacer le comportement par défaut. Utilisez-le pour personnaliser la façon dont OpenCode traite les demandes. +- `token` : jeton d'accès GitHub facultatif pour effectuer des opérations telles que la création de commentaires, la validation de modifications et l'ouverture de demandes d'extraction. Par défaut, OpenCode utilise le jeton d'accès à l'installation de l'application OpenCode GitHub, de sorte que les validations, les commentaires et les demandes d'extraction apparaissent comme provenant de l'application. + +Vous pouvez également utiliser le `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) intégré du GitHub Action Runner sans installer l'application OpenCode GitHub. Assurez-vous simplement d'accorder les autorisations requises dans votre flux de travail : + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + +Vous pouvez également utiliser un [jetons d'accès personnels](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) si vous préférez. + +--- + +## Événements pris en charge + +OpenCode peut être déclenché par les événements GitHub suivants : + +| Type d'événement | Déclenché par | Détails | +| ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | Commenter un problème ou un PR | Mentionnez `/opencode` ou `/oc` dans votre commentaire. OpenCode lit le contexte et peut créer des branches, ouvrir des PR ou répondre. | +| `pull_request_review_comment` | Commentez des lignes de code spécifiques dans un PR | Mentionnez `/opencode` ou `/oc` lors de la révision du code. OpenCode reçoit le chemin du fichier, les numéros de ligne et le contexte de comparaison. | +| `issues` | Numéro ouvert ou modifié | Déclenchez automatiquement OpenCode lorsque des problèmes sont créés ou modifiés. Nécessite une entrée `prompt`. | +| `pull_request` | PR ouvert ou mis à jour | Déclenchez automatiquement OpenCode lorsque les PR sont ouverts, synchronisés ou rouverts. Utile pour les avis automatisés. | +| `schedule` | Planification basée sur Cron | Exécutez OpenCode selon un planning. Nécessite une entrée `prompt`. La sortie va aux journaux et aux PR (aucun problème à commenter). | +| `workflow_dispatch` | Déclenchement manuel depuis l'interface utilisateur GitHub | Déclenchez OpenCode à la demande via l'onglet Actions. Nécessite une entrée `prompt`. La sortie va aux journaux et aux PR. | + +### Exemple d'horaire + +Exécutez OpenCode selon un planning pour effectuer des tâches automatisées : + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +Pour les événements planifiés, l'entrée `prompt` est **obligatoire** car il n'y a aucun commentaire pour extraire les instructions. Les workflows planifiés s'exécutent sans contexte utilisateur pour vérifier les autorisations. Le workflow doit donc accorder `contents: write` et `pull-requests: write` si vous vous attendez à ce que OpenCode crée des branches ou des PR. + +--- + +### Exemple de demande de tirage + +Examinez automatiquement les PR lorsqu'ils sont ouverts ou mis à jour : + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Pour les événements `pull_request`, si aucun `prompt` n'est fourni, OpenCode examine par défaut la demande d'extraction. + +--- + +### Exemple de tri des problèmes + +Triez automatiquement les nouveaux problèmes. Cet exemple filtre les comptes datant de plus de 30 jours pour réduire le spam : + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +Pour les événements `issues`, l'entrée `prompt` est **obligatoire** car il n'y a aucun commentaire à partir duquel extraire les instructions. + +--- + +## Invites personnalisées + +Remplacez l'invite par défaut pour personnaliser le comportement de OpenCode pour votre flux de travail. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Ceci est utile pour appliquer des critères d’évaluation spécifiques, des normes de codage ou des domaines d’intervention pertinents pour votre projet. + +--- + +## Exemples + +Voici quelques exemples de la façon dont vous pouvez utiliser OpenCode dans GitHub. + +- **Expliquez un problème** + +Ajoutez ce commentaire dans un numéro GitHub. + + ``` + /opencode explain this issue + ``` + +OpenCode lira l'intégralité du fil de discussion, y compris tous les commentaires, et répondra avec une explication claire. + +- **Résoudre un problème** + +Dans un numéro GitHub, dites : + + ``` + /opencode fix this + ``` + +Et OpenCode créera une nouvelle branche, mettra en œuvre les modifications et ouvrira un PR avec les modifications. + +- **Examinez les PR et apportez des modifications** + +Laissez le commentaire suivant sur un PR GitHub. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + +OpenCode mettra en œuvre la modification demandée et la validera dans le même PR. + +- **Revoir des lignes de code spécifiques** + +Laissez un commentaire directement sur les lignes de code dans l'onglet "Fichiers" du PR. OpenCode détecte automatiquement le fichier, les numéros de ligne et le contexte de comparaison pour fournir des réponses précises. + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + +Lorsqu'il commente des lignes spécifiques, OpenCode reçoit : + - Le dossier exact en cours d'examen + - Les lignes de code spécifiques + - Le contexte différentiel environnant + - Informations sur le numéro de ligne + +Cela permet des requêtes plus ciblées sans avoir besoin de spécifier manuellement les chemins de fichiers ou les numéros de ligne. diff --git a/packages/web/src/content/docs/fr/gitlab.mdx b/packages/web/src/content/docs/fr/gitlab.mdx new file mode 100644 index 000000000..8a630c2cb --- /dev/null +++ b/packages/web/src/content/docs/fr/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: Utilisez OpenCode dans les problèmes GitLab et les demandes de fusion. +--- + +OpenCode s'intègre à votre flux de travail GitLab via votre pipeline CI/CD GitLab ou avec GitLab Duo. + +Dans les deux cas, OpenCode fonctionnera sur vos coureurs GitLab. + +--- + +## GitLab CI + +OpenCode fonctionne dans un pipeline GitLab régulier. Vous pouvez l'intégrer dans un pipeline en tant que [composant CI](https://docs.gitlab.com/ee/ci/components/) + +Ici, nous utilisons un composant CI/CD créé par la communauté pour OpenCode — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### Caractéristiques + +- **Utiliser une configuration personnalisée par tâche** : configurez OpenCode avec un répertoire de configuration personnalisé, par exemple `./config/#custom-directory` pour activer ou désactiver la fonctionnalité par appel OpenCode. +- **Configuration minimale** : le composant CI configure OpenCode en arrière-plan, il vous suffit de créer la configuration OpenCode et l'invite initiale. +- **Flexible** : le composant CI prend en charge plusieurs entrées pour personnaliser son comportement + +--- + +### Installation + +1. Stockez votre authentification OpenCode JSON en tant que variables d'environnement CI de type fichier sous **Paramètres** > **CI/CD** > **Variables**. Assurez-vous de les marquer comme « Masqués et cachés ». +2. Ajoutez ce qui suit à votre fichier `.gitlab-ci.yml`. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +Pour plus d'entrées et de cas d'utilisation [consultez la docs](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) pour ce composant. + +--- + +## GitLab Duo + +OpenCode s'intègre à votre flux de travail GitLab. +Mentionnez `@opencode` dans un commentaire et OpenCode exécutera les tâches au sein de votre pipeline CI GitLab. + +--- + +### Caractéristiques + +- **Problèmes de triage** : demandez à OpenCode d'examiner un problème et de vous l'expliquer. +- **Réparer et implémenter** : demandez à OpenCode de résoudre un problème ou d'implémenter une fonctionnalité. +Cela créera une nouvelle branche et déclenchera une demande de fusion avec les modifications. +- **Sécurisé** : OpenCode fonctionne sur vos coureurs GitLab. + +--- + +### Installation + +OpenCode s'exécute dans votre pipeline CI/CD GitLab. Voici ce dont vous aurez besoin pour le configurer : + +:::tip +Consultez les [**GitLab docs**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) pour obtenir des instructions à jour. +::: + +1. Configurez votre environnement GitLab +2. Configurer CI/CD +3. Obtenez la clé API d'un fournisseur de modèles d'IA +4. Créer un compte de service +5. Configurer les variables CI/CD +6. Créez un fichier de configuration de flux, voici un exemple : + +
+ + Configuration du flux + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +Vous pouvez vous référer aux [GitLab CLI agents docs](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) pour des instructions détaillées. + +--- + +### Exemples + +Voici quelques exemples de la façon dont vous pouvez utiliser OpenCode dans GitLab. + +:::tip +Vous pouvez configurer pour utiliser une phrase de déclenchement différente de `@opencode`. +::: + +- **Expliquez un problème** + +Ajoutez ce commentaire dans un numéro GitLab. + + ``` + @opencode explain this issue + ``` + +OpenCode lira le problème et répondra avec une explication claire. + +- **Résoudre un problème** + +Dans un numéro GitLab, dites : + + ``` + @opencode fix this + ``` + +OpenCode créera une nouvelle branche, mettra en œuvre les modifications et ouvrira une demande de fusion avec les modifications. + +- **Examiner les demandes de fusion** + +Laissez le commentaire suivant sur une demande de fusion GitLab. + + ``` + @opencode review this merge request + ``` + +OpenCode examinera la demande de fusion et fournira des commentaires. diff --git a/packages/web/src/content/docs/fr/ide.mdx b/packages/web/src/content/docs/fr/ide.mdx new file mode 100644 index 000000000..74551fc6b --- /dev/null +++ b/packages/web/src/content/docs/fr/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: L'extension OpenCode pour VS Code, Cursor et autres IDE +--- + +OpenCode s'intègre à VS Code, Cursor ou tout IDE prenant en charge un terminal. Exécutez simplement `opencode` dans le terminal pour commencer. + +--- + +## Usage + +- **Lancement rapide** : utilisez `Cmd+Esc` (Mac) ou `Ctrl+Esc` (Windows/Linux) pour ouvrir OpenCode dans une vue de terminal divisée, ou concentrez-vous sur une session de terminal existante si elle est déjà en cours d'exécution. +- **Nouvelle session** : utilisez `Cmd+Shift+Esc` (Mac) ou `Ctrl+Shift+Esc` (Windows/Linux) pour démarrer une nouvelle session de terminal OpenCode, même si elle est déjà ouverte. Vous pouvez également cliquer sur le bouton OpenCode dans l'interface utilisateur. +- **Conscience du contexte** : partagez automatiquement votre sélection ou onglet actuel avec OpenCode. +- **Raccourcis de référence de fichier** : utilisez `Cmd+Option+K` (Mac) ou `Alt+Ctrl+K` (Linux/Windows) pour insérer des références de fichier. Par exemple, `@File#L37-42`. + +--- + +## Installation + +Pour installer OpenCode sur VS Code et les forks populaires comme Cursor, Windsurf, VSCodium : + +1. Ouvrir VS Code +2. Ouvrez le terminal intégré +3. Exécutez `opencode` - l'extension s'installe automatiquement + +Si, d'un autre côté, vous souhaitez utiliser votre propre IDE lorsque vous exécutez `/editor` ou `/export` à partir du TUI, vous devrez définir `export EDITOR="code --wait"`. [En savoir plus](/docs/tui/#editor-setup). + +--- + +### Installation manuelle + +Recherchez **OpenCode** dans Extension Marketplace et cliquez sur **Installer**. + +--- + +### Dépannage + +Si l'extension ne parvient pas à s'installer automatiquement : + +- Assurez-vous que vous exécutez `opencode` dans le terminal intégré. +- Confirmez que la CLI de votre IDE est installée : + - Pour VS Code : commande `code` + - Pour le curseur : commande `cursor` + - Pour la planche à voile : commande `windsurf` + - Pour VSCodium : commande `codium` + - Sinon, exécutez `Cmd+Shift+P` (Mac) ou `Ctrl+Shift+P` (Windows/Linux) et recherchez « Commande Shell : installez la commande 'code' dans PATH » (ou l'équivalent pour votre IDE) +- Assurez-vous que VS Code est autorisé à installer des extensions diff --git a/packages/web/src/content/docs/fr/index.mdx b/packages/web/src/content/docs/fr/index.mdx new file mode 100644 index 000000000..9024afb7b --- /dev/null +++ b/packages/web/src/content/docs/fr/index.mdx @@ -0,0 +1,359 @@ +--- +title: Introduction +description: Commencez avec OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) est un agent de codage d'IA open source. Il est disponible sous forme d'interface basée sur un terminal, d'application de bureau ou d'extension IDE. + +![OpenCode TUI avec le thème opencode](../../../assets/lander/screenshot.png) + +Commençons. + +--- + +#### Conditions préalables + +Pour utiliser OpenCode dans votre terminal, vous aurez besoin de : + +1. Un émulateur de terminal moderne comme : + - [WezTerm](https://wezterm.org), multiplateforme + - [Alacritty](https://alacritty.org), multiplateforme + - [Ghostty](https://ghostty.org), Linux et macOS + - [Kitty](https://sw.kovidgoyal.net/kitty/), Linux et macOS + +2. Clés API pour les fournisseurs LLM que vous souhaitez utiliser. + +--- + +## Installer + +Le moyen le plus simple d'installer OpenCode consiste à utiliser le script d'installation. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +Vous pouvez également l'installer avec les commandes suivantes : + +- **En utilisant Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **Utilisation de Homebrew sur macOS et Linux** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > Nous vous recommandons d'utiliser le tap OpenCode pour les versions les plus récentes. La formule officielle `brew install opencode` est maintenue par l'équipe Homebrew et est mise à jour moins fréquemment. + +- **Utilisation de Paru sur Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### Windows + +:::tip[Recommandé : utilisez WSL] +Pour une expérience optimale sur Windows, nous vous recommandons d'utiliser le sous-système [Windows pour Linux (WSL)](/docs/windows-wsl). Il offre de meilleures performances et une compatibilité totale avec les fonctionnalités de OpenCode. +::: + +- **Utiliser Chocolatey** + + ```bash + choco install opencode + ``` + +- **Utilisation de Scoop** + + ```bash + scoop install opencode + ``` + +- **En utilisant NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **Utiliser Mise** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **En utilisant Docker** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +La prise en charge de l'installation de OpenCode sur Windows à l'aide de Bun est actuellement en cours. + +Vous pouvez également récupérer le binaire dans le fichier [Releases](https://github.com/anomalyco/opencode/releases). + +--- + +## Configurer + +Avec OpenCode, vous pouvez utiliser n'importe quel fournisseur LLM en configurant ses clés API. + +Si vous débutez avec les fournisseurs LLM, nous vous recommandons d'utiliser [OpenCode Zen](/docs/zen). +Il s'agit d'une liste organisée de modèles qui ont été testés et vérifiés par le OpenCode +équipe. + +1. Exécutez la commande `/connect` dans le TUI, sélectionnez opencode et dirigez-vous vers [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Connectez-vous, ajoutez vos informations de facturation et copiez votre clé API. + +3. Collez votre clé API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +Vous pouvez également sélectionner l'un des autres fournisseurs. [En savoir plus](/docs/providers#directory). + +--- + +## Initialiser + +Maintenant que vous avez configuré un fournisseur, vous pouvez accéder à un projet qui +vous voulez travailler. + +```bash +cd /path/to/project +``` + +Et exécutez OpenCode. + +```bash +opencode +``` + +Ensuite, initialisez OpenCode pour le projet en exécutant la commande suivante. + +```bash frame="none" +/init +``` + +Cela permettra à OpenCode d'analyser votre projet et de créer un fichier `AGENTS.md` dans +la racine du projet. + +:::tip +Vous devez valider le fichier `AGENTS.md` de votre projet dans Git. +::: + +Cela aide OpenCode à comprendre la structure du projet et les modèles de codage +utilisé. + +--- + +## Usage + +Vous êtes maintenant prêt à utiliser OpenCode pour travailler sur votre projet. N'hésitez pas à le demander +rien! + +Si vous débutez dans l'utilisation d'un agent de codage IA, voici quelques exemples qui pourraient +aide. + +--- + +### Posez des questions + +Vous pouvez demander à OpenCode de vous expliquer la base de code. + +:::tip +Utilisez la touche `@` pour effectuer une recherche floue de fichiers dans le projet. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +Ceci est utile s'il y a une partie de la base de code sur laquelle vous n'avez pas travaillé. + +--- + +### Ajouter des fonctionnalités + +Vous pouvez demander à OpenCode d'ajouter de nouvelles fonctionnalités à votre projet. Cependant, nous recommandons d’abord de lui demander de créer un plan. + +1. **Créer un plan** + +OpenCode dispose d'un _Mode Plan_ qui désactive sa capacité à apporter des modifications et +suggérez plutôt _comment_ il implémentera la fonctionnalité. + +Accédez-y à l'aide de la touche **Tab**. Vous verrez un indicateur à cet effet dans le coin inférieur droit. + +```bash frame="none" title="Switch to Plan mode" + +``` + +Décrivons maintenant ce que nous voulons qu'il fasse. + +```txt frame="none" +When a user deletes a note, we'd like to flag it as deleted in the database. +Then create a screen that shows all the recently deleted notes. +From this screen, the user can undelete a note or permanently delete it. +``` + +Vous souhaitez donner à OpenCode suffisamment de détails pour comprendre ce que vous voulez. Ça aide +pour lui parler comme si vous parliez à un développeur junior de votre équipe. + +:::tip +Donnez à OpenCode beaucoup de contexte et d'exemples pour l'aider à comprendre ce que vous +vouloir. +::: + +2. **Itérer sur le plan** + +Une fois qu'il vous donne un plan, vous pouvez lui faire part de vos commentaires ou ajouter plus de détails. + +```txt frame="none" +We'd like to design this new screen using a design I've used before. +[Image #1] Take a look at this image and use it as a reference. +``` + +:::tip +Faites glisser et déposez des images dans le terminal pour les ajouter à l'invite. +::: + +OpenCode peut numériser toutes les images que vous lui donnez et les ajouter à l'invite. Tu peux +faites-le en faisant glisser et en déposant une image dans le terminal. + +3. **Créez la fonctionnalité** + +Une fois que vous vous sentez à l'aise avec le plan, revenez au _Mode Construction_ en +appuyer à nouveau sur la touche **Tab**. + +```bash frame="none" + +``` + +Et lui demander d'apporter les modifications. + +```bash frame="none" +Sounds good! Go ahead and make the changes. +``` + +--- + +### Apporter des modifications + +Pour des modifications plus simples, vous pouvez demander à OpenCode de le construire directement +sans avoir à revoir le plan au préalable. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +Vous voulez vous assurer de fournir une bonne quantité de détails afin que OpenCode fasse le bon choix. +changements. + +--- + +### Annuler les modifications + +Disons que vous demandez à OpenCode d'apporter quelques modifications. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Mais vous réalisez que ce n’est pas ce que vous vouliez. Vous **pouvez annuler** les modifications +à l'aide de la commande `/undo`. + +```bash frame="none" +/undo +``` + +OpenCode annulera désormais les modifications que vous avez apportées et affichera votre message d'origine +encore. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +À partir de là, vous pouvez modifier l'invite et demander à OpenCode de réessayer. + +:::tip +Vous pouvez exécuter `/undo` plusieurs fois pour annuler plusieurs modifications. +::: + +Ou vous **pouvez refaire** les modifications à l'aide de la commande `/redo`. + +```bash frame="none" +/redo +``` + +--- + +## Partager + +Les conversations que vous avez avec OpenCode peuvent être [partagées avec votre +équipe](/docs/share). + +```bash frame="none" +/share +``` + +Cela créera un lien vers la conversation en cours et le copiera dans votre presse-papiers. + +:::note +Les conversations ne sont pas partagées par défaut. +::: + +Voici un [exemple de conversation](https://opencode.ai/s/4XP1fce5) avec OpenCode. + +--- + +## Personnaliser + +Et c'est tout ! Vous êtes désormais un pro de l'utilisation de OpenCode. + +Pour vous l'approprier, nous vous recommandons de [choisir un thème](/docs/themes), [de personnaliser les raccourcis clavier](/docs/keybinds), de [configurer les formateurs de code](/docs/formatters), de [créer des commandes personnalisées](/docs/commands) ou de jouer avec la [OpenCode config](/docs/config). diff --git a/packages/web/src/content/docs/fr/keybinds.mdx b/packages/web/src/content/docs/fr/keybinds.mdx new file mode 100644 index 000000000..df584fa42 --- /dev/null +++ b/packages/web/src/content/docs/fr/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: Raccourcis clavier +description: Personnalisez vos raccourcis clavier. +--- + +OpenCode a une liste de raccourcis clavier que vous pouvez personnaliser via la configuration OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## Clé du leader + +OpenCode utilise une touche `leader` pour la plupart des raccourcis clavier. Cela évite les conflits dans votre terminal. + +Par défaut, `ctrl+x` est la touche leader et la plupart des actions nécessitent que vous appuyiez d'abord sur la touche leader, puis sur le raccourci. Par exemple, pour démarrer une nouvelle session, appuyez d'abord sur `ctrl+x`, puis sur `n`. + +Vous n'avez pas besoin d'utiliser une touche leader pour vos raccourcis clavier, mais nous vous recommandons de le faire. + +--- + +## Désactiver le raccourci clavier + +Vous pouvez désactiver un raccourci clavier en ajoutant la clé à votre configuration avec la valeur « aucun ». + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## Raccourcis d'invite du bureau + +L'entrée d'invite de l'application de bureau OpenCode prend en charge les raccourcis courants de style Readline/Emacs pour l'édition de texte. Ceux-ci sont intégrés et actuellement non configurables via `opencode.json`. + +| Raccourci | Actions | +| -------- | ---------------------------------------- | +| `ctrl+a` | Déplacer au début de la ligne actuelle | +| `ctrl+e` | Aller à la fin de la ligne actuelle | +| `ctrl+b` | Reculer le curseur d'un caractère | +| `ctrl+f` | Avancer le curseur d'un caractère | +| `alt+b` | Reculer le curseur d'un mot | +| `alt+f` | Avancer le curseur d'un mot | +| `ctrl+d` | Supprimer le caractère sous le curseur | +| `ctrl+k` | Tuer jusqu'au bout de la ligne | +| `ctrl+u` | Tuer au début de la ligne | +| `ctrl+w` | Tuer le mot précédent | +| `alt+d` | Tuer le mot suivant | +| `ctrl+t` | Transposer les caractères | +| `ctrl+g` | Annuler les popovers/abandonner l'exécution de la réponse | + +--- + +## Maj+Entrée + +Certains terminaux n'envoient pas de touches de modification avec Entrée par défaut. Vous devrez peut-être configurer votre terminal pour envoyer `Shift+Enter` comme séquence d'échappement. + +### Borne Windows + +Ouvrez votre `settings.json` à : + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +Ajoutez ceci au tableau `actions` de niveau racine : + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Ajoutez ceci au tableau `keybindings` de niveau racine : + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Enregistrez le fichier et redémarrez le terminal Windows ou ouvrez un nouvel onglet. diff --git a/packages/web/src/content/docs/fr/lsp.mdx b/packages/web/src/content/docs/fr/lsp.mdx new file mode 100644 index 000000000..aaa4fc17f --- /dev/null +++ b/packages/web/src/content/docs/fr/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: Serveurs LSP +description: OpenCode s'intègre à vos serveurs LSP. +--- + +OpenCode s'intègre à votre protocole de serveur de langue (LSP) pour aider le LLM à interagir avec votre base de code. Il utilise des diagnostics pour fournir des commentaires au LLM. + +--- + +## Intégré + +OpenCode est livré avec plusieurs serveurs LSP intégrés pour les langues populaires : + +| Serveur LSP | Rallonges | Exigences | +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +| astro | .astro | Installations automatiques pour les projets Astro | +| coup | .sh, .bash, .zsh, .ksh | Installe automatiquement le serveur bash-langage | +| clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Installations automatiques pour les projets C/C++ | +| cpointu | .cs | `.NET SDK` installé | +| clojure-lsp | .clj, .cljs, .cljc, .edn | Commande `clojure-lsp` disponible | +| fléchette | .dart | Commande `dart` disponible | +| déno | .ts, .tsx, .js, .jsx, .mjs | Commande `deno` disponible (détection automatique deno.json/deno.jsonc) | +| élixir-ls | .ex, .ex | Commande `elixir` disponible | +| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | Dépendance `eslint` dans le projet | +| fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` installé | +| lueur | .lueur | Commande `gleam` disponible | +| gopls | .aller | Commande `go` disponible | +| hls | .hs, .lhs | Commande `haskell-language-server-wrapper` disponible | +| jdtls | .java | `Java SDK (version 21+)` installé | +| kotlin-ls | .kt, .kts | Installations automatiques pour les projets Kotlin | +| lua-ls | .lua | Installations automatiques pour les projets Lua | +| rien | .nix | Commande `nixd` disponible | +| ocaml-lsp | .ml, .mli | Commande `ocamllsp` disponible | +| plinthe de boeuf | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | Dépendance `oxlint` dans le projet | +| php intelligence | .php | Installations automatiques pour les projets PHP | +| prisme | .prisma | Commande `prisma` disponible | +| droit d'auteur | .py, .pyi | Dépendance `pyright` installée | +| rubis-lsp (rubocop) | .rb, .rake, .gemspec, .ru | Commandes `ruby` et `gem` disponibles | +| rouille | .rs | Commande `rust-analyzer` disponible | +| sourcekit-lsp | .swift, .objc, .objcpp | `swift` installé (`xcode` sur macOS) | +| svelte | .svelte | Installations automatiques pour les projets Svelte | +| terraformer | .tf, .tfvars | Installations automatiques à partir des versions GitHub | +| petite brume | .typ, .typc | Installations automatiques à partir des versions GitHub | +| dactylographié | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | Dépendance `typescript` dans le projet | +| vue | .vue | Installations automatiques pour les projets Vue | +| yaml-ls | .yaml, .yml | Installe automatiquement le serveur yaml-langage-Red Hat | +| zls | .zig, .zon | Commande `zig` disponible | + +Les serveurs LSP sont automatiquement activés lorsque l'une des extensions de fichier ci-dessus est détectée et que les exigences sont remplies. + +:::note +Vous pouvez désactiver les téléchargements automatiques du serveur LSP en définissant la variable d'environnement `OPENCODE_DISABLE_LSP_DOWNLOAD` sur `true`. +::: + +--- + +## Comment ça marche + +Lorsque opencode ouvre un fichier, il : + +1. Vérifie l'extension du fichier par rapport à tous les serveurs LSP activés. +2. Démarre le serveur LSP approprié s'il n'est pas déjà en cours d'exécution. + +--- + +## Configurer + +Vous pouvez personnaliser les serveurs LSP via la section `lsp` de votre configuration opencode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Chaque serveur LSP prend en charge les éléments suivants : + +| Propriété | Tapez | Descriptif | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` | booléen | Définissez ceci sur `true` pour désactiver le serveur LSP | +| `command` | chaîne[] | La commande pour démarrer le serveur LSP | +| `extensions` | chaîne[] | Extensions de fichiers que ce serveur LSP doit gérer | +| `env` | objet | Variables d'environnement à définir lors du démarrage du serveur | +| `initialization` | objet | Options d'initialisation à envoyer au serveur LSP | + +Regardons quelques exemples. + +--- + +### Variables d'environnement + +Utilisez la propriété `env` pour définir les variables d'environnement lors du démarrage du serveur LSP : + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### Options d'initialisation + +Utilisez la propriété `initialization` pour transmettre les options d'initialisation au serveur LSP. Il s'agit de paramètres spécifiques au serveur envoyés lors de la requête LSP `initialize` : + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +Les options d'initialisation varient selon le serveur LSP. Consultez la documentation de votre serveur LSP pour connaître les options disponibles. +::: + +--- + +### Désactivation des serveurs LSP + +Pour désactiver **tous** les serveurs LSP dans le monde, définissez `lsp` sur `false` : + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +Pour désactiver un serveur LSP **spécifique**, définissez `disabled` sur `true` : + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Serveurs LSP personnalisés + +Vous pouvez ajouter des serveurs LSP personnalisés en spécifiant les extensions de commande et de fichier : + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## Informations Complémentaires + +### PHP Intelligence + +PHP Intelephense offre des fonctionnalités premium via une clé de licence. Vous pouvez fournir une clé de licence en plaçant (uniquement) la clé dans un fichier texte à l'adresse : + +- Le macOS/Linux : `$HOME/intelephense/licence.txt` +- Le Windows : `%USERPROFILE%/intelephense/licence.txt` + +Le fichier doit contenir uniquement la clé de licence sans contenu supplémentaire. diff --git a/packages/web/src/content/docs/fr/mcp-servers.mdx b/packages/web/src/content/docs/fr/mcp-servers.mdx new file mode 100644 index 000000000..65ccd212f --- /dev/null +++ b/packages/web/src/content/docs/fr/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: Serveurs MCP +description: Ajoutez des outils MCP locaux et distants. +--- + +Vous pouvez ajouter des outils externes à OpenCode à l'aide du _Model Context Protocol_ ou MCP. OpenCode prend en charge les serveurs locaux et distants. + +Une fois ajoutés, les outils MCP sont automatiquement disponibles pour le LLM aux côtés des outils intégrés. + +--- + +#### Mises en garde + +Lorsque vous utilisez un serveur MCP, cela ajoute au contexte. Cela peut vite s’additionner si vous disposez de beaucoup d’outils. Nous vous recommandons donc de faire attention aux serveurs MCP que vous utilisez. + +:::tip +Les serveurs MCP s'ajoutent à votre contexte, vous devez donc faire attention à ceux que vous activez. +::: + +Certains serveurs MCP, comme le serveur GitHub MCP, ont tendance à ajouter beaucoup de jetons et peuvent facilement dépasser la limite de contexte. + +--- + +## Activer + +Vous pouvez définir des serveurs MCP dans votre [OpenCode Config](https://opencode.ai/docs/config/) sous `mcp`. Ajoutez chaque MCP avec un nom unique. Vous pouvez faire référence à ce MCP par son nom lorsque vous demandez le LLM. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +Vous pouvez également désactiver un serveur en définissant `enabled` sur `false`. Ceci est utile si vous souhaitez désactiver temporairement un serveur sans le supprimer de votre configuration. + +--- + +### Remplacement des valeurs par défaut distantes + +Les organisations peuvent fournir des serveurs MCP par défaut via leur point de terminaison `.well-known/opencode`. Ces serveurs peuvent être désactivés par défaut, permettant aux utilisateurs de choisir ceux dont ils ont besoin. + +Pour activer un serveur spécifique à partir de la configuration distante de votre organisation, ajoutez-le à votre configuration locale avec `enabled: true` : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +Vos valeurs de configuration locales remplacent les valeurs par défaut distantes. Voir [config precedence](/docs/config#precedence-order) pour plus de détails. + +--- + +## Locale + +Ajoutez des serveurs MCP locaux en utilisant `type` à `"local"` dans l'objet MCP. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +La commande indique comment le serveur MCP local est démarré. Vous pouvez également transmettre une liste de variables d’environnement. + +Par exemple, voici comment ajouter le serveur de test [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +Et pour l'utiliser, je peux ajouter `use the mcp_everything tool` à mes invites. + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### Possibilités + +Voici toutes les options pour configurer un serveur MCP local. + +| Options | Tapez | Obligatoire | Descriptif | +| ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | Chaîne | Oui | Le type de connexion au serveur MCP doit être `"local"`. | +| `command` | Tableau | Oui | Commande et arguments pour exécuter le serveur MCP. | +| `environment` | Objet | | Variables d'environnement à définir lors de l'exécution du serveur. | +| `enabled` | Booléen | | Activez ou désactivez le serveur MCP au démarrage. | +| `timeout` | Numéro | | Délai d'expiration en ms pour la récupération des outils depuis le serveur MCP. La valeur par défaut est 5 000 (5 secondes). | + +--- + +## Télécommande + +Ajoutez des serveurs MCP distants en définissant `type` sur `"remote"`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +Le `url` est le URL du serveur distant MCP et avec l'option `headers` vous pouvez transmettre une liste d'en-têtes. + +--- + +#### Possibilités + +| Options | Tapez | Obligatoire | Descriptif | +| --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | Chaîne | Oui | Le type de connexion au serveur MCP doit être `"remote"`. | +| `url` | Chaîne | Oui | URL du serveur MCP distant. | +| `enabled` | Booléen | | Activez ou désactivez le serveur MCP au démarrage. | +| `headers` | Objet | | En-têtes à envoyer avec la demande. | +| `oauth` | Objet | | Configuration de l'authentification OAuth. Voir la section [OAuth](#oauth) ci-dessous. | +| `timeout` | Numéro | | Délai d'expiration en ms pour la récupération des outils depuis le serveur MCP. La valeur par défaut est 5 000 (5 secondes). | + +--- + +## OAuth + +OpenCode gère automatiquement l'authentification OAuth pour les serveurs MCP distants. Lorsqu'un serveur nécessite une authentification, OpenCode : + +1. Détectez la réponse 401 et lancez le flux OAuth +2. Utilisez **Enregistrement client dynamique (RFC 7591)** s'il est pris en charge par le serveur. +3. Stockez les jetons en toute sécurité pour les demandes futures + +--- + +### Automatique + +Pour la plupart des serveurs MCP compatibles OAuth, aucune configuration particulière n'est nécessaire. Configurez simplement le serveur distant : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +Si le serveur nécessite une authentification, OpenCode vous demandera de vous authentifier lorsque vous essayez de l'utiliser pour la première fois. Sinon, vous pouvez [déclencher manuellement le flux](#authenticating) avec `opencode mcp auth `. + +--- + +### Pré-inscrit + +Si vous disposez des informations d'identification client du fournisseur de serveur MCP, vous pouvez les configurer : + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### Authentification + +Vous pouvez déclencher manuellement l'authentification ou gérer les informations d'identification. + +Authentifiez-vous auprès d'un serveur MCP spécifique : + +```bash +opencode mcp auth my-oauth-server +``` + +Répertoriez tous les serveurs MCP et leur statut d'authentification : + +```bash +opencode mcp list +``` + +Supprimez les informations d'identification stockées : + +```bash +opencode mcp logout my-oauth-server +``` + +La commande `mcp auth` ouvrira votre navigateur pour autorisation. Après votre autorisation, OpenCode stockera les jetons en toute sécurité dans `~/.local/share/opencode/mcp-auth.json`. + +--- + +#### Désactivation de OAuth + +Si vous souhaitez désactiver le OAuth automatique pour un serveur (par exemple, pour les serveurs qui utilisent les clés API à la place), définissez `oauth` sur `false` : + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### Options OAuth + +| Options | Tapez | Descriptif | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` | Objet \| faux | Objet de configuration OAuth, ou `false` pour désactiver la détection automatique OAuth. | +| `clientId` | Chaîne | ID client OAuth. S’il n’est pas fourni, l’enregistrement dynamique du client sera tenté. | +| `clientSecret` | Chaîne | OAuth secret client, si requis par le serveur d'autorisation. | +| `scope` | Chaîne | OAuth scopes à demander lors de l'autorisation. | + +#### Débogage + +Si un serveur MCP distant ne parvient pas à s'authentifier, vous pouvez diagnostiquer les problèmes avec : + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +La commande `mcp debug` affiche l'état d'authentification actuel, teste la connectivité HTTP et tente le flux de découverte OAuth. + +--- + +## Gérer + +Vos MCP sont disponibles sous forme d'outils dans OpenCode, aux côtés des outils intégrés. Vous pouvez donc les gérer via la configuration OpenCode comme n'importe quel autre outil. + +--- + +### Mondial + +Cela signifie que vous pouvez les activer ou les désactiver globalement. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +Nous pouvons également utiliser un modèle global pour désactiver tous les MCP correspondants. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +Ici, nous utilisons le modèle global `my-mcp*` pour désactiver tous les MCP. + +--- + +### Par agent + +Si vous disposez d'un grand nombre de serveurs MCP, vous souhaiterez peut-être les activer uniquement par agent et les désactiver globalement. Pour ce faire : + +1. Désactivez-le en tant qu'outil à l'échelle mondiale. +2. Dans votre [agent config](/docs/agents#tools), activez le serveur MCP en tant qu'outil. + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### Modèles globaux + +Le modèle glob utilise des modèles de globbing regex simples : + +- `*` correspond à zéro ou plusieurs caractères (par exemple, `"my-mcp*"` correspond à `my-mcp_search`, `my-mcp_list`, etc.) +- `?` correspond exactement à un caractère +- Tous les autres caractères correspondent littéralement + +:::note +Les outils serveur MCP sont enregistrés avec le nom du serveur comme préfixe, donc pour désactiver tous les outils d'un serveur, utilisez simplement : + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## Exemples + +Vous trouverez ci-dessous des exemples de serveurs MCP courants. Vous pouvez soumettre un PR si vous souhaitez documenter d'autres serveurs. + +--- + +### Sentinelle + +Ajoutez le [serveur Sentry MCP](https://mcp.sentry.dev) pour interagir avec vos projets et problèmes Sentry. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +Après avoir ajouté la configuration, authentifiez-vous auprès de Sentry : + +```bash +opencode mcp auth sentry +``` + +Cela ouvrira une fenêtre de navigateur pour terminer le flux OAuth et connecter OpenCode à votre compte Sentry. + +Une fois authentifié, vous pouvez utiliser les outils Sentry dans vos invites pour interroger les problèmes, les projets et les données d'erreur. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Contexte7 + +Ajoutez le [Context7 MCP server](https://github.com/upstash/context7) pour effectuer une recherche dans les documents. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +Si vous avez créé un compte gratuit, vous pouvez utiliser votre clé API et obtenir des limites de débit plus élevées. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +Ici, nous supposons que la variable d'environnement `CONTEXT7_API_KEY` est définie. + +Ajoutez `use context7` à vos invites pour utiliser le serveur Context7 MCP. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +Alternativement, vous pouvez ajouter quelque chose comme ceci à votre [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep de Vercel + +Ajoutez le serveur [Grep by Vercel](https://grep.app) MCP pour rechercher des extraits de code sur GitHub. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +Puisque nous avons nommé notre serveur MCP `gh_grep`, vous pouvez ajouter `use the gh_grep tool` à vos invites pour que l'agent l'utilise. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +Alternativement, vous pouvez ajouter quelque chose comme ceci à votre [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/fr/models.mdx b/packages/web/src/content/docs/fr/models.mdx new file mode 100644 index 000000000..b01055453 --- /dev/null +++ b/packages/web/src/content/docs/fr/models.mdx @@ -0,0 +1,223 @@ +--- +title: Modèles +description: Configuration d'un fournisseur et d'un modèle LLM. +--- + +OpenCode utilise [AI SDK](https://ai-sdk.dev/) et [Models.dev](https://models.dev) pour prendre en charge **75+ fournisseurs LLM** et prend en charge l'exécution de modèles locaux. + +--- + +## Fournisseurs + +Les fournisseurs les plus populaires sont préchargés par défaut. Si vous avez ajouté les informations d'identification d'un fournisseur via la commande `/connect`, elles seront disponibles lorsque vous démarrerez OpenCode. + +En savoir plus sur [fournisseurs](/docs/providers). + +--- + +## Sélectionnez un modèle + +Une fois que vous avez configuré votre fournisseur, vous pouvez sélectionner le modèle souhaité en tapant : + +```bash frame="none" +/models +``` + +--- + +## Modèles recommandés + +Il existe de nombreux modèles et de nouveaux modèles sortent chaque semaine. + +:::tip +Pensez à utiliser l’un des modèles que nous recommandons. +::: + +Cependant, seuls quelques-uns d’entre eux savent à la fois générer du code et appeler des outils. + +Voici plusieurs modèles qui fonctionnent bien avec OpenCode, sans ordre particulier. (Cette liste n’est pas exhaustive et n’est pas nécessairement à jour) : + +- GPT 5.2 +- Codex GPT 5.1 +- Claude Opus 4.5 +- Claude Sonnet 4.5 +- Minimax M2.1 +- Gémeaux 3 Pro + +--- + +## Définir une valeur par défaut + +Pour définir l'un d'entre eux comme modèle par défaut, vous pouvez définir la clé `model` dans votre +OpenCode configuration. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Ici, l'identifiant complet est `provider_id/model_id`. Par exemple, si vous utilisez [OpenCode Zen](/docs/zen), vous utiliserez `opencode/gpt-5.1-codex` pour GPT 5.1 Codex. + +Si vous avez configuré un [fournisseur personnalisé](/docs/providers#custom), le `provider_id` est la clé de la partie `provider` de votre configuration et le `model_id` est la clé de `provider.models`. + +--- + +## Configurer les modèles + +Vous pouvez configurer globalement les options d'un modèle via le fichier config. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Ici, nous configurons les paramètres globaux pour deux modèles intégrés : `gpt-5` lorsqu'il est accessible via le fournisseur `openai` et `claude-sonnet-4-20250514` lorsqu'il est accessible via le fournisseur `anthropic`. +Les noms du fournisseur intégré et des modèles peuvent être trouvés sur [Models.dev](https://models.dev). + +Vous pouvez également configurer ces options pour tous les agents que vous utilisez. La configuration de l'agent remplace ici toutes les options globales. [En savoir plus](/docs/agents/#additional). + +Vous pouvez également définir des variantes personnalisées qui étendent celles intégrées. Les variantes vous permettent de configurer différents paramètres pour le même modèle sans créer d'entrées en double : + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## Variantes + +De nombreux modèles prennent en charge plusieurs variantes avec différentes configurations. OpenCode est livré avec des variantes par défaut intégrées pour les fournisseurs populaires. + +### Variantes intégrées + +OpenCode est livré avec des variantes par défaut pour de nombreux fournisseurs : + +**Anthropique** : + +- `high` - Budget de réflexion élevé (par défaut) +- `max` - Budget de réflexion maximum + +**OpenAI** : + +Varie selon le modèle mais en gros : + +- `none` - Aucun raisonnement +- `minimal` - Effort de raisonnement minimal +- `low` - Faible effort de raisonnement +- `medium` - Effort de raisonnement moyen +- `high` – Effort de raisonnement élevé +- `xhigh` - Effort de raisonnement très élevé + +**Google**: + +- `low` – Budget d'effort/jetons réduit +- `high` – Budget d'effort/de jetons plus élevé + +:::tip +Cette liste n'est pas exhaustive. De nombreux autres fournisseurs ont également des paramètres par défaut intégrés. +::: + +### Variantes personnalisées + +Vous pouvez remplacer les variantes existantes ou ajouter les vôtres : + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### Variantes de cycles + +Utilisez le raccourci clavier `variant_cycle` pour basculer rapidement entre les variantes. [En savoir plus](/docs/keybinds). + +--- + +## Chargement des modèles + +Lorsque OpenCode démarre, il recherche les modèles dans l'ordre de priorité suivant : + +1. L'indicateur de ligne de commande `--model` ou `-m`. Le format est le même que dans le fichier de configuration : `provider_id/model_id`. + +2. La liste des modèles dans la configuration OpenCode. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + +Le format ici est `provider/model`. + +3. Le dernier modèle utilisé. + +4. Le premier modèle utilisant une priorité interne. diff --git a/packages/web/src/content/docs/fr/modes.mdx b/packages/web/src/content/docs/fr/modes.mdx new file mode 100644 index 000000000..5abeed24c --- /dev/null +++ b/packages/web/src/content/docs/fr/modes.mdx @@ -0,0 +1,331 @@ +--- +title: Modes +description: Différents modes pour différents cas d'utilisation. +--- + +:::caution +Les modes sont désormais configurés via l'option `agent` dans la configuration opencode. Le +L’option `mode` est désormais obsolète. [En savoir plus](/docs/agents). +::: + +Les modes dans opencode vous permettent de personnaliser le comportement, les outils et les invites pour différents cas d'utilisation. + +Il est livré avec deux modes intégrés : **build** et **plan**. Vous pouvez personnaliser +ceux-ci ou configurez les vôtres via la configuration opencode. + +Vous pouvez basculer entre les modes au cours d'une session ou les configurer dans votre fichier de configuration. + +--- + +## Intégré + +opencode est livré avec deux modes intégrés. + +--- + +### Construire + +Build est le mode **par défaut** avec tous les outils activés. Il s'agit du mode standard pour le travail de développement dans lequel vous avez besoin d'un accès complet aux opérations sur les fichiers et aux commandes système. + +--- + +### Plan + +Un mode restreint conçu pour la planification et l’analyse. En mode plan, les outils suivants sont désactivés par défaut : + +- `write` - Impossible de créer de nouveaux fichiers +- `edit` - Impossible de modifier les fichiers existants, à l'exception des fichiers situés à `.opencode/plans/*.md` pour détailler le plan lui-même +- `patch` - Impossible d'appliquer les correctifs +- `bash` - Impossible d'exécuter les commandes shell + +Ce mode est utile lorsque vous souhaitez que l'IA analyse le code, suggère des modifications ou crée des plans sans apporter de modifications réelles à votre base de code. + +--- + +## Commutation + +Vous pouvez basculer entre les modes au cours d'une session à l'aide de la touche _Tab_. Ou votre raccourci clavier `switch_mode` configuré. + +Voir également : [Formatters](/docs/formatters) pour plus d'informations sur la configuration du formatage du code. + +--- + +## Configurer + +Vous pouvez personnaliser les modes intégrés ou créer les vôtres via la configuration. Les modes peuvent être configurés de deux manières : + +### JSONConfiguration + +Configurez les modes dans votre fichier de configuration `opencode.json` : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Configuration de démarque + +Vous pouvez également définir des modes à l'aide de fichiers markdown. Placez-les dans : + +- Mondial : `~/.config/opencode/modes/` +- Projet : `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Le nom du fichier markdown devient le nom du mode (par exemple, `review.md` crée un mode `review`). + +Examinons ces options de configuration en détail. + +--- + +### Modèle + +Utilisez la configuration `model` pour remplacer le modèle par défaut pour ce mode. Utile pour utiliser différents modèles optimisés pour différentes tâches. Par exemple, un modèle de planification plus rapide, un modèle de mise en œuvre plus performant. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Température + +Contrôlez le caractère aléatoire et la créativité des réponses de l'IA avec la configuration `temperature`. Des valeurs faibles rendent les réponses plus ciblées et déterministes, tandis que des valeurs plus élevées augmentent la créativité et la variabilité. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Les valeurs de température varient généralement de 0,0 à 1,0 : + +- **0,0-0,2** : réponses très ciblées et déterministes, idéales pour l'analyse et la planification du code +- **0,3-0,5** : réponses équilibrées avec une certaine créativité, idéales pour les tâches de développement générales +- **0,6-1,0** : réponses plus créatives et variées, utiles pour le brainstorming et l'exploration + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Si aucune température n'est spécifiée, opencode utilise les valeurs par défaut spécifiques au modèle (généralement 0 pour la plupart des modèles, 0,55 pour les modèles Qwen). + +--- + +### Rapide + +Spécifiez un fichier d'invite système personnalisé pour ce mode avec la configuration `prompt`. Le fichier d'invite doit contenir des instructions spécifiques à l'objectif du mode. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Ce chemin est relatif à l'emplacement du fichier de configuration. Donc ça marche pour +à la fois la configuration globale opencode et la configuration spécifique au projet. + +--- + +### Outils + +Contrôlez quels outils sont disponibles dans ce mode avec la configuration `tools`. Vous pouvez activer ou désactiver des outils spécifiques en les définissant sur `true` ou `false`. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +Si aucun outil n'est spécifié, tous les outils sont activés par défaut. + +--- + +#### Outils disponibles + +Voici tous les outils pouvant être contrôlés via le mode config. + +| Outil | Descriptif | +| ----------- | ----------------------- | +| `bash` | Exécuter des commandes shell | +| `edit` | Modifier des fichiers existants | +| `write` | Créer de nouveaux fichiers | +| `read` | Lire le contenu du fichier | +| `grep` | Rechercher le contenu du fichier | +| `glob` | Rechercher des fichiers par modèle | +| `list` | Liste du contenu du répertoire | +| `patch` | Appliquer des correctifs aux fichiers | +| `todowrite` | Gérer les listes de tâches | +| `todoread` | Lire les listes de tâches | +| `webfetch` | Récupérer du contenu Web | + +--- + +## Modes personnalisés + +Vous pouvez créer vos propres modes personnalisés en les ajoutant à la configuration. Voici des exemples utilisant les deux approches : + +### Utilisation de la configuration JSON + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Utiliser des fichiers de démarque + +Créez des fichiers de mode dans `.opencode/modes/` pour les modes spécifiques au projet ou `~/.config/opencode/modes/` pour les modes globaux : + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### Cas d'utilisation + +Voici quelques cas d’utilisation courants pour différents modes. + +- **Mode build** : travail de développement complet avec tous les outils activés +- **Mode Plan** : Analyse et planification sans apporter de modifications +- **Mode révision** : révision du code avec accès en lecture seule et outils de documentation +- **Mode débogage** : axé sur l'investigation avec les outils bash et read activés +- **Mode Docs** : écriture de documentation avec des opérations sur les fichiers mais pas de commandes système + +Vous constaterez peut-être également que différents modèles conviennent à différents cas d’utilisation. diff --git a/packages/web/src/content/docs/fr/network.mdx b/packages/web/src/content/docs/fr/network.mdx new file mode 100644 index 000000000..4f45342e0 --- /dev/null +++ b/packages/web/src/content/docs/fr/network.mdx @@ -0,0 +1,57 @@ +--- +title: Réseau +description: Configurez les proxys et les certificats personnalisés. +--- + +OpenCode prend en charge les variables d'environnement proxy standard et les certificats personnalisés pour les environnements réseau d'entreprise. + +--- + +## Procuration + +OpenCode respecte les variables d'environnement proxy standard. + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::caution +Le TUI communique avec un serveur HTTP local. Vous devez contourner le proxy pour cette connexion afin d'éviter les boucles de routage. +::: + +Vous pouvez configurer le port et le nom d'hôte du serveur à l'aide de [CLI flags](/docs/cli#run). + +--- + +### Authentifier + +Si votre proxy nécessite une authentification de base, incluez les informations d'identification dans le URL. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::caution +Évitez de coder en dur les mots de passe. Utilisez des variables d’environnement ou un stockage sécurisé des informations d’identification. +::: + +Pour les proxys nécessitant une authentification avancée comme NTLM ou Kerberos, envisagez d'utiliser une passerelle LLM qui prend en charge votre méthode d'authentification. + +--- + +## Certificats personnalisés + +Si votre entreprise utilise des autorités de certification personnalisées pour les connexions HTTPS, configurez OpenCode pour leur faire confiance. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +Cela fonctionne à la fois pour les connexions proxy et pour l'accès direct à API. diff --git a/packages/web/src/content/docs/fr/permissions.mdx b/packages/web/src/content/docs/fr/permissions.mdx new file mode 100644 index 000000000..1b9a469f6 --- /dev/null +++ b/packages/web/src/content/docs/fr/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: Autorisations +description: Contrôlez quelles actions nécessitent une approbation pour être exécutées. +--- + +OpenCode utilise la configuration `permission` pour décider si une action donnée doit s'exécuter automatiquement, vous inviter ou être bloquée. + +Depuis `v1.1.1`, l'ancienne configuration booléenne `tools` est obsolète et a été fusionnée dans `permission`. L'ancienne configuration `tools` est toujours prise en charge pour des raisons de compatibilité ascendante. + +--- + +## Actes + +Chaque règle d'autorisation se résout en l'une des suivantes : + +- `"allow"` – exécuter sans approbation +- `"ask"` – demande d'approbation +- `"deny"` — bloque l'action + +--- + +## Configuration + +Vous pouvez définir des autorisations globalement (avec `*`) et remplacer des outils spécifiques. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +Vous pouvez également définir toutes les autorisations en même temps : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## Règles granulaires (syntaxe d'objet) + +Pour la plupart des autorisations, vous pouvez utiliser un objet pour appliquer différentes actions en fonction de la saisie de l'outil. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +Les règles sont évaluées par correspondance de modèle, la **dernière règle correspondante étant gagnante**. Un modèle courant consiste à placer la règle fourre-tout `"*"` en premier, et les règles plus spécifiques après. + +### Caractères génériques + +Les modèles d'autorisation utilisent une simple correspondance de caractères génériques : + +- `*` correspond à zéro ou plusieurs caractères +- `?` correspond exactement à un caractère +- Tous les autres caractères correspondent littéralement + +### Extension du répertoire personnel + +Vous pouvez utiliser `~` ou `$HOME` au début d'un modèle pour référencer votre répertoire personnel. Ceci est particulièrement utile pour les règles [`external_directory`](#external-directories). + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### Répertoires externes + +Utilisez `external_directory` pour autoriser les appels d'outils qui touchent des chemins en dehors du répertoire de travail où OpenCode a été démarré. Cela s'applique à tout outil qui prend un chemin en entrée (par exemple `read`, `edit`, `list`, `glob`, `grep` et de nombreuses commandes `bash`). + +L'expansion de la maison (comme `~/...`) n'affecte que la façon dont un modèle est écrit. Cela n'intègre pas un chemin externe à l'espace de travail actuel, donc les chemins en dehors du répertoire de travail doivent toujours être autorisés via `external_directory`. + +Par exemple, cela permet d'accéder à tout ce qui se trouve sous `~/projects/personal/` : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +Tout répertoire autorisé ici hérite des mêmes valeurs par défaut que l'espace de travail actuel. Étant donné que [`read` est par défaut `allow`](#defaults), les lectures sont également autorisées pour les entrées sous `external_directory`, sauf dérogation. Ajoutez des règles explicites lorsqu'un outil doit être restreint dans ces chemins, comme bloquer les modifications tout en conservant les lectures : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +Gardez la liste centrée sur les chemins approuvés et superposez des règles d'autorisation ou de refus supplémentaires selon les besoins pour d'autres outils (par exemple `bash`). + +--- + +## Autorisations disponibles + +Les autorisations OpenCode sont classées par nom d'outil, plus quelques gardes de sécurité : + +- `read` — lecture d'un fichier (correspond au chemin du fichier) +- `edit` — toutes les modifications de fichiers (couvre `edit`, `write`, `patch`, `multiedit`) +- `glob` — globalisation de fichiers (correspond au modèle global) +- `grep` — recherche de contenu (correspond au modèle regex) +- `list` — listant les fichiers dans un répertoire (correspond au chemin du répertoire) +- `bash` - exécution de commandes shell (correspond aux commandes analysées comme `git status --porcelain`) +- `task` — lancement de sous-agents (correspond au type de sous-agent) +- `skill` — chargement d'une compétence (correspond au nom de la compétence) +- `lsp` — exécution de requêtes LSP (actuellement non granulaires) +- `todoread`, `todowrite` — lecture/mise à jour de la liste de tâches +- `webfetch` — récupérer un URL (correspond au URL) +- `websearch`, `codesearch` — recherche Web/code (correspond à la requête) +- `external_directory` - déclenché lorsqu'un outil touche des chemins en dehors du répertoire de travail du projet +- `doom_loop` — déclenché lorsque le même appel d'outil se répète 3 fois avec une entrée identique + +--- + +## Valeurs par défaut + +Si vous ne spécifiez rien, OpenCode démarre avec les valeurs par défaut permissives : + +- La plupart des autorisations sont par défaut `"allow"`. +- `doom_loop` et `external_directory` sont par défaut `"ask"`. +- `read` est `"allow"`, mais les fichiers `.env` sont refusés par défaut : + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## Que fait « Demander » ? + +Lorsque OpenCode demande l'approbation, l'interface utilisateur propose trois résultats : + +- `once` — approuve uniquement cette demande +- `always` — approuve les futures demandes correspondant aux modèles suggérés (pour le reste de la session OpenCode en cours) +- `reject` — refuser la demande + +L'ensemble des modèles que `always` approuverait est fourni par l'outil (par exemple, les approbations bash mettent généralement sur liste blanche un préfixe de commande sûr comme `git status*`). + +--- + +## Agents + +Vous pouvez remplacer les autorisations par agent. Les autorisations des agents sont fusionnées avec la configuration globale et les règles des agents sont prioritaires. [En savoir plus](/docs/agents#permissions) sur les autorisations des agents. + +:::note +Reportez-vous à la section [Règles granulaires (syntaxe d'objet)](#granular-rules-object-syntax) ci-dessus pour des exemples de correspondance de modèles plus détaillés. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +Vous pouvez également configurer les autorisations des agents dans Markdown : + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tip +Utilisez la correspondance de modèles pour les commandes avec des arguments. `"grep *"` autorise `grep pattern file.txt`, tandis que `"grep"` seul le bloquerait. Les commandes comme `git status` fonctionnent pour le comportement par défaut mais nécessitent une autorisation explicite (comme `"git status *"`) lorsque des arguments sont passés. +::: diff --git a/packages/web/src/content/docs/fr/plugins.mdx b/packages/web/src/content/docs/fr/plugins.mdx new file mode 100644 index 000000000..615633fc8 --- /dev/null +++ b/packages/web/src/content/docs/fr/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: Plugins +description: Écrivez vos propres plugins pour étendre OpenCode. +--- + +Les plugins vous permettent d'étendre OpenCode en vous connectant à divers événements et en personnalisant le comportement. Vous pouvez créer des plugins pour ajouter de nouvelles fonctionnalités, intégrer des services externes ou modifier le comportement par défaut de OpenCode. + +Pour des exemples, consultez les [plugins](/docs/ecosystem#plugins) créés par la communauté. + +--- + +## Utiliser un plugin + +Il existe deux manières de charger des plugins. + +--- + +### À partir de fichiers locaux + +Placez les fichiers JavaScript ou TypeScript dans le répertoire du plugin. + +- `.opencode/plugins/` - Plugins au niveau du projet +- `~/.config/opencode/plugins/` - Plugins globaux + +Les fichiers de ces répertoires sont automatiquement chargés au démarrage. + +--- + +### De npm + +Spécifiez les packages npm dans votre fichier de configuration. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +Les packages npm standards et étendus sont pris en charge. + +Parcourez les plugins disponibles dans le [ecosystem](/docs/ecosystem#plugins). + +--- + +### Comment les plugins sont installés + +Les **plugins npm** sont installés automatiquement à l'aide de Bun au démarrage. Les packages et leurs dépendances sont mis en cache dans `~/.cache/opencode/node_modules/`. + +Les **plugins locaux** sont chargés directement depuis le répertoire des plugins. Pour utiliser des packages externes, vous devez créer un `package.json` dans votre répertoire de configuration (voir [Dépendances](#dependencies)), ou publier le plugin sur npm et [l'ajouter à votre config](/docs/config#plugins). + +--- + +### Ordre de chargement + +Les plugins sont chargés à partir de toutes les sources et tous les hooks s'exécutent dans l'ordre. L'ordre de chargement est le suivant : + +1. Configuration globale (`~/.config/opencode/opencode.json`) +2. Configuration du projet (`opencode.json`) +3. Répertoire global des plugins (`~/.config/opencode/plugins/`) +4. Répertoire des plugins du projet (`.opencode/plugins/`) + +Les packages npm en double avec le même nom et la même version sont chargés une fois. Cependant, un plugin local et un plugin npm portant des noms similaires sont tous deux chargés séparément. + +--- + +## Créer un plugin + +Un plugin est un **module JavaScript/TypeScript** qui exporte un ou plusieurs plugins +fonctions. Chaque fonction reçoit un objet contextuel et renvoie un objet hooks. + +--- + +### Dépendances + +Les plugins locaux et les outils personnalisés peuvent utiliser des packages npm externes. Ajoutez un `package.json` à votre répertoire de configuration avec les dépendances dont vous avez besoin. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode exécute `bun install` au démarrage pour les installer. Vos plugins et outils peuvent ensuite les importer. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### Structure de base + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +La fonction plugin reçoit : + +- `project` : informations sur le projet actuel. +- `directory` : le répertoire de travail actuel. +- `worktree` : le chemin de l'arbre de travail git. +- `client` : un client SDK opencode pour interagir avec l'IA. +- `$` : [shell API](https://bun.com/docs/runtime/shell) de Bun pour l'exécution de commandes. + +--- + +### Prise en charge de TypeScript + +Pour les plugins TypeScript, vous pouvez importer des types à partir du package du plugin : + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### Événements + +Les plugins peuvent s'abonner à des événements comme indiqué ci-dessous dans la section Exemples. Voici une liste des différents événements disponibles. + +#### Événements de commande + +- `command.executed` + +#### Événements de fichier + +- `file.edited` +- `file.watcher.updated` + +#### Événements d'installation + +- `installation.updated` + +#### LSP Événements + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### Événements de messages + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### Événements d'autorisation + +- `permission.asked` +- `permission.replied` + +#### Événements du serveur + +- `server.connected` + +#### Événements de session + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### Événements à faire + +- `todo.updated` + +#### Événements Shell + +- `shell.env` + +#### Événements d'outils + +- `tool.execute.after` +- `tool.execute.before` + +#### TUI Événements + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## Exemples + +Voici quelques exemples de plugins que vous pouvez utiliser pour étendre opencode. + +--- + +### Envoyer des notifications + +Envoyez des notifications lorsque certains événements se produisent : + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +Nous utilisons `osascript` pour exécuter AppleScript sur macOS. Ici, nous l'utilisons pour envoyer des notifications. + +:::note +Si vous utilisez l'application de bureau OpenCode, elle peut envoyer automatiquement des notifications système lorsqu'une réponse est prête ou en cas d'erreur de session. +::: + +--- + +### Protection .env + +Empêchez opencode de lire les fichiers `.env` : + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### Injecter des variables d'environnement + +Injectez des variables d'environnement dans toutes les exécutions du shell (outils d'IA et terminaux utilisateur) : + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### Outils personnalisés + +Les plugins peuvent également ajouter des outils personnalisés à opencode : + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +L'assistant `tool` crée un outil personnalisé que opencode peut appeler. Il prend une fonction de schéma Zod et renvoie une définition d'outil avec : + +- `description` : ce que fait l'outil +- `args` : schéma Zod pour les arguments de l'outil +- `execute` : Fonction qui s'exécute lorsque l'outil est appelé + +Vos outils personnalisés seront disponibles pour opencode aux côtés des outils intégrés. + +--- + +### Enregistrement + +Utilisez `client.app.log()` au lieu de `console.log` pour la journalisation structurée : + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +Niveaux : `debug`, `info`, `warn`, `error`. Voir la [documentation du SDK](https://opencode.ai/docs/sdk) pour plus de détails. + +--- + +### Crochets de compactage + +Personnalisez le contexte inclus lorsqu'une session est compactée : + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +Le hook `experimental.session.compacting` se déclenche avant que le LLM ne génère un résumé de continuation. Utilisez-le pour injecter un contexte spécifique au domaine que l'invite de compactage par défaut manquerait. + +Vous pouvez également remplacer entièrement l'invite de compactage en définissant `output.prompt` : + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +Lorsque `output.prompt` est défini, il remplace complètement l'invite de compactage par défaut. Le tableau `output.context` est ignoré dans ce cas. diff --git a/packages/web/src/content/docs/fr/providers.mdx b/packages/web/src/content/docs/fr/providers.mdx new file mode 100644 index 000000000..11591a040 --- /dev/null +++ b/packages/web/src/content/docs/fr/providers.mdx @@ -0,0 +1,1895 @@ +--- +title: Fournisseurs +description: Utiliser n’importe quel fournisseur LLM en OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode utilise [AI SDK](https://ai-sdk.dev/) et [Models.dev](https://models.dev) pour prendre en charge **75+ fournisseurs LLM** et prend en charge l'exécution de modèles locaux. + +Pour ajouter un fournisseur, vous devez : + +1. Ajoutez les clés API pour le fournisseur à l'aide de la commande `/connect`. +2. Configurez le fournisseur dans votre configuration OpenCode. + +--- + +### Informations d'identification + +Lorsque vous ajoutez les clés API d'un fournisseur avec la commande `/connect`, elles sont stockées +en `~/.local/share/opencode/auth.json`. + +--- + +### Configuration + +Vous pouvez personnaliser les fournisseurs via la section `provider` de votre OpenCode +configuration. + +--- + +#### Socle URL + +Vous pouvez personnaliser la base URL pour n'importe quel fournisseur en définissant l'option `baseURL`. Ceci est utile lors de l'utilisation de services proxy ou de points de terminaison personnalisés. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen est une liste de modèles fournis par l'équipe OpenCode qui ont été +testé et vérifié pour fonctionner correctement avec OpenCode. [En savoir plus](/docs/zen). + +:::tip +Si vous êtes nouveau, nous vous recommandons de commencer par OpenCode Zen. +::: + +1. Exécutez la commande `/connect` dans le TUI, sélectionnez opencode et dirigez-vous vers [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Connectez-vous, ajoutez vos informations de facturation et copiez votre clé API. + +3. Collez votre clé API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez `/models` dans le TUI pour voir la liste des modèles que nous recommandons. + + ```txt + /models + ``` + +Il fonctionne comme n’importe quel autre fournisseur dans OpenCode et son utilisation est totalement facultative. + +--- + +## Annuaire + +Examinons certains fournisseurs en détail. Si vous souhaitez ajouter un fournisseur au +liste, n'hésitez pas à ouvrir un PR. + +:::note +Vous ne voyez pas de fournisseur ici ? Soumettez un PR. +::: + +--- + +### 302.IA + +1. Rendez-vous sur la [console 302.AI](https://302.ai/), créez un compte et générez une clé API. + +2. Exécutez la commande `/connect` et recherchez **302.AI**. + + ```txt + /connect + ``` + +3. Saisissez votre clé 302.AI API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle. + + ```txt + /models + ``` + +--- + +### Socle amazonien + +Pour utiliser Amazon Bedrock avec OpenCode : + +1. Rendez-vous sur le **Catalogue de modèles** dans la console Amazon Bedrock et demandez + accédez aux modèles que vous souhaitez. + + :::tip + Vous devez avoir accès au modèle souhaité dans Amazon Bedrock. + ::: + +2. **Configurez l'authentification** à l'aide de l'une des méthodes suivantes : + + #### Variables d'environnement (démarrage rapide) + +Définissez l'une de ces variables d'environnement lors de l'exécution de opencode : + +```bash +# Option 1: Using AWS access keys +AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + +# Option 2: Using named AWS profile +AWS_PROFILE=my-profile opencode + +# Option 3: Using Bedrock bearer token +AWS_BEARER_TOKEN_BEDROCK=XXX opencode +``` + +Ou ajoutez-les à votre profil bash : + +```bash title="~/.bash_profile" +export AWS_PROFILE=my-dev-profile +export AWS_REGION=us-east-1 +``` + +#### Fichier de configuration (recommandé) + +Pour une configuration spécifique au projet ou persistante, utilisez `opencode.json` : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } +} +``` + +**Options disponibles :** + +- `region` - Région AWS (par exemple, `us-east-1`, `eu-west-1`) +- `profile` - Profil nommé AWS de `~/.aws/credentials` +- `endpoint` - Point de terminaison personnalisé URL pour les points de terminaison d'un VPC (alias pour l'option générique `baseURL`) + +:::tip +Les options du fichier de configuration sont prioritaires sur les variables d'environnement. +::: + +#### Avancé : points de terminaison d'un VPC + +Si vous utilisez des points de terminaison d'un VPC pour Bedrock : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +:::note +L'option `endpoint` est un alias pour l'option générique `baseURL`, utilisant la terminologie spécifique à AWS. Si `endpoint` et `baseURL` sont spécifiés, `endpoint` est prioritaire. +::: + +#### Méthodes d'authentification + +- **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`** : créez un utilisateur IAM et générez des clés d'accès dans la console AWS +- **`AWS_PROFILE`** : utilisez les profils nommés de `~/.aws/credentials`. Configurez d'abord avec `aws configure --profile my-profile` ou `aws sso login` +- **`AWS_BEARER_TOKEN_BEDROCK`** : Générez des clés API à long terme à partir de la console Amazon Bedrock +- **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`** : pour EKS IRSA (rôles IAM pour les comptes de service) ou d'autres environnements Kubernetes avec fédération OIDC. Ces variables d'environnement sont automatiquement injectées par Kubernetes lors de l'utilisation des annotations de compte de service. + +#### Priorité d'authentification + +Amazon Bedrock utilise la priorité d'authentification suivante : + +1. **Bearer Token** - Variable d'environnement `AWS_BEARER_TOKEN_BEDROCK` ou jeton de la commande `/connect` +2. **AWS Credential Chain** - Profil, clés d'accès, informations d'identification partagées, rôles IAM, jetons d'identité Web (EKS IRSA), métadonnées d'instance + +:::note +Lorsqu'un jeton de porteur est défini (via `/connect` ou `AWS_BEARER_TOKEN_BEDROCK`), il est prioritaire sur toutes les méthodes d'identification AWS, y compris les profils configurés. +::: + +3. Exécutez la commande `/models` pour sélectionner le modèle souhaité. + + ```txt + /models + ``` + +:::note +Pour les profils d'inférence personnalisés, utilisez le nom du modèle et du fournisseur dans la clé et définissez la propriété `id` sur l'arn. Cela garantit une mise en cache correcte : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### Anthropique + +1. Une fois inscrit, exécutez la commande `/connect` et sélectionnez Anthropic. + + ```txt + /connect + ``` + +2. Ici, vous pouvez sélectionner l'option **Claude Pro/Max** et cela ouvrira votre navigateur. + et vous demande de vous authentifier. + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. Désormais, tous les modèles Anthropic devraient être disponibles lorsque vous utilisez la commande `/models`. + + ```txt + /models + ``` + +:::info +L'utilisation de votre abonnement Claude Pro/Max dans OpenCode n'est pas officiellement prise en charge par [Anthropic](https://anthropic.com). +::: + +##### Utilisation des clés API + +Vous pouvez également sélectionner **Créer une clé API** si vous n'avez pas d'abonnement Pro/Max. Il ouvrira également votre navigateur et vous demandera de vous connecter à Anthropic et vous donnera un code que vous pourrez coller dans votre terminal. + +Ou si vous disposez déjà d'une clé API, vous pouvez sélectionner **Entrer manuellement la clé API** et la coller dans votre terminal. + +--- + +### Azur OpenAI + +:::note +Si vous rencontrez des erreurs « Je suis désolé, mais je ne peux pas vous aider avec cette demande », essayez de modifier le filtre de contenu de **DefaultV2** à **Default** dans votre ressource Azure. +::: + +1. Rendez-vous sur le [portail Azure](https://portal.azure.com/) et créez une ressource **Azure OpenAI**. Vous aurez besoin de : + - **Nom de la ressource** : cela fait partie de votre point de terminaison API (`https://RESOURCE_NAME.openai.azure.com/`) + - **Clé API** : soit `KEY 1` ou `KEY 2` de votre ressource + +2. Accédez à [Azure AI Foundry](https://ai.azure.com/) et déployez un modèle. + + :::note + Le nom du déploiement doit correspondre au nom du modèle pour que opencode fonctionne correctement. + ::: + +3. Exécutez la commande `/connect` et recherchez **Azure**. + + ```txt + /connect + ``` + +4. Entrez votre clé API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Définissez le nom de votre ressource comme variable d'environnement : + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + +Ou ajoutez-le à votre profil bash : + +```bash title="~/.bash_profile" +export AZURE_RESOURCE_NAME=XXX +``` + +6. Exécutez la commande `/models` pour sélectionner votre modèle déployé. + + ```txt + /models + ``` + +--- + +### Services cognitifs Azure + +1. Rendez-vous sur le [portail Azure](https://portal.azure.com/) et créez une ressource **Azure OpenAI**. Vous aurez besoin de : + - **Nom de la ressource** : cela fait partie de votre point de terminaison API (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) + - **Clé API** : soit `KEY 1` ou `KEY 2` de votre ressource + +2. Accédez à [Azure AI Foundry](https://ai.azure.com/) et déployez un modèle. + + :::note + Le nom du déploiement doit correspondre au nom du modèle pour que opencode fonctionne correctement. + ::: + +3. Exécutez la commande `/connect` et recherchez **Azure Cognitive Services**. + + ```txt + /connect + ``` + +4. Entrez votre clé API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Définissez le nom de votre ressource comme variable d'environnement : + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + +Ou ajoutez-le à votre profil bash : + +```bash title="~/.bash_profile" +export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX +``` + +6. Exécutez la commande `/models` pour sélectionner votre modèle déployé. + + ```txt + /models + ``` + +--- + +### Baseten + +1. Rendez-vous sur [Baseten](https://app.baseten.co/), créez un compte et générez une clé API. + +2. Exécutez la commande `/connect` et recherchez **Baseten**. + + ```txt + /connect + ``` + +3. Entrez votre clé Baseten API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle. + + ```txt + /models + ``` + +--- + +### Cérébraux + +1. Rendez-vous sur la [console Cerebras](https://inference.cerebras.ai/), créez un compte et générez une clé API. + +2. Exécutez la commande `/connect` et recherchez **Cerebras**. + + ```txt + /connect + ``` + +3. Entrez votre clé Cerebras API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### Passerelle IA Cloudflare + +Cloudflare AI Gateway vous permet d'accéder aux modèles de OpenAI, Anthropic, Workers AI et bien plus encore via un point de terminaison unifié. Avec [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/), vous n'avez pas besoin de clés API distinctes pour chaque fournisseur. + +1. Rendez-vous sur le [tableau de bord Cloudflare](https://dash.cloudflare.com/), accédez à **AI** > **AI Gateway** et créez une nouvelle passerelle. + +2. Définissez votre ID de compte et votre ID de passerelle comme variables d'environnement. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. Exécutez la commande `/connect` et recherchez **Cloudflare AI Gateway**. + + ```txt + /connect + ``` + +4. Entrez votre jeton Cloudflare API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +Ou définissez-le comme variable d'environnement. + +```bash title="~/.bash_profile" +export CLOUDFLARE_API_TOKEN=your-api-token +``` + +5. Exécutez la commande `/models` pour sélectionner un modèle. + + ```txt + /models + ``` + +Vous pouvez également ajouter des modèles via votre configuration opencode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } +} +``` + +--- + +### Cortecs + +1. Rendez-vous sur la [console Cortecs](https://cortecs.ai/), créez un compte et générez une clé API. + +2. Exécutez la commande `/connect` et recherchez **Cortecs**. + + ```txt + /connect + ``` + +3. Entrez votre clé Cortecs API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Recherche profonde + +1. Rendez-vous sur la [console DeepSeek](https://platform.deepseek.com/), créez un compte et cliquez sur **Créer une nouvelle clé API**. + +2. Exécutez la commande `/connect` et recherchez **DeepSeek**. + + ```txt + /connect + ``` + +3. Entrez votre clé DeepSeek API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle DeepSeek tel que _DeepSeek Reasoner_. + + ```txt + /models + ``` + +--- + +### Infra Profond + +1. Rendez-vous sur le [tableau de bord Deep Infra](https://deepinfra.com/dash), créez un compte et générez une clé API. + +2. Exécutez la commande `/connect` et recherchez **Deep Infra**. + + ```txt + /connect + ``` + +3. Entrez votre clé Deep Infra API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle. + + ```txt + /models + ``` + +--- + +### Micrologiciel + +1. Rendez-vous sur le [Tableau de bord du micrologiciel](https://app.firmware.ai/signup), créez un compte et générez une clé API. + +2. Exécutez la commande `/connect` et recherchez **Firmware**. + + ```txt + /connect + ``` + +3. Entrez la clé API de votre micrologiciel. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle. + + ```txt + /models + ``` + +--- + +### IA de feux d'artifice + +1. Rendez-vous sur la [console Fireworks AI](https://app.fireworks.ai/), créez un compte et cliquez sur **Créer une clé API**. + +2. Exécutez la commande `/connect` et recherchez **Fireworks AI**. + + ```txt + /connect + ``` + +3. Entrez votre clé Fireworks AI API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### GitLab Duo + +GitLab Duo fournit un chat agent basé sur l'IA avec des capacités d'appel d'outils natives via le proxy Anthropic de GitLab. + +1. Exécutez la commande `/connect` et sélectionnez GitLab. + + ```txt + /connect + ``` + +2. Choisissez votre méthode d'authentification : + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### Utilisation de OAuth (recommandé) + +Sélectionnez **OAuth** et votre navigateur s'ouvrira pour autorisation. + +#### Utilisation d'un jeton d'accès personnel + +1. Accédez à [GitLab Paramètres utilisateur > Jetons d'accès](https://gitlab.com/-/user_settings/personal_access_tokens) +2. Cliquez sur **Ajouter un nouveau jeton** +3. Nom : `OpenCode`, Portées : `api` +4. Copiez le jeton (commence par `glpat-`) +5. Entrez-le dans le terminal + +6. Exécutez la commande `/models` pour voir les modèles disponibles. + + ```txt + /models + ``` + +Trois modèles basés sur Claude sont disponibles : + +- **duo-chat-haiku-4-5** (Par défaut) - Réponses rapides pour des tâches rapides +- **duo-chat-sonnet-4-5** - Performances équilibrées pour la plupart des flux de travail +- **duo-chat-opus-4-5** - Le plus capable pour les analyses complexes + +:::note +Vous pouvez également spécifier la variable d'environnement 'GITLAB_TOKEN' si vous ne souhaitez pas +pour stocker le jeton dans le stockage d'authentification opencode. +::: + +##### GitLab auto-hébergé + +:::note[note de conformité] +OpenCode utilise un petit modèle pour certaines tâches d'IA telles que la génération du titre de la session. +Il est configuré pour utiliser gpt-5-nano par défaut, hébergé par Zen. Pour verrouiller OpenCode +pour utiliser uniquement votre propre instance hébergée par GitLab, ajoutez ce qui suit à votre +Fichier `opencode.json`. Il est également recommandé de désactiver le partage de session. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +Pour les instances GitLab auto-hébergées : + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +Si votre instance exécute une AI Gateway personnalisée : + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +Ou ajoutez à votre profil bash : + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +Votre administrateur GitLab doit activer les éléments suivants : + +1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) pour l'utilisateur, le groupe ou l'instance +2. Indicateurs de fonctionnalités (via la console Rails) : + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### OAuth pour les instances auto-hébergées + +Afin que Oauth fonctionne pour votre instance auto-hébergée, vous devez créer +une nouvelle application (Paramètres → Applications) avec le +rappel URL `http://127.0.0.1:8080/callback` et étendues suivantes : + +- api (Accédez au API en votre nom) +- read_user (Lire vos informations personnelles) +- read_repository (Autorise l'accès en lecture seule au référentiel) + +Exposez ensuite l'ID de l'application en tant que variable d'environnement : + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +Plus de documentation sur la page d'accueil [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth). + +##### Configuration + +Personnalisez via `opencode.json` : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### Outils GitLab API (facultatif, mais fortement recommandé) + +Pour accéder aux outils GitLab (demandes de fusion, tickets, pipelines, CI/CD, etc.) : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +Ce plugin fournit des fonctionnalités complètes de gestion du référentiel GitLab, notamment les examens MR, le suivi des problèmes, la surveillance du pipeline, etc. + +--- + +### GitHub Copilot + +Pour utiliser votre abonnement GitHub Copilot avec opencode : + +:::note +Certains modèles peuvent avoir besoin d'un [Pro+ +abonnement](https://github.com/features/copilot/plans) à utiliser. + +Certains modèles doivent être activés manuellement dans vos [GitHub Copilot paramètres](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. Exécutez la commande `/connect` et recherchez GitHub Copilot. + + ```txt + /connect + ``` + +2. Accédez à [github.com/login/device](https://github.com/login/device) et entrez le code. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. Exécutez maintenant la commande `/models` pour sélectionner le modèle souhaité. + + ```txt + /models + ``` + +--- + +### Google Vertex AI + +Pour utiliser Google Vertex AI avec OpenCode : + +1. Rendez-vous sur **Model Garden** dans Google Cloud Console et vérifiez les + modèles disponibles dans votre région. + + :::note + Vous devez disposer d'un projet Google Cloud avec Vertex AI API activé. + ::: + +2. Définissez les variables d'environnement requises : + - `GOOGLE_CLOUD_PROJECT` : ID de votre projet Google Cloud + - `VERTEX_LOCATION` (facultatif) : région pour Vertex AI (par défaut : `global`) + - Authentification (au choix) : + - `GOOGLE_APPLICATION_CREDENTIALS` : chemin d'accès au fichier de clé JSON de votre compte de service + - Authentifiez-vous à l'aide de gcloud CLI : `gcloud auth application-default login` + +Définissez-les lors de l'exécution de opencode. + +```bash +GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode +``` + +Ou ajoutez-les à votre profil bash. + +```bash title="~/.bash_profile" +export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json +export GOOGLE_CLOUD_PROJECT=your-project-id +export VERTEX_LOCATION=global +``` + +:::tip +La région `global` améliore la disponibilité et réduit les erreurs sans frais supplémentaires. Utilisez des points de terminaison régionaux (par exemple, `us-central1`) pour les exigences de résidence des données. [En savoir plus](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. Exécutez la commande `/models` pour sélectionner le modèle souhaité. + + ```txt + /models + ``` + +--- + +### Groq + +1. Rendez-vous sur la [console Groq](https://console.groq.com/), cliquez sur **Créer une clé API** et copiez la clé. + +2. Exécutez la commande `/connect` et recherchez Groq. + + ```txt + /connect + ``` + +3. Saisissez la clé API du fournisseur. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner celle que vous souhaitez. + + ```txt + /models + ``` + +--- + +### Visage câlin + +[Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers) donne accès à des modèles ouverts pris en charge par plus de 17 fournisseurs. + +1. Rendez-vous sur [Hugging Face settings](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) pour créer un jeton avec l'autorisation de passer des appels aux fournisseurs d'inférence. + +2. Exécutez la commande `/connect` et recherchez **Hugging Face**. + + ```txt + /connect + ``` + +3. Entrez votre jeton Hugging Face. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle comme _Kimi-K2-Instruct_ ou _GLM-4.6_. + + ```txt + /models + ``` + +--- + +### Hélicone + +[Helicone](https://helicone.ai) est une plate-forme d'observabilité LLM qui fournit la journalisation, la surveillance et l'analyse de vos applications d'IA. L'Helicone AI Gateway achemine automatiquement vos demandes vers le fournisseur approprié en fonction du modèle. + +1. Rendez-vous sur [Helicone](https://helicone.ai), créez un compte et générez une clé API à partir de votre tableau de bord. + +2. Exécutez la commande `/connect` et recherchez **Helicone**. + + ```txt + /connect + ``` + +3. Entrez votre clé Helicone API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle. + + ```txt + /models + ``` + +Pour plus de fournisseurs et de fonctionnalités avancées telles que la mise en cache et la limitation de débit, consultez la [documentation Helicone](https://docs.helicone.ai). + +#### Configurations facultatives + +Si vous voyez une fonctionnalité ou un modèle d'Helicone qui n'est pas configuré automatiquement via opencode, vous pouvez toujours le configurer vous-même. + +Voici le [Répertoire des modèles d'Helicone](https://helicone.ai/models), vous en aurez besoin pour récupérer les identifiants des modèles que vous souhaitez ajouter. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### En-têtes personnalisés + +Helicone prend en charge les en-têtes personnalisés pour des fonctionnalités telles que la mise en cache, le suivi des utilisateurs et la gestion des sessions. Ajoutez-les à la configuration de votre fournisseur en utilisant `options.headers` : + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### Suivi des sessions + +La fonctionnalité [Sessions](https://docs.helicone.ai/features/sessions) d'Helicone vous permet de regrouper les requêtes LLM associées. Utilisez le plugin [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) pour enregistrer automatiquement chaque conversation OpenCode en tant que session dans Helicone. + +```bash +npm install -g opencode-helicone-session +``` + +Ajoutez-le à votre configuration. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +Le plugin injecte les en-têtes `Helicone-Session-Id` et `Helicone-Session-Name` dans vos requêtes. Sur la page Sessions d'Helicone, vous verrez chaque conversation OpenCode répertoriée comme une session distincte. + +##### En-têtes Helicone communs + +| En-tête | Descriptif | +| -------------------------- | ------------------------------------------------------------------------------------ | +| `Helicone-Cache-Enabled` | Activer la mise en cache des réponses (`true`/`false`) | +| `Helicone-User-Id` | Suivre les métriques par utilisateur | +| `Helicone-Property-[Name]` | Ajouter des propriétés personnalisées (par exemple, `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | Associer les requêtes aux versions d'invite | + +Consultez le [Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory) pour tous les en-têtes disponibles. + +--- + +### lama.cpp + +Vous pouvez configurer opencode pour utiliser des modèles locaux via l'utilitaire llama-server de [llama.cpp's](https://github.com/ggml-org/llama.cpp) + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +Dans cet exemple : + +- `llama.cpp` est l'ID du fournisseur personnalisé. Cela peut être n’importe quelle chaîne de votre choix. +- `npm` spécifie le package à utiliser pour ce fournisseur. Ici, `@ai-sdk/openai-compatible` est utilisé pour tout API compatible OpenAI. +- `name` est le nom d'affichage du fournisseur dans l'interface utilisateur. +- `options.baseURL` est le point de terminaison du serveur local. +- `models` est une carte des ID de modèle avec leurs configurations. Le nom du modèle sera affiché dans la liste de sélection du modèle. + +--- + +### IO.NET + +IO.NET propose 17 modèles optimisés pour différents cas d'utilisation : + +1. Rendez-vous sur la [console IO.NET](https://ai.io.net/), créez un compte et générez une clé API. + +2. Exécutez la commande `/connect` et recherchez **IO.NET**. + + ```txt + /connect + ``` + +3. Entrez votre clé IO.NET API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle. + + ```txt + /models + ``` + +--- + +### Studio LM + +Vous pouvez configurer opencode pour utiliser des modèles locaux via LM Studio. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +Dans cet exemple : + +- `lmstudio` est l'ID du fournisseur personnalisé. Cela peut être n’importe quelle chaîne de votre choix. +- `npm` spécifie le package à utiliser pour ce fournisseur. Ici, `@ai-sdk/openai-compatible` est utilisé pour tout API compatible OpenAI. +- `name` est le nom d'affichage du fournisseur dans l'interface utilisateur. +- `options.baseURL` est le point de terminaison du serveur local. +- `models` est une carte des ID de modèle avec leurs configurations. Le nom du modèle sera affiché dans la liste de sélection du modèle. + +--- + +### IA Moonshot + +Pour utiliser Kimi K2 de Moonshot AI : + +1. Rendez-vous sur la [console Moonshot AI](https://platform.moonshot.ai/console), créez un compte et cliquez sur **Créer une clé API**. + +2. Exécutez la commande `/connect` et recherchez **Moonshot AI**. + + ```txt + /connect + ``` + +3. Entrez votre clé Moonshot API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner _Kimi K2_. + + ```txt + /models + ``` + +--- + +### MiniMax + +1. Rendez-vous sur la [Console MiniMax API](https://platform.minimax.io/login), créez un compte et générez une clé API. + +2. Exécutez la commande `/connect` et recherchez **MiniMax**. + + ```txt + /connect + ``` + +3. Entrez votre clé MiniMax API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _M2.1_. + + ```txt + /models + ``` + +--- + +### Usine de jetons Nebius + +1. Rendez-vous sur la [console Nebius Token Factory](https://tokenfactory.nebius.com/), créez un compte et cliquez sur **Ajouter une clé**. + +2. Exécutez la commande `/connect` et recherchez **Nebius Token Factory**. + + ```txt + /connect + ``` + +3. Entrez votre clé Nebius Token Factory API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Ollama + +Vous pouvez configurer opencode pour utiliser des modèles locaux via Ollama. + +:::tip +Ollama peut se configurer automatiquement pour OpenCode. Voir les [documents d'intégration Ollama](https://docs.ollama.com/integrations/opencode) pour plus de détails. +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +Dans cet exemple : + +- `ollama` est l'ID du fournisseur personnalisé. Cela peut être n’importe quelle chaîne de votre choix. +- `npm` spécifie le package à utiliser pour ce fournisseur. Ici, `@ai-sdk/openai-compatible` est utilisé pour tout API compatible OpenAI. +- `name` est le nom d'affichage du fournisseur dans l'interface utilisateur. +- `options.baseURL` est le point de terminaison du serveur local. +- `models` est une carte des ID de modèle avec leurs configurations. Le nom du modèle sera affiché dans la liste de sélection du modèle. + +:::tip +Si les appels d'outils ne fonctionnent pas, essayez d'augmenter `num_ctx` dans Ollama. Commencez vers 16k - 32k. +::: + +--- + +### Nuage Ollama + +Pour utiliser Ollama Cloud avec OpenCode : + +1. Rendez-vous sur [https://ollama.com/](https://ollama.com/) et connectez-vous ou créez un compte. + +2. Accédez à **Paramètres** > **Clés** et cliquez sur **Ajouter une clé API** pour générer une nouvelle clé API. + +3. Copiez la clé API à utiliser dans OpenCode. + +4. Exécutez la commande `/connect` et recherchez **Ollama Cloud**. + + ```txt + /connect + ``` + +5. Entrez votre clé Ollama Cloud API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **Important** : Avant d'utiliser des modèles cloud dans OpenCode, vous devez extraire les informations du modèle localement : + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. Exécutez la commande `/models` pour sélectionner votre modèle Ollama Cloud. + + ```txt + /models + ``` + +--- + +### OpenAI + +Nous vous recommandons de vous inscrire à [ChatGPT Plus ou Pro](https://chatgpt.com/pricing). + +1. Une fois inscrit, exécutez la commande `/connect` et sélectionnez OpenAI. + + ```txt + /connect + ``` + +2. Ici, vous pouvez sélectionner l'option **ChatGPT Plus/Pro** et cela ouvrira votre navigateur. + et vous demande de vous authentifier. + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. Désormais, tous les modèles OpenAI devraient être disponibles lorsque vous utilisez la commande `/models`. + + ```txt + /models + ``` + +##### Utilisation des clés API + +Si vous disposez déjà d'une clé API, vous pouvez sélectionner **Entrer manuellement la clé API** et la coller dans votre terminal. + +--- + +### OpenCode Zen + +OpenCode Zen est une liste de modèles testés et vérifiés fournie par l'équipe OpenCode. [En savoir plus](/docs/zen). + +1. Connectez-vous à **OpenCode Zen** et cliquez sur **Créer une clé API**. + +2. Exécutez la commande `/connect` et recherchez **OpenCode Zen**. + + ```txt + /connect + ``` + +3. Entrez votre clé OpenCode API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### OuvrirRouter + +1. Rendez-vous sur le [tableau de bord OpenRouter](https://openrouter.ai/settings/keys), cliquez sur **Créer une clé API** et copiez la clé. + +2. Exécutez la commande `/connect` et recherchez OpenRouter. + + ```txt + /connect + ``` + +3. Saisissez la clé API du fournisseur. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. De nombreux modèles OpenRouter sont préchargés par défaut, exécutez la commande `/models` pour sélectionner celui que vous souhaitez. + + ```txt + /models + ``` + +Vous pouvez également ajouter des modèles supplémentaires via votre configuration opencode. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } +} +``` + +5. Vous pouvez également les personnaliser via votre configuration opencode. Voici un exemple de spécification d'un fournisseur + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP IA Core + +SAP AI Core donne accès à plus de 40 modèles de OpenAI, Anthropic, Google, Amazon, Meta, Mistral et AI21 via une plateforme unifiée. + +1. Accédez à votre [SAP BTP Cockpit](https://account.hana.ondemand.com/), accédez à votre instance de service SAP AI Core et créez une clé de service. + + :::tip + La clé de service est un objet JSON contenant `clientid`, `clientsecret`, `url` et `serviceurls.AI_API_URL`. Vous pouvez trouver votre instance AI Core sous **Services** > **Instances et abonnements** dans le cockpit BTP. + ::: + +2. Exécutez la commande `/connect` et recherchez **SAP AI Core**. + + ```txt + /connect + ``` + +3. Entrez votre clé de service JSON. + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + +Ou définissez la variable d'environnement `AICORE_SERVICE_KEY` : + +```bash +AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode +``` + +Ou ajoutez-le à votre profil bash : + +```bash title="~/.bash_profile" +export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' +``` + +4. Définissez éventuellement l'ID de déploiement et le groupe de ressources : + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::note + Ces paramètres sont facultatifs et doivent être configurés en fonction de votre configuration SAP AI Core. + ::: + +5. Exécutez la commande `/models` pour sélectionner parmi plus de 40 modèles disponibles. + + ```txt + /models + ``` + +--- + +### Points de terminaison IA OVHcloud + +1. Rendez-vous sur le [Panneau OVHcloud](https://ovh.com/manager). Accédez à la section `Public Cloud`, `AI & Machine Learning` > `AI Endpoints` et dans l'onglet `API Keys`, cliquez sur **Créer une nouvelle clé API**. + +2. Exécutez la commande `/connect` et recherchez **OVHcloud AI Endpoints**. + + ```txt + /connect + ``` + +3. Saisissez votre clé OVHcloud AI Endpoints API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Échelle + +Pour utiliser [Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/) avec Opencode : + +1. Rendez-vous dans les [Paramètres IAM de la console Scaleway](https://console.scaleway.com/iam/api-keys) pour générer une nouvelle clé API. + +2. Exécutez la commande `/connect` et recherchez **Scaleway**. + + ```txt + /connect + ``` + +3. Entrez votre clé Scaleway API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _devstral-2-123b-instruct-2512_ ou _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Ensemble IA + +1. Rendez-vous sur [Together AI console](https://api.together.ai), créez un compte et cliquez sur **Ajouter une clé**. + +2. Exécutez la commande `/connect` et recherchez **Together AI**. + + ```txt + /connect + ``` + +3. Entrez votre clé Together AI API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Venise IA + +1. Rendez-vous sur la [Venice AI console](https://venice.ai), créez un compte et générez une clé API. + +2. Exécutez la commande `/connect` et recherchez **Venice AI**. + + ```txt + /connect + ``` + +3. Entrez votre clé Venise AI API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _Llama 3.3 70B_. + + ```txt + /models + ``` + +--- + +### Passerelle IA Vercel + +Vercel AI Gateway vous permet d'accéder aux modèles de OpenAI, Anthropic, Google, xAI et plus encore via un point de terminaison unifié. Les modèles sont proposés au prix catalogue sans majoration. + +1. Rendez-vous sur le [tableau de bord Vercel](https://vercel.com/), accédez à l'onglet **AI Gateway** et cliquez sur **API Keys** pour créer une nouvelle clé API. + +2. Exécutez la commande `/connect` et recherchez **Vercel AI Gateway**. + + ```txt + /connect + ``` + +3. Entrez votre clé Vercel AI Gateway API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle. + + ```txt + /models + ``` + +Vous pouvez également personnaliser les modèles via votre configuration opencode. Voici un exemple de spécification de l'ordre de routage du fournisseur. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +Quelques options de routage utiles : + +| Options | Descriptif | +| ------------------- | ------------------------------------------------------------------------------------------- | +| `order` | Séquence de fournisseur à essayer | +| `only` | Restreindre à des fournisseurs spécifiques | +| `zeroDataRetention` | Utilisez uniquement des fournisseurs avec des politiques de conservation des données nulles | + +--- + +### xAI + +1. Rendez-vous sur la [console xAI](https://console.x.ai/), créez un compte et générez une clé API. + +2. Exécutez la commande `/connect` et recherchez **xAI**. + + ```txt + /connect + ``` + +3. Entrez votre clé xAI API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _Grok Beta_. + + ```txt + /models + ``` + +--- + +### Z.AI + +1. Rendez-vous sur la [console Z.AI API](https://z.ai/manage-apikey/apikey-list), créez un compte et cliquez sur **Créer une nouvelle clé API**. + +2. Exécutez la commande `/connect` et recherchez **Z.AI**. + + ```txt + /connect + ``` + +Si vous êtes abonné au **Plan de codage GLM**, sélectionnez **Plan de codage Z.AI**. + +3. Entrez votre clé Z.AI API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Exécutez la commande `/models` pour sélectionner un modèle tel que _GLM-4.7_. + + ```txt + /models + ``` + +--- + +### ZenMux + +1. Rendez-vous sur le [tableau de bord ZenMux](https://zenmux.ai/settings/keys), cliquez sur **Créer une clé API** et copiez la clé. + +2. Exécutez la commande `/connect` et recherchez ZenMux. + + ```txt + /connect + ``` + +3. Saisissez la clé API du fournisseur. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. De nombreux modèles ZenMux sont préchargés par défaut, exécutez la commande `/models` pour sélectionner celui que vous souhaitez. + + ```txt + /models + ``` + +Vous pouvez également ajouter des modèles supplémentaires via votre configuration opencode. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } +} +``` + +--- + +## Fournisseur personnalisé + +Pour ajouter un fournisseur **OpenAI-compatible** qui n'est pas répertorié dans la commande `/connect` : + +:::tip +Vous pouvez utiliser n'importe quel fournisseur compatible OpenAI avec opencode. La plupart des fournisseurs d'IA modernes proposent des API compatibles OpenAI. +::: + +1. Exécutez la commande `/connect` et faites défiler jusqu'à **Autre**. + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. Saisissez un identifiant unique pour le fournisseur. + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note + Choisissez un identifiant mémorable, vous l'utiliserez dans votre fichier de configuration. + ::: + +3. Entrez votre clé API pour le fournisseur. + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. Créez ou mettez à jour votre fichier `opencode.json` dans le répertoire de votre projet : + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + +Voici les options de configuration : + +- **npm** : package AI SDK à utiliser, `@ai-sdk/openai-compatible` pour les fournisseurs compatibles OpenAI +- **nom** : nom à afficher dans l'interface utilisateur. +- **modèles** : Modèles disponibles. +- **options.baseURL** : API point de terminaison URL. +- **options.apiKey** : définissez éventuellement la clé API, si vous n'utilisez pas d'authentification. +- **options.headers** : définissez éventuellement des en-têtes personnalisés. + +En savoir plus sur les options avancées dans l'exemple ci-dessous. + +5. Exécutez la commande `/models` et votre fournisseur et vos modèles personnalisés apparaîtront dans la liste de sélection. + +--- + +##### Exemple + +Voici un exemple de définition des options `apiKey`, `headers` et modèle `limit`. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +Détails de configuration : + +- **apiKey** : défini à l'aide de la syntaxe de variable `env`, [en savoir plus](/docs/config#env-vars). +- **en-têtes** : en-têtes personnalisés envoyés avec chaque demande. +- **limit.context** : nombre maximal de jetons d'entrée acceptés par le modèle. +- **limit.output** : nombre maximal de jetons que le modèle peut générer. + +Les champs `limit` permettent à OpenCode de comprendre la quantité de contexte qu'il vous reste. Les fournisseurs standard les extraient automatiquement de models.dev. + +--- + +## Dépannage + +Si vous rencontrez des difficultés lors de la configuration d'un fournisseur, vérifiez les points suivants : + +1. **Vérifiez la configuration de l'authentification** : exécutez `opencode auth list` pour voir si les informations d'identification + pour le fournisseur sont ajoutés à votre configuration. + +Cela ne s'applique pas aux fournisseurs comme Amazon Bedrock, qui s'appuient sur des variables d'environnement pour leur authentification. + +2. Pour les fournisseurs personnalisés, vérifiez la configuration opencode et : + - Assurez-vous que l'ID du fournisseur utilisé dans la commande `/connect` correspond à l'ID de votre configuration opencode. + - Le bon package npm est utilisé pour le fournisseur. Par exemple, utilisez `@ai-sdk/cerebras` pour Cerebras. Et pour tous les autres fournisseurs compatibles OpenAI, utilisez `@ai-sdk/openai-compatible`. + - Vérifiez que le point de terminaison API correct est utilisé dans le champ `options.baseURL`. diff --git a/packages/web/src/content/docs/fr/rules.mdx b/packages/web/src/content/docs/fr/rules.mdx new file mode 100644 index 000000000..f5f9f4682 --- /dev/null +++ b/packages/web/src/content/docs/fr/rules.mdx @@ -0,0 +1,180 @@ +--- +title: Règles +description: Définissez des instructions personnalisées pour opencode. +--- + +Vous pouvez fournir des instructions personnalisées à opencode en créant un fichier `AGENTS.md`. Ceci est similaire aux règles du curseur. Il contient des instructions qui seront incluses dans le contexte du LLM pour personnaliser son comportement pour votre projet spécifique. + +--- + +## Initialiser + +Pour créer un nouveau fichier `AGENTS.md`, vous pouvez exécuter la commande `/init` dans opencode. + +:::tip +Vous devez valider le fichier `AGENTS.md` de votre projet dans Git. +::: + +Cela analysera votre projet et tout son contenu pour comprendre de quoi il s'agit et générera un fichier `AGENTS.md` avec celui-ci. Cela aide opencode à mieux naviguer dans le projet. + +Si vous avez un fichier `AGENTS.md` existant, cela tentera de l'ajouter. + +--- + +## Exemple + +Vous pouvez également simplement créer ce fichier manuellement. Voici un exemple de certaines choses que vous pouvez mettre dans un fichier `AGENTS.md`. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +Nous ajoutons ici des instructions spécifiques au projet et celles-ci seront partagées au sein de votre équipe. + +--- + +## Espèces + +opencode prend également en charge la lecture du fichier `AGENTS.md` à partir de plusieurs emplacements. Et cela répond à des objectifs différents. + +### Projet + +Placez un `AGENTS.md` à la racine de votre projet pour les règles spécifiques au projet. Celles-ci ne s'appliquent que lorsque vous travaillez dans ce répertoire ou ses sous-répertoires. + +### Mondial + +Vous pouvez également avoir des règles globales dans un fichier `~/.config/opencode/AGENTS.md`. Ceci est appliqué à toutes les sessions opencode. + +Étant donné que cela n'est pas validé par Git ni partagé avec votre équipe, nous vous recommandons de l'utiliser pour spécifier les règles personnelles que le LLM doit suivre. + +### Compatibilité des codes Claude + +Pour les utilisateurs migrant depuis Claude Code, OpenCode prend en charge les conventions de fichiers de Claude Code comme solutions de secours : + +- **Règles du projet** : `CLAUDE.md` dans le répertoire de votre projet (utilisé si aucun `AGENTS.md` n'existe) +- **Règles globales** : `~/.claude/CLAUDE.md` (utilisé si aucun `~/.config/opencode/AGENTS.md` n'existe) +- **Compétences** : `~/.claude/skills/` — voir [Compétences de l'agent](/docs/skills/) pour plus de détails + +Pour désactiver la compatibilité Claude Code, définissez l'une de ces variables d'environnement : + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## Priorité + +Lorsque opencode démarre, il recherche les fichiers de règles dans cet ordre : + +1. **Fichiers locaux** en parcourant le répertoire actuel (`AGENTS.md`, `CLAUDE.md`) +2. **Fichier global** à `~/.config/opencode/AGENTS.md` +3. **Fichier Claude Code** à `~/.claude/CLAUDE.md` (sauf si désactivé) + +Le premier fichier correspondant gagne dans chaque catégorie. Par exemple, si vous possédez à la fois `AGENTS.md` et `CLAUDE.md`, seul `AGENTS.md` est utilisé. De même, `~/.config/opencode/AGENTS.md` a priorité sur `~/.claude/CLAUDE.md`. + +--- + +## Instructions personnalisées + +Vous pouvez spécifier des fichiers d'instructions personnalisés dans votre `opencode.json` ou dans le `~/.config/opencode/opencode.json` global. Cela vous permet, à vous et à votre équipe, de réutiliser les règles existantes plutôt que d'avoir à les dupliquer dans AGENTS.md. + +Exemple: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Vous pouvez également utiliser des URL distantes pour charger des instructions à partir du Web. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +Les instructions à distance sont récupérées avec un délai d'attente de 5 secondes. + +Tous les fichiers d'instructions sont combinés avec vos fichiers `AGENTS.md`. + +--- + +## Référencement de fichiers externes + +Bien que opencode n'analyse pas automatiquement les références de fichiers dans `AGENTS.md`, vous pouvez obtenir des fonctionnalités similaires de deux manières : + +### Utilisation de opencode.json + +L'approche recommandée consiste à utiliser le champ `instructions` dans `opencode.json` : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Instructions manuelles dans AGENTS.md + +Vous pouvez apprendre à opencode à lire des fichiers externes en fournissant des instructions explicites dans votre `AGENTS.md`. Voici un exemple pratique : + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +Cette approche vous permet de : + +- Créez des fichiers de règles modulaires et réutilisables +- Partagez des règles entre projets via des liens symboliques ou des sous-modules git +- Gardez AGENTS.md concis tout en faisant référence à des directives détaillées +- Assurez-vous que opencode charge les fichiers uniquement lorsque cela est nécessaire pour une tâche spécifique. + +:::tip +Pour les monorepos ou les projets avec des normes partagées, l'utilisation de `opencode.json` avec des modèles globaux (comme `packages/*/AGENTS.md`) est plus maintenable que les instructions manuelles. +::: diff --git a/packages/web/src/content/docs/fr/sdk.mdx b/packages/web/src/content/docs/fr/sdk.mdx new file mode 100644 index 000000000..13ab37603 --- /dev/null +++ b/packages/web/src/content/docs/fr/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: Client JS de type sécurisé pour le serveur opencode. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Le SDK opencode JS/TS fournit un client de type sécurisé pour interagir avec le serveur. +Utilisez-le pour créer des intégrations et contrôler opencode par programme. + +[En savoir plus](/docs/server) sur le fonctionnement du serveur. Pour des exemples, consultez les [projects](/docs/ecosystem#projects) construits par la communauté. + +--- + +## Installer + +Installez le SDK à partir de npm : + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## Créer un client + +Créez une instance de opencode : + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +Cela démarre à la fois un serveur et un client + +#### Possibilités + +| Options | Tapez | Descriptif | Par défaut | +| ---------- | ------------- | -------------------------------------------------- | ----------- | +| `hostname` | `string` | Nom d'hôte du serveur | `127.0.0.1` | +| `port` | `number` | Port du serveur | `4096` | +| `signal` | `AbortSignal` | Signal d'abandon pour annulation | `undefined` | +| `timeout` | `number` | Délai d'attente en ms pour le démarrage du serveur | `5000` | +| `config` | `Config` | Objet de configuration | `{}` | + +--- + +## Configuration + +Vous pouvez transmettre un objet de configuration pour personnaliser le comportement. L'instance récupère toujours votre `opencode.json`, mais vous pouvez remplacer ou ajouter une configuration en ligne : + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## Client uniquement + +Si vous disposez déjà d'une instance en cours d'exécution de opencode, vous pouvez créer une instance client pour vous y connecter : + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### Possibilités + +| Options | Tapez | Descriptif | Par défaut | +| --------------- | ---------- | -------------------------------------------- | ----------------------- | +| `baseUrl` | `string` | URL du serveur | `http://localhost:4096` | +| `fetch` | `function` | Implémentation de récupération personnalisée | `globalThis.fetch` | +| `parseAs` | `string` | Méthode d'analyse des réponses | `auto` | +| `responseStyle` | `string` | Style de retour : `data` ou `fields` | `fields` | +| `throwOnError` | `boolean` | Lancez des erreurs au lieu de return | `false` | + +--- + +## Espèces + +Le SDK inclut des définitions TypeScript pour tous les types API. Importez-les directement : + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +Tous les types sont générés à partir de la spécification OpenAPI du serveur et disponibles dans le fichier de types. + +--- + +## Erreurs + +Le SDK peut générer des erreurs que vous pouvez détecter et gérer : + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## Apis + +Le SDK expose toutes les API du serveur via un client de type sécurisé. + +--- + +### Mondial + +| Méthode | Descriptif | Réponse | +| ----------------- | ---------------------------------------- | ------------------------------------ | +| `global.health()` | Vérifier l'état et la version du serveur | `{ healthy: true, version: string }` | + +--- + +#### Exemples + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### Application + +| Méthode | Descriptif | Réponse | +| -------------- | --------------------------------- | ------------------------------------------- | +| `app.log()` | Écrire une entrée de journal | `boolean` | +| `app.agents()` | Liste tous les agents disponibles | Agent[] | + +--- + +#### Exemples + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### Projet + +| Méthode | Descriptif | Réponse | +| ------------------- | -------------------------- | -------------------------------------------- | +| `project.list()` | Lister tous les projets | Projet[] | +| `project.current()` | Obtenir le projet en cours | Projet | + +--- + +#### Exemples + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### Chemin + +| Méthode | Descriptif | Réponse | +| ------------ | ------------------------ | ------------------------------------------ | +| `path.get()` | Obtenir le chemin actuel | Chemin | + +--- + +#### Exemples + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### Configuration + +| Méthode | Descriptif | Réponse | +| -------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| `config.get()` | Obtenir des informations de configuration | Configuration | +| `config.providers()` | Liste des fournisseurs et modèles par défaut | `{ providers: `Fournisseur[]`, default: { [key: string]: string } }` | + +--- + +#### Exemples + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### Séances + +| Méthode | Descriptif | Remarques | +| ---------------------------------------------------------- | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` | Liste des séances | Renvoie Session[] | +| `session.get({ path })` | Obtenir une session | Renvoie Session | +| `session.children({ path })` | Liste des sessions enfants | Renvoie Session[] | +| `session.create({ body })` | Créer une séance | Renvoie Session | +| `session.delete({ path })` | Supprimer la séance | Renvoie `boolean` | +| `session.update({ path, body })` | Mettre à jour les propriétés de la session | Renvoie Session | +| `session.init({ path, body })` | Analysez l'application et créez `AGENTS.md` | Renvoie `boolean` | +| `session.abort({ path })` | Abandonner une session en cours | Renvoie `boolean` | +| `session.share({ path })` | Séance de partage | Renvoie Session | +| `session.unshare({ path })` | Annuler le partage de la session | Renvoie Session | +| `session.summarize({ path, body })` | Résumer la séance | Renvoie `boolean` | +| `session.messages({ path })` | Liste des messages dans une session | Renvoie `{ info: `Message`, parts: `Part[]`}[]` | +| `session.message({ path })` | Obtenir les détails du message | Renvoie `{ info: `Message`, parts: `Part[]`}` | +| `session.prompt({ path, body })` | Envoyer un message d'invite | `body.noReply: true` renvoie UserMessage (contexte uniquement). La valeur par défaut renvoie AssistantMessage avec réponse IA | +| `session.command({ path, body })` | Envoyer la commande à la session | Renvoie `{ info: `AssistantMessage`, parts: `Part[]`}` | +| `session.shell({ path, body })` | Exécuter une commande shell | Renvoie AssistantMessage | +| `session.revert({ path, body })` | Rétablir un message | Renvoie Session | +| `session.unrevert({ path })` | Restaurer les messages annulés | Renvoie Session | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | Répondre à une demande d'autorisation | Renvoie `boolean` | + +--- + +#### Exemples + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### Fichiers + +| Méthode | Descriptif | Réponse | +| ------------------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| `find.text({ query })` | Rechercher du texte dans des fichiers | Tableau d'objets correspondant avec `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `find.files({ query })` | Rechercher des fichiers et des répertoires par nom | `string[]` (chemins) | +| `find.symbols({ query })` | Rechercher des symboles d'espace de travail | Symbole[] | +| `file.read({ query })` | Lire un fichier | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | Obtenir le statut des fichiers suivis | Fichier[] | + +`find.files` prend en charge quelques champs de requête facultatifs : + +- `type` : `"file"` ou `"directory"` +- `directory` : remplace la racine du projet pour la recherche +- `limit` : résultats maximum (1 à 200) + +--- + +#### Exemples + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +| Méthode | Descriptif | Réponse | +| ------------------------------ | ---------------------------------- | --------- | +| `tui.appendPrompt({ body })` | Ajouter du texte à l'invite | `boolean` | +| `tui.openHelp()` | Ouvrir la boîte de dialogue d'aide | `boolean` | +| `tui.openSessions()` | Ouvrez le sélecteur de session | `boolean` | +| `tui.openThemes()` | Ouvrez le sélecteur de thème | `boolean` | +| `tui.openModels()` | Ouvrez le sélecteur de modèle | `boolean` | +| `tui.submitPrompt()` | Soumettre l'invite actuelle | `boolean` | +| `tui.clearPrompt()` | Effacez l'invite | `boolean` | +| `tui.executeCommand({ body })` | Exécuter une commande | `boolean` | +| `tui.showToast({ body })` | Afficher la notification toast | `boolean` | + +--- + +#### Exemples + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### Authentification + +| Méthode | Descriptif | Réponse | +| ------------------- | ------------------------------------------- | --------- | +| `auth.set({ ... })` | Définir les informations d'authentification | `boolean` | + +--- + +#### Exemples + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### Événements + +| Méthode | Descriptif | Réponse | +| ------------------- | ---------------------------------------- | ---------------------------------------- | +| `event.subscribe()` | Flux d'événements envoyés par le serveur | Flux d'événements envoyés par le serveur | + +--- + +#### Exemples + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/fr/server.mdx b/packages/web/src/content/docs/fr/server.mdx new file mode 100644 index 000000000..7a6eaae8a --- /dev/null +++ b/packages/web/src/content/docs/fr/server.mdx @@ -0,0 +1,287 @@ +--- +title: Serveur +description: Interagissez avec le serveur opencode via HTTP. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +La commande `opencode serve` exécute un serveur HTTP sans tête qui expose un point de terminaison OpenAPI qu'un client opencode peut utiliser. + +--- + +### Usage + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### Possibilités + +| Drapeau | Descriptif | Par défaut | +| --------------- | -------------------------------------------------- | ---------------- | +| `--port` | Port à écouter sur | `4096` | +| `--hostname` | Nom d'hôte sur lequel écouter | `127.0.0.1` | +| `--mdns` | Activer la découverte mDNS | `false` | +| `--mdns-domain` | Nom de domaine personnalisé pour le service mDNS | `opencode.local` | +| `--cors` | Origines de navigateur supplémentaires à autoriser | `[]` | + +`--cors` peut être transmis plusieurs fois : + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### Authentification + +Définissez `OPENCODE_SERVER_PASSWORD` pour protéger le serveur avec l'authentification de base HTTP. Le nom d'utilisateur est par défaut `opencode`, ou définissez `OPENCODE_SERVER_USERNAME` pour le remplacer. Cela s’applique à la fois à `opencode serve` et à `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### Comment ça marche + +Lorsque vous exécutez `opencode`, il démarre un TUI et un serveur. Où le TUI est le +client qui parle au serveur. Le serveur expose une spécification OpenAPI 3.1 +point final. Ce point de terminaison est également utilisé pour générer un [SDK](/docs/sdk). + +:::tip +Utilisez le serveur opencode pour interagir avec opencode par programmation. +::: + +Cette architecture permet à opencode de prendre en charge plusieurs clients et vous permet d'interagir avec opencode par programme. + +Vous pouvez exécuter `opencode serve` pour démarrer un serveur autonome. Si vous avez le +opencode TUI en cours d'exécution, `opencode serve` démarrera un nouveau serveur. + +--- + +#### Connectez-vous à un serveur existant + +Lorsque vous démarrez le TUI, il attribue de manière aléatoire un port et un nom d'hôte. Vous pouvez à la place transmettre les `--hostname` et `--port` [flags](/docs/cli). Utilisez-le ensuite pour vous connecter à son serveur. + +Le point de terminaison [`/tui`](#tui) peut être utilisé pour piloter le TUI via le serveur. Par exemple, vous pouvez pré-remplir ou exécuter une invite. Cette configuration est utilisée par les plugins OpenCode [IDE](/docs/ide). + +--- + +## Spécification + +Le serveur publie une spécification OpenAPI 3.1 qui peut être consultée à l'adresse : + +``` +http://:/doc +``` + +Par exemple, `http://localhost:4096/doc`. Utilisez la spécification pour générer des clients ou inspecter les types de requêtes et de réponses. Ou visualisez-le dans un explorateur Swagger. + +--- + +## Apis + +Le serveur opencode expose les API suivantes. + +--- + +### Mondial + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ---------------- | ------------------------------------------ | ------------------------------------ | +| `GET` | `/global/health` | Obtenir l'état et la version du serveur | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | Obtenez des événements mondiaux (flux SSE) | Flux d'événements | + +--- + +### Projet + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ------------------ | -------------------------- | -------------------------------------------- | +| `GET` | `/project` | Lister tous les projets | Projet[] | +| `GET` | `/project/current` | Obtenez le projet en cours | Projet | + +--- + +### Chemin et VCS + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ------- | ---------------------------------------------------- | ------------------------------------------- | +| `GET` | `/path` | Obtenir le chemin actuel | Chemin | +| `GET` | `/vcs` | Obtenir des informations VCS pour le projet en cours | VcsInfo | + +--- + +### Exemple + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ------------------- | ----------------------------- | --------- | +| `POST` | `/instance/dispose` | Supprimer l'instance actuelle | `boolean` | + +--- + +### Configuration + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------- | +| `GET` | `/config` | Obtenir des informations de configuration | Configuration | +| `PATCH` | `/config` | Mettre à jour la configuration | Configuration | +| `GET` | `/config/providers` | Liste des fournisseurs et modèles par défaut | `{ providers: `Fournisseur[]`, default: { [key: string]: string } }` | + +--- + +### Fournisseur + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | -------------------------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------- | +| `GET` | `/provider` | Liste de tous les fournisseurs | `{ all: `Fournisseur[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | Obtenir les méthodes d'authentification du fournisseur | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | Autoriser un fournisseur en utilisant OAuth | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | Gérer le rappel OAuth pour un fournisseur | `boolean` | + +--- + +### Séances + +| Méthode | Chemin | Descriptif | Remarques | +| -------- | ---------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------ | +| `GET` | `/session` | Liste toutes les sessions | Renvoie Session[] | +| `POST` | `/session` | Créer une nouvelle session | corps : `{ parentID?, title? }`, renvoie Session | +| `GET` | `/session/status` | Obtenir l'état de la session pour toutes les sessions | Renvoie `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | Obtenez les détails de la session | Renvoie Session | +| `DELETE` | `/session/:id` | Supprimer une session et toutes ses données | Renvoie `boolean` | +| `PATCH` | `/session/:id` | Mettre à jour les propriétés de la session | corps : `{ title? }`, renvoie Session | +| `GET` | `/session/:id/children` | Obtenir les sessions enfants d'une session | Renvoie Session[] | +| `GET` | `/session/:id/todo` | Obtenez la liste de tâches pour une session | Renvoie Todo[] | +| `POST` | `/session/:id/init` | Analysez l'application et créez `AGENTS.md` | corps : `{ messageID, providerID, modelID }`, renvoie `boolean` | +| `POST` | `/session/:id/fork` | Forkez une session existante à un message | corps : `{ messageID? }`, renvoie Session | +| `POST` | `/session/:id/abort` | Abandonner une session en cours | Renvoie `boolean` | +| `POST` | `/session/:id/share` | Partager une séance | Renvoie Session | +| `DELETE` | `/session/:id/share` | Annuler le partage d'une session | Renvoie Session | +| `GET` | `/session/:id/diff` | Obtenez le diff pour cette session | requête : `messageID?`, renvoie FileDiff[] | +| `POST` | `/session/:id/summarize` | Résumer la séance | corps : `{ providerID, modelID }`, renvoie `boolean` | +| `POST` | `/session/:id/revert` | Rétablir un message | corps : `{ messageID, partID? }`, renvoie `boolean` | +| `POST` | `/session/:id/unrevert` | Restaurer tous les messages annulés | Renvoie `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | Répondre à une demande d'autorisation | corps : `{ response, remember? }`, renvoie `boolean` | + +--- + +### Messages + +| Méthode | Chemin | Descriptif | Remarques | +| ------- | --------------------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` | Liste des messages dans une session | requête : `limit?`, renvoie `{ info: `Message`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` | Envoyer un message et attendre une réponse | corps : `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, renvoie `{ info: `Message`, parts: `Part[]`}` | +| `GET` | `/session/:id/message/:messageID` | Obtenir les détails du message | Renvoie `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/prompt_async` | Envoyer un message de manière asynchrone (pas d'attente) | body : identique à `/session/:id/message`, renvoie `204 No Content` | +| `POST` | `/session/:id/command` | Exécuter une commande slash | corps : `{ messageID?, agent?, model?, command, arguments }`, renvoie `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/shell` | Exécuter une commande shell | corps : `{ agent, model?, command }`, renvoie `{ info: `Message`, parts: `Part[]`}` | + +--- + +### Commandes + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ---------- | -------------------------- | --------------------------------------------- | +| `GET` | `/command` | Liste toutes les commandes | Command[] | + +--- + +### Fichiers + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ------------------------ | -------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | Rechercher du texte dans des fichiers | Tableau d'objets correspondant avec `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | Rechercher des fichiers et des répertoires par nom | `string[]` (chemins) | +| `GET` | `/find/symbol?query=` | Rechercher des symboles d'espace de travail | Symbole[] | +| `GET` | `/file?path=` | Liste des fichiers et répertoires | FileNode[] | +| `GET` | `/file/content?path=

` | Lire un fichier | FileContent | +| `GET` | `/file/status` | Obtenir le statut des fichiers suivis | Fichier[] | + +#### Paramètres de requête `/find/file` + +- `query` (obligatoire) — chaîne de recherche (correspondance floue) +- `type` (facultatif) — limiter les résultats à `"file"` ou `"directory"` +- `directory` (facultatif) — remplace la racine du projet pour la recherche +- `limit` (facultatif) — résultats maximum (1 à 200) +- `dirs` (facultatif) — indicateur hérité (`"false"` renvoie uniquement les fichiers) + +--- + +### Outils (expérimentaux) + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ------------------------------------------- | ----------------------------------------------------------- | -------------------------------------------------- | +| `GET` | `/experimental/tool/ids` | Répertorier tous les ID d'outils | ToolIDs | +| `GET` | `/experimental/tool?provider=

&model=` | Répertorier les outils avec des schémas JSON pour un modèle | Liste d'outils | + +--- + +### LSP, formateurs et MCP + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ------------ | ------------------------------------ | -------------------------------------------------------- | +| `GET` | `/lsp` | Obtenir l'état du serveur LSP | LSPStatus[] | +| `GET` | `/formatter` | Obtenir le statut du formateur | FormatterStatus[] | +| `GET` | `/mcp` | Obtenir l'état du serveur MCP | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | Ajouter dynamiquement le serveur MCP | corps : `{ name, config }`, renvoie l'objet d'état MCP | + +--- + +### Agents + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | -------- | --------------------------------- | ------------------------------------------- | +| `GET` | `/agent` | Liste tous les agents disponibles | Agent[] | + +--- + +### Enregistrement + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ------ | --------------------------------------------------------------------------- | --------- | +| `POST` | `/log` | Écrire une entrée de journal. Corps : `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ----------------------- | -------------------------------------------------- | ---------------------------- | +| `POST` | `/tui/append-prompt` | Ajouter du texte à l'invite | `boolean` | +| `POST` | `/tui/open-help` | Ouvrir la boîte de dialogue d'aide | `boolean` | +| `POST` | `/tui/open-sessions` | Ouvrez le sélecteur de session | `boolean` | +| `POST` | `/tui/open-themes` | Ouvrez le sélecteur de thème | `boolean` | +| `POST` | `/tui/open-models` | Ouvrez le sélecteur de modèle | `boolean` | +| `POST` | `/tui/submit-prompt` | Soumettre l'invite actuelle | `boolean` | +| `POST` | `/tui/clear-prompt` | Effacez l'invite | `boolean` | +| `POST` | `/tui/execute-command` | Exécuter une commande (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | Afficher le toast (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | Attendre la prochaine demande de contrôle | Objet de demande de contrôle | +| `POST` | `/tui/control/response` | Répondre à une demande de contrôle (`{ body }`) | `boolean` | + +--- + +### Authentification + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ----------- | --------------------------------------------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | Définissez les informations d'authentification. Le corps doit correspondre au schéma du fournisseur | `boolean` | + +--- + +### Événements + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | -------- | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | +| `GET` | `/event` | Flux d’événements envoyés par le serveur. Le premier événement est `server.connected`, puis les événements de bus | Flux d'événements envoyés par le serveur | + +--- + +### Documents + +| Méthode | Chemin | Descriptif | Réponse | +| ------- | ------ | ------------------------- | ------------------------------------ | +| `GET` | `/doc` | Spécification OpenAPI 3.1 | Page HTML avec spécification OpenAPI | diff --git a/packages/web/src/content/docs/fr/share.mdx b/packages/web/src/content/docs/fr/share.mdx new file mode 100644 index 000000000..acc7c03f8 --- /dev/null +++ b/packages/web/src/content/docs/fr/share.mdx @@ -0,0 +1,128 @@ +--- +title: Partager +description: Partagez vos conversations OpenCode. +--- + +La fonctionnalité de partage de OpenCode vous permet de créer des liens publics vers vos conversations OpenCode, afin que vous puissiez collaborer avec vos coéquipiers ou obtenir de l'aide d'autres personnes. + +:::note +Les conversations partagées sont accessibles publiquement à toute personne disposant du lien. +::: + +--- + +## Comment ça marche + +Lorsque vous partagez une conversation, OpenCode : + +1. Crée un URL public unique pour votre session +2. Synchronise l'historique de vos conversations avec nos serveurs +3. Rend la conversation accessible via le lien partageable — `opncd.ai/s/` + +--- + +## Partage + +OpenCode prend en charge trois modes de partage qui contrôlent la manière dont les conversations sont partagées : + +--- + +### Manuel (par défaut) + +Par défaut, OpenCode utilise le mode de partage manuel. Les sessions ne sont pas partagées automatiquement, mais vous pouvez les partager manuellement à l'aide de la commande `/share` : + +``` +/share +``` + +Cela générera un URL unique qui sera copié dans votre presse-papiers. + +Pour définir explicitement le mode manuel dans votre [fichier de configuration](/docs/config) : + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### Partage automatique + +Vous pouvez activer le partage automatique pour toutes les nouvelles conversations en définissant l'option `share` sur `"auto"` dans votre [fichier de configuration](/docs/config) : + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +Avec le partage automatique activé, chaque nouvelle conversation sera automatiquement partagée et un lien sera généré. + +--- + +### Désactivé + +Vous pouvez désactiver entièrement le partage en définissant l'option `share` sur `"disabled"` dans votre [fichier de configuration](/docs/config) : + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +Pour appliquer cela au sein de votre équipe pour un projet donné, ajoutez-le au `opencode.json` dans votre projet et enregistrez-vous dans Git. + +--- + +## Annuler le partage + +Pour arrêter de partager une conversation et la supprimer de l'accès public : + +``` +/unshare +``` + +Cela supprimera le lien de partage et supprimera les données liées à la conversation. + +--- + +## Confidentialité + +Il y a quelques points à garder à l’esprit lorsque vous partagez une conversation. + +--- + +### Conservation des données + +Les conversations partagées restent accessibles jusqu'à ce que vous les annuliez explicitement. Ce +comprend : + +- Historique complet des conversations +- Tous les messages et réponses +- Métadonnées de session + +--- + +### Recommandations + +- Partagez uniquement les conversations qui ne contiennent pas d'informations sensibles. +- Examinez le contenu de la conversation avant de la partager. +- Annulez le partage des conversations une fois la collaboration terminée. +- Évitez de partager des conversations avec du code propriétaire ou des données confidentielles. +- Pour les projets sensibles, désactivez complètement le partage. + +--- + +## Pour les entreprises + +Pour les déploiements en entreprise, la fonctionnalité de partage peut être : + +- **Désactivé** entièrement pour des raisons de conformité en matière de sécurité +- **Réservé** aux utilisateurs authentifiés via SSO uniquement +- **Auto-hébergé** sur votre propre infrastructure + +[En savoir plus](/docs/enterprise) sur l'utilisation de opencode dans votre organisation. diff --git a/packages/web/src/content/docs/fr/skills.mdx b/packages/web/src/content/docs/fr/skills.mdx new file mode 100644 index 000000000..86f6b9f27 --- /dev/null +++ b/packages/web/src/content/docs/fr/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "Compétences des agents" +description: "Définir un comportement réutilisable via les définitions SKILL.md" +--- + +Les compétences d'agent permettent à OpenCode de découvrir des instructions réutilisables à partir de votre dépôt ou de votre répertoire personnel. +Les compétences sont chargées à la demande via l'outil natif `skill` : les agents voient les compétences disponibles et peuvent charger le contenu complet en cas de besoin. + +--- + +## Placer des fichiers + +Créez un dossier par nom de compétence et insérez-y un `SKILL.md`. +OpenCode recherche ces emplacements : + +- Configuration du projet : `.opencode/skills//SKILL.md` +- Configuration globale : `~/.config/opencode/skills//SKILL.md` +- Compatible Projet Claude : `.claude/skills//SKILL.md` +- Compatible Global Claude : `~/.claude/skills//SKILL.md` +- Compatible avec l'agent de projet : `.agents/skills//SKILL.md` +- Compatible avec les agents globaux : `~/.agents/skills//SKILL.md` + +--- + +## Comprendre la découverte + +Pour les chemins locaux du projet, OpenCode remonte de votre répertoire de travail actuel jusqu'à ce qu'il atteigne l'arbre de travail git. +Il charge tout `skills/*/SKILL.md` correspondant dans `.opencode/` et tout `.claude/skills/*/SKILL.md` ou `.agents/skills/*/SKILL.md` correspondant en cours de route. + +Les définitions globales sont également chargées à partir de `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` et `~/.agents/skills/*/SKILL.md`. + +--- + +## Écrire un texte de présentation + +Chaque `SKILL.md` doit commencer par YAML frontmatter. +Seuls ces champs sont reconnus : + +- `name` (obligatoire) +- `description` (obligatoire) +- `license` (facultatif) +- `compatibility` (facultatif) +- `metadata` (facultatif, mappage chaîne à chaîne) + +Les champs de contenu inconnus sont ignorés. + +--- + +## Valider les noms + +`name` doit : + +- Comprenant entre 1 et 64 caractères +- Être alphanumérique en minuscules avec des séparateurs à tiret unique +- Ne commence ni ne termine par `-` +- Ne contient pas de `--` consécutifs +- Faites correspondre le nom du répertoire qui contient `SKILL.md` + +Expression régulière équivalente : + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## Suivez les règles de longueur + +`description` doit comporter entre 1 et 1 024 caractères. +Gardez-le suffisamment précis pour que l'agent puisse choisir correctement. + +--- + +## Utiliser un exemple + +Créez `.opencode/skills/git-release/SKILL.md` comme ceci : + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## Reconnaître la description de l'outil + +OpenCode répertorie les compétences disponibles dans la description de l'outil `skill`. +Chaque entrée comprend le nom et la description de la compétence : + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +L'agent charge une compétence en appelant l'outil : + +``` +skill({ name: "git-release" }) +``` + +--- + +## Configurer les autorisations + +Contrôlez les compétences auxquelles les agents peuvent accéder à l'aide d'autorisations basées sur des modèles dans `opencode.json` : + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Autorisation | Comportement | +| ---------- | ----------------------------------------- | +| `allow` | Les compétences se chargent immédiatement | +| `deny` | Compétence masquée à l'agent, accès refusé | +| `ask` | L'utilisateur est invité à donner son approbation avant le chargement | + +Les modèles prennent en charge les caractères génériques : `internal-*` correspond à `internal-docs`, `internal-tools`, etc. + +--- + +## Remplacement par agent + +Accordez à des agents spécifiques des autorisations différentes de celles par défaut globales. + +**Pour les agents personnalisés** (dans la rubrique Agent) : + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**Pour les agents intégrés** (dans `opencode.json`) : + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## Désactiver l'outil de compétences + +Désactivez complètement les compétences pour les agents qui ne devraient pas les utiliser : + +**Pour les agents personnalisés** : + +```yaml +--- +tools: + skill: false +--- +``` + +**Pour les agents intégrés** : + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +Lorsqu'elle est désactivée, la section `` est entièrement omise. + +--- + +## Dépanner le chargement + +Si une compétence n'apparaît pas : + +1. Vérifiez que `SKILL.md` est écrit en majuscules +2. Vérifiez que le frontmatter inclut `name` et `description` +3. Assurez-vous que les noms des compétences sont uniques sur tous les sites +4. Vérifiez les autorisations : les compétences avec `deny` sont masquées aux agents diff --git a/packages/web/src/content/docs/fr/themes.mdx b/packages/web/src/content/docs/fr/themes.mdx new file mode 100644 index 000000000..0ae974cf7 --- /dev/null +++ b/packages/web/src/content/docs/fr/themes.mdx @@ -0,0 +1,369 @@ +--- +title: Thèmes +description: Sélectionnez un thème intégré ou définissez le vôtre. +--- + +Avec OpenCode, vous pouvez choisir parmi plusieurs thèmes intégrés, utiliser un thème qui s'adapte au thème de votre terminal ou définir votre propre thème personnalisé. + +Par défaut, OpenCode utilise notre propre thème `opencode`. + +--- + +## Exigences des terminaux + +Pour que les thèmes s'affichent correctement avec leur palette de couleurs complète, votre terminal doit prendre en charge **truecolor** (couleur 24 bits). La plupart des terminaux modernes le prennent en charge par défaut, mais vous devrez peut-être l'activer : + +- **Vérifiez le support** : Exécutez `echo $COLORTERM` - il devrait afficher `truecolor` ou `24bit` +- **Activer truecolor** : définissez la variable d'environnement `COLORTERM=truecolor` dans votre profil shell +- **Compatibilité des terminaux** : assurez-vous que votre émulateur de terminal prend en charge les couleurs 24 bits (la plupart des terminaux modernes comme iTerm2, Alacritty, Kitty, Windows Terminal et les versions récentes de GNOME Terminal le font) + +Sans la prise en charge de TrueColor, les thèmes peuvent apparaître avec une précision des couleurs réduite ou revenir à l'approximation de 256 couleurs la plus proche. + +--- + +## Thèmes intégrés + +OpenCode est livré avec plusieurs thèmes intégrés. + +| Nom | Descriptif | +| ---------------------- | ---------------------------------------------------------------------------- | +| `system` | S'adapte à la couleur de fond de votre terminal | +| `tokyonight` | Basé sur le thème [Tokyonight](https://github.com/folke/tokyonight.nvim) | +| `everforest` | Basé sur le thème [Everforest](https://github.com/sainnhe/everforest) | +| `ayu` | Basé sur le thème sombre [Ayu](https://github.com/ayu-theme) | +| `catppuccin` | Basé sur le thème [Catppuccin](https://github.com/catppuccin) | +| `catppuccin-macchiato` | Basé sur le thème [Catppuccin](https://github.com/catppuccin) | +| `gruvbox` | Basé sur le thème [Gruvbox](https://github.com/morhetz/gruvbox) | +| `kanagawa` | Basé sur le thème [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | +| `nord` | Basé sur le thème [Nord](https://github.com/nordtheme/nord) | +| `matrix` | Vert style hacker sur thème noir | +| `one-dark` | Basé sur le thème [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) Dark | + +De plus, nous ajoutons constamment de nouveaux thèmes. + +--- + +## Thème système + +Le thème `system` est conçu pour s'adapter automatiquement à la palette de couleurs de votre terminal. Contrairement aux thèmes traditionnels qui utilisent des couleurs fixes, le thème _system_ : + +- **Génère une échelle de gris** : crée une échelle de gris personnalisée basée sur la couleur d'arrière-plan de votre terminal, garantissant un contraste optimal. +- **Utilise les couleurs ANSI** : exploite les couleurs ANSI standard (0-15) pour la coloration syntaxique et les éléments de l'interface utilisateur, qui respectent la palette de couleurs de votre terminal. +- **Préserve les paramètres par défaut du terminal** : utilise `none` pour les couleurs du texte et de l'arrière-plan afin de conserver l'apparence native de votre terminal. + +Le thème système est destiné aux utilisateurs qui : + +- Vous souhaitez que OpenCode corresponde à l'apparence de leur terminal +- Utiliser des schémas de couleurs de terminal personnalisés +- Préférez une apparence cohérente sur toutes les applications de terminal + +--- + +## Utiliser un thème + +Vous pouvez sélectionner un thème en affichant la sélection de thème avec la commande `/theme`. Ou vous pouvez le spécifier dans votre [config](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Thèmes personnalisés + +OpenCode prend en charge un système de thèmes flexible basé sur JSON qui permet aux utilisateurs de créer et de personnaliser facilement des thèmes. + +--- + +### Hiérarchie + +Les thèmes sont chargés à partir de plusieurs répertoires dans l'ordre suivant, les répertoires ultérieurs remplaçant les précédents : + +1. **Thèmes intégrés** - Ceux-ci sont intégrés au binaire +2. **Répertoire de configuration utilisateur** - Défini dans `~/.config/opencode/themes/*.json` ou `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Répertoire racine du projet** - Défini dans `/.opencode/themes/*.json` +4. **Répertoire de travail actuel** - Défini dans `./.opencode/themes/*.json` + +Si plusieurs répertoires contiennent un thème portant le même nom, le thème du répertoire ayant la priorité la plus élevée sera utilisé. + +--- + +### Création d'un thème + +Pour créer un thème personnalisé, créez un fichier JSON dans l'un des répertoires de thème. + +Pour les thèmes à l’échelle de l’utilisateur : + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +Et pour des thèmes spécifiques au projet. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### Format JSON + +Les thèmes utilisent un format JSON flexible avec prise en charge de : + +- **Couleurs hexadécimales** : `"#ffffff"` +- **Couleurs ANSI** : `3` (0-255) +- **Références de couleurs** : `"primary"` ou définitions personnalisées +- **Variantes sombre/clair** : `{"dark": "#000", "light": "#fff"}` +- **Aucune couleur** : `"none"` - Utilise la couleur par défaut du terminal ou le transparent + +--- + +### Définitions des couleurs + +La section `defs` est facultative et elle permet de définir des couleurs réutilisables pouvant être référencées dans le thème. + +--- + +### Paramètres par défaut du terminal + +La valeur spéciale `"none"` peut être utilisée pour n'importe quelle couleur afin d'hériter de la couleur par défaut du terminal. Ceci est particulièrement utile pour créer des thèmes qui se fondent parfaitement dans la palette de couleurs de votre terminal : + +- `"text": "none"` - Utilise la couleur de premier plan par défaut du terminal +- `"background": "none"` - Utilise la couleur d'arrière-plan par défaut du terminal + +--- + +### Exemple + +Voici un exemple de thème personnalisé : + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/fr/tools.mdx b/packages/web/src/content/docs/fr/tools.mdx new file mode 100644 index 000000000..20045e147 --- /dev/null +++ b/packages/web/src/content/docs/fr/tools.mdx @@ -0,0 +1,379 @@ +--- +title: Outils +description: Gérez les outils qu'un LLM peut utiliser. +--- + +Les outils permettent au LLM d'effectuer des actions dans votre base de code. OpenCode est livré avec un ensemble d'outils intégrés, mais vous pouvez l'étendre avec [outils personnalisés](/docs/custom-tools) ou [serveurs MCP](/docs/mcp-servers). + +Par défaut, tous les outils sont **activés** et n'ont pas besoin d'autorisation pour s'exécuter. Vous pouvez contrôler le comportement de l'outil via [permissions](/docs/permissions). + +--- + +## Configurer + +Utilisez le champ `permission` pour contrôler le comportement de l'outil. Vous pouvez autoriser, refuser ou exiger une approbation pour chaque outil. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +Vous pouvez également utiliser des caractères génériques pour contrôler plusieurs outils à la fois. Par exemple, pour exiger l'approbation de tous les outils d'un serveur MCP : + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[En savoir plus](/docs/permissions) sur la configuration des autorisations. + +--- + +## Intégré + +Voici tous les outils intégrés disponibles dans OpenCode. + +--- + +### frapper + +Exécutez des commandes shell dans votre environnement de projet. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +Cet outil permet au LLM d'exécuter des commandes de terminal telles que `npm install`, `git status` ou toute autre commande shell. + +--- + +### modifier + +Modifiez les fichiers existants en utilisant des remplacements de chaînes exacts. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Cet outil effectue des modifications précises des fichiers en remplaçant les correspondances de texte exactes. C'est la principale façon dont LLM modifie le code. + +--- + +### écrire + +Créez de nouveaux fichiers ou écrasez ceux existants. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Utilisez-le pour permettre au LLM de créer de nouveaux fichiers. Il écrasera les fichiers existants s'ils existent déjà. + +:::note +L'outil `write` est contrôlé par l'autorisation `edit`, qui couvre toutes les modifications de fichiers (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### lire + +Lisez le contenu du fichier à partir de votre base de code. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +Cet outil lit les fichiers et renvoie leur contenu. Il prend en charge la lecture de plages de lignes spécifiques pour les fichiers volumineux. + +--- + +### grep + +Recherchez le contenu du fichier à l’aide d’expressions régulières. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Recherche rapide de contenu dans votre base de code. Prend en charge la syntaxe regex complète et le filtrage des modèles de fichiers. + +--- + +### globe + +Recherchez des fichiers par correspondance de modèles. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +Recherchez des fichiers à l'aide de modèles globaux tels que `**/*.js` ou `src/**/*.ts`. Renvoie les chemins de fichiers correspondants triés par heure de modification. + +--- + +### liste + +Répertoriez les fichiers et les répertoires dans un chemin donné. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +Cet outil répertorie le contenu du répertoire. Il accepte les modèles globaux pour filtrer les résultats. + +--- + +### lsp (expérimental) + +Interagissez avec vos serveurs LSP configurés pour obtenir des fonctionnalités d'intelligence du code telles que des définitions, des références, des informations de survol et une hiérarchie d'appels. + +:::note +Cet outil n'est disponible que lorsque `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (ou `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +Les opérations prises en charge incluent `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` et `outgoingCalls`. + +Pour configurer les serveurs LSP disponibles pour votre projet, consultez [LSP Servers](/docs/lsp). + +--- + +### correctif + +Appliquez des correctifs aux fichiers. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Cet outil applique les fichiers de correctifs à votre base de code. Utile pour appliquer des différences et des correctifs provenant de diverses sources. + +:::note +L'outil `patch` est contrôlé par l'autorisation `edit`, qui couvre toutes les modifications de fichiers (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### compétence + +Chargez une [skill](/docs/skills) (un fichier `SKILL.md`) et renvoyez son contenu dans la conversation. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### à écrire + +Gérez les listes de tâches pendant les sessions de codage. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +Crée et met à jour des listes de tâches pour suivre la progression lors d'opérations complexes. Le LLM l'utilise pour organiser des tâches en plusieurs étapes. + +:::note +Cet outil est désactivé par défaut pour les sous-agents, mais vous pouvez l'activer manuellement. [En savoir plus](/docs/agents/#permissions) +::: + +--- + +### todore + +Lisez les listes de tâches existantes. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +Lit l'état actuel de la liste de tâches. Utilisé par le LLM pour suivre les tâches en attente ou terminées. + +:::note +Cet outil est désactivé par défaut pour les sous-agents, mais vous pouvez l'activer manuellement. [En savoir plus](/docs/agents/#permissions) +::: + +--- + +### récupération sur le Web + +Récupérer du contenu Web. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +Permet au LLM de récupérer et de lire des pages Web. Utile pour rechercher de la documentation ou rechercher des ressources en ligne. + +--- + +### recherche sur le Web + +Recherchez des informations sur le Web. + +:::note +Cet outil n'est disponible que lors de l'utilisation du fournisseur OpenCode ou lorsque la variable d'environnement `OPENCODE_ENABLE_EXA` est définie sur une valeur véridique (par exemple, `true` ou `1`). + +À activer lors du lancement de OpenCode : + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Effectue des recherches sur le Web à l'aide d'Exa AI pour trouver des informations pertinentes en ligne. Utile pour rechercher des sujets, trouver des événements actuels ou collecter des informations au-delà de la limite des données de formation. + +Aucune clé API n'est requise : l'outil se connecte directement au service MCP hébergé d'Exa AI sans authentification. + +:::tip +Utilisez `websearch` lorsque vous avez besoin de rechercher des informations (découverte) et `webfetch` lorsque vous devez récupérer le contenu d'un URL spécifique (récupération). +::: + +--- + +### question + +Posez des questions à l'utilisateur pendant l'exécution. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +Cet outil permet au LLM de poser des questions à l'utilisateur lors d'une tâche. C'est utile pour : + +- Recueillir les préférences ou les exigences des utilisateurs +- Clarifier les instructions ambiguës +- Obtenir des décisions sur les choix de mise en œuvre +- Offrir des choix sur la direction à prendre + +Chaque question comprend un en-tête, le texte de la question et une liste d'options. Les utilisateurs peuvent choisir parmi les options proposées ou saisir une réponse personnalisée. Lorsqu'il y a plusieurs questions, les utilisateurs peuvent naviguer entre elles avant de soumettre toutes les réponses. + +--- + +## Outils personnalisés + +Les outils personnalisés vous permettent de définir vos propres fonctions que le LLM peut appeler. Ceux-ci sont définis dans votre fichier de configuration et peuvent exécuter du code arbitraire. + +[En savoir plus](/docs/custom-tools) sur la création d'outils personnalisés. + +--- + +## Serveurs MCP + +Les serveurs MCP (Model Context Protocol) vous permettent d'intégrer des outils et services externes. Cela inclut l'accès à la base de données, les intégrations API et les services tiers. + +[En savoir plus](/docs/mcp-servers) sur la configuration des serveurs MCP. + +--- + +## Internes + +En interne, des outils comme `grep`, `glob` et `list` utilisent [ripgrep](https://github.com/BurntSushi/ripgrep) sous le capot. Par défaut, ripgrep respecte les modèles `.gitignore`, ce qui signifie que les fichiers et répertoires répertoriés dans votre `.gitignore` seront exclus des recherches et des listes. + +--- + +### Ignorer les modèles + +Pour inclure des fichiers qui seraient normalement ignorés, créez un fichier `.ignore` à la racine de votre projet. Ce fichier peut autoriser explicitement certains chemins. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +Par exemple, ce fichier `.ignore` permet à ripgrep de rechercher dans les répertoires `node_modules/`, `dist/` et `build/` même s'ils sont répertoriés dans `.gitignore`. diff --git a/packages/web/src/content/docs/fr/troubleshooting.mdx b/packages/web/src/content/docs/fr/troubleshooting.mdx new file mode 100644 index 000000000..b33e476e2 --- /dev/null +++ b/packages/web/src/content/docs/fr/troubleshooting.mdx @@ -0,0 +1,300 @@ +--- +title: Dépannage +description: Problèmes courants et comment les résoudre. +--- + +Pour déboguer les problèmes avec OpenCode, commencez par vérifier les journaux et les données locales qu'il stocke sur le disque. + +--- + +## Journaux + +Les fichiers journaux sont écrits dans : + +- **macOS/Linux** : `~/.local/share/opencode/log/` +- **Windows** : appuyez sur `WIN+R` et collez `%USERPROFILE%\.local\share\opencode\log` + +Les fichiers journaux sont nommés avec des horodatages (par exemple, `2025-01-09T123456.log`) et les 10 fichiers journaux les plus récents sont conservés. + +Vous pouvez définir le niveau de journalisation avec l'option de ligne de commande `--log-level` pour obtenir des informations de débogage plus détaillées. Par exemple, `opencode --log-level DEBUG`. + +--- + +## Stockage + +opencode stocke les données de session et autres données d'application sur le disque à l'emplacement : + +- **macOS/Linux** : `~/.local/share/opencode/` +- **Windows** : appuyez sur `WIN+R` et collez `%USERPROFILE%\.local\share\opencode` + +Ce répertoire contient : + +- `auth.json` - Données d'authentification telles que les clés API, les jetons OAuth +- `log/` - Journaux d'applications +- `project/` - Données spécifiques au projet telles que les données de session et de message + - Si le projet se trouve dans un dépôt Git, il est stocké dans `.//storage/` + - S'il ne s'agit pas d'un dépôt Git, il est stocké dans `./global/storage/` + +--- + +## Application de bureau + +OpenCode Desktop exécute un serveur OpenCode local (le side-car `opencode-cli`) en arrière-plan. La plupart des problèmes sont causés par un plugin qui se comporte mal, un cache corrompu ou un mauvais paramètre du serveur. + +### Vérifications rapides + +- Quittez complètement et relancez l'application. +- Si l'application affiche un écran d'erreur, cliquez sur **Redémarrer** et copiez les détails de l'erreur. +- macOS uniquement : menu `OpenCode` -> **Recharger la vue Web** (aide si l'interface utilisateur est vide/gelée). + +--- + +### Désactiver les plugins + +Si l'application de bureau plante au lancement, se bloque ou se comporte étrangement, commencez par désactiver les plugins. + +#### Vérifiez la configuration globale + +Ouvrez votre fichier de configuration global et recherchez une clé `plugin`. + +- **macOS/Linux** : `~/.config/opencode/opencode.jsonc` (ou `~/.config/opencode/opencode.json`) +- **macOS/Linux** (anciennes installations) : `~/.local/share/opencode/opencode.jsonc` +- **Windows** : appuyez sur `WIN+R` et collez `%USERPROFILE%\.config\opencode\opencode.jsonc` + +Si vous avez configuré des plugins, désactivez-les temporairement en supprimant la clé ou en la définissant sur un tableau vide : + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### Vérifiez les répertoires des plugins + +OpenCode peut également charger des plugins locaux à partir du disque. Écartez-les temporairement (ou renommez le dossier) et redémarrez l'application de bureau : + +- **Plugins mondiaux** + - **macOS/Linux** : `~/.config/opencode/plugins/` + - **Windows** : appuyez sur `WIN+R` et collez `%USERPROFILE%\.config\opencode\plugins` +- **Plugins de projet** (uniquement si vous utilisez une configuration par projet) + - `/.opencode/plugins/` + +Si l'application recommence à fonctionner, réactivez les plugins un par un pour trouver celui à l'origine du problème. + +--- + +### Vider le cache + +Si la désactivation des plugins ne résout pas le problème (ou si l'installation d'un plugin est bloquée), videz le cache afin que OpenCode puisse le reconstruire. + +1. Quittez complètement OpenCode Desktop. +2. Supprimez le répertoire cache : + +- **macOS** : Finder -> `Cmd+Shift+G` -> coller `~/.cache/opencode` +- **Linux** : supprimez `~/.cache/opencode` (ou exécutez `rm -rf ~/.cache/opencode`) +- **Windows** : appuyez sur `WIN+R` et collez `%USERPROFILE%\.cache\opencode` + +3. Redémarrez le bureau OpenCode. + +--- + +### Résoudre les problèmes de connexion au serveur + +OpenCode Desktop peut soit démarrer son propre serveur local (par défaut), soit se connecter à un serveur URL que vous avez configuré. + +Si vous voyez une boîte de dialogue **« Échec de la connexion »** (ou si l'application ne dépasse jamais l'écran de démarrage), recherchez un serveur personnalisé URL. + +#### Effacer le serveur par défaut du bureau URL + +Depuis l'écran d'accueil, cliquez sur le nom du serveur (avec le point d'état) pour ouvrir le sélecteur de serveur. Dans la section **Serveur par défaut**, cliquez sur **Effacer**. + +#### Supprimez `server.port` / `server.hostname` de votre configuration + +Si votre `opencode.json(c)` contient une section `server`, supprimez-la temporairement et redémarrez l'application de bureau. + +#### Vérifier les variables d'environnement + +Si `OPENCODE_PORT` est défini dans votre environnement, l'application de bureau tentera d'utiliser ce port pour le serveur local. + +- Désactivez `OPENCODE_PORT` (ou choisissez un port libre) et redémarrez. + +--- + +### Linux : Problèmes Wayland / X11 + +Sur Linux, certaines configurations Wayland peuvent provoquer des fenêtres vides ou des erreurs de composition. + +- Si vous êtes sur Wayland et que l'application est vide/plante, essayez de la lancer avec `OC_ALLOW_WAYLAND=1`. +- Si cela aggrave les choses, supprimez-le et essayez plutôt de le lancer sous une session X11. + +--- + +### Windows : exécution WebView2 + +Sur Windows, OpenCode Desktop nécessite Microsoft Edge **WebView2 Runtime**. Si l'application s'ouvre sur une fenêtre vide ou ne démarre pas, installez/mettez à jour WebView2 et réessayez. + +--- + +### Windows : problèmes de performances généraux + +Si vous rencontrez des performances lentes, des problèmes d'accès aux fichiers ou des problèmes de terminal sur Windows, essayez d'utiliser [WSL (Windows Sous-système pour Linux)](/docs/windows-wsl). WSL fournit un environnement Linux qui fonctionne de manière plus transparente avec les fonctionnalités de OpenCode. + +--- + +### Les notifications ne s'affichent pas + +OpenCode Desktop affiche uniquement les notifications système lorsque : + +- les notifications sont activées pour OpenCode dans les paramètres de votre système d'exploitation, et +- la fenêtre de l'application n'est pas ciblée. + +--- + +### Réinitialiser le stockage des applications de bureau (dernier recours) + +Si l'application ne démarre pas et que vous ne pouvez pas effacer les paramètres depuis l'interface utilisateur, réinitialisez l'état enregistré de l'application de bureau. + +1. Quittez le bureau OpenCode. +2. Recherchez et supprimez ces fichiers (ils se trouvent dans le répertoire de données de l'application OpenCode Desktop) : + +- `opencode.settings.dat` (serveur de bureau par défaut URL) +- `opencode.global.dat` et `opencode.workspace.*.dat` (état de l'interface utilisateur comme les serveurs/projets récents) + +Pour trouver rapidement le répertoire : + +- **macOS** : Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (puis recherchez les noms de fichiers ci-dessus) +- **Linux** : recherchez sous `~/.local/share` les noms de fichiers ci-dessus +- **Windows** : appuyez sur `WIN+R` -> `%APPDATA%` (puis recherchez les noms de fichiers ci-dessus) + +--- + +## Obtenir de l'aide + +Si vous rencontrez des problèmes avec OpenCode : + +1. **Signaler les problèmes le GitHub** + +La meilleure façon de signaler des bogues ou de demander des fonctionnalités consiste à utiliser notre référentiel GitHub : + +[**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + +Avant de créer un nouveau problème, recherchez les problèmes existants pour voir si votre problème a déjà été signalé. + +2. **Rejoignez notre Discord** + +Pour obtenir de l'aide en temps réel et une discussion communautaire, rejoignez notre serveur Discord : + +[**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Problèmes courants + +Voici quelques problèmes courants et comment les résoudre. + +--- + +### OpenCode ne démarre pas + +1. Vérifiez les journaux pour les messages d'erreur +2. Essayez d'exécuter avec `--print-logs` pour voir la sortie dans le terminal +3. Assurez-vous d'avoir la dernière version avec `opencode upgrade` + +--- + +### Problèmes d'authentification + +1. Essayez de vous réauthentifier avec la commande `/connect` dans le TUI +2. Vérifiez que vos clés API sont valides +3. Assurez-vous que votre réseau autorise les connexions au API du fournisseur. + +--- + +### Modèle non disponible + +1. Vérifiez que vous êtes authentifié auprès du fournisseur +2. Vérifiez que le nom du modèle dans votre configuration est correct +3. Certains modèles peuvent nécessiter un accès ou des abonnements spécifiques + +Si vous rencontrez `ProviderModelNotFoundError`, vous avez probablement tort +faire référence à un modèle quelque part. +Les modèles doivent être référencés comme suit : `/` + +Exemples : + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +Pour déterminer à quels modèles vous avez accès, exécutez `opencode models` + +--- + +### ErreurInit du fournisseur + +Si vous rencontrez une ProviderInitError, vous avez probablement une configuration non valide ou corrompue. + +Pour résoudre ce problème : + +1. Tout d'abord, vérifiez que votre fournisseur est correctement configuré en suivant le [guide du fournisseur](/docs/providers) +2. Si le problème persiste, essayez d'effacer votre configuration stockée : + + ```bash + rm -rf ~/.local/share/opencode + ``` + +Sur Windows, appuyez sur `WIN+R` et supprimez : `%USERPROFILE%\.local\share\opencode` + +3. Ré-authentifiez-vous auprès de votre fournisseur à l'aide de la commande `/connect` dans le TUI. + +--- + +### Problèmes liés à AI_APICallError et au package du fournisseur + +Si vous rencontrez des erreurs d’appel API, cela peut être dû à des packages de fournisseurs obsolètes. opencode installe dynamiquement les packages du fournisseur (OpenAI, Anthropic, Google, etc.) selon les besoins et les met en cache localement. + +Pour résoudre les problèmes liés au package du fournisseur : + +1. Videz le cache du package du fournisseur : + + ```bash + rm -rf ~/.cache/opencode + ``` + +Sur Windows, appuyez sur `WIN+R` et supprimez : `%USERPROFILE%\.cache\opencode` + +2. Redémarrez opencode pour réinstaller les derniers packages du fournisseur + +Cela forcera opencode à télécharger les versions les plus récentes des packages du fournisseur, ce qui résout souvent les problèmes de compatibilité avec les paramètres du modèle et les modifications de API. + +--- + +### Le copier/coller ne fonctionne pas sur Linux + +Les utilisateurs de Linux doivent disposer de l'un des utilitaires de presse-papiers suivants installés pour que la fonctionnalité copier/coller fonctionne : + +**Pour les systèmes X11 :** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**Pour les systèmes Wayland :** + +```bash +apt install -y wl-clipboard +``` + +**Pour les environnements sans tête :** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode détectera si vous utilisez Wayland et préférez `wl-clipboard`, sinon il essaiera de trouver les outils du presse-papiers dans l'ordre : `xclip` et `xsel`. diff --git a/packages/web/src/content/docs/fr/tui.mdx b/packages/web/src/content/docs/fr/tui.mdx new file mode 100644 index 000000000..aa1bea901 --- /dev/null +++ b/packages/web/src/content/docs/fr/tui.mdx @@ -0,0 +1,390 @@ +--- +title: TUI +description: Utilisation de l’interface utilisateur du terminal OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode fournit une interface de terminal interactif ou TUI pour travailler sur vos projets avec un LLM. + +L’exécution de OpenCode démarre le TUI pour le répertoire actuel. + +```bash +opencode +``` + +Ou vous pouvez le démarrer pour un répertoire de travail spécifique. + +```bash +opencode /path/to/project +``` + +Une fois que vous êtes dans le TUI, vous pouvez lui envoyer un message. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## Références de fichiers + +Vous pouvez référencer des fichiers dans vos messages en utilisant `@`. Cela effectue une recherche de fichier floue dans le répertoire de travail actuel. + +:::tip +Vous pouvez également utiliser `@` pour référencer des fichiers dans vos messages. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +Le contenu du fichier est automatiquement ajouté à la conversation. + +--- + +## Commandes Bash + +Démarrez un message avec `!` pour exécuter une commande shell. + +```bash frame="none" +!ls -la +``` + +Le résultat de la commande est ajouté à la conversation en tant que résultat de l'outil. + +--- + +## Commandes + +Lorsque vous utilisez le OpenCode TUI, vous pouvez taper `/` suivi d'un nom de commande pour exécuter rapidement des actions. Par exemple: + +```bash frame="none" +/help +``` + +La plupart des commandes ont également une liaison clavier utilisant `ctrl+x` comme touche leader, où `ctrl+x` est la touche leader par défaut. [En savoir plus](/docs/keybinds). + +Voici toutes les commandes slash disponibles : + +--- + +### connecter + +Ajoutez un fournisseur à OpenCode. Vous permet de sélectionner parmi les fournisseurs disponibles et d’ajouter leurs clés API. + +```bash frame="none" +/connect +``` + +--- + +### compact + +Compactez la session en cours. _Alias_ : `/summarize` + +```bash frame="none" +/compact +``` + +**Reliure de touches :** `ctrl+x c` + +--- + +### détails + +Basculer les détails d'exécution de l'outil. + +```bash frame="none" +/details +``` + +**Reliure de touches :** `ctrl+x d` + +--- + +### éditeur + +Ouvrez un éditeur externe pour rédiger des messages. Utilise l'éditeur défini dans votre variable d'environnement `EDITOR`. [En savoir plus](#editor-setup). + +```bash frame="none" +/editor +``` + +**Reliure de touches :** `ctrl+x e` + +--- + +### sortie + +Quittez OpenCode. _Alias_ : `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Reliure de touches :** `ctrl+x q` + +--- + +### exporter + +Exportez la conversation en cours vers Markdown et ouvrez-la dans votre éditeur par défaut. Utilise l'éditeur défini dans votre variable d'environnement `EDITOR`. [En savoir plus](#editor-setup). + +```bash frame="none" +/export +``` + +**Reliure de touches :** `ctrl+x x` + +--- + +### aide + +Afficher la boîte de dialogue d'aide. + +```bash frame="none" +/help +``` + +**Reliure de touches :** `ctrl+x h` + +--- + +### initialisation + +Créez ou mettez à jour le fichier `AGENTS.md`. [En savoir plus](/docs/rules). + +```bash frame="none" +/init +``` + +**Reliure de touches :** `ctrl+x i` + +--- + +### modèles + +Liste des modèles disponibles. + +```bash frame="none" +/models +``` + +**Reliure de touches :** `ctrl+x m` + +--- + +### nouveau + +Démarrez une nouvelle session. _Alias_ : `/clear` + +```bash frame="none" +/new +``` + +**Reliure de touches :** `ctrl+x n` + +--- + +### refaire + +Refaire un message précédemment annulé. Disponible uniquement après avoir utilisé `/undo`. + +:::tip +Toutes les modifications de fichiers seront également restaurées. +::: + +En interne, cela utilise Git pour gérer les modifications de fichiers. Votre projet **doit donc +être un dépôt Git**. + +```bash frame="none" +/redo +``` + +**Reliure de touches :** `ctrl+x r` + +--- + +### séances + +Répertoriez et basculez entre les sessions. _Alias_ : `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Reliure de touches :** `ctrl+x l` + +--- + +### partager + +Partager la session en cours. [En savoir plus](/docs/share). + +```bash frame="none" +/share +``` + +**Reliure de touches :** `ctrl+x s` + +--- + +### thèmes + +Répertoriez les thèmes disponibles. + +```bash frame="none" +/theme +``` + +**Reliure de touches :** `ctrl+x t` + +--- + +### pensée + +Activez/désactivez la visibilité des blocages de réflexion/raisonnement dans la conversation. Lorsque cette option est activée, vous pouvez voir le processus de raisonnement du modèle pour les modèles prenant en charge la réflexion étendue. + +:::note +Cette commande contrôle uniquement si les blocs de réflexion sont **affichés** ; elle n'active ni ne désactive les capacités de raisonnement du modèle. Pour basculer entre les capacités de raisonnement réelles, utilisez `ctrl+t` pour parcourir les variantes du modèle. +::: + +```bash frame="none" +/thinking +``` + +--- + +### défaire + +Annuler le dernier message de la conversation. Supprime le message utilisateur le plus récent, toutes les réponses ultérieures et toutes les modifications de fichier. + +:::tip +Toutes les modifications apportées au fichier seront également annulées. +::: + +En interne, cela utilise Git pour gérer les modifications de fichiers. Votre projet **doit donc +être un dépôt Git**. + +```bash frame="none" +/undo +``` + +**Reliure de touches :** `ctrl+x u` + +--- + +### annuler le partage + +Annuler le partage de la session en cours. [En savoir plus](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## Configuration de l'éditeur + +Les commandes `/editor` et `/export` utilisent l'éditeur spécifié dans votre variable d'environnement `EDITOR`. + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + +Pour le rendre permanent, ajoutez-le à votre profil shell ; +`~/.bashrc`, `~/.zshrc`, etc. + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + +Pour le rendre permanent, utilisez **Propriétés système** > **Environnement +Variables**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + +Pour le rendre permanent, ajoutez-le à votre profil PowerShell. + + + + +Les options d'éditeur populaires incluent : + +- `code`-Code Visual Studio +- `cursor` - Curseur +- `windsurf` - Planche à voile +- `nvim` - Editeur Néovim +- `vim` - Éditeur Vim +- `nano` - Éditeur nano +- `notepad` - Windows Bloc-notes +- `subl` - Texte sublime + +:::note +Certains éditeurs comme VS Code doivent être démarrés avec le drapeau `--wait`. +::: + +Certains éditeurs ont besoin d'arguments de ligne de commande pour s'exécuter en mode blocage. L'indicateur `--wait` bloque le processus de l'éditeur jusqu'à sa fermeture. + +--- + +## Configurer + +Vous pouvez personnaliser le comportement de TUI via votre fichier de configuration OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### Possibilités + +- `scroll_acceleration` - Activez l'accélération de défilement de style macOS pour un défilement fluide et naturel. Lorsqu'elle est activée, la vitesse de défilement augmente avec les gestes de défilement rapides et reste précise pour les mouvements plus lents. **Ce paramètre est prioritaire sur `scroll_speed` et le remplace lorsqu'il est activé.** +- `scroll_speed` - Contrôle la vitesse de défilement du TUI lors de l'utilisation des commandes de défilement (minimum : `1`). La valeur par défaut est `3`. **Remarque : Ceci est ignoré si `scroll_acceleration.enabled` est défini sur `true`.** + +--- + +## Personnalisation + +Vous pouvez personnaliser divers aspects de la vue TUI à l'aide de la palette de commandes (`ctrl+x h` ou `/help`). Ces paramètres persistent lors des redémarrages. + +--- + +#### Affichage du nom d'utilisateur + +Indiquez si votre nom d'utilisateur apparaît dans les messages de discussion. Accédez-y via : + +- Palette de commandes : recherchez "nom d'utilisateur" ou "masquer le nom d'utilisateur" +- Le paramètre persiste automatiquement et sera mémorisé au cours de TUI sessions. diff --git a/packages/web/src/content/docs/fr/web.mdx b/packages/web/src/content/docs/fr/web.mdx new file mode 100644 index 000000000..2cf8e531b --- /dev/null +++ b/packages/web/src/content/docs/fr/web.mdx @@ -0,0 +1,142 @@ +--- +title: Web +description: En utilisant OpenCode dans votre navigateur. +--- + +OpenCode peut s'exécuter comme une application Web dans votre navigateur, offrant la même expérience puissante de codage d'IA sans avoir besoin d'un terminal. + +![OpenCode Web - Nouvelle session](../../../assets/web/web-homepage-new-session.png) + +## Commencer + +Démarrez l'interface Web en exécutant : + +```bash +opencode web +``` + +Cela démarre un serveur local sur `127.0.0.1` avec un port disponible aléatoire et ouvre automatiquement OpenCode dans votre navigateur par défaut. + +:::caution +Si `OPENCODE_SERVER_PASSWORD` n'est pas défini, le serveur ne sera pas sécurisé. C'est bien pour une utilisation locale mais doit être défini pour l'accès au réseau. +::: + +:::tip[Windows Utilisateurs] +Pour une expérience optimale, exécutez `opencode web` à partir de [WSL](/docs/windows-wsl) plutôt que de PowerShell. Cela garantit un accès correct au système de fichiers et une intégration du terminal. +::: + +--- + +## Configuration + +Vous pouvez configurer le serveur Web à l'aide d'indicateurs de ligne de commande ou dans votre [fichier de configuration](/docs/config). + +### Port + +Par défaut, OpenCode sélectionne un port disponible. Vous pouvez spécifier un port : + +```bash +opencode web --port 4096 +``` + +### Nom d'hôte + +Par défaut, le serveur se lie à `127.0.0.1` (localhost uniquement). Pour rendre OpenCode accessible sur votre réseau : + +```bash +opencode web --hostname 0.0.0.0 +``` + +Lorsque vous utilisez `0.0.0.0`, OpenCode affichera les adresses locales et réseau : + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### mDNS Découverte + +Activez mDNS pour rendre votre serveur visible sur le réseau local : + +```bash +opencode web --mdns +``` + +Cela définit automatiquement le nom d'hôte sur `0.0.0.0` et annonce le serveur comme `opencode.local`. + +Vous pouvez personnaliser le nom de domaine mDNS pour exécuter plusieurs instances sur le même réseau : + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +Pour autoriser des domaines supplémentaires pour CORS (utile pour les frontends personnalisés) : + +```bash +opencode web --cors https://example.com +``` + +### Authentification + +Pour protéger l'accès, définissez un mot de passe à l'aide de la variable d'environnement `OPENCODE_SERVER_PASSWORD` : + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +Le nom d'utilisateur par défaut est `opencode` mais peut être modifié avec `OPENCODE_SERVER_USERNAME`. + +--- + +## Utilisation de l'interface Web + +Une fois démarrée, l'interface web permet d'accéder à vos sessions OpenCode. + +### Séances + +Consultez et gérez vos sessions depuis la page d'accueil. Vous pouvez voir les sessions actives et en démarrer de nouvelles. + +![OpenCode Web - Session active](../../../assets/web/web-homepage-active-session.png) + +### Statut du serveur + +Cliquez sur "Voir les serveurs" pour afficher les serveurs connectés et leur état. + +![OpenCode Web - Voir Serveurs](../../../assets/web/web-homepage-see-servers.png) + +--- + +## Attacher un terminal + +Vous pouvez connecter un terminal TUI à un serveur Web en cours d'exécution : + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +Cela vous permet d'utiliser simultanément l'interface Web et le terminal, en partageant les mêmes sessions et le même état. + +--- + +## Fichier de configuration + +Vous pouvez également configurer les paramètres du serveur dans votre fichier de configuration `opencode.json` : + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +Les indicateurs de ligne de commande ont priorité sur les paramètres du fichier de configuration. diff --git a/packages/web/src/content/docs/fr/windows-wsl.mdx b/packages/web/src/content/docs/fr/windows-wsl.mdx new file mode 100644 index 000000000..e4c157987 --- /dev/null +++ b/packages/web/src/content/docs/fr/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: Execute OpenCode sur Windows avec WSL pour une experience optimale. +--- + +import { Steps } from "@astrojs/starlight/components" + +Meme si OpenCode peut fonctionner directement sur Windows, nous recommandons d'utiliser [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) pour la meilleure experience. WSL fournit un environnement Linux qui s'integre parfaitement aux fonctionnalites d'OpenCode. + +:::tip[Pourquoi WSL?] +WSL offre de meilleures performances du systeme de fichiers, une prise en charge complete du terminal et la compatibilite avec les outils de developpement dont OpenCode depend. +::: + +--- + +## Configuration + + + +1. **Installez WSL** + + Si ce n'est pas encore fait, [installez WSL](https://learn.microsoft.com/en-us/windows/wsl/install) a l'aide du guide officiel Microsoft. + +2. **Installez OpenCode dans WSL** + + Une fois WSL configure, ouvrez votre terminal WSL et installez OpenCode avec l'une des [methodes d'installation](/docs/). + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **Utilisez OpenCode depuis WSL** + + Allez dans votre dossier de projet (accedez aux fichiers Windows via `/mnt/c/`, `/mnt/d/`, etc.) et lancez OpenCode. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## Application bureau + serveur WSL + +Si vous preferez utiliser l'application bureau OpenCode mais executer le serveur dans WSL: + +1. **Demarrez le serveur dans WSL** avec `--hostname 0.0.0.0` pour autoriser les connexions externes: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Connectez l'application bureau** a `http://localhost:4096` + +:::note +Si `localhost` ne fonctionne pas dans votre configuration, utilisez plutot l'adresse IP WSL (depuis WSL: `hostname -I`) et `http://:4096`. +::: + +:::caution +Lorsque vous utilisez `--hostname 0.0.0.0`, definissez `OPENCODE_SERVER_PASSWORD` pour securiser le serveur. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Client web + WSL + +Pour la meilleure experience web sous Windows: + +1. **Executez `opencode web` dans le terminal WSL** plutot que dans PowerShell: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Accedez-y depuis votre navigateur Windows** a `http://localhost:` (OpenCode affiche l'URL) + +Lancer `opencode web` depuis WSL garantit un acces correct au systeme de fichiers et une bonne integration terminal, tout en restant accessible depuis votre navigateur Windows. + +--- + +## Acceder aux fichiers Windows + +WSL peut acceder a tous vos fichiers Windows via le repertoire `/mnt/`: + +- Lecteur `C:` → `/mnt/c/` +- Lecteur `D:` → `/mnt/d/` +- Et ainsi de suite... + +Exemple: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +Pour une experience plus fluide, vous pouvez cloner/copier votre depot dans le systeme de fichiers WSL (par exemple sous `~/code/`) et y executer OpenCode. +::: + +--- + +## Conseils + +- Gardez OpenCode dans WSL pour les projets stockes sur des lecteurs Windows: l'acces aux fichiers est fluide +- Utilisez l'[extension WSL de VS Code](https://code.visualstudio.com/docs/remote/wsl) avec OpenCode pour un flux de travail integre +- Votre configuration OpenCode et vos sessions sont stockees dans l'environnement WSL a `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/fr/zen.mdx b/packages/web/src/content/docs/fr/zen.mdx new file mode 100644 index 000000000..3588ab9f0 --- /dev/null +++ b/packages/web/src/content/docs/fr/zen.mdx @@ -0,0 +1,254 @@ +--- +title: Zen +description: Liste organisée de modèles fournis par OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen est une liste de modèles testés et vérifiés fournie par l'équipe OpenCode. + +:::note +OpenCode Zen est actuellement en version bêta. +::: + +Zen fonctionne comme n'importe quel autre fournisseur dans OpenCode. Vous vous connectez à OpenCode Zen et obtenez +votre clé API. C'est **complètement facultatif** et vous n'avez pas besoin de l'utiliser pour l'utiliser +OpenCode. + +--- + +## Arrière-plan + +Il existe un grand nombre de modèles, mais seulement quelques-uns d'entre eux +ces modèles fonctionnent bien comme agents de codage. De plus, la plupart des fournisseurs sont +configuré très différemment; vous obtenez donc des performances et une qualité très différentes. + +:::tip +Nous avons testé un groupe sélectionné de modèles et de fournisseurs qui fonctionnent bien avec OpenCode. +::: + +Donc, si vous utilisez un modèle via quelque chose comme OpenRouter, vous ne pourrez jamais être +assurez-vous que vous obtenez la meilleure version du modèle que vous souhaitez. + +Pour résoudre ce problème, nous avons effectué plusieurs opérations : + +1. Nous avons testé un groupe sélectionné de modèles et discuté avec leurs équipes de la manière de + mieux vaut les exécuter. +2. Nous avons ensuite travaillé avec quelques prestataires pour nous assurer qu'ils étaient servis. + correctement. +3. Enfin, nous avons comparé la combinaison modèle/fournisseur et sommes arrivés + avec une liste que nous nous ferons un plaisir de recommander. + +OpenCode Zen est une passerelle IA qui vous donne accès à ces modèles. + +--- + +## Comment ça marche + +OpenCode Zen fonctionne comme n'importe quel autre fournisseur dans OpenCode. + +1. Vous vous connectez à **OpenCode Zen**, ajoutez votre facturation + détails et copiez votre clé API. +2. Vous exécutez la commande `/connect` dans le TUI, sélectionnez OpenCode Zen et collez votre clé API. +3. Exécutez `/models` dans le TUI pour voir la liste des modèles que nous recommandons. + +Vous êtes facturé par demande et vous pouvez ajouter des crédits à votre compte. + +--- + +## Points de terminaison + +Vous pouvez également accéder à nos modèles via les points de terminaison API suivants. + +| Modèle | ID du modèle | Point de terminaison | Package SDK IA | +| -------------------- | -------------------- | -------------------------------------------------- | --------------------------- | +| TPG 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Codex GPT 5.2 | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Codex GPT 5.1 | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| TPG 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Codex GPT5 | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT5Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haïku 4.5 | claude-haïku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haïku 3.5 | claude-3-5-haïku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Gémeaux 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Gémeaux 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Gratuit | minimax-m2.1-gratuit | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Gratuit | glm-4.7-gratuit | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Gratuit | kimi-k2.5-gratuit | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 Pensée | kimi-k2-pensée | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Codeur Qwen3 480B | codeur qwen3 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Gros cornichon | gros cornichon | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +Le [id du modèle](/docs/config/#models) dans votre configuration OpenCode +utilise le format `opencode/`. Par exemple, pour le Codex GPT 5.2, vous devez +utilisez `opencode/gpt-5.2-codex` dans votre configuration. + +--- + +### Modèles + +Vous pouvez récupérer la liste complète des modèles disponibles et leurs métadonnées à partir de : + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## Tarifs + +Nous soutenons un modèle de paiement à l'utilisation. Vous trouverez ci-dessous les prix **par 1 million de jetons**. + +| Modèle | Entrée | Sortie | Lecture en cache | Écriture en cache | +| --------------------------------- | ------- | ------- | ---------------- | ----------------- | +| Gros cornichon | Gratuit | Gratuit | Gratuit | - | +| MiniMax M2.1 Gratuit | Gratuit | Gratuit | Gratuit | - | +| MiniMax M2.1 | 0,30 $ | 1,20 $ | 0,10 $ | - | +| GLM 4.7 Gratuit | Gratuit | Gratuit | Gratuit | - | +| GLM 4.7 | 0,60 $ | 2,20 $ | 0,10 $ | - | +| GLM 4.6 | 0,60 $ | 2,20 $ | 0,10 $ | - | +| Kimi K2.5 Gratuit | Gratuit | Gratuit | Gratuit | - | +| Kimi K2.5 | 0,60 $ | 3,00 $ | 0,08 $ | - | +| Kimi K2 Pensée | 0,40 $ | 2,50 $ | - | - | +| Kimi K2 | 0,40 $ | 2,50 $ | - | - | +| Codeur Qwen3 480B | 0,45 $ | 1,50 $ | - | - | +| Claude Sonnet 4.5 (≤ 200K jetons) | 3,00 $ | 15,00 $ | 0,30 $ | 3,75 $ | +| Claude Sonnet 4.5 (> 200K jetons) | 6,00 $ | 22,50 $ | 0,60 $ | 7,50 $ | +| Claude Sonnet 4 (≤ 200K jetons) | 3,00 $ | 15,00 $ | 0,30 $ | 3,75 $ | +| Claude Sonnet 4 (> 200K jetons) | 6,00 $ | 22,50 $ | 0,60 $ | 7,50 $ | +| Claude Haïku 4.5 | 1,00 $ | 5,00 $ | 0,10 $ | 1,25 $ | +| Claude Haïku 3.5 | 0,80 $ | 4,00 $ | 0,08 $ | 1,00 $ | +| Claude Opus 4.6 (≤ 200K jetons) | 5,00 $ | 25,00 $ | 0,50 $ | 6,25 $ | +| Claude Opus 4.6 (> 200K jetons) | 10,00 $ | 37,50 $ | 1,00 $ | 12,50 $ | +| Claude Opus 4.5 | 5,00 $ | 25,00 $ | 0,50 $ | 6,25 $ | +| Claude Opus 4.1 | 15,00 $ | 75,00 $ | 1,50 $ | 18,75 $ | +| Gemini 3 Pro (≤ 200 000 jetons) | 2,00 $ | 12,00 $ | 0,20 $ | - | +| Gemini 3 Pro (> 200 000 jetons) | 4,00 $ | 18,00 $ | 0,40 $ | - | +| Gémeaux 3 Flash | 0,50 $ | 3,00 $ | 0,05 $ | - | +| TPG 5.2 | 1,75 $ | 14,00 $ | 0,175 $ | - | +| Codex GPT 5.2 | 1,75 $ | 14,00 $ | 0,175 $ | - | +| GPT 5.1 | 1,07 $ | 8,50 $ | 0,107 $ | - | +| Codex GPT 5.1 | 1,07 $ | 8,50 $ | 0,107 $ | - | +| GPT 5.1 Codex Max | 1,25 $ | 10,00 $ | 0,125 $ | - | +| GPT 5.1 Codex Mini | 0,25 $ | 2,00 $ | 0,025 $ | - | +| TPG 5 | 1,07 $ | 8,50 $ | 0,107 $ | - | +| Codex GPT5 | 1,07 $ | 8,50 $ | 0,107 $ | - | +| GPT5Nano | Gratuit | Gratuit | Gratuit | - | + +Vous remarquerez peut-être _Claude Haiku 3.5_ dans votre historique d'utilisation. Il s'agit d'un [modèle low cost](/docs/config/#models) qui est utilisé pour générer les titres de vos sessions. + +:::note +Les frais de carte de crédit sont répercutés au prix coûtant (4,4 % + 0,30 $ par transaction) ; nous ne facturons rien au-delà. +::: + +Les modèles gratuits : + +- GLM 4.7 Free est disponible sur OpenCode pour une durée limitée. L’équipe profite de ce temps pour recueillir des commentaires et améliorer le modèle. +- Kimi K2.5 Free est disponible sur OpenCode pour une durée limitée. L’équipe profite de ce temps pour recueillir des commentaires et améliorer le modèle. +- MiniMax M2.1 Free est disponible sur OpenCode pour une durée limitée. L’équipe profite de ce temps pour recueillir des commentaires et améliorer le modèle. +- Big Pickle est un modèle furtif gratuit sur OpenCode pour une durée limitée. L’équipe profite de ce temps pour recueillir des commentaires et améliorer le modèle. + +Contactez-nous si vous avez des questions. + +--- + +### Rechargement automatique + +Si votre solde descend en dessous de 5 $, Zen rechargera automatiquement 20 $. + +Vous pouvez modifier le montant du rechargement automatique. Vous pouvez également désactiver complètement le rechargement automatique. + +--- + +### Limites mensuelles + +Vous pouvez également définir une limite d'utilisation mensuelle pour l'ensemble de l'espace de travail et pour chaque +membre de votre équipe. + +Par exemple, disons que vous définissez une limite d'utilisation mensuelle à 20 $, Zen n'utilisera pas +plus de 20 $ par mois. Mais si le rechargement automatique est activé, Zen pourrait finir par +vous facturant plus de 20 $ si votre solde descend en dessous de 5 $. + +--- + +## Confidentialité + +Tous nos modèles sont hébergés aux États-Unis. Nos fournisseurs suivent une politique de rétention zéro et n'utilisent pas vos données pour la formation de modèles, avec les exceptions suivantes : + +- Big Pickle : Pendant sa période gratuite, les données collectées peuvent être utilisées pour améliorer le modèle. +- GLM 4.7 Gratuit : Pendant sa période gratuite, les données collectées peuvent être utilisées pour améliorer le modèle. +- Kimi K2.5 Gratuit : Pendant sa période gratuite, les données collectées peuvent être utilisées pour améliorer le modèle. +- MiniMax M2.1 Gratuit : Pendant sa période gratuite, les données collectées peuvent être utilisées pour améliorer le modèle. +- API OpenAI : les demandes sont conservées pendant 30 jours conformément aux politiques de données de [OpenAI](https://platform.openai.com/docs/guides/your-data). +- API Anthropic : les demandes sont conservées pendant 30 jours conformément aux [Politiques de données d'Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## Pour les équipes + +Zen fonctionne également très bien pour les équipes. Vous pouvez inviter des coéquipiers, attribuer des rôles, organiser +les modèles utilisés par votre équipe, et bien plus encore. + +:::note +Les espaces de travail sont actuellement gratuits pour les équipes dans le cadre de la version bêta. +::: + +La gestion de votre espace de travail est actuellement gratuite pour les équipes dans le cadre de la version bêta. Nous serons +partagera bientôt plus de détails sur les prix. + +--- + +### Rôles + +Vous pouvez inviter des coéquipiers dans votre espace de travail et attribuer des rôles : + +- **Administrateur** : gérez les modèles, les membres, les clés API et la facturation. +- **Membre** : gérer uniquement ses propres clés API + +Les administrateurs peuvent également définir des limites de dépenses mensuelles pour chaque membre afin de garder les coûts sous contrôle. + +--- + +### Accès au modèle + +Les administrateurs peuvent activer ou désactiver des modèles spécifiques pour l'espace de travail. Les requêtes adressées à un modèle désactivé renverront une erreur. + +Ceci est utile dans les cas où vous souhaitez désactiver l'utilisation d'un modèle qui +collecte des données. + +--- + +### Apportez votre propre clé + +Vous pouvez utiliser vos propres clés OpenAI ou Anthropic API tout en accédant à d'autres modèles dans Zen. + +Lorsque vous utilisez vos propres clés, les tokens sont facturés directement par le fournisseur et non par Zen. + +Par exemple, votre organisation dispose peut-être déjà d'une clé pour OpenAI ou Anthropic +et vous souhaitez l'utiliser à la place de celui fourni par Zen. + +--- + +## Objectifs + +Nous avons créé OpenCode Zen pour : + +1. **Benchmark** les meilleurs modèles/fournisseurs d'agents de codage. +2. Ayez accès aux options de **la plus haute qualité** et ne dégradez pas les performances ni ne vous dirigez vers des fournisseurs moins chers. +3. Répercutez toute **baisse de prix** en vendant au prix coûtant ; la seule majoration est donc pour couvrir nos frais de traitement. +4. N'ayez **aucun verrouillage** en vous permettant de l'utiliser avec n'importe quel autre agent de codage. Et laissez-vous toujours utiliser n'importe quel autre fournisseur avec OpenCode également. diff --git a/packages/web/src/content/docs/it/1-0.mdx b/packages/web/src/content/docs/it/1-0.mdx new file mode 100644 index 000000000..0c6b20f45 --- /dev/null +++ b/packages/web/src/content/docs/it/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: Migrazione a 1.0 +description: Novita in OpenCode 1.0. +--- + +OpenCode 1.0 e una riscrittura completa della TUI. + +Siamo passati dalla TUI basata su go+bubbletea, che aveva problemi di prestazioni e di capacita, a un framework interno (OpenTUI) scritto in zig+solidjs. + +La nuova TUI funziona come la precedente, dato che si connette allo stesso server opencode. + +--- + +## Upgrading + +Non dovresti essere aggiornato automaticamente a 1.0 se stai usando una versione precedente. +Detto questo, alcune versioni piu vecchie di OpenCode installano sempre l'ultima. + +Per aggiornare manualmente, esegui: + +```bash +$ opencode upgrade 1.0.0 +``` + +Per tornare a 0.x, esegui: + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## Cambiamenti UX + +La cronologia della sessione e piu compatta: mostra i dettagli completi solo per gli strumenti edit e bash. + +Abbiamo aggiunto una command bar attraverso cui passa quasi tutto. Premi ctrl+p in qualunque contesto per aprirla e vedere tutto cio che puoi fare. + +Abbiamo aggiunto una sidebar di sessione (attivabile/disattivabile) con informazioni utili. + +Abbiamo rimosso alcune funzionalita che non eravamo sicuri venissero davvero usate. Se manca qualcosa di importante, apri una issue e la riaggiungeremo rapidamente. + +--- + +## Modifiche incompatibili + +### Keybind rinominati + +- messages_revert -> messages_undo +- switch_agent -> agent_cycle +- switch_agent_reverse -> agent_cycle_reverse +- switch_mode -> agent_cycle +- switch_mode_reverse -> agent_cycle_reverse + +### Keybind rimossi + +- messages_layout_toggle +- messages_next +- messages_previous +- file_diff_toggle +- file_search +- file_close +- file_list +- app_help +- project_init +- tool_details +- thinking_blocks diff --git a/packages/web/src/content/docs/it/acp.mdx b/packages/web/src/content/docs/it/acp.mdx new file mode 100644 index 000000000..48b474aa4 --- /dev/null +++ b/packages/web/src/content/docs/it/acp.mdx @@ -0,0 +1,156 @@ +--- +title: Supporto ACP +description: Usa OpenCode in qualunque editor compatibile con ACP. +--- + +OpenCode supporta [Agent Client Protocol](https://agentclientprotocol.com) (ACP), permettendoti di usarlo direttamente in editor e IDE compatibili. + +:::tip +Per una lista di editor e tool che supportano ACP, vedi l'[ACP progress report](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP e un protocollo aperto che standardizza la comunicazione tra editor di codice e agenti di coding AI. + +--- + +## Configure + +Per usare OpenCode via ACP, configura l'editor in modo che esegua il comando `opencode acp`. + +Il comando avvia OpenCode come sottoprocesso compatibile con ACP che comunica con l'editor via JSON-RPC su stdio. + +Qui sotto trovi esempi per editor popolari che supportano ACP. + +--- + +### Zed + +Aggiungi alla configurazione di [Zed](https://zed.dev) (`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +Per aprirlo, usa l'azione `agent: new thread` nella **Command Palette**. + +Puoi anche assegnare una scorciatoia da tastiera modificando `keymap.json`: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### JetBrains IDEs + +Aggiungi al tuo acp.json per [JetBrains IDE](https://www.jetbrains.com/) secondo la [documentazione](https://www.jetbrains.com/help/ai-assistant/acp.html): + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +Per aprirlo, seleziona il nuovo agente 'OpenCode' nel selettore agenti di AI Chat. + +--- + +### Avante.nvim + +Aggiungi alla configurazione di [Avante.nvim](https://github.com/yetone/avante.nvim): + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +Se devi passare variabili d'ambiente: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +Per usare OpenCode come agente ACP in [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim), aggiungi quanto segue alla config di Neovim: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +Questa config imposta CodeCompanion per usare OpenCode come agente ACP per la chat. + +Se devi passare variabili d'ambiente (come `OPENCODE_API_KEY`), vedi [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) nella documentazione di CodeCompanion.nvim. + +## Support + +OpenCode funziona via ACP come nel terminale. Tutte le funzionalita sono supportate: + +:::note +Alcuni comandi slash integrati come `/undo` e `/redo` non sono attualmente supportati. +::: + +- Built-in tools (file operations, terminal commands, etc.) +- Custom tools and slash commands +- MCP servers configured in your OpenCode config +- Project-specific rules from `AGENTS.md` +- Custom formatters and linters +- Agents and permissions system diff --git a/packages/web/src/content/docs/it/agents.mdx b/packages/web/src/content/docs/it/agents.mdx new file mode 100644 index 000000000..51c287fcf --- /dev/null +++ b/packages/web/src/content/docs/it/agents.mdx @@ -0,0 +1,746 @@ +--- +title: Agenti +description: Configura e usa agenti specializzati. +--- + +Gli agenti sono assistenti AI specializzati che puoi configurare per task e workflow specifici. Ti permettono di creare strumenti mirati con prompt personalizzati, modelli e accesso agli strumenti. + +:::tip +Usa l'agente plan per analizzare codice e valutare suggerimenti senza apportare modifiche al codice. +::: + +Puoi passare da un agente all'altro durante una sessione oppure invocarli con la menzione `@`. + +--- + +## Tipi + +In OpenCode esistono due tipi di agenti: agenti primari e subagenti. + +--- + +### Agenti primari + +Gli agenti primari sono gli assistenti principali con cui interagisci direttamente. Puoi scorrerli usando il tasto **Tab** o la scorciatoia `switch_agent` configurata. Questi agenti gestiscono la conversazione principale. L'accesso agli strumenti si configura tramite i permessi: per esempio, Build ha tutti gli strumenti abilitati, mentre Plan e' limitato. + +:::tip +Puoi usare **Tab** per passare tra gli agenti primari durante una sessione. +::: + +OpenCode include due agenti primari integrati: **Build** e **Plan**. Li vediamo sotto. + +--- + +### Subagenti + +I subagenti sono assistenti specializzati che gli agenti primari possono invocare per task specifici. Puoi anche invocarli manualmente **menzionandoli con @** nei tuoi messaggi. + +OpenCode include due subagenti integrati: **General** e **Explore**. Li vediamo sotto. + +--- + +## Integrati + +OpenCode include due agenti primari integrati e due subagenti integrati. + +--- + +### Usa build + +_Mode_: `primary` + +Build e' l'agente primario **predefinito** con tutti gli strumenti abilitati. E' l'agente standard per lavoro di sviluppo quando ti serve pieno accesso a operazioni sui file e comandi di sistema. + +--- + +### Usa plan + +_Mode_: `primary` + +Un agente limitato pensato per pianificazione e analisi. Usiamo un sistema di permessi per darti piu' controllo e prevenire modifiche non intenzionali. +Di default, tutte le seguenti sono impostate a `ask`: + +- `file edits`: tutte le scritture, patch ed edit +- `bash`: tutti i comandi bash + +Questo agente e' utile quando vuoi che l'LLM analizzi il codice, suggerisca modifiche o crei piani senza effettuare alcuna modifica reale al codebase. + +--- + +### Usa general + +_Mode_: `subagent` + +Un agente general-purpose per ricercare domande complesse ed eseguire task multi-step. Ha accesso completo agli strumenti (tranne todo), quindi puo' modificare file quando serve. Usalo per eseguire piu' unita' di lavoro in parallelo. + +--- + +### Usa explore + +_Mode_: `subagent` + +Un agente rapido in sola lettura per esplorare codebase. Non puo' modificare file. Usalo quando devi trovare rapidamente file tramite pattern, cercare nel codice per keyword o rispondere a domande sul codebase. + +--- + +### Usa compaction + +_Mode_: `primary` + +Agente di sistema nascosto che compatta contesti lunghi in un riassunto piu' piccolo. Viene eseguito automaticamente quando serve e non e' selezionabile nella UI. + +--- + +### Usa title + +_Mode_: `primary` + +Agente di sistema nascosto che genera titoli brevi per le sessioni. Viene eseguito automaticamente quando serve e non e' selezionabile nella UI. + +--- + +### Usa summary + +_Mode_: `primary` + +Agente di sistema nascosto che crea riassunti di sessione. Viene eseguito automaticamente quando serve e non e' selezionabile nella UI. + +--- + +## Utilizzo + +1. Per gli agenti primari, usa il tasto **Tab** per scorrerli durante una sessione. Puoi anche usare la scorciatoia `switch_agent` configurata. + +2. I subagenti possono essere invocati: + - **Automaticamente** dagli agenti primari per task specializzati in base alle loro descrizioni. + - Manualmente **menzionando con @** un subagente nel tuo messaggio. Per esempio. + + ```txt frame="none" + @general help me search for this function + ``` + +3. **Navigazione tra sessioni**: quando i subagenti creano le loro child session, puoi navigare tra la sessione padre e tutte le sessioni figlie usando: + - **\+Right** (o la scorciatoia `session_child_cycle` configurata) per ciclare in avanti tra parent → child1 → child2 → ... → parent + - **\+Left** (o la scorciatoia `session_child_cycle_reverse` configurata) per ciclare indietro tra parent ← child1 ← child2 ← ... ← parent + + Questo ti permette di passare senza soluzione di continuita' tra la conversazione principale e il lavoro specializzato dei subagenti. + +--- + +## Configura + +Puoi personalizzare gli agenti integrati o crearne di tuoi tramite configurazione. Gli agenti possono essere configurati in due modi: + +--- + +### JSON + +Configura gli agenti nel file `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Markdown + +Puoi anche definire agenti usando file markdown. Mettili in: + +- Globale: `~/.config/opencode/agents/` +- Per progetto: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Il nome del file markdown diventa il nome dell'agente. Per esempio, `review.md` crea un agente `review`. + +--- + +## Opzioni + +Vediamo nel dettaglio queste opzioni di configurazione. + +--- + +### Descrizione + +Usa l'opzione `description` per fornire una breve descrizione di cosa fa l'agente e quando usarlo. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +Questa e' un'opzione di configurazione **obbligatoria**. + +--- + +### Temperatura + +Controlla casualita' e creativita' delle risposte dell'LLM con la config `temperature`. + +Valori bassi rendono le risposte piu' focalizzate e deterministiche, mentre valori alti aumentano creativita' e variabilita'. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +I valori di temperature tipicamente vanno da 0.0 a 1.0: + +- **0.0-0.2**: risposte molto focalizzate e deterministiche, ideali per analisi del codice e pianificazione +- **0.3-0.5**: risposte bilanciate con un po' di creativita', adatte a task generali di sviluppo +- **0.6-1.0**: risposte piu' creative e varie, utili per brainstorming ed esplorazione + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Se non specifichi una temperature, OpenCode usa i default specifici del modello; tipicamente 0 per la maggior parte dei modelli e 0.55 per i modelli Qwen. + +--- + +### Passi massimi + +Controlla il numero massimo di iterazioni agentiche che un agente puo' eseguire prima di essere forzato a rispondere solo con testo. Questo permette a chi vuole controllare i costi di impostare un limite alle azioni agentiche. + +Se non e' impostato, l'agente continuera' a iterare finche' il modello sceglie di fermarsi o l'utente interrompe la sessione. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +Quando viene raggiunto il limite, l'agente riceve un system prompt speciale che lo istruisce a rispondere con un riassunto del lavoro svolto e con i task rimanenti consigliati. + +:::caution +Il campo legacy `maxSteps` e' deprecato. Usa `steps`. +::: + +--- + +### Disabilita + +Imposta a `true` per disabilitare l'agente. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Prompt + +Specifica un file di system prompt personalizzato per questo agente tramite la config `prompt`. Il file deve contenere istruzioni specifiche per lo scopo dell'agente. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Questo path e' relativo alla posizione del file di configurazione. Quindi funziona sia per la config globale di OpenCode sia per la config specifica del progetto. + +--- + +### Modello + +Usa la config `model` per sovrascrivere il modello per questo agente. Utile per usare modelli diversi ottimizzati per task diversi. Per esempio, un modello piu' veloce per la pianificazione e uno piu' capace per l'implementazione. + +:::tip +Se non specifichi un modello, gli agenti primari usano il [modello configurato globalmente](/docs/config#models), mentre i subagenti useranno il modello dell'agente primario che li ha invocati. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +L'ID modello nella configurazione OpenCode usa il formato `provider/model-id`. Per esempio, se stai usando [OpenCode Zen](/docs/zen), useresti `opencode/gpt-5.1-codex` per GPT 5.1 Codex. + +--- + +### Strumenti + +Controlla quali strumenti sono disponibili per questo agente tramite la config `tools`. Puoi abilitare o disabilitare strumenti specifici impostandoli a `true` o `false`. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +La configurazione specifica dell'agente sovrascrive la configurazione globale. +::: + +Puoi anche usare wildcard per controllare piu' strumenti in una volta. Per esempio, per disabilitare tutti gli strumenti di un server MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[Scopri di piu' sugli strumenti](/docs/tools). + +--- + +### Permessi + +Puoi configurare i permessi per gestire quali azioni un agente puo' eseguire. Attualmente, i permessi per gli strumenti `edit`, `bash` e `webfetch` possono essere configurati come: + +- `"ask"` — chiede approvazione prima di eseguire lo strumento +- `"allow"` — consente tutte le operazioni senza approvazione +- `"deny"` — disabilita lo strumento + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +Puoi sovrascrivere questi permessi per agente. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +Puoi anche impostare permessi negli agenti Markdown. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +Puoi impostare permessi per comandi bash specifici. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +Questo puo' usare un glob pattern. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +E puoi anche usare la wildcard `*` per gestire i permessi per tutti i comandi. +Dato che l'ultima regola che corrisponde ha la precedenza, metti prima la wildcard `*` e poi le regole specifiche. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[Scopri di piu' sui permessi](/docs/permissions). + +--- + +### Modalita' + +Controlla la modalita' dell'agente con la config `mode`. L'opzione `mode` determina come l'agente puo' essere usato. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +`mode` puo' essere `primary`, `subagent` o `all`. Se `mode` non e' specificato, il default e' `all`. + +--- + +### Nascosto + +Nascondi un subagente dal menu autocomplete di `@` con `hidden: true`. Utile per subagenti interni che dovrebbero essere invocati solo programmaticamente da altri agenti tramite lo strumento Task. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +Questo influisce solo sulla visibilita' per l'utente nel menu autocomplete. Gli agenti nascosti possono comunque essere invocati dal modello tramite lo strumento Task se i permessi lo consentono. + +:::note +Si applica solo ad agenti con `mode: subagent`. +::: + +--- + +### Permessi Task + +Controlla quali subagenti un agente puo' invocare tramite lo strumento Task con `permission.task`. Usa glob pattern per un matching flessibile. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +Quando e' impostato a `deny`, il subagente viene rimosso interamente dalla descrizione dello strumento Task, quindi il modello non provera' a invocarlo. + +:::tip +Le regole vengono valutate in ordine e **vince l'ultima regola che corrisponde**. Nell'esempio sopra, `orchestrator-planner` corrisponde sia a `*` (deny) sia a `orchestrator-*` (allow), ma dato che `orchestrator-*` viene dopo `*`, il risultato e' `allow`. +::: + +:::tip +Gli utenti possono sempre invocare qualunque subagente direttamente dal menu autocomplete `@`, anche se i permessi task dell'agente lo negherebbero. +::: + +--- + +### Colore + +Personalizza l'aspetto visivo dell'agente nella UI con l'opzione `color`. Questo influisce su come l'agente appare nell'interfaccia. + +Usa un colore hex valido (ad es. `#FF5733`) o un colore tema: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### Top P + +Controlla la diversita' delle risposte con l'opzione `top_p`. Alternativa alla temperature per controllare la casualita'. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +I valori vanno da 0.0 a 1.0. Valori piu' bassi sono piu' focalizzati, valori piu' alti piu' diversi. + +--- + +### Opzioni aggiuntive + +Qualsiasi altra opzione che specifichi nella configurazione dell'agente verra' **passata direttamente** al provider come opzione del modello. Questo ti permette di usare feature e parametri specifici del provider. + +Per esempio, con i modelli di reasoning di OpenAI, puoi controllare lo sforzo di ragionamento: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +Queste opzioni aggiuntive sono specifiche per modello e provider. Controlla la documentazione del provider per i parametri disponibili. + +:::tip +Esegui `opencode models` per vedere la lista dei modelli disponibili. +::: + +--- + +## Crea agenti + +Puoi creare nuovi agenti usando il comando seguente: + +```bash +opencode agent create +``` + +Questo comando interattivo: + +1. Chiede dove salvare l'agente: globale o specifico del progetto. +2. Chiede una descrizione di cosa dovrebbe fare l'agente. +3. Genera un system prompt appropriato e un identificatore. +4. Ti fa selezionare a quali strumenti l'agente puo' accedere. +5. Infine, crea un file markdown con la configurazione dell'agente. + +--- + +## Casi d'uso + +Ecco alcuni casi d'uso comuni per agenti diversi. + +- **Build agent**: sviluppo completo con tutti gli strumenti abilitati +- **Plan agent**: analisi e pianificazione senza apportare modifiche +- **Review agent**: code review con accesso in sola lettura piu' strumenti documentazione +- **Debug agent**: focalizzato sull'investigazione con strumenti bash e read abilitati +- **Docs agent**: scrittura documentazione con operazioni sui file ma senza comandi di sistema + +--- + +## Esempi + +Ecco alcuni agenti di esempio che potresti trovare utili. + +:::tip +Hai un agente che vorresti condividere? [Invia una PR](https://github.com/anomalyco/opencode). +::: + +--- + +### Agente documentazione + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### Auditor di sicurezza + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/it/cli.mdx b/packages/web/src/content/docs/it/cli.mdx new file mode 100644 index 000000000..861a928de --- /dev/null +++ b/packages/web/src/content/docs/it/cli.mdx @@ -0,0 +1,601 @@ +--- +title: CLI +description: Opzioni e comandi della CLI di OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +La CLI di OpenCode, per impostazione predefinita, avvia la [TUI](/docs/tui) quando viene eseguita senza argomenti. + +```bash +opencode +``` + +Ma accetta anche i comandi documentati in questa pagina. Questo ti permette di interagire con OpenCode in modo programmatico. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui + +Avvia l'interfaccia testuale di OpenCode (terminal user interface). + +```bash +opencode [project] +``` + +#### Flag + +| Flag | Breve | Descrizione | +| ------------ | ----- | ----------------------------------- | +| `--continue` | `-c` | Continua l'ultima sessione | +| `--session` | `-s` | ID sessione da continuare | +| `--prompt` | | Prompt da usare | +| `--model` | `-m` | Modello nel formato provider/model | +| `--agent` | | Agente da usare | +| `--port` | | Porta su cui mettersi in ascolto | +| `--hostname` | | Hostname su cui mettersi in ascolto | + +--- + +## Comandi + +La CLI di OpenCode include anche i seguenti comandi. + +--- + +### agent + +Gestisci gli agenti per OpenCode. + +```bash +opencode agent [command] +``` + +--- + +### attach + +Collega un terminale a un backend server di OpenCode gia' in esecuzione avviato tramite i comandi `serve` o `web`. + +```bash +opencode attach [url] +``` + +Questo consente di usare la TUI con un backend OpenCode remoto. Per esempio: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### Flag + +| Flag | Breve | Descrizione | +| ----------- | ----- | --------------------------------------- | +| `--dir` | | Working directory in cui avviare la TUI | +| `--session` | `-s` | ID sessione da continuare | + +--- + +#### create + +Crea un nuovo agente con configurazione personalizzata. + +```bash +opencode agent create +``` + +Questo comando ti guida nella creazione di un nuovo agente con un system prompt personalizzato e configurazione degli strumenti. + +--- + +#### list + +Elenca tutti gli agenti disponibili. + +```bash +opencode agent list +``` + +--- + +### auth + +Comando per gestire le credenziali e il login dei provider. + +```bash +opencode auth [command] +``` + +--- + +#### login + +OpenCode si basa sull'elenco provider di [Models.dev](https://models.dev), quindi puoi usare `opencode auth login` per configurare le API key per qualunque provider tu voglia usare. Le credenziali vengono salvate in `~/.local/share/opencode/auth.json`. + +```bash +opencode auth login +``` + +Quando OpenCode si avvia, carica i provider dal file delle credenziali e, se presenti, anche eventuali key definite nell'ambiente o in un file `.env` nel progetto. + +--- + +#### list + +Elenca tutti i provider autenticati come salvati nel file delle credenziali. + +```bash +opencode auth list +``` + +Oppure la versione corta. + +```bash +opencode auth ls +``` + +--- + +#### logout + +Esegue il logout da un provider rimuovendolo dal file delle credenziali. + +```bash +opencode auth logout +``` + +--- + +### github + +Gestisci l'agente GitHub per l'automazione dei repository. + +```bash +opencode github [command] +``` + +--- + +#### install + +Installa l'agente GitHub nel tuo repository. + +```bash +opencode github install +``` + +Questo configura il workflow GitHub Actions necessario e ti guida nel processo di configurazione. [Scopri di piu'](/docs/github). + +--- + +#### run + +Esegui l'agente GitHub. Tipicamente usato in GitHub Actions. + +```bash +opencode github run +``` + +##### Flag + +| Flag | Descrizione | +| --------- | -------------------------------------------- | +| `--event` | Evento GitHub mock per cui eseguire l'agente | +| `--token` | GitHub personal access token | + +--- + +### mcp + +Gestisci i server Model Context Protocol. + +```bash +opencode mcp [command] +``` + +--- + +#### add + +Aggiungi un server MCP alla tua configurazione. + +```bash +opencode mcp add +``` + +Questo comando ti guida nell'aggiunta di un server MCP locale o remoto. + +--- + +#### list + +Elenca tutti i server MCP configurati e il loro stato di connessione. + +```bash +opencode mcp list +``` + +Oppure la versione corta. + +```bash +opencode mcp ls +``` + +--- + +#### auth + +Autentica con un server MCP con OAuth abilitato. + +```bash +opencode mcp auth [name] +``` + +Se non fornisci un nome server, ti verra' chiesto di selezionare tra i server OAuth-capable disponibili. + +Puoi anche elencare i server OAuth-capable e il loro stato di autenticazione. + +```bash +opencode mcp auth list +``` + +Oppure la versione corta. + +```bash +opencode mcp auth ls +``` + +--- + +#### logout + +Rimuovi le credenziali OAuth per un server MCP. + +```bash +opencode mcp logout [name] +``` + +--- + +#### debug + +Esegui debug di problemi di connessione OAuth per un server MCP. + +```bash +opencode mcp debug +``` + +--- + +### models + +Elenca tutti i modelli disponibili dai provider configurati. + +```bash +opencode models [provider] +``` + +Questo comando mostra tutti i modelli disponibili tra i provider configurati nel formato `provider/model`. + +E' utile per capire l'esatto nome del modello da usare nella [config](/docs/config/). + +Puoi anche passare opzionalmente un ID provider per filtrare i modelli a quel provider. + +```bash +opencode models anthropic +``` + +#### Flag + +| Flag | Descrizione | +| ----------- | --------------------------------------------------- | +| `--refresh` | Aggiorna la cache modelli da models.dev | +| `--verbose` | Output piu' verboso (include metadati come i costi) | + +Usa `--refresh` per aggiornare l'elenco modelli in cache. E' utile quando nuovi modelli vengono aggiunti a un provider e vuoi vederli in OpenCode. + +```bash +opencode models --refresh +``` + +--- + +### run + +Esegui opencode in modalita' non interattiva passando un prompt direttamente. + +```bash +opencode run [message..] +``` + +E' utile per scripting, automazione o quando vuoi una risposta rapida senza avviare la TUI completa. Per esempio. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +Puoi anche collegarti a una istanza `opencode serve` gia' in esecuzione per evitare i cold boot dei server MCP ad ogni esecuzione: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### Flag + +| Flag | Breve | Descrizione | +| ------------ | ----- | --------------------------------------------------------------------- | +| `--command` | | Il comando da eseguire; usa message per gli argomenti | +| `--continue` | `-c` | Continua l'ultima sessione | +| `--session` | `-s` | ID sessione da continuare | +| `--share` | | Condividi la sessione | +| `--model` | `-m` | Modello nel formato provider/model | +| `--agent` | | Agente da usare | +| `--file` | `-f` | File da allegare al messaggio | +| `--format` | | Formato: default (formattato) o json (eventi JSON grezzi) | +| `--title` | | Titolo sessione (usa prompt troncato se non viene fornito un valore) | +| `--attach` | | Attach a un server opencode in esecuzione (es. http://localhost:4096) | +| `--port` | | Porta per il server locale (di default una porta casuale) | + +--- + +### serve + +Avvia un server OpenCode headless per accesso via API. Vedi le [server docs](/docs/server) per l'interfaccia HTTP completa. + +```bash +opencode serve +``` + +Avvia un server HTTP che espone accesso API alle funzionalita' di opencode senza la TUI. Imposta `OPENCODE_SERVER_PASSWORD` per abilitare HTTP basic auth (username di default `opencode`). + +#### Flag + +| Flag | Descrizione | +| ------------ | ---------------------------------------------- | +| `--port` | Porta su cui mettersi in ascolto | +| `--hostname` | Hostname su cui mettersi in ascolto | +| `--mdns` | Abilita discovery mDNS | +| `--cors` | Origin browser addizionali per consentire CORS | + +--- + +### session + +Gestisci le sessioni OpenCode. + +```bash +opencode session [command] +``` + +--- + +#### list + +Elenca tutte le sessioni OpenCode. + +```bash +opencode session list +``` + +##### Flag + +| Flag | Breve | Descrizione | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` | Limita alle N sessioni piu' recenti | +| `--format` | | Formato output: table o json (table) | + +--- + +### stats + +Mostra statistiche di utilizzo token e costo per le sessioni OpenCode. + +```bash +opencode stats +``` + +#### Flag + +| Flag | Descrizione | +| ----------- | ------------------------------------------------------------------------------------- | +| `--days` | Mostra statistiche per gli ultimi N giorni (all time) | +| `--tools` | Numero di strumenti da mostrare (all) | +| `--models` | Mostra breakdown di utilizzo modelli (nascosto di default). Passa un numero per top N | +| `--project` | Filtra per progetto (tutti i progetti; stringa vuota: progetto corrente) | + +--- + +### export + +Esporta i dati di sessione come JSON. + +```bash +opencode export [sessionID] +``` + +Se non fornisci un ID sessione, ti verra' chiesto di selezionare tra le sessioni disponibili. + +--- + +### import + +Importa i dati di sessione da un file JSON o da un URL di condivisione OpenCode. + +```bash +opencode import +``` + +Puoi importare da un file locale o da un URL di condivisione OpenCode. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### web + +Avvia un server OpenCode headless con interfaccia web. + +```bash +opencode web +``` + +Avvia un server HTTP e apre un browser per accedere a OpenCode tramite interfaccia web. Imposta `OPENCODE_SERVER_PASSWORD` per abilitare HTTP basic auth (username di default `opencode`). + +#### Flag + +| Flag | Descrizione | +| ------------ | ---------------------------------------------- | +| `--port` | Porta su cui mettersi in ascolto | +| `--hostname` | Hostname su cui mettersi in ascolto | +| `--mdns` | Abilita discovery mDNS | +| `--cors` | Origin browser addizionali per consentire CORS | + +--- + +### acp + +Avvia un server ACP (Agent Client Protocol). + +```bash +opencode acp +``` + +Questo comando avvia un server ACP che comunica via stdin/stdout usando nd-JSON. + +#### Flag + +| Flag | Descrizione | +| ------------ | ----------------------------------- | +| `--cwd` | Directory di lavoro | +| `--port` | Porta su cui mettersi in ascolto | +| `--hostname` | Hostname su cui mettersi in ascolto | + +--- + +### uninstall + +Disinstalla OpenCode e rimuove tutti i file correlati. + +```bash +opencode uninstall +``` + +#### Flag + +| Flag | Breve | Descrizione | +| --------------- | ----- | -------------------------------------------- | +| `--keep-config` | `-c` | Mantieni i file di configurazione | +| `--keep-data` | `-d` | Mantieni dati di sessione e snapshot | +| `--dry-run` | | Mostra cosa verrebbe rimosso senza rimuovere | +| `--force` | `-f` | Salta le richieste di conferma | + +--- + +### upgrade + +Aggiorna opencode all'ultima versione o a una versione specifica. + +```bash +opencode upgrade [target] +``` + +Per aggiornare all'ultima versione: + +```bash +opencode upgrade +``` + +Per aggiornare a una versione specifica: + +```bash +opencode upgrade v0.1.48 +``` + +#### Flag + +| Flag | Breve | Descrizione | +| ---------- | ----- | --------------------------------------------------------- | +| `--method` | `-m` | Metodo di installazione usato: curl, npm, pnpm, bun, brew | + +--- + +## Flag globali + +La CLI di opencode accetta i seguenti flag globali. + +| Flag | Breve | Descrizione | +| -------------- | ----- | -------------------------------------- | +| `--help` | `-h` | Mostra l'help | +| `--version` | `-v` | Stampa il numero di versione | +| `--print-logs` | | Stampa i log su stderr | +| `--log-level` | | Livello log (DEBUG, INFO, WARN, ERROR) | + +--- + +## Variabili d'ambiente + +OpenCode puo' essere configurato tramite variabili d'ambiente. + +| Variabile | Tipo | Descrizione | +| ------------------------------------- | ------- | ----------------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | boolean | Condivide automaticamente le sessioni | +| `OPENCODE_GIT_BASH_PATH` | string | Percorso all'eseguibile Git Bash su Windows | +| `OPENCODE_CONFIG` | string | Percorso al file di configurazione | +| `OPENCODE_CONFIG_DIR` | string | Percorso alla directory di configurazione | +| `OPENCODE_CONFIG_CONTENT` | string | Contenuto JSON di config inline | +| `OPENCODE_DISABLE_AUTOUPDATE` | boolean | Disabilita i controlli automatici di aggiornamento | +| `OPENCODE_DISABLE_PRUNE` | boolean | Disabilita la potatura dei dati vecchi | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | boolean | Disabilita aggiornamenti automatici del titolo terminale | +| `OPENCODE_PERMISSION` | string | Config permessi JSON inline | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | boolean | Disabilita i plugin di default | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | boolean | Disabilita download automatico dei server LSP | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | boolean | Abilita modelli sperimentali | +| `OPENCODE_DISABLE_AUTOCOMPACT` | boolean | Disabilita compaction automatica del contesto | +| `OPENCODE_DISABLE_CLAUDE_CODE` | boolean | Disabilita lettura da `.claude` (prompt + skill) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | boolean | Disabilita lettura di `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | boolean | Disabilita caricamento di `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | boolean | Disabilita fetch dei modelli da fonti remote | +| `OPENCODE_FAKE_VCS` | string | Provider VCS finto per scopi di test | +| `OPENCODE_DISABLE_FILETIME_CHECK` | boolean | Disabilita controllo file time per ottimizzazione | +| `OPENCODE_CLIENT` | string | Identificatore client (default `cli`) | +| `OPENCODE_ENABLE_EXA` | boolean | Abilita gli strumenti di web search Exa | +| `OPENCODE_SERVER_PASSWORD` | string | Abilita basic auth per `serve`/`web` | +| `OPENCODE_SERVER_USERNAME` | string | Sovrascrive lo username basic auth (default `opencode`) | +| `OPENCODE_MODELS_URL` | string | URL personalizzato per recuperare la configurazione modelli | + +--- + +### Sperimentale + +Queste variabili d'ambiente abilitano funzionalita' sperimentali che potrebbero cambiare o essere rimosse. + +| Variabile | Tipo | Descrizione | +| ----------------------------------------------- | ------- | ------------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | boolean | Abilita tutte le funzionalita' sperimentali | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | boolean | Abilita icon discovery | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | boolean | Disabilita copy on select nella TUI | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | number | Timeout di default per comandi bash in ms | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | number | Massimo token di output per risposte LLM | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | boolean | Abilita file watcher per l'intera dir | +| `OPENCODE_EXPERIMENTAL_OXFMT` | boolean | Abilita formatter oxfmt | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | boolean | Abilita strumento LSP sperimentale | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | boolean | Disabilita file watcher | +| `OPENCODE_EXPERIMENTAL_EXA` | boolean | Abilita funzionalita' Exa sperimentali | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | boolean | Abilita type checking LSP sperimentale | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | boolean | Abilita markdown sperimentale | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | boolean | Abilita plan mode | diff --git a/packages/web/src/content/docs/it/commands.mdx b/packages/web/src/content/docs/it/commands.mdx new file mode 100644 index 000000000..c6f8a874a --- /dev/null +++ b/packages/web/src/content/docs/it/commands.mdx @@ -0,0 +1,322 @@ +--- +title: Comandi +description: Crea comandi personalizzati per task ripetitivi. +--- + +I comandi personalizzati ti permettono di definire un prompt da eseguire quando quel comando viene lanciato nella TUI. + +```bash frame="none" +/my-command +``` + +I comandi personalizzati si aggiungono a quelli integrati come `/init`, `/undo`, `/redo`, `/share`, `/help`. [Scopri di piu](/docs/tui#commands). + +--- + +## Crea file di comando + +Crea file markdown nella directory `commands/` per definire comandi personalizzati. + +Crea `.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Il frontmatter definisce le proprieta del comando. Il contenuto diventa il template. + +Usa il comando digitando `/` seguito dal nome del comando. + +```bash frame="none" +"/test" +``` + +--- + +## Configura + +Puoi aggiungere comandi personalizzati tramite la config di OpenCode o creando file markdown nella directory `commands/`. + +--- + +### JSON + +Usa l'opzione `command` nella [config](/docs/config) di OpenCode: + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Ora puoi eseguire questo comando nella TUI: + +```bash frame="none" +/test +``` + +--- + +### Markdown + +Puoi anche definire comandi usando file markdown. Mettili in: + +- Globale: `~/.config/opencode/commands/` +- Per progetto: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Il nome del file markdown diventa il nome del comando. Per esempio, `test.md` ti permette di eseguire: + +```bash frame="none" +/test +``` + +--- + +## Configurazione del prompt + +I prompt dei comandi personalizzati supportano diversi placeholder e sintassi speciali. + +--- + +### Argomenti + +Passa argomenti ai comandi usando il placeholder `$ARGUMENTS`. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +Esegui il comando con argomenti: + +```bash frame="none" +/component Button +``` + +E `$ARGUMENTS` verra sostituito con `Button`. + +Puoi anche accedere ai singoli argomenti usando parametri posizionali: + +- `$1` - Primo argomento +- `$2` - Secondo argomento +- `$3` - Terzo argomento +- E cosi via... + +Per esempio: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +Esegui il comando: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +Questo sostituisce: + +- `$1` con `config.json` +- `$2` con `src` +- `$3` con `{ "key": "value" }` + +--- + +### Output della shell + +Usa _!`command`_ per inserire nel prompt l'output di un [comando bash](/docs/tui#bash-commands). + +Per esempio, per creare un comando personalizzato che analizzi la copertura dei test: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +Oppure per rivedere modifiche recenti: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +I comandi vengono eseguiti nella root del progetto e il loro output diventa parte del prompt. + +--- + +### Riferimenti ai file + +Includi file nel comando usando `@` seguito dal nome del file. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +Il contenuto del file viene incluso automaticamente nel prompt. + +--- + +## Opzioni + +Vediamo le opzioni di configurazione nel dettaglio. + +--- + +### Modello di prompt + +L'opzione `template` definisce il prompt che verra inviato all'LLM quando il comando viene eseguito. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +Questa e un'opzione di config **obbligatoria**. + +--- + +### Descrizione + +Usa l'opzione `description` per fornire una breve descrizione di cosa fa il comando. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +Questo viene mostrato come descrizione nella TUI quando digiti il comando. + +--- + +### Agente + +Usa la config `agent` per specificare opzionalmente quale [agente](/docs/agents) deve eseguire il comando. +Se e un [subagent](/docs/agents/#subagents), il comando attiva per default l'invocazione di un subagent. +Per disabilitare questo comportamento, imposta `subtask` a `false`. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +Questa e un'opzione di config **opzionale**. Se non specificata, usa l'agente corrente. + +--- + +### Sottotask + +Usa il booleano `subtask` per forzare il comando ad attivare l'invocazione di un [subagent](/docs/agents/#subagents). +E utile se vuoi evitare che il comando inquini il contesto principale e **forza** l'agente ad agire come subagent, +anche se `mode` e impostato su `primary` nella configurazione dell'[agente](/docs/agents). + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +Questa e un'opzione di config **opzionale**. + +--- + +### Modello + +Usa la config `model` per sovrascrivere il modello predefinito per questo comando. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Questa e un'opzione di config **opzionale**. + +--- + +## Integrati + +opencode include diversi comandi integrati come `/init`, `/undo`, `/redo`, `/share`, `/help`; [scopri di piu](/docs/tui#commands). + +:::note +I comandi personalizzati possono sovrascrivere quelli integrati. +::: + +Se definisci un comando personalizzato con lo stesso nome, sovrascrivera il comando integrato. diff --git a/packages/web/src/content/docs/it/config.mdx b/packages/web/src/content/docs/it/config.mdx new file mode 100644 index 000000000..363f0aef7 --- /dev/null +++ b/packages/web/src/content/docs/it/config.mdx @@ -0,0 +1,681 @@ +--- +title: Config +description: Usa la config JSON di OpenCode. +--- + +Puoi configurare OpenCode usando un file di configurazione JSON. + +--- + +## Formato + +OpenCode supporta sia **JSON** sia **JSONC** (JSON con commenti). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## Posizioni + +Puoi mettere la configurazione in diverse posizioni e ognuna ha un ordine di precedenza diverso. + +:::note +I file di configurazione vengono **uniti (merge)**, non sostituiti. +::: + +I file di configurazione vengono uniti (merge), non sostituiti. Le impostazioni provenienti dalle posizioni qui sotto vengono combinate. Le configurazioni caricate dopo sovrascrivono quelle precedenti solo per le chiavi in conflitto. Le impostazioni non in conflitto vengono preservate. + +Per esempio, se la tua configurazione globale imposta `theme: "opencode"` e `autoupdate: true`, e la configurazione del progetto imposta `model: "anthropic/claude-sonnet-4-5"`, la configurazione finale includera tutte e tre le impostazioni. + +--- + +### Ordine di precedenza + +Le sorgenti di configurazione vengono caricate in questo ordine (le successive sovrascrivono le precedenti): + +1. **Config remota** (da `.well-known/opencode`) - default dell'organizzazione +2. **Config globale** (`~/.config/opencode/opencode.json`) - preferenze utente +3. **Config personalizzata** (variabile d'ambiente `OPENCODE_CONFIG`) - sovrascritture personalizzate +4. **Config di progetto** (`opencode.json` nel progetto) - impostazioni specifiche del progetto +5. **Directory `.opencode`** - agenti, comandi, plugin +6. **Config inline** (variabile d'ambiente `OPENCODE_CONFIG_CONTENT`) - sovrascritture a runtime + +Questo significa che la configurazione di progetto puo sovrascrivere i default globali, e la configurazione globale puo sovrascrivere i default remoti dell'organizzazione. + +:::note +Le directory `.opencode` e `~/.config/opencode` usano **nomi al plurale** per le sottodirectory: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/` e `themes/`. I nomi al singolare (ad es. `agent/`) sono supportati per retrocompatibilita. +::: + +--- + +### Remota + +Le organizzazioni possono fornire una configurazione predefinita tramite l'endpoint `.well-known/opencode`. Viene recuperata automaticamente quando ti autentichi con un provider che lo supporta. + +La configurazione remota viene caricata per prima e fa da livello base. Tutte le altre sorgenti (globale, progetto) possono sovrascrivere questi default. + +Per esempio, se la tua organizzazione fornisce server MCP disabilitati per impostazione predefinita: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +Puoi abilitare server specifici nella tua configurazione locale: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### Globale + +Metti la configurazione globale di OpenCode in `~/.config/opencode/opencode.json`. Usa la configurazione globale per preferenze valide per l'utente (ad es. temi, provider o keybind). + +La configurazione globale sovrascrive i default remoti dell'organizzazione. + +--- + +### Per progetto + +Aggiungi `opencode.json` nella root del progetto. La configurazione di progetto ha la precedenza piu alta tra i file standard: sovrascrive sia la configurazione globale sia quella remota. + +:::tip +Metti la configurazione specifica del progetto nella root del progetto. +::: + +Quando OpenCode si avvia, cerca un file di configurazione nella directory corrente oppure risale fino alla directory Git piu vicina. + +Questo file puo essere tranquillamente versionato in Git e usa lo stesso schema di quello globale. + +--- + +### Percorso personalizzato + +Specifica un percorso personalizzato per il file di configurazione usando la variabile d'ambiente `OPENCODE_CONFIG`. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +La configurazione personalizzata viene caricata tra quella globale e quella di progetto nell'ordine di precedenza. + +--- + +### Directory personalizzata + +Specifica una directory di configurazione personalizzata usando la variabile d'ambiente `OPENCODE_CONFIG_DIR`. Questa directory verra usata per cercare agenti, comandi, modalita e plugin proprio come la directory standard `.opencode` e dovrebbe seguire la stessa struttura. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +La directory personalizzata viene caricata dopo la configurazione globale e le directory `.opencode`, quindi **puo sovrascrivere** le loro impostazioni. + +--- + +## Schema + +Il file di configurazione ha uno schema definito in [**`opencode.ai/config.json`**](https://opencode.ai/config.json). + +Il tuo editor dovrebbe poter validare e suggerire l'autocompletamento in base allo schema. + +--- + +### TUI + +Puoi configurare impostazioni specifiche della TUI tramite l'opzione `tui`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +Opzioni disponibili: + +- `scroll_acceleration.enabled` - Abilita l'accelerazione di scorrimento in stile macOS. **Ha precedenza su `scroll_speed`.** +- `scroll_speed` - Moltiplicatore personalizzato della velocita di scorrimento (predefinito: `3`, minimo: `1`). Ignorato se `scroll_acceleration.enabled` e `true`. +- `diff_style` - Controlla la resa delle diff. `"auto"` si adatta alla larghezza del terminale, `"stacked"` mostra sempre una singola colonna. + +[Scopri di piu sull'uso della TUI](/docs/tui). + +--- + +### Server + +Puoi configurare le impostazioni del server per i comandi `opencode serve` e `opencode web` tramite l'opzione `server`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +Opzioni disponibili: + +- `port` - Porta su cui ascoltare. +- `hostname` - Nome host su cui ascoltare. Quando `mdns` e abilitato e non e impostato alcun hostname, il default e `0.0.0.0`. +- `mdns` - Abilita la scoperta del servizio mDNS. Questo permette ad altri dispositivi sulla rete di scoprire il tuo server OpenCode. +- `mdnsDomain` - Nome di dominio personalizzato per il servizio mDNS. Predefinito: `opencode.local`. Utile per eseguire piu istanze sulla stessa rete. +- `cors` - Origini aggiuntive da consentire per CORS quando usi il server HTTP da un client basato su browser. I valori devono essere origini complete (schema + host + porta opzionale), ad es. `https://app.example.com`. + +[Scopri di piu sul server](/docs/server). + +--- + +### Strumenti + +Puoi gestire gli strumenti che un LLM puo usare tramite l'opzione `tools`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[Scopri di piu sugli strumenti](/docs/tools). + +--- + +### Modelli + +Puoi configurare provider e modelli da usare in OpenCode tramite le opzioni `provider`, `model` e `small_model`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +The `small_model` option configures a separate model for lightweight tasks like title generation. By default, OpenCode tries to use a cheaper model if one is available from your provider, otherwise it falls back to your main model. + +Provider options can include `timeout` and `setCacheKey`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - Timeout della richiesta in millisecondi (predefinito: 300000). Imposta a `false` per disabilitare. +- `setCacheKey` - Assicura che venga sempre impostata una cache key per il provider indicato. + +Puoi anche configurare i [modelli locali](/docs/models#local). [Scopri di piu](/docs/models). + +--- + +#### Opzioni specifiche del provider + +Alcuni provider supportano opzioni di configurazione aggiuntive oltre alle impostazioni generiche `timeout` e `apiKey`. + +##### Amazon Bedrock + +Amazon Bedrock supporta una configurazione specifica per AWS: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - Regione AWS per Bedrock (default: variabile d'ambiente `AWS_REGION` oppure `us-east-1`) +- `profile` - Profilo AWS nominato da `~/.aws/credentials` (default: variabile d'ambiente `AWS_PROFILE`) +- `endpoint` - URL endpoint personalizzato per gli endpoint VPC. E un alias dell'opzione generica `baseURL` usando la terminologia AWS. Se sono specificati sia `endpoint` sia `baseURL`, `endpoint` ha precedenza. + +:::note +I bearer token (`AWS_BEARER_TOKEN_BEDROCK` o `/connect`) hanno precedenza sull'autenticazione basata su profilo. Vedi [ordine di precedenza dell'autenticazione](/docs/providers#authentication-precedence) per i dettagli. +::: + +[Scopri di piu sulla configurazione di Amazon Bedrock](/docs/providers#amazon-bedrock). + +--- + +### Temi + +Puoi configurare il tema da usare in OpenCode tramite l'opzione `theme`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[Scopri di piu](/docs/themes). + +--- + +### Agenti + +Puoi configurare agenti specializzati per task specifici tramite l'opzione `agent`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +Puoi anche definire agenti usando file markdown in `~/.config/opencode/agents/` o `.opencode/agents/`. [Scopri di piu](/docs/agents). + +--- + +### Agente predefinito + +Puoi impostare l'agente predefinito usando l'opzione `default_agent`. Questo determina quale agente viene usato quando non ne specifichi uno esplicitamente. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +L'agente predefinito deve essere un agente primary (non un subagent). Puo essere un agente integrato come `"build"` o `"plan"`, oppure un [agente personalizzato](/docs/agents) che hai definito. Se l'agente specificato non esiste o e un subagent, OpenCode fara fallback su `"build"` mostrando un avviso. + +Questa impostazione si applica a tutte le interfacce: TUI, CLI (`opencode run`), app desktop e GitHub Action. + +--- + +### Condivisione + +Puoi configurare la funzione di [condivisione](/docs/share) tramite l'opzione `share`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +Valori supportati: + +- `"manual"` - Consenti la condivisione manuale tramite comandi (predefinito) +- `"auto"` - Condividi automaticamente le nuove conversazioni +- `"disabled"` - Disabilita completamente la condivisione + +Per impostazione predefinita, la condivisione e in modalita manuale e devi condividere esplicitamente le conversazioni usando il comando `/share`. + +--- + +### Comandi + +Puoi configurare comandi personalizzati per task ripetitivi tramite l'opzione `command`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +Puoi anche definire comandi usando file markdown in `~/.config/opencode/commands/` o `.opencode/commands/`. [Scopri di piu](/docs/commands). + +--- + +### Scorciatoie + +Puoi personalizzare i keybind tramite l'opzione `keybinds`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[Scopri di piu](/docs/keybinds). + +--- + +### Aggiornamenti automatici + +OpenCode scarichera automaticamente eventuali aggiornamenti quando si avvia. Puoi disabilitare questa funzione con l'opzione `autoupdate`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +Se non vuoi aggiornamenti automatici ma vuoi essere avvisato quando e disponibile una nuova versione, imposta `autoupdate` a `"notify"`. +Nota che questo funziona solo se non e stato installato con un package manager come Homebrew. + +--- + +### Formatter + +Puoi configurare i formatter di codice tramite l'opzione `formatter`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[Scopri di piu sui formatter](/docs/formatters). + +--- + +### Permessi + +Per impostazione predefinita, opencode **consente tutte le operazioni** senza richiedere un'approvazione esplicita. Puoi cambiarlo usando l'opzione `permission`. + +Per esempio, per fare in modo che gli strumenti `edit` e `bash` richiedano l'approvazione dell'utente: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[Scopri di piu sui permessi](/docs/permissions). + +--- + +### Compattazione + +Puoi controllare il comportamento di compattazione del contesto tramite l'opzione `compaction`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - Compatta automaticamente la sessione quando il contesto e pieno (predefinito: `true`). +- `prune` - Rimuove output vecchi degli strumenti per risparmiare token (predefinito: `true`). + +--- + +### Monitoraggio file + +Puoi configurare i pattern di ignoramento del file watcher tramite l'opzione `watcher`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +I pattern seguono la sintassi glob. Usali per escludere directory rumorose dal monitoraggio dei file. + +--- + +### Server MCP + +Puoi configurare i server MCP che vuoi usare tramite l'opzione `mcp`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[Scopri di piu](/docs/mcp-servers). + +--- + +### Plugin + +[I plugin](/docs/plugins) estendono OpenCode con strumenti personalizzati, hook e integrazioni. + +Metti i file dei plugin in `.opencode/plugins/` o `~/.config/opencode/plugins/`. Puoi anche caricare plugin da npm tramite l'opzione `plugin`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[Scopri di piu](/docs/plugins). + +--- + +### Istruzioni + +Puoi configurare le istruzioni per il modello che stai usando tramite l'opzione `instructions`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Accetta un array di percorsi e pattern glob verso file di istruzioni. [Scopri di piu +sulle regole](/docs/rules). + +--- + +### Provider disabilitati + +Puoi disabilitare i provider caricati automaticamente tramite l'opzione `disabled_providers`. E utile quando vuoi impedire il caricamento di alcuni provider anche se le credenziali sono disponibili. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +`disabled_providers` ha priorita su `enabled_providers`. +::: + +L'opzione `disabled_providers` accetta un array di ID provider. Quando un provider e disabilitato: + +- Non verra caricato anche se sono impostate variabili d'ambiente. +- Non verra caricato anche se le chiavi API sono configurate tramite il comando `/connect`. +- I modelli del provider non appariranno nella lista di selezione dei modelli. + +--- + +### Provider abilitati + +Puoi specificare un'allowlist di provider tramite l'opzione `enabled_providers`. Se impostata, solo i provider indicati verranno abilitati e tutti gli altri saranno ignorati. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +E utile quando vuoi limitare OpenCode a usare solo alcuni provider invece di disabilitarli uno per uno. + +:::note +`disabled_providers` ha priorita su `enabled_providers`. +::: + +Se un provider appare sia in `enabled_providers` sia in `disabled_providers`, `disabled_providers` ha priorita per retrocompatibilita. + +--- + +### Sperimentale + +La chiave `experimental` contiene opzioni in sviluppo attivo. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::caution +Le opzioni sperimentali non sono stabili. Possono cambiare o essere rimosse senza preavviso. +::: + +--- + +## Variabili + +Puoi usare la sostituzione di variabili nei file di configurazione per referenziare variabili d'ambiente e contenuti di file. + +--- + +### Variabili d'ambiente + +Usa `{env:VARIABLE_NAME}` per sostituire variabili d'ambiente: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +Se la variabile d'ambiente non e impostata, verra sostituita con una stringa vuota. + +--- + +### File + +Usa `{file:path/to/file}` per sostituire il contenuto di un file: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +I percorsi dei file possono essere: + +- Relativi alla directory del file di configurazione +- Oppure percorsi assoluti che iniziano con `/` o `~` + +Sono utili per: + +- Tenere dati sensibili (come chiavi API) in file separati. +- Includere file di istruzioni grandi senza appesantire la configurazione. +- Condividere snippet di configurazione comuni tra piu file di configurazione. diff --git a/packages/web/src/content/docs/it/custom-tools.mdx b/packages/web/src/content/docs/it/custom-tools.mdx new file mode 100644 index 000000000..9dd1be7ce --- /dev/null +++ b/packages/web/src/content/docs/it/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: Strumenti personalizzati +description: Crea strumenti che l'LLM puo chiamare in opencode. +--- + +Gli strumenti personalizzati sono funzioni che crei e che l'LLM puo chiamare durante le conversazioni. Funzionano insieme agli [strumenti integrati](/docs/tools) di opencode come `read`, `write` e `bash`. + +--- + +## Creating a tool + +Gli strumenti sono definiti come file **TypeScript** o **JavaScript**. Tuttavia, la definizione dello strumento puo invocare script scritti in **qualsiasi linguaggio**: TypeScript o JavaScript vengono usati solo per la definizione in se. + +--- + +### Location + +Possono essere definiti: + +- In locale, mettendoli nella directory `.opencode/tools/` del progetto. +- Oppure in globale, mettendoli in `~/.config/opencode/tools/`. + +--- + +### Structure + +Il modo piu semplice per creare strumenti e usare l'helper `tool()` che fornisce type-safety e validazione. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +Il **nome del file** diventa il **nome dello strumento**. L'esempio sopra crea lo strumento `database`. + +--- + +#### Multiple tools per file + +Puoi anche esportare piu strumenti da un singolo file. Ogni export diventa **uno strumento separato** con nome **`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +Questo crea due strumenti: `math_add` e `math_multiply`. + +--- + +### Arguments + +Puoi usare `tool.schema`, che e semplicemente [Zod](https://zod.dev), per definire i tipi degli argomenti. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +Puoi anche importare [Zod](https://zod.dev) direttamente e restituire un oggetto semplice: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### Context + +Gli strumenti ricevono un contesto sulla sessione corrente: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +Usa `context.directory` per la working directory della sessione. +Usa `context.worktree` per la root del worktree git. + +--- + +## Examples + +### Scrivi uno strumento in Python + +Puoi scrivere gli strumenti in qualunque linguaggio. Ecco un esempio che somma due numeri usando Python. + +Per prima cosa, crea lo strumento come script Python: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +Poi crea la definizione dello strumento che lo invoca: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +Qui usiamo l'utility [`Bun.$`](https://bun.com/docs/runtime/shell) per eseguire lo script Python. diff --git a/packages/web/src/content/docs/it/ecosystem.mdx b/packages/web/src/content/docs/it/ecosystem.mdx new file mode 100644 index 000000000..3241c4321 --- /dev/null +++ b/packages/web/src/content/docs/it/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: Ecosistema +description: Progetti e integrazioni costruiti con OpenCode. +--- + +Una raccolta di progetti della comunita costruiti su OpenCode. + +:::note +Vuoi aggiungere il tuo progetto legato a OpenCode a questa lista? Apri una PR. +::: + +Puoi anche dare un'occhiata a [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) e [opencode.cafe](https://opencode.cafe), una comunita che aggrega ecosistema e community. + +--- + +## Plugins + +| Nome | Descrizione | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | Esegue automaticamente sessioni OpenCode in sandbox Daytona isolate con sync git e anteprime live | +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Inietta automaticamente gli header di sessione Helicone per raggruppare le richieste | +| [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Inietta automaticamente tipi TypeScript/Svelte nelle letture dei file con tool di lookup | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Usa il tuo abbonamento ChatGPT Plus/Pro invece dei crediti API | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Usa il tuo piano Gemini esistente invece della fatturazione API | +| [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Usa i modelli gratuiti di Antigravity invece della fatturazione API | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Isolamento devcontainer multi-branch con shallow clone e porte assegnate automaticamente | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Plugin OAuth Google Antigravity, con supporto a Google Search e gestione API piu robusta | +| [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Ottimizza l'uso dei token eliminando output obsoleti degli strumenti | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Aggiunge supporto websearch nativo per provider supportati con stile grounded di Google | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Permette agli agenti AI di eseguire processi in background in una PTY e inviare input interattivo | +| [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Istruzioni per comandi shell non interattivi: evita blocchi dovuti a operazioni dipendenti da TTY | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Traccia l'uso di OpenCode con Wakatime | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Ripulisce le tabelle markdown prodotte dai LLM | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | Editing del codice 10x piu veloce con Morph Fast Apply API e marker lazy edit | +| [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Agenti in background, tool LSP/AST/MCP predefiniti, agenti curati, compatibile con Claude Code | +| [opencode-notificator](https://github.com/panta82/opencode-notificator) | Notifiche desktop e avvisi sonori per le sessioni OpenCode | +| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Notifiche desktop e avvisi sonori per eventi di permesso, completamento ed errore | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | Naming automatico delle sessioni Zellij basato sul contesto OpenCode | +| [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Permette agli agenti OpenCode di caricare prompt al bisogno con discovery e injection di skill | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Memoria persistente tra sessioni usando Supermemory | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Revisione interattiva dei piani con annotazione visiva e condivisione privata/offline | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Estende opencode /commands in un sistema di orchestrazione con controllo di flusso granulare | +| [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Pianifica job ricorrenti con launchd (Mac) o systemd (Linux) usando sintassi cron | +| [micode](https://github.com/vtemian/micode) | Workflow strutturato Brainstorm → Plan → Implement con continuita di sessione | +| [octto](https://github.com/vtemian/octto) | UI browser interattiva per brainstorming AI con moduli multi-domanda | +| [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Agenti in background stile Claude Code con delega async e persistenza del contesto | +| [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Notifiche native del sistema per OpenCode: sai quando i task finiscono | +| [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Harness di orchestrazione multi-agente bundle: 16 componenti, una installazione | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Git worktree senza attriti per OpenCode | + +--- + +## Projects + +| Nome | Descrizione | +| ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | Bot Discord per controllare sessioni OpenCode, costruito sull'SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Plugin Neovim per prompt consapevoli dell'editor, costruito sull'API | +| [portal](https://github.com/hosenur/portal) | Web UI mobile-first per OpenCode su Tailscale/VPN | +| [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | Template per costruire plugin OpenCode | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Frontend Neovim per opencode: un agente di coding AI da terminale | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Provider Vercel AI SDK per usare OpenCode tramite @opencode-ai/sdk | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | App Web/Desktop ed estensione VS Code per OpenCode | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Plugin Obsidian che integra OpenCode nella UI di Obsidian | +| [OpenWork](https://github.com/different-ai/openwork) | Alternativa open source a Claude Cowork, alimentata da OpenCode | +| [ocx](https://github.com/kdcokenny/ocx) | Gestore di estensioni OpenCode con profili portabili e isolati | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | App client Desktop, Web, Mobile e remota per OpenCode | + +--- + +## Agents + +| Nome | Descrizione | +| ----------------------------------------------------------------- | --------------------------------------------------------- | +| [Agentic](https://github.com/Cluster444/agentic) | Agenti AI modulari e comandi per uno sviluppo strutturato | +| [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Config, prompt, agenti e plugin per workflow migliorati | diff --git a/packages/web/src/content/docs/it/enterprise.mdx b/packages/web/src/content/docs/it/enterprise.mdx new file mode 100644 index 000000000..25bc79146 --- /dev/null +++ b/packages/web/src/content/docs/it/enterprise.mdx @@ -0,0 +1,165 @@ +--- +title: Enterprise +description: Usa OpenCode in sicurezza nella tua organizzazione. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise e pensato per organizzazioni che vogliono assicurarsi che codice e dati non escano mai dalla propria infrastruttura. Questo e possibile grazie a una config centralizzata che si integra con SSO e con il gateway AI interno. + +:::note +OpenCode non memorizza alcun tuo codice o dato di contesto. +::: + +Per iniziare con OpenCode Enterprise: + +1. Fai una prova interna con il tuo team. +2. **Contattaci** per parlare di prezzi e opzioni di implementazione. + +--- + +## Trial + +OpenCode e open source e non memorizza alcun tuo codice o dato di contesto, quindi i tuoi sviluppatori possono semplicemente [iniziare](/docs/) e fare una prova. + +--- + +### Data handling + +**OpenCode non memorizza il tuo codice o i tuoi dati di contesto.** Tutta l'elaborazione avviene in locale o tramite chiamate API dirette al tuo provider AI. + +Questo significa che, finche usi un provider di cui ti fidi o un gateway AI interno, puoi usare OpenCode in modo sicuro. + +L'unica eccezione e la funzione opzionale `/share`. + +--- + +#### Sharing conversations + +Se un utente abilita la funzione `/share`, la conversazione e i dati associati vengono inviati al servizio che usiamo per ospitare queste pagine di condivisione su opencode.ai. + +I dati sono serviti tramite la rete edge della nostra CDN e vengono messi in cache vicino ai tuoi utenti. + +Ti consigliamo di disabilitarla durante la prova. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[Learn more about sharing](/docs/share). + +--- + +### Code ownership + +**Sei proprietario di tutto il codice prodotto da OpenCode.** Non ci sono restrizioni di licenza o rivendicazioni di proprieta. + +--- + +## Pricing + +Usiamo un modello per-seat per OpenCode Enterprise. Se hai un tuo gateway LLM, non addebitiamo i token usati. Per maggiori dettagli su prezzi e opzioni di implementazione, **contattaci**. + +--- + +## Deployment + +Quando hai completato la prova e sei pronto a usare OpenCode nella tua organizzazione, puoi **contattarci** per discutere prezzi e opzioni di implementazione. + +--- + +### Central Config + +Possiamo configurare OpenCode per usare un'unica config centralizzata per tutta l'organizzazione. + +Questa config centralizzata puo integrarsi col provider SSO e garantisce che tutti gli utenti accedano solo al gateway AI interno. + +--- + +### SSO integration + +Tramite la config centralizzata, OpenCode puo integrarsi col provider SSO della tua organizzazione per l'autenticazione. + +Questo consente a OpenCode di ottenere credenziali per il gateway AI interno tramite il sistema di identity management esistente. + +--- + +### Internal AI gateway + +Con la config centralizzata, OpenCode puo anche essere configurato per usare solo il tuo gateway AI interno. + +Puoi anche disabilitare tutti gli altri provider AI, assicurandoti che tutte le richieste passino dall'infrastruttura approvata dalla tua organizzazione. + +--- + +### Self-hosting + +Anche se consigliamo di disabilitare le pagine di condivisione per assicurarti che i dati non escano mai dall'organizzazione, possiamo anche aiutarti a ospitarle sulla tua infrastruttura. + +Questa funzionalita e nella nostra roadmap. Se ti interessa, **faccelo sapere**. + +--- + +## FAQ + +

+Che cos'e OpenCode Enterprise? + +OpenCode Enterprise e pensato per organizzazioni che vogliono assicurarsi che codice e dati non escano mai dalla propria infrastruttura. Questo e possibile grazie a una config centralizzata che si integra con SSO e con il gateway AI interno. + +
+ +
+Come posso iniziare con OpenCode Enterprise? + +Inizia semplicemente con una prova interna con il tuo team. Per impostazione predefinita OpenCode non memorizza il tuo codice o i dati di contesto, quindi e facile partire. + +Poi **contattaci** per discutere prezzi e opzioni di implementazione. + +
+ +
+Come funziona il pricing enterprise? + +Offriamo pricing enterprise per-seat. Se hai un tuo gateway LLM, non addebitiamo i token usati. Per maggiori dettagli, **contattaci** per un preventivo su misura in base alle esigenze della tua organizzazione. + +
+ +
+I miei dati sono al sicuro con OpenCode Enterprise? + +Si. OpenCode non memorizza il tuo codice o i dati di contesto. Tutta l'elaborazione avviene in locale o tramite chiamate API dirette al tuo provider AI. Con config centralizzata e integrazione SSO, i dati restano all'interno dell'infrastruttura della tua organizzazione. + +
+ +
+Possiamo usare un registry NPM privato? + +OpenCode supporta registry npm privati tramite il supporto nativo di Bun per i file `.npmrc`. Se la tua organizzazione usa un registry privato, come JFrog Artifactory, Nexus o simili, assicurati che gli sviluppatori siano autenticati prima di eseguire OpenCode. + +Per configurare l'autenticazione col registry privato: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +Questo crea `~/.npmrc` con i dettagli di autenticazione. OpenCode lo rilevera automaticamente. + +:::caution +Devi essere autenticato nel registry privato prima di eseguire OpenCode. +::: + +In alternativa, puoi configurare manualmente un file `.npmrc`: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Gli sviluppatori devono essere autenticati nel registry privato prima di eseguire OpenCode per garantire che i pacchetti possano essere installati dal registry enterprise. + +
diff --git a/packages/web/src/content/docs/it/formatters.mdx b/packages/web/src/content/docs/it/formatters.mdx new file mode 100644 index 000000000..b2c51653e --- /dev/null +++ b/packages/web/src/content/docs/it/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: Formattatori +description: OpenCode usa formattatori specifici per linguaggio. +--- + +OpenCode formatta automaticamente i file dopo che vengono scritti o modificati usando formattatori specifici per linguaggio. Questo assicura che il codice generato segua lo stile del tuo progetto. + +--- + +## Built-in + +OpenCode include diversi formattatori integrati per linguaggi e framework popolari. Qui sotto trovi la lista dei formattatori, delle estensioni supportate e dei comandi o opzioni di config richiesti. + +| Formattatore | Estensioni | Requisiti | +| -------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| gofmt | .go | `gofmt` command available | +| mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` command available | +| prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://prettier.io/docs/en/index.html) | `prettier` dependency in `package.json` | +| biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://biomejs.dev/) | `biome.json(c)` config file | +| zig | .zig, .zon | `zig` command available | +| clang-format | .c, .cpp, .h, .hpp, .ino, and [more](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` config file | +| ktlint | .kt, .kts | `ktlint` command available | +| ruff | .py, .pyi | `ruff` command available with config | +| rustfmt | .rs | `rustfmt` command available | +| cargofmt | .rs | `cargo fmt` command available | +| uv | .py, .pyi | `uv` command available | +| rubocop | .rb, .rake, .gemspec, .ru | `rubocop` command available | +| standardrb | .rb, .rake, .gemspec, .ru | `standardrb` command available | +| htmlbeautifier | .erb, .html.erb | `htmlbeautifier` command available | +| air | .R | `air` command available | +| dart | .dart | `dart` command available | +| ocamlformat | .ml, .mli | `ocamlformat` command available and `.ocamlformat` config file | +| terraform | .tf, .tfvars | `terraform` command available | +| gleam | .gleam | `gleam` command available | +| nixfmt | .nix | `nixfmt` command available | +| shfmt | .sh, .bash | `shfmt` command available | +| pint | .php | `laravel/pint` dependency in `composer.json` | +| oxfmt (Experimental) | .js, .jsx, .ts, .tsx | `oxfmt` dependency in `package.json` and an [experimental env variable flag](/docs/cli/#experimental) | +| ormolu | .hs | `ormolu` command available | + +Quindi, se il progetto ha `prettier` in `package.json`, OpenCode lo usera automaticamente. + +--- + +## How it works + +Quando OpenCode scrive o modifica un file: + +1. Controlla l'estensione del file rispetto a tutti i formattatori abilitati. +2. Esegue il comando del formattatore appropriato sul file. +3. Applica automaticamente le modifiche di formattazione. + +Questo processo avviene in background, mantenendo lo stile del codice senza passaggi manuali. + +--- + +## Configure + +Puoi personalizzare i formattatori nella sezione `formatter` della config di OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +Ogni configurazione di formattatore supporta: + +| Proprieta | Tipo | Descrizione | +| ------------- | -------- | --------------------------------------------------- | +| `disabled` | boolean | Impostalo a `true` per disabilitare il formattatore | +| `command` | string[] | Il comando da eseguire per la formattazione | +| `environment` | object | Variabili d'ambiente da impostare quando si esegue | +| `extensions` | string[] | Estensioni file gestite da questo formattatore | + +Vediamo alcuni esempi. + +--- + +### Disabling formatters + +Per disabilitare **tutti** i formattatori globalmente, imposta `formatter` a `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +Per disabilitare un formattatore **specifico**, imposta `disabled` a `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Custom formatters + +Puoi sovrascrivere i formattatori integrati o aggiungerne di nuovi specificando comando, variabili d'ambiente ed estensioni file: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +Il **placeholder `$FILE`** nel comando viene sostituito con il percorso del file in fase di formattazione. diff --git a/packages/web/src/content/docs/it/github.mdx b/packages/web/src/content/docs/it/github.mdx new file mode 100644 index 000000000..c18ab7eb1 --- /dev/null +++ b/packages/web/src/content/docs/it/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: Usa OpenCode in issue e pull request su GitHub. +--- + +OpenCode si integra nel tuo workflow GitHub. Menziona `/opencode` o `/oc` in un commento e OpenCode eseguira' i task dentro il runner di GitHub Actions. + +--- + +## Funzionalita' + +- **Triage delle issue**: chiedi a OpenCode di indagare su una issue e spiegartela. +- **Fix e implementazioni**: chiedi a OpenCode di risolvere una issue o implementare una feature. Lavorera' su un nuovo branch e inviera' una PR con tutte le modifiche. +- **Sicuro**: OpenCode gira all'interno dei runner GitHub. + +--- + +## Installazione + +Esegui il comando seguente in un progetto che si trova in un repo GitHub: + +```bash +opencode github install +``` + +Questo ti guidera' nell'installazione della GitHub app, nella creazione del workflow e nella configurazione dei secret. + +--- + +### Configurazione manuale + +In alternativa, puoi configurarlo manualmente. + +1. **Installa la GitHub app** + + Vai su [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). Assicurati che sia installata sul repository di destinazione. + +2. **Aggiungi il workflow** + + Aggiungi il seguente file workflow in `.github/workflows/opencode.yml` nel tuo repo. Assicurati di impostare il `model` appropriato e le API key richieste in `env`. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **Salva le API key nei secret** + + Nelle **impostazioni** della tua organizzazione o progetto, espandi **Secrets and variables** sulla sinistra e seleziona **Actions**. Poi aggiungi le API key richieste. + +--- + +## Configurazione + +- `model`: il modello da usare con OpenCode. Usa il formato `provider/model`. E' **obbligatorio**. +- `agent`: l'agente da usare. Deve essere un agente primario. Se non trovato, usa `default_agent` dalla config o `"build"`. +- `share`: se condividere la sessione OpenCode. Di default e' **true** per repository pubblici. +- `prompt`: prompt personalizzato opzionale per sovrascrivere il comportamento di default. Usalo per personalizzare come OpenCode processa le richieste. +- `token`: token di accesso GitHub opzionale per eseguire operazioni come creare commenti, committare modifiche e aprire pull request. Di default, OpenCode usa l'installation access token della OpenCode GitHub App, quindi commit, commenti e pull request risultano provenire dalla app. + + In alternativa, puoi usare il [token integrato `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) del runner GitHub Actions senza installare la OpenCode GitHub App. Assicurati solo di concedere i permessi necessari nel workflow: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + Se preferisci, puoi anche usare un [personal access tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT). + +--- + +## Eventi supportati + +OpenCode puo' essere attivato dai seguenti eventi GitHub: + +| Tipo evento | Attivato da | Dettagli | +| ----------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | Commento su una issue o PR | Menziona `/opencode` o `/oc` nel commento. OpenCode legge il contesto e puo' creare branch, aprire PR o rispondere. | +| `pull_request_review_comment` | Commento su specifiche righe in una PR | Menziona `/opencode` o `/oc` durante una review. OpenCode riceve path file, numeri di riga e contesto del diff. | +| `issues` | Issue aperta o modificata | Attiva automaticamente OpenCode quando le issue vengono create o modificate. Richiede l'input `prompt`. | +| `pull_request` | PR aperta o aggiornata | Attiva automaticamente OpenCode quando le PR vengono aperte, sincronizzate o riaperte. Utile per review automatiche. | +| `schedule` | Pianificazione basata su cron | Esegue OpenCode a pianificazione. Richiede l'input `prompt`. Output nei log e nelle PR (nessuna issue su cui commentare). | +| `workflow_dispatch` | Trigger manuale dalla UI GitHub | Attiva OpenCode on-demand dalla tab Actions. Richiede l'input `prompt`. Output nei log e nelle PR. | + +### Esempio con schedule + +Esegui OpenCode a pianificazione per eseguire task automatizzati: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +Per gli eventi schedulati, l'input `prompt` e' **obbligatorio** dato che non c'e' un commento da cui estrarre le istruzioni. I workflow schedulati girano senza un contesto utente per i controlli di permesso, quindi il workflow deve concedere `contents: write` e `pull-requests: write` se ti aspetti che OpenCode crei branch o PR. + +--- + +### Esempio di pull request + +Review automatica delle PR quando vengono aperte o aggiornate: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Per gli eventi `pull_request`, se non viene fornito alcun `prompt`, OpenCode fa di default la review della pull request. + +--- + +### Esempio di triage delle issue + +Triage automatico delle nuove issue. Questo esempio filtra gli account piu' vecchi di 30 giorni per ridurre lo spam: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +Per gli eventi `issues`, l'input `prompt` e' **obbligatorio** dato che non c'e' un commento da cui estrarre le istruzioni. + +--- + +## Prompt personalizzati + +Sovrascrivi il prompt di default per personalizzare il comportamento di OpenCode nel tuo workflow. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +E' utile per imporre criteri specifici di review, standard di codice o aree di focus rilevanti per il progetto. + +--- + +## Esempi + +Ecco alcuni esempi di come puoi usare OpenCode su GitHub. + +- **Spiega una issue** + + Aggiungi questo commento in una issue GitHub. + + ``` + /opencode explain this issue + ``` + + OpenCode leggera' l'intero thread, inclusi tutti i commenti, e rispondera' con una spiegazione chiara. + +- **Risolvi una issue** + + In una issue GitHub, scrivi: + + ``` + /opencode fix this + ``` + + OpenCode creera' un nuovo branch, implementera' le modifiche e aprira' una PR con i cambiamenti. + +- **Rivedi PR e fai modifiche** + + Lascia il seguente commento su una PR GitHub. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + OpenCode implementera' la modifica richiesta e la committera' nella stessa PR. + +- **Rivedi righe specifiche di codice** + + Lascia un commento direttamente sulle righe di codice nella tab "Files" della PR. OpenCode rileva automaticamente file, numeri di riga e contesto del diff per fornire risposte precise. + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + Quando commenti su righe specifiche, OpenCode riceve: + - Il file esatto in review + - Le righe di codice specifiche + - Il contesto del diff circostante + - Informazioni sul numero di riga + + Questo permette richieste piu' mirate senza dover specificare manualmente path file o numeri di riga. diff --git a/packages/web/src/content/docs/it/gitlab.mdx b/packages/web/src/content/docs/it/gitlab.mdx new file mode 100644 index 000000000..5b3de5c44 --- /dev/null +++ b/packages/web/src/content/docs/it/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: Usa OpenCode in issue e merge request su GitLab. +--- + +OpenCode si integra nel tuo workflow GitLab tramite la pipeline GitLab CI/CD o con GitLab Duo. + +In entrambi i casi, OpenCode girera' sui tuoi runner GitLab. + +--- + +## GitLab CI + +OpenCode funziona in una pipeline GitLab standard. Puoi integrarlo nella pipeline come [componente CI](https://docs.gitlab.com/ee/ci/components/). + +Qui usiamo un componente CI/CD creato dalla community per OpenCode — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### Funzionalita' + +- **Configurazione personalizzata per job**: configura OpenCode con una directory di configurazione personalizzata, ad esempio `./config/#custom-directory`, per abilitare o disabilitare funzionalita' per ogni invocazione di OpenCode. +- **Setup minimo**: il componente CI prepara OpenCode in background; devi solo creare la configurazione OpenCode e il prompt iniziale. +- **Flessibile**: il componente CI supporta diversi input per personalizzarne il comportamento. + +--- + +### Setup + +1. Salva il JSON di autenticazione di OpenCode come variabile d'ambiente CI di tipo File in **Settings** > **CI/CD** > **Variables**. Assicurati di marcarla come "Masked and hidden". +2. Aggiungi quanto segue al tuo file `.gitlab-ci.yml`. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +Per altri input e casi d'uso, [consulta la documentazione](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) di questo componente. + +--- + +## GitLab Duo + +OpenCode si integra nel tuo workflow GitLab. +Menziona `@opencode` in un commento e OpenCode eseguira' i task dentro la tua pipeline GitLab CI. + +--- + +### Funzionalita' + +- **Triage delle issue**: chiedi a OpenCode di indagare su una issue e spiegartela. +- **Fix e implementazioni**: chiedi a OpenCode di risolvere una issue o implementare una feature. + Creera' un nuovo branch e aprira' una merge request con le modifiche. +- **Sicuro**: OpenCode gira sui tuoi runner GitLab. + +--- + +### Setup + +OpenCode gira nella pipeline GitLab CI/CD. Ecco cosa ti serve per configurarlo: + +:::tip +Dai un'occhiata alle [**GitLab docs**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) per istruzioni aggiornate. +::: + +1. Configura l'ambiente GitLab +2. Configura CI/CD +3. Ottieni una API key di un provider di modelli AI +4. Crea un service account +5. Configura le variabili CI/CD +6. Crea un file di configurazione del flow, ecco un esempio: + +
+ + Flow configuration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +Puoi fare riferimento alla [documentazione GitLab CLI agents](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) per istruzioni dettagliate. + +--- + +### Esempi + +Ecco alcuni esempi di come puoi usare OpenCode in GitLab. + +:::tip +Puoi configurare una frase trigger diversa da `@opencode`. +::: + +- **Spiega una issue** + + Aggiungi questo commento in una issue GitLab. + + ``` + @opencode explain this issue + ``` + + OpenCode leggera' la issue e rispondera' con una spiegazione chiara. + +- **Risolvi una issue** + + In una issue GitLab, scrivi: + + ``` + @opencode fix this + ``` + + OpenCode creera' un nuovo branch, implementera' le modifiche e aprira' una merge request con i cambiamenti. + +- **Rivedi merge request** + + Lascia il seguente commento su una merge request GitLab. + + ``` + @opencode review this merge request + ``` + + OpenCode rivedra' la merge request e fornira' feedback. diff --git a/packages/web/src/content/docs/it/ide.mdx b/packages/web/src/content/docs/it/ide.mdx new file mode 100644 index 000000000..37948acc1 --- /dev/null +++ b/packages/web/src/content/docs/it/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: L'estensione OpenCode per VS Code, Cursor e altri IDE +--- + +OpenCode si integra con VS Code, Cursor o qualunque IDE che supporti un terminale. Basta eseguire `opencode` nel terminale per iniziare. + +--- + +## Utilizzo + +- **Avvio rapido**: usa `Cmd+Esc` (Mac) o `Ctrl+Esc` (Windows/Linux) per aprire OpenCode in una vista terminale divisa, oppure per mettere a fuoco una sessione esistente se e gia in esecuzione. +- **Nuova sessione**: usa `Cmd+Shift+Esc` (Mac) o `Ctrl+Shift+Esc` (Windows/Linux) per avviare una nuova sessione di OpenCode, anche se ne esiste gia una aperta. Puoi anche cliccare il pulsante OpenCode nell'interfaccia. +- **Consapevolezza del contesto**: condividi automaticamente con OpenCode la selezione corrente o la scheda attiva. +- **Scorciatoie per riferimenti file**: usa `Cmd+Option+K` (Mac) o `Alt+Ctrl+K` (Linux/Windows) per inserire riferimenti a file. Per esempio, `@File#L37-42`. + +--- + +## Installazione + +Per installare OpenCode su VS Code e fork popolari come Cursor, Windsurf, VSCodium: + +1. Apri VS Code +2. Apri il terminale integrato +3. Esegui `opencode` - l'estensione si installa automaticamente + +Se invece vuoi usare il tuo IDE quando esegui `/editor` o `/export` dalla TUI, devi impostare `export EDITOR="code --wait"`. [Scopri di piu](/docs/tui/#editor-setup). + +--- + +### Installazione manuale + +Cerca **OpenCode** nel Marketplace delle estensioni e clicca **Install**. + +--- + +### Risoluzione dei problemi + +Se l'estensione non si installa automaticamente: + +- Assicurati di eseguire `opencode` nel terminale integrato. +- Verifica che la CLI del tuo IDE sia installata: + - Per VS Code: comando `code` + - Per Cursor: comando `cursor` + - Per Windsurf: comando `windsurf` + - Per VSCodium: comando `codium` + - In caso contrario, esegui `Cmd+Shift+P` (Mac) o `Ctrl+Shift+P` (Windows/Linux) e cerca "Shell Command: Install 'code' command in PATH" (o l'equivalente per il tuo IDE) +- Assicurati che VS Code abbia i permessi per installare estensioni diff --git a/packages/web/src/content/docs/it/index.mdx b/packages/web/src/content/docs/it/index.mdx new file mode 100644 index 000000000..fc594c946 --- /dev/null +++ b/packages/web/src/content/docs/it/index.mdx @@ -0,0 +1,343 @@ +--- +title: Introduzione +description: Inizia con OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) e un agente di programmazione AI open source. E disponibile come interfaccia da terminale, app desktop o estensione per IDE. + +![OpenCode TUI con il tema opencode](../../../assets/lander/screenshot.png) + +Iniziamo. + +--- + +#### Prerequisiti + +Per usare OpenCode nel terminale, ti serve: + +1. Un emulatore di terminale moderno, come: + - [WezTerm](https://wezterm.org), cross-platform + - [Alacritty](https://alacritty.org), cross-platform + - [Ghostty](https://ghostty.org), Linux and macOS + - [Kitty](https://sw.kovidgoyal.net/kitty/), Linux and macOS + +2. Le chiavi API dei provider LLM che vuoi usare. + +--- + +## Installa + +Il modo piu semplice per installare OpenCode e usare lo script di installazione. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +Puoi anche installarlo con i seguenti comandi: + +- **Con Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **Con Homebrew su macOS e Linux** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > Ti consigliamo di usare il tap di OpenCode per avere le release piu aggiornate. La formula ufficiale `brew install opencode` e mantenuta dal team Homebrew e viene aggiornata meno spesso. + +- **Con Paru su Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### Windows + +:::tip[Consigliato: usa WSL] +Per la migliore esperienza su Windows, ti consigliamo di usare [Windows Subsystem for Linux (WSL)](/docs/windows-wsl). Offre prestazioni migliori e piena compatibilita con le funzionalita di OpenCode. +::: + +- **Con Chocolatey** + + ```bash + choco install opencode + ``` + +- **Con Scoop** + + ```bash + scoop install opencode + ``` + +- **Con NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **Con Mise** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **Con Docker** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +Il supporto per installare OpenCode su Windows usando Bun e attualmente in lavorazione. + +Puoi anche scaricare il binario dalle [Releases](https://github.com/anomalyco/opencode/releases). + +--- + +## Configura + +Con OpenCode puoi usare qualsiasi provider LLM configurando le relative chiavi API. + +Se e la prima volta che usi provider LLM, ti consigliamo [OpenCode Zen](/docs/zen). +E una lista curata di modelli testati e verificati dal team di OpenCode. + +1. Esegui il comando `/connect` nella TUI, seleziona opencode e vai su [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Accedi, aggiungi i dettagli di fatturazione e copia la tua chiave API. + +3. Incolla la tua chiave API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +In alternativa, puoi selezionare uno degli altri provider. [Scopri di piu](/docs/providers#directory). + +--- + +## Inizializza + +Ora che hai configurato un provider, puoi spostarti in un progetto su cui vuoi lavorare. + +```bash +cd /path/to/project +``` + +E avviare OpenCode. + +```bash +opencode +``` + +Poi inizializza OpenCode per il progetto eseguendo il comando seguente. + +```bash frame="none" +/init +``` + +Questo fara analizzare il progetto a OpenCode e creera un file `AGENTS.md` nella root del progetto. + +:::tip +Dovresti committare il file `AGENTS.md` del progetto su Git. +::: + +Questo aiuta OpenCode a capire la struttura del progetto e gli stili di codice usati. + +--- + +## Usage + +Ora sei pronto a usare OpenCode sul tuo progetto. Sentiti libero di chiedergli qualsiasi cosa! + +Se e la prima volta che usi un agente di programmazione AI, ecco alcuni esempi che possono aiutare. + +--- + +### Fai domande + +Puoi chiedere a OpenCode di spiegarti la codebase. + +:::tip +Usa il tasto `@` per fare una ricerca fuzzy dei file nel progetto. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +Questo e utile se c'e una parte della codebase su cui non hai lavorato. + +--- + +### Aggiungi funzionalita + +Puoi chiedere a OpenCode di aggiungere nuove funzionalita al progetto. Pero ti consigliamo prima di chiedergli di creare un piano. + +1. **Create a plan** + + OpenCode ha una _Plan mode_ che disabilita la possibilita di fare modifiche e si limita a suggerire _come_ implementera la funzionalita. + + Passaci con il tasto **Tab**. Vedrai un indicatore nell'angolo in basso a destra. + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + Ora descriviamo cosa vogliamo che faccia. + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + Devi dare a OpenCode abbastanza dettagli per capire cosa vuoi. Aiuta parlargli come se stessi parlando a uno sviluppatore junior del tuo team. + + :::tip + Dai a OpenCode molto contesto ed esempi per aiutarlo a capire cosa vuoi. + ::: + +2. **Iterate on the plan** + + Una volta che ti da un piano, puoi dargli feedback o aggiungere piu dettagli. + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::tip + Trascina e rilascia le immagini nel terminale per aggiungerle al prompt. + ::: + + OpenCode puo analizzare le immagini che gli dai e aggiungerle al prompt. Puoi farlo trascinando e rilasciando un'immagine nel terminale. + +3. **Build the feature** + + Quando ti senti a tuo agio con il piano, torna in _Build mode_ premendo di nuovo il tasto **Tab**. + + ```bash frame="none" + + ``` + + E chiedigli di fare le modifiche. + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### Apporta modifiche + +Per modifiche piu semplici, puoi chiedere a OpenCode di implementarle direttamente senza dover prima rivedere un piano. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +Assicurati di fornire abbastanza dettagli, cosi OpenCode fa le modifiche giuste. + +--- + +### Annulla modifiche + +Mettiamo che tu chieda a OpenCode di fare alcune modifiche. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Ma ti accorgi che non e quello che volevi. Puoi **annullare** le modifiche usando il comando `/undo`. + +```bash frame="none" +/undo +``` + +OpenCode ora ripristina le modifiche e mostra di nuovo il tuo messaggio originale. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Da qui puoi modificare il prompt e chiedere a OpenCode di riprovare. + +:::tip +Puoi eseguire `/undo` piu volte per annullare piu modifiche. +::: + +Oppure puoi **rifare** le modifiche usando il comando `/redo`. + +```bash frame="none" +/redo +``` + +--- + +## Condividi + +Le conversazioni che fai con OpenCode possono essere [condivise con il tuo team](/docs/share). + +```bash frame="none" +/share +``` + +Questo creera un link alla conversazione corrente e lo copiera negli appunti. + +:::note +Le conversazioni non vengono condivise per impostazione predefinita. +::: + +Ecco un'[esempio di conversazione](https://opencode.ai/s/4XP1fce5) con OpenCode. + +--- + +## Personalizza + +E tutto qui! Ora sei un pro nell'usare OpenCode. + +Per renderlo davvero tuo, ti consigliamo di [scegliere un tema](/docs/themes), [personalizzare i tasti rapidi](/docs/keybinds), [configurare i formatter](/docs/formatters), [creare comandi personalizzati](/docs/commands) o sperimentare con la [configurazione di OpenCode](/docs/config). diff --git a/packages/web/src/content/docs/it/keybinds.mdx b/packages/web/src/content/docs/it/keybinds.mdx new file mode 100644 index 000000000..eb08c2c28 --- /dev/null +++ b/packages/web/src/content/docs/it/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: Scorciatoie +description: Personalizza le scorciatoie da tastiera. +--- + +OpenCode ha una lista di scorciatoie che puoi personalizzare tramite la configurazione di OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## Tasto leader + +OpenCode usa un tasto `leader` per la maggior parte delle scorciatoie. Questo evita conflitti nel terminale. + +Per impostazione predefinita, `ctrl+x` e il tasto leader e la maggior parte delle azioni richiede di premere prima il leader e poi la scorciatoia. Per esempio, per avviare una nuova sessione premi `ctrl+x` e poi `n`. + +Non sei obbligato a usare un tasto leader per le scorciatoie, ma lo consigliamo. + +--- + +## Disabilitare una scorciatoia + +Puoi disabilitare una scorciatoia aggiungendo la chiave nella configurazione con valore "none". + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## Scorciatoie del prompt desktop + +Il campo di input del prompt nell'app desktop di OpenCode supporta scorciatoie comuni in stile Readline/Emacs per modificare il testo. Sono integrate e al momento non configurabili tramite `opencode.json`. + +| Scorciatoia | Azione | +| ----------- | ------------------------------------------ | +| `ctrl+a` | Vai all'inizio della riga corrente | +| `ctrl+e` | Vai alla fine della riga corrente | +| `ctrl+b` | Sposta il cursore indietro di un carattere | +| `ctrl+f` | Sposta il cursore avanti di un carattere | +| `alt+b` | Sposta il cursore indietro di una parola | +| `alt+f` | Sposta il cursore avanti di una parola | +| `ctrl+d` | Elimina il carattere sotto il cursore | +| `ctrl+k` | Elimina fino alla fine della riga | +| `ctrl+u` | Elimina fino all'inizio della riga | +| `ctrl+w` | Elimina la parola precedente | +| `alt+d` | Elimina la parola successiva | +| `ctrl+t` | Scambia i caratteri | +| `ctrl+g` | Annulla popover / interrompe la risposta | + +--- + +## Shift+Enter + +Alcuni terminali non inviano di default i tasti modificatori insieme a Invio. Potrebbe essere necessario configurare il terminale per inviare `Shift+Enter` come sequenza di escape. + +### Windows Terminal + +Apri il tuo `settings.json` in: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +Aggiungi questo all'array `actions` a livello root: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Aggiungi questo all'array `keybindings` a livello root: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Salva il file e riavvia Windows Terminal oppure apri una nuova scheda. diff --git a/packages/web/src/content/docs/it/lsp.mdx b/packages/web/src/content/docs/it/lsp.mdx new file mode 100644 index 000000000..6480bc590 --- /dev/null +++ b/packages/web/src/content/docs/it/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: Server LSP +description: OpenCode si integra con i tuoi server LSP. +--- + +OpenCode si integra con il tuo Language Server Protocol (LSP) per aiutare l'LLM a interagire con la tua codebase. Usa le diagnostiche per fornire feedback all'LLM. + +--- + +## Integrati + +OpenCode include diversi server LSP integrati per linguaggi popolari: + +| Server LSP | Estensioni | Requisiti | +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| astro | .astro | Installazione automatica per progetti Astro | +| bash | .sh, .bash, .zsh, .ksh | Installazione automatica di bash-language-server | +| clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Installazione automatica per progetti C/C++ | +| csharp | .cs | `.NET SDK` installato | +| clojure-lsp | .clj, .cljs, .cljc, .edn | comando `clojure-lsp` disponibile | +| dart | .dart | comando `dart` disponibile | +| deno | .ts, .tsx, .js, .jsx, .mjs | comando `deno` disponibile (rileva automaticamente deno.json/deno.jsonc) | +| elixir-ls | .ex, .exs | comando `elixir` disponibile | +| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | dipendenza `eslint` nel progetto | +| fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` installato | +| gleam | .gleam | comando `gleam` disponibile | +| gopls | .go | comando `go` disponibile | +| hls | .hs, .lhs | comando `haskell-language-server-wrapper` disponibile | +| jdtls | .java | `Java SDK (version 21+)` installato | +| kotlin-ls | .kt, .kts | Installazione automatica per progetti Kotlin | +| lua-ls | .lua | Installazione automatica per progetti Lua | +| nixd | .nix | comando `nixd` disponibile | +| ocaml-lsp | .ml, .mli | comando `ocamllsp` disponibile | +| oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | dipendenza `oxlint` nel progetto | +| php intelephense | .php | Installazione automatica per progetti PHP | +| prisma | .prisma | comando `prisma` disponibile | +| pyright | .py, .pyi | dipendenza `pyright` installata | +| ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | comandi `ruby` e `gem` disponibili | +| rust | .rs | comando `rust-analyzer` disponibile | +| sourcekit-lsp | .swift, .objc, .objcpp | `swift` installato (`xcode` su macOS) | +| svelte | .svelte | Installazione automatica per progetti Svelte | +| terraform | .tf, .tfvars | Installazione automatica dalle release GitHub | +| tinymist | .typ, .typc | Installazione automatica dalle release GitHub | +| typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | dipendenza `typescript` nel progetto | +| vue | .vue | Installazione automatica per progetti Vue | +| yaml-ls | .yaml, .yml | Installazione automatica di Red Hat yaml-language-server | +| zls | .zig, .zon | comando `zig` disponibile | + +I server LSP vengono abilitati automaticamente quando viene rilevata una delle estensioni qui sopra e i requisiti sono soddisfatti. + +:::note +Puoi disabilitare il download automatico dei server LSP impostando la variabile d'ambiente `OPENCODE_DISABLE_LSP_DOWNLOAD` a `true`. +::: + +--- + +## Come funziona + +Quando opencode apre un file: + +1. Controlla l'estensione del file rispetto a tutti i server LSP abilitati. +2. Avvia il server LSP appropriato se non e gia in esecuzione. + +--- + +## Configura + +Puoi personalizzare i server LSP tramite la sezione `lsp` nella configurazione di opencode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Ogni server LSP supporta i seguenti campi: + +| Proprieta | Tipo | Descrizione | +| ---------------- | -------- | ------------------------------------------------ | +| `disabled` | boolean | Imposta a `true` per disabilitare il server LSP | +| `command` | string[] | Il comando per avviare il server LSP | +| `extensions` | string[] | Estensioni file gestite da questo server LSP | +| `env` | object | Variabili d'ambiente da impostare all'avvio | +| `initialization` | object | Opzioni di inizializzazione da inviare al server | + +Vediamo alcuni esempi. + +--- + +### Variabili d'ambiente + +Usa la proprieta `env` per impostare variabili d'ambiente quando avvii il server LSP: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### Opzioni di inizializzazione + +Usa la proprieta `initialization` per passare opzioni di inizializzazione al server LSP. Sono impostazioni specifiche del server inviate durante la richiesta LSP `initialize`: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +Le opzioni di inizializzazione variano da server a server. Consulta la documentazione del tuo server LSP per le opzioni disponibili. +::: + +--- + +### Disabilitare i server LSP + +Per disabilitare **tutti** i server LSP globalmente, imposta `lsp` a `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +Per disabilitare un server LSP **specifico**, imposta `disabled` a `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Server LSP personalizzati + +Puoi aggiungere server LSP personalizzati specificando il comando e le estensioni file: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## Informazioni aggiuntive + +### PHP Intelephense + +PHP Intelephense offre funzionalita premium tramite una chiave di licenza. Puoi fornire la chiave inserendo (solo) la chiave in un file di testo in: + +- Su macOS/Linux: `$HOME/intelephense/licence.txt` +- Su Windows: `%USERPROFILE%/intelephense/licence.txt` + +Il file deve contenere solo la chiave di licenza, senza contenuti aggiuntivi. diff --git a/packages/web/src/content/docs/it/mcp-servers.mdx b/packages/web/src/content/docs/it/mcp-servers.mdx new file mode 100644 index 000000000..a067d9963 --- /dev/null +++ b/packages/web/src/content/docs/it/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: Server MCP +description: Aggiungi strumenti MCP locali e remoti. +--- + +Puoi aggiungere strumenti esterni a OpenCode usando il _Model Context Protocol_, o MCP. OpenCode supporta sia server locali sia remoti. + +Una volta aggiunti, gli strumenti MCP sono automaticamente disponibili all'LLM insieme agli strumenti integrati. + +--- + +#### Avvertenze + +Quando usi un server MCP, aggiunge contenuto al contesto. Questo puo' crescere rapidamente se hai molti strumenti. Per questo consigliamo di fare attenzione a quali server MCP abiliti. + +:::tip +I server MCP aumentano il contesto, quindi e' meglio essere prudenti su quali abilitare. +::: + +Alcuni server MCP, come il server MCP di GitHub, tendono ad aggiungere molti token e possono facilmente superare il limite di contesto. + +--- + +## Abilita + +Puoi definire server MCP nella tua [OpenCode Config](https://opencode.ai/docs/config/) sotto `mcp`. Aggiungi ogni MCP con un nome univoco. Puoi riferirti a quell'MCP per nome quando fai prompt all'LLM. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +Puoi anche disabilitare un server impostando `enabled` a `false`. E' utile se vuoi disabilitare temporaneamente un server senza rimuoverlo dalla configurazione. + +--- + +### Sovrascrivere i default remoti + +Le organizzazioni possono fornire server MCP predefiniti tramite l'endpoint `.well-known/opencode`. Questi server possono essere disabilitati di default, lasciando agli utenti la possibilita' di fare opt-in su quelli necessari. + +Per abilitare un server specifico dalla configurazione remota dell'organizzazione, aggiungilo alla configurazione locale con `enabled: true`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +I valori della configurazione locale sovrascrivono i default remoti. Vedi [config precedence](/docs/config#precedence-order) per maggiori dettagli. + +--- + +## Locali + +Aggiungi server MCP locali impostando `type` a `"local"` dentro l'oggetto `mcp`. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +Il comando e' come viene avviato il server MCP locale. Puoi anche passare un elenco di variabili d'ambiente. + +Per esempio, ecco come aggiungere il server MCP di test [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +E per usarlo posso aggiungere `use the mcp_everything tool` ai miei prompt. + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### Opzioni + +Ecco tutte le opzioni per configurare un server MCP locale. + +| Opzione | Tipo | Richiesto | Descrizione | +| ------------- | ------- | --------- | ------------------------------------------------------------------------------------ | +| `type` | String | Y | Tipo di connessione del server MCP, deve essere `"local"`. | +| `command` | Array | Y | Comando e argomenti per eseguire il server MCP. | +| `environment` | Object | | Variabili d'ambiente da impostare quando si esegue il server. | +| `enabled` | Boolean | | Abilita o disabilita il server MCP all'avvio. | +| `timeout` | Number | | Timeout in ms per recuperare gli strumenti dal server MCP. Default 5000 (5 secondi). | + +--- + +## Remoti + +Aggiungi server MCP remoti impostando `type` a `"remote"`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` e' l'URL del server MCP remoto e con l'opzione `headers` puoi passare un elenco di header. + +--- + +#### Opzioni + +| Opzione | Tipo | Richiesto | Descrizione | +| --------- | ------- | --------- | ------------------------------------------------------------------------------------ | +| `type` | String | Y | Tipo di connessione del server MCP, deve essere `"remote"`. | +| `url` | String | Y | URL del server MCP remoto. | +| `enabled` | Boolean | | Abilita o disabilita il server MCP all'avvio. | +| `headers` | Object | | Header da inviare con la richiesta. | +| `oauth` | Object | | Configurazione autenticazione OAuth. Vedi sezione [OAuth](#oauth) sotto. | +| `timeout` | Number | | Timeout in ms per recuperare gli strumenti dal server MCP. Default 5000 (5 secondi). | + +--- + +## OAuth + +OpenCode gestisce automaticamente l'autenticazione OAuth per i server MCP remoti. Quando un server richiede autenticazione, OpenCode: + +1. Rileva la risposta 401 e avvia il flusso OAuth +2. Usa **Dynamic Client Registration (RFC 7591)** se supportato dal server +3. Memorizza i token in modo sicuro per richieste future + +--- + +### Automatico + +Per la maggior parte dei server MCP con OAuth, non serve alcuna configurazione speciale. Basta configurare il server remoto: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +Se il server richiede autenticazione, OpenCode ti chiedera' di autenticarti la prima volta che provi a usarlo. In caso contrario, puoi [attivare manualmente il flusso](#authenticating) con `opencode mcp auth `. + +--- + +### Pre-registrato + +Se hai credenziali client dal provider del server MCP, puoi configurarle: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### Autenticazione + +Puoi avviare manualmente l'autenticazione o gestire le credenziali. + +Autentica con un server MCP specifico: + +```bash +opencode mcp auth my-oauth-server +``` + +Elenca tutti i server MCP e il loro stato di autenticazione: + +```bash +opencode mcp list +``` + +Rimuovi credenziali memorizzate: + +```bash +opencode mcp logout my-oauth-server +``` + +Il comando `mcp auth` aprira' il browser per l'autorizzazione. Dopo l'autorizzazione, OpenCode memorizzera' i token in modo sicuro in `~/.local/share/opencode/mcp-auth.json`. + +--- + +#### Disabilitare OAuth + +Se vuoi disabilitare l'OAuth automatico per un server (ad esempio per server che usano API key), imposta `oauth` a `false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### Opzioni OAuth + +| Opzione | Tipo | Descrizione | +| -------------- | --------------- | --------------------------------------------------------------------------- | +| `oauth` | Object \| false | Oggetto config OAuth, o `false` per disabilitare l'auto-detection di OAuth. | +| `clientId` | String | OAuth client ID. Se non fornito, si prova la dynamic client registration. | +| `clientSecret` | String | OAuth client secret, se richiesto dal server di autorizzazione. | +| `scope` | String | Scope OAuth da richiedere durante l'autorizzazione. | + +#### Debug + +Se un server MCP remoto non riesce ad autenticarsi, puoi diagnosticare i problemi con: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +Il comando `mcp debug` mostra lo stato di autenticazione corrente, testa la connettivita' HTTP e prova il flusso di discovery OAuth. + +--- + +## Gestione + +I tuoi MCP sono disponibili come strumenti in OpenCode insieme agli strumenti integrati. Quindi puoi gestirli tramite la configurazione OpenCode come qualunque altro strumento. + +--- + +### Globale + +Questo significa che puoi abilitarli o disabilitarli globalmente. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +Possiamo anche usare un pattern glob per disabilitare tutti gli MCP corrispondenti. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +Qui stiamo usando il pattern glob `my-mcp*` per disabilitare tutti gli MCP. + +--- + +### Per agente + +Se hai molti server MCP, potresti volerli abilitare solo per agente e disabilitarli globalmente. Per farlo: + +1. Disabilitalo globalmente come strumento. +2. Nella tua [config dell'agente](/docs/agents#tools), abilita il server MCP come strumento. + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### Pattern glob + +Il pattern glob usa semplici regole di globbing: + +- `*` corrisponde a zero o piu' caratteri qualsiasi (ad esempio `"my-mcp*"` corrisponde a `my-mcp_search`, `my-mcp_list`, ecc.) +- `?` corrisponde esattamente a un carattere +- Tutti gli altri caratteri corrispondono letteralmente + +:::note +Gli strumenti del server MCP vengono registrati con il nome del server come prefisso, quindi per disabilitare tutti gli strumenti di un server e' sufficiente usare: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## Esempi + +Qui sotto trovi esempi di alcuni server MCP comuni. Puoi inviare una PR se vuoi documentare altri server. + +--- + +### Sentry + +Aggiungi il [server MCP di Sentry](https://mcp.sentry.dev) per interagire con i tuoi progetti e le issue di Sentry. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +Dopo aver aggiunto la configurazione, autentica con Sentry: + +```bash +opencode mcp auth sentry +``` + +Questo aprira' una finestra del browser per completare il flusso OAuth e collegare OpenCode al tuo account Sentry. + +Una volta autenticato, puoi usare gli strumenti Sentry nei tuoi prompt per interrogare issue, progetti e dati sugli errori. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Context7 + +Aggiungi il [server MCP Context7](https://github.com/upstash/context7) per cercare nella documentazione. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +Se ti sei registrato per un account gratuito, puoi usare la tua API key e ottenere rate limit piu' alti. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +Qui assumiamo che tu abbia impostato la variabile d'ambiente `CONTEXT7_API_KEY`. + +Aggiungi `use context7` ai tuoi prompt per usare il server MCP Context7. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +In alternativa, puoi aggiungere qualcosa del genere al tuo [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep by Vercel + +Aggiungi il server MCP [Grep by Vercel](https://grep.app) per cercare snippet di codice su GitHub. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +Dato che abbiamo chiamato il nostro server MCP `gh_grep`, puoi aggiungere `use the gh_grep tool` ai tuoi prompt per fare in modo che l'agente lo usi. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +In alternativa, puoi aggiungere qualcosa del genere al tuo [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/it/models.mdx b/packages/web/src/content/docs/it/models.mdx new file mode 100644 index 000000000..a1ee9a5db --- /dev/null +++ b/packages/web/src/content/docs/it/models.mdx @@ -0,0 +1,222 @@ +--- +title: Modelli +description: Configurare un provider LLM e un modello. +--- + +OpenCode usa [AI SDK](https://ai-sdk.dev/) e [Models.dev](https://models.dev) per supportare **75+ provider LLM** e supporta anche l'esecuzione di modelli locali. + +--- + +## Providers + +I provider piu popolari sono precaricati per impostazione predefinita. Se hai aggiunto le credenziali di un provider tramite il comando `/connect`, saranno disponibili quando avvii OpenCode. + +[Scopri di piu](/docs/providers) sui provider. + +--- + +## Seleziona un modello + +Dopo aver configurato il provider, puoi selezionare il modello che vuoi digitando: + +```bash frame="none" +/models +``` + +--- + +## Modelli consigliati + +Esistono moltissimi modelli, e ne escono di nuovi ogni settimana. + +:::tip +Valuta di usare uno dei modelli che consigliamo. +::: + +Tuttavia, solo alcuni sono davvero bravi sia a generare codice sia a chiamare strumenti. + +Ecco alcuni modelli che funzionano bene con OpenCode, in nessun ordine particolare. (Non e una lista esaustiva e potrebbe non essere aggiornata): + +- GPT 5.2 +- GPT 5.1 Codex +- Claude Opus 4.5 +- Claude Sonnet 4.5 +- Minimax M2.1 +- Gemini 3 Pro + +--- + +## Imposta un predefinito + +Per impostarne uno come modello predefinito, puoi impostare la chiave `model` nella config di OpenCode. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Qui l'ID completo e `provider_id/model_id`. Per esempio, se usi [OpenCode Zen](/docs/zen), useresti `opencode/gpt-5.1-codex` per GPT 5.1 Codex. + +Se hai configurato un [provider personalizzato](/docs/providers#custom), `provider_id` e la chiave nella sezione `provider` della config e `model_id` e la chiave in `provider.models`. + +--- + +## Configure models + +Puoi configurare globalmente le opzioni di un modello tramite la config. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Qui stiamo configurando impostazioni globali per due modelli integrati: `gpt-5` quando viene usato tramite il provider `openai` e `claude-sonnet-4-20250514` quando viene usato tramite il provider `anthropic`. +I nomi di provider e modelli integrati si trovano su [Models.dev](https://models.dev). + +Puoi anche configurare queste opzioni per gli agenti che usi. La config dell'agente sovrascrive le opzioni globali definite qui. [Scopri di piu](/docs/agents/#additional). + +Puoi anche definire varianti personalizzate che estendono quelle integrate. Le varianti ti permettono di configurare impostazioni diverse per lo stesso modello senza creare voci duplicate: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## Variants + +Molti modelli supportano piu varianti con configurazioni diverse. OpenCode include varianti predefinite integrate per i provider piu comuni. + +### Built-in variants + +OpenCode include varianti predefinite per molti provider: + +**Anthropic**: + +- `high` - High thinking budget (default) +- `max` - Maximum thinking budget + +**OpenAI**: + +Varies by model but roughly: + +- `none` - No reasoning +- `minimal` - Minimal reasoning effort +- `low` - Low reasoning effort +- `medium` - Medium reasoning effort +- `high` - High reasoning effort +- `xhigh` - Extra high reasoning effort + +**Google**: + +- `low` - Lower effort/token budget +- `high` - Higher effort/token budget + +:::tip +Questa lista non e completa. Anche molti altri provider hanno default integrati. +::: + +### Custom variants + +Puoi sovrascrivere varianti esistenti o aggiungerne di tue: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### Cycle variants + +Usa il keybind `variant_cycle` per passare rapidamente tra le varianti. [Scopri di piu](/docs/keybinds). + +--- + +## Loading models + +Quando OpenCode si avvia, controlla i modelli in questo ordine di priorita: + +1. Il flag da riga di comando `--model` o `-m`. Il formato e lo stesso della config: `provider_id/model_id`. + +2. La lista dei modelli nella config di OpenCode. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + Qui il formato e `provider/model`. + +3. L'ultimo modello usato. + +4. Il primo modello in base a una priorita interna. diff --git a/packages/web/src/content/docs/it/modes.mdx b/packages/web/src/content/docs/it/modes.mdx new file mode 100644 index 000000000..5b0ebe885 --- /dev/null +++ b/packages/web/src/content/docs/it/modes.mdx @@ -0,0 +1,330 @@ +--- +title: Modalita +description: Modalita diverse per casi d'uso diversi. +--- + +:::caution +Le modalita ora si configurano tramite l'opzione `agent` nella configurazione di opencode. L'opzione +`mode` e ora deprecata. [Scopri di piu](/docs/agents). +::: + +Le modalita in opencode ti permettono di personalizzare comportamento, strumenti e prompt per casi d'uso diversi. + +Include due modalita integrate: **build** e **plan**. Puoi personalizzarle oppure configurarne di tue tramite la configurazione di opencode. + +Puoi passare da una modalita all'altra durante una sessione oppure configurarle nel file di configurazione. + +--- + +## Integrate + +opencode include due modalita integrate. + +--- + +### Build + +Build e la modalita **predefinita** con tutti gli strumenti abilitati. E la modalita standard per il lavoro di sviluppo quando ti serve accesso completo alle operazioni sui file e ai comandi di sistema. + +--- + +### Plan + +Una modalita limitata pensata per pianificazione e analisi. In modalita plan, i seguenti strumenti sono disabilitati per impostazione predefinita: + +- `write` - Non puo creare nuovi file +- `edit` - Non puo modificare file esistenti, tranne i file in `.opencode/plans/*.md` per dettagliare il piano +- `patch` - Non puo applicare patch +- `bash` - Non puo eseguire comandi shell + +Questa modalita e utile quando vuoi che l'AI analizzi il codice, suggerisca modifiche o crei piani senza apportare modifiche effettive alla codebase. + +--- + +## Cambiare modalita + +Puoi cambiare modalita durante una sessione usando il tasto _Tab_. In alternativa, puoi usare il keybind `switch_mode` che hai configurato. + +Vedi anche: [Formatter](/docs/formatters) per informazioni sulla configurazione della formattazione del codice. + +--- + +## Configura + +Puoi personalizzare le modalita integrate o crearne di tue tramite configurazione. Le modalita si possono configurare in due modi: + +### Configurazione JSON + +Configura le modalita nel file di configurazione `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Configurazione Markdown + +Puoi anche definire modalita usando file markdown. Mettili in: + +- Globale: `~/.config/opencode/modes/` +- Progetto: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Il nome del file markdown diventa il nome della modalita (ad es. `review.md` crea una modalita `review`). + +Vediamo queste opzioni di configurazione nel dettaglio. + +--- + +### Modello + +Usa la configurazione `model` per sovrascrivere il modello predefinito per questa modalita. E utile per usare modelli diversi ottimizzati per task diversi: per esempio, un modello piu veloce per la pianificazione e uno piu capace per l'implementazione. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Temperatura + +Controlla casualita e creativita delle risposte dell'AI con la configurazione `temperature`. Valori piu bassi rendono le risposte piu focalizzate e deterministiche, mentre valori piu alti aumentano creativita e variabilita. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +I valori di temperatura di solito vanno da 0.0 a 1.0: + +- **0.0-0.2**: risposte molto focalizzate e deterministiche, ideali per analisi del codice e pianificazione +- **0.3-0.5**: risposte bilanciate con un po' di creativita, buone per task di sviluppo generici +- **0.6-1.0**: risposte piu creative e variabili, utili per brainstorming ed esplorazione + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Se non viene specificata alcuna temperatura, opencode usa i default specifici del modello (tipicamente 0 per la maggior parte dei modelli, 0.55 per i modelli Qwen). + +--- + +### Prompt + +Specifica un file di prompt di sistema personalizzato per questa modalita con la configurazione `prompt`. Il file dovrebbe contenere istruzioni specifiche per lo scopo della modalita. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Questo percorso e relativo a dove si trova il file di configurazione. Quindi funziona +sia per la configurazione globale di opencode sia per quella specifica del progetto. + +--- + +### Strumenti + +Controlla quali strumenti sono disponibili in questa modalita con la configurazione `tools`. Puoi abilitare o disabilitare strumenti specifici impostandoli a `true` o `false`. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +Se non specifichi gli strumenti, tutti gli strumenti sono abilitati per impostazione predefinita. + +--- + +#### Strumenti disponibili + +Ecco tutti gli strumenti che possono essere controllati tramite la configurazione della modalita. + +| Strumento | Descrizione | +| ----------- | --------------------------------- | +| `bash` | Esegue comandi shell | +| `edit` | Modifica file esistenti | +| `write` | Crea nuovi file | +| `read` | Legge contenuti dei file | +| `grep` | Cerca nei contenuti dei file | +| `glob` | Trova file per pattern | +| `list` | Elenca contenuti di una directory | +| `patch` | Applica patch ai file | +| `todowrite` | Gestisce liste todo | +| `todoread` | Legge liste todo | +| `webfetch` | Recupera contenuti web | + +--- + +## Modalita personalizzate + +Puoi creare modalita personalizzate aggiungendole alla configurazione. Ecco esempi con entrambi gli approcci: + +### Usando la configurazione JSON + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Usando file markdown + +Crea file di modalita in `.opencode/modes/` per modalita specifiche del progetto oppure in `~/.config/opencode/modes/` per modalita globali: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### Casi d'uso + +Ecco alcuni casi d'uso comuni per le diverse modalita. + +- **Modalita Build**: sviluppo completo con tutti gli strumenti abilitati +- **Modalita Plan**: analisi e pianificazione senza apportare modifiche +- **Modalita Review**: code review con accesso in sola lettura piu strumenti di documentazione +- **Modalita Debug**: focalizzata sull'investigazione con strumenti bash e read abilitati +- **Modalita Docs**: scrittura di documentazione con operazioni sui file ma senza comandi di sistema + +Potresti anche trovare che modelli diversi funzionano meglio per casi d'uso diversi. diff --git a/packages/web/src/content/docs/it/network.mdx b/packages/web/src/content/docs/it/network.mdx new file mode 100644 index 000000000..866494430 --- /dev/null +++ b/packages/web/src/content/docs/it/network.mdx @@ -0,0 +1,57 @@ +--- +title: Rete +description: Configura proxy e certificati personalizzati. +--- + +OpenCode supporta le variabili d'ambiente standard per i proxy e certificati personalizzati per ambienti di rete enterprise. + +--- + +## Proxy + +OpenCode rispetta le variabili d'ambiente standard dei proxy. + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::caution +La TUI comunica con un server HTTP locale. Devi bypassare il proxy per questa connessione per evitare loop di instradamento. +::: + +Puoi configurare porta e hostname del server usando i [flag della CLI](/docs/cli#run). + +--- + +### Autenticazione + +Se il proxy richiede autenticazione basic, includi le credenziali nell'URL. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::caution +Evita di hardcodare le password. Usa variabili d'ambiente o un archivio sicuro per le credenziali. +::: + +Per proxy che richiedono autenticazioni avanzate come NTLM o Kerberos, valuta l'uso di un LLM Gateway che supporti il tuo metodo di autenticazione. + +--- + +## Certificati personalizzati + +Se la tua organizzazione usa CA personalizzate per connessioni HTTPS, configura OpenCode in modo che si fidi di esse. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +Questo funziona sia per connessioni tramite proxy sia per l'accesso diretto alle API. diff --git a/packages/web/src/content/docs/it/permissions.mdx b/packages/web/src/content/docs/it/permissions.mdx new file mode 100644 index 000000000..d0f014a84 --- /dev/null +++ b/packages/web/src/content/docs/it/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: Permessi +description: Controlla quali azioni richiedono approvazione prima di essere eseguite. +--- + +OpenCode usa la configurazione `permission` per decidere se una determinata azione deve essere eseguita automaticamente, se deve chiederti conferma o se deve essere bloccata. + +A partire da `v1.1.1`, la vecchia configurazione booleana `tools` e' deprecata ed e' stata incorporata in `permission`. La vecchia configurazione `tools` e' ancora supportata per retrocompatibilita'. + +--- + +## Azioni + +Ogni regola di permesso si risolve in uno tra: + +- `"allow"` — esegui senza approvazione +- `"ask"` — chiedi approvazione +- `"deny"` — blocca l'azione + +--- + +## Configurazione + +Puoi impostare i permessi globalmente (con `*`) e sovrascrivere quelli di strumenti specifici. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +Puoi anche impostare tutti i permessi in una sola volta: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## Regole granulari (sintassi a oggetto) + +Per la maggior parte dei permessi, puoi usare un oggetto per applicare azioni diverse in base all'input dello strumento. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +Le regole vengono valutate per corrispondenza di pattern e **vince l'ultima regola che corrisponde**. Un pattern comune e' mettere prima la regola jolly `"*"` e poi regole piu' specifiche. + +### Wildcard + +I pattern dei permessi usano un semplice matching con wildcard: + +- `*` corrisponde a zero o piu' caratteri qualsiasi +- `?` corrisponde esattamente a un carattere +- Tutti gli altri caratteri corrispondono letteralmente + +### Espansione della home directory + +Puoi usare `~` o `$HOME` all'inizio di un pattern per riferirti alla tua home directory. Questo e' particolarmente utile per le regole [`external_directory`](#external-directories). + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### Directory esterne + +Usa `external_directory` per consentire chiamate a strumenti che toccano percorsi al di fuori della directory di lavoro da cui e' stato avviato OpenCode. Si applica a qualsiasi strumento che accetta un path come input (ad esempio `read`, `edit`, `list`, `glob`, `grep` e molti comandi `bash`). + +L'espansione della home (come `~/...`) influisce solo su come viene scritto un pattern. Non rende un percorso esterno parte della workspace corrente, quindi i path fuori dalla directory di lavoro devono comunque essere consentiti tramite `external_directory`. + +Per esempio, questo consente l'accesso a tutto sotto `~/projects/personal/`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +Qualsiasi directory consentita qui eredita gli stessi default della workspace corrente. Dato che [`read` di default e' `allow`](#defaults), anche le letture sono consentite per le voci sotto `external_directory` a meno di sovrascritture. Aggiungi regole esplicite quando uno strumento deve essere limitato su questi path, ad esempio bloccando le modifiche ma lasciando consentite le letture: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +Mantieni l'elenco limitato a percorsi fidati e aggiungi regole extra di allow/deny quando serve per altri strumenti (ad esempio `bash`). + +--- + +## Permessi disponibili + +I permessi di OpenCode sono indicizzati per nome dello strumento, piu' un paio di guardrail di sicurezza: + +- `read` — lettura di un file (corrisponde al percorso del file) +- `edit` — tutte le modifiche ai file (include `edit`, `write`, `patch`, `multiedit`) +- `glob` — ricerca file tramite glob (corrisponde al pattern glob) +- `grep` — ricerca nel contenuto (corrisponde al pattern regex) +- `list` — elenco file in una directory (corrisponde al path della directory) +- `bash` — esecuzione comandi di shell (corrisponde a comandi parsati come `git status --porcelain`) +- `task` — avvio subagenti (corrisponde al tipo di subagente) +- `skill` — caricamento di una skill (corrisponde al nome della skill) +- `lsp` — esecuzione query LSP (attualmente non granulare) +- `todoread`, `todowrite` — lettura/aggiornamento della todo list +- `webfetch` — fetch di un URL (corrisponde all'URL) +- `websearch`, `codesearch` — ricerca web/codice (corrisponde alla query) +- `external_directory` — si attiva quando uno strumento tocca percorsi fuori dalla working directory del progetto +- `doom_loop` — si attiva quando la stessa chiamata a uno strumento si ripete 3 volte con input identico + +--- + +## Default + +Se non specifichi nulla, OpenCode parte da default permissivi: + +- La maggior parte dei permessi di default e' `"allow"`. +- `doom_loop` ed `external_directory` di default sono `"ask"`. +- `read` e' `"allow"`, ma i file `.env` sono negati di default: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## Cosa fa "Ask" + +Quando OpenCode chiede approvazione, la UI offre tre esiti: + +- `once` — approva solo questa richiesta +- `always` — approva richieste future che corrispondono ai pattern suggeriti (per il resto della sessione corrente di OpenCode) +- `reject` — nega la richiesta + +L'insieme di pattern che `always` approverebbe e' fornito dallo strumento (ad esempio, le approvazioni per bash in genere mettono in whitelist un prefisso di comando sicuro come `git status*`). + +--- + +## Agenti + +Puoi sovrascrivere i permessi per agente. I permessi dell'agente vengono uniti alla configurazione globale e le regole dell'agente hanno precedenza. [Scopri di piu'](/docs/agents#permissions) sui permessi degli agenti. + +:::note +Fai riferimento alla sezione [Regole granulari (sintassi a oggetto)](#granular-rules-object-syntax) per esempi piu' dettagliati di pattern matching. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +Puoi anche configurare i permessi dell'agente in Markdown: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tip +Usa il pattern matching per comandi con argomenti. `"grep *"` consente `grep pattern file.txt`, mentre `"grep"` da solo lo bloccherebbe. Comandi come `git status` funzionano per il comportamento di default ma richiedono un permesso esplicito (come `"git status *"`) quando vengono passati argomenti. +::: diff --git a/packages/web/src/content/docs/it/plugins.mdx b/packages/web/src/content/docs/it/plugins.mdx new file mode 100644 index 000000000..eba231865 --- /dev/null +++ b/packages/web/src/content/docs/it/plugins.mdx @@ -0,0 +1,384 @@ +--- +title: Plugin +description: Scrivi plugin per estendere OpenCode. +--- + +I plugin ti permettono di estendere OpenCode agganciandoti a vari eventi e personalizzando il comportamento. Puoi creare plugin per aggiungere nuove funzionalita', integrare servizi esterni o modificare il comportamento predefinito di OpenCode. + +Per esempi, dai un'occhiata ai [plugin](/docs/ecosystem#plugins) creati dalla community. + +--- + +## Usare un plugin + +Ci sono due modi per caricare i plugin. + +--- + +### Da file locali + +Metti file JavaScript o TypeScript nella directory dei plugin. + +- `.opencode/plugins/` - plugin a livello progetto +- `~/.config/opencode/plugins/` - plugin globali + +I file in queste directory vengono caricati automaticamente all'avvio. + +--- + +### Da npm + +Specifica i pacchetti npm nel tuo file di configurazione. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +Sono supportati sia pacchetti npm normali sia scoped. + +Sfoglia i plugin disponibili nell'[ecosistema](/docs/ecosystem#plugins). + +--- + +### Come vengono installati i plugin + +I **plugin npm** vengono installati automaticamente usando Bun all'avvio. I pacchetti e le loro dipendenze vengono cache-ati in `~/.cache/opencode/node_modules/`. + +I **plugin locali** vengono caricati direttamente dalla directory dei plugin. Per usare pacchetti esterni, devi creare un `package.json` nella directory di configurazione (vedi [Dipendenze](#dependencies)) oppure pubblicare il plugin su npm e [aggiungerlo alla configurazione](/docs/config#plugins). + +--- + +### Ordine di caricamento + +I plugin vengono caricati da tutte le sorgenti e tutti gli hook vengono eseguiti in sequenza. L'ordine di caricamento e': + +1. Config globale (`~/.config/opencode/opencode.json`) +2. Config di progetto (`opencode.json`) +3. Directory plugin globale (`~/.config/opencode/plugins/`) +4. Directory plugin di progetto (`.opencode/plugins/`) + +I pacchetti npm duplicati con lo stesso nome e versione vengono caricati una sola volta. Tuttavia, un plugin locale e un plugin npm con nomi simili vengono entrambi caricati separatamente. + +--- + +## Creare un plugin + +Un plugin e' un **modulo JavaScript/TypeScript** che esporta una o piu' funzioni di plugin. Ogni funzione riceve un oggetto di contesto e restituisce un oggetto di hook. + +--- + +### Dipendenze + +I plugin locali e gli strumenti personalizzati possono usare pacchetti npm esterni. Aggiungi un `package.json` alla tua directory di configurazione con le dipendenze di cui hai bisogno. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode esegue `bun install` all'avvio per installarle. I tuoi plugin e strumenti potranno poi importarle. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### Struttura base + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +La funzione del plugin riceve: + +- `project`: informazioni sul progetto corrente. +- `directory`: la working directory corrente. +- `worktree`: il path del worktree git. +- `client`: un client SDK di opencode per interagire con l'AI. +- `$`: la [shell API](https://bun.com/docs/runtime/shell) di Bun per eseguire comandi. + +--- + +### Supporto TypeScript + +Per i plugin TypeScript, puoi importare i tipi dal pacchetto plugin: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### Eventi + +I plugin possono sottoscrivere eventi come mostrato sotto nella sezione Esempi. Ecco l'elenco dei diversi eventi disponibili. + +#### Eventi dei comandi + +- `command.executed` + +#### Eventi dei file + +- `file.edited` +- `file.watcher.updated` + +#### Eventi di installazione + +- `installation.updated` + +#### Eventi LSP + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### Eventi dei messaggi + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### Eventi dei permessi + +- `permission.asked` +- `permission.replied` + +#### Eventi del server + +- `server.connected` + +#### Eventi delle sessioni + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### Eventi della todo + +- `todo.updated` + +#### Eventi della shell + +- `shell.env` + +#### Eventi degli strumenti + +- `tool.execute.after` +- `tool.execute.before` + +#### Eventi TUI + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## Esempi + +Ecco alcuni esempi di plugin che puoi usare per estendere opencode. + +--- + +### Invia notifiche + +Invia notifiche quando avvengono certi eventi: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +Stiamo usando `osascript` per eseguire AppleScript su macOS. Qui lo usiamo per inviare notifiche. + +:::note +Se usi l'app desktop di OpenCode, puo' inviare automaticamente notifiche di sistema quando una risposta e' pronta o quando una sessione va in errore. +::: + +--- + +### Protezione .env + +Impedisci a opencode di leggere i file `.env`: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### Inietta variabili d'ambiente + +Inietta variabili d'ambiente in tutte le esecuzioni di shell (strumenti AI e terminali utente): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### Strumenti personalizzati + +I plugin possono anche aggiungere strumenti personalizzati a opencode: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +L'helper `tool` crea uno strumento personalizzato che opencode puo' chiamare. Accetta una funzione di schema Zod e restituisce una definizione di tool con: + +- `description`: cosa fa lo strumento +- `args`: schema Zod per gli argomenti dello strumento +- `execute`: funzione eseguita quando lo strumento viene chiamato + +I tuoi strumenti personalizzati saranno disponibili in opencode insieme agli strumenti integrati. + +--- + +### Logging + +Usa `client.app.log()` invece di `console.log` per logging strutturato: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +Livelli: `debug`, `info`, `warn`, `error`. Vedi la [documentazione SDK](https://opencode.ai/docs/sdk) per i dettagli. + +--- + +### Hook di compaction + +Personalizza il contesto incluso quando una sessione viene compattata: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +L'hook `experimental.session.compacting` scatta prima che l'LLM generi un riassunto di continuazione. Usalo per iniettare contesto specifico di dominio che il prompt di compaction predefinito potrebbe non includere. + +Puoi anche sostituire completamente il prompt di compaction impostando `output.prompt`: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +Quando `output.prompt` e' impostato, sostituisce completamente il prompt di compaction predefinito. In questo caso l'array `output.context` viene ignorato. diff --git a/packages/web/src/content/docs/it/providers.mdx b/packages/web/src/content/docs/it/providers.mdx new file mode 100644 index 000000000..dc032d0df --- /dev/null +++ b/packages/web/src/content/docs/it/providers.mdx @@ -0,0 +1,1888 @@ +--- +title: Providers +description: Usa qualsiasi provider LLM in OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode usa [AI SDK](https://ai-sdk.dev/) e [Models.dev](https://models.dev) per supportare **oltre 75 provider LLM** e anche modelli locali. + +Per aggiungere un provider devi: + +1. Aggiungere le API key del provider con il comando `/connect`. +2. Configurare il provider nella configurazione di OpenCode. + +--- + +### Credenziali + +Quando aggiungi le API key di un provider con `/connect`, vengono salvate +in `~/.local/share/opencode/auth.json`. + +--- + +### Configurazione + +Puoi personalizzare i provider tramite la sezione `provider` nella +configurazione di OpenCode. + +--- + +#### URL base + +Puoi personalizzare l'URL base per qualsiasi provider impostando l'opzione `baseURL`. E utile quando usi servizi proxy o endpoint personalizzati. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen e una lista di modelli forniti dal team OpenCode, testati e +verificati per funzionare bene con OpenCode. [Scopri di piu](/docs/zen). + +:::tip +Se sei all'inizio, ti consigliamo di partire da OpenCode Zen. +::: + +1. Esegui `/connect` nella TUI, seleziona opencode e vai su [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Accedi, aggiungi i dati di fatturazione e copia la tua API key. + +3. Incolla la tua API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Esegui `/models` nella TUI per vedere la lista di modelli consigliati. + + ```txt + /models + ``` + +Funziona come qualsiasi altro provider in OpenCode ed e totalmente opzionale. + +--- + +## Elenco + +Vediamo alcuni provider nel dettaglio. Se vuoi aggiungerne uno +all'elenco, apri pure una PR. + +:::note +Non vedi un provider qui? Invia una PR. +::: + +--- + +### 302.AI + +1. Head over to the [302.AI console](https://302.ai/), create an account, and generate an API key. + +2. Run the `/connect` command and search for **302.AI**. + + ```txt + /connect + ``` + +3. Enter your 302.AI API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model. + + ```txt + /models + ``` + +--- + +### Amazon Bedrock + +To use Amazon Bedrock with OpenCode: + +1. Head over to the **Model catalog** in the Amazon Bedrock console and request + access to the models you want. + + :::tip + You need to have access to the model you want in Amazon Bedrock. + ::: + +2. **Configure authentication** using one of the following methods: + + #### Environment Variables (Quick Start) + + Set one of these environment variables while running opencode: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + Or add them to your bash profile: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### Configuration File (Recommended) + + For project-specific or persistent configuration, use `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **Available options:** + - `region` - AWS region (e.g., `us-east-1`, `eu-west-1`) + - `profile` - AWS named profile from `~/.aws/credentials` + - `endpoint` - Custom endpoint URL for VPC endpoints (alias for generic `baseURL` option) + + :::tip + Configuration file options take precedence over environment variables. + ::: + + #### Advanced: VPC Endpoints + + If you're using VPC endpoints for Bedrock: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::note + The `endpoint` option is an alias for the generic `baseURL` option, using AWS-specific terminology. If both `endpoint` and `baseURL` are specified, `endpoint` takes precedence. + ::: + + #### Authentication Methods + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: Create an IAM user and generate access keys in the AWS Console + - **`AWS_PROFILE`**: Use named profiles from `~/.aws/credentials`. First configure with `aws configure --profile my-profile` or `aws sso login` + - **`AWS_BEARER_TOKEN_BEDROCK`**: Generate long-term API keys from the Amazon Bedrock console + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: For EKS IRSA (IAM Roles for Service Accounts) or other Kubernetes environments with OIDC federation. These environment variables are automatically injected by Kubernetes when using service account annotations. + + #### Authentication Precedence + + Amazon Bedrock uses the following authentication priority: + 1. **Bearer Token** - `AWS_BEARER_TOKEN_BEDROCK` environment variable or token from `/connect` command + 2. **AWS Credential Chain** - Profile, access keys, shared credentials, IAM roles, Web Identity Tokens (EKS IRSA), instance metadata + + :::note + When a bearer token is set (via `/connect` or `AWS_BEARER_TOKEN_BEDROCK`), it takes precedence over all AWS credential methods including configured profiles. + ::: + +3. Run the `/models` command to select the model you want. + + ```txt + /models + ``` + +:::note +For custom inference profiles, use the model and provider name in the key and set the `id` property to the arn. This ensures correct caching: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### Anthropic + +1. Once you've signed up, run the `/connect` command and select Anthropic. + + ```txt + /connect + ``` + +2. Here you can select the **Claude Pro/Max** option and it'll open your browser + and ask you to authenticate. + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. Now all the Anthropic models should be available when you use the `/models` command. + + ```txt + /models + ``` + +:::info +Using your Claude Pro/Max subscription in OpenCode is not officially supported by [Anthropic](https://anthropic.com). +::: + +##### Using API keys + +You can also select **Create an API Key** if you don't have a Pro/Max subscription. It'll also open your browser and ask you to login to Anthropic and give you a code you can paste in your terminal. + +Or if you already have an API key, you can select **Manually enter API Key** and paste it in your terminal. + +--- + +### Azure OpenAI + +:::note +If you encounter "I'm sorry, but I cannot assist with that request" errors, try changing the content filter from **DefaultV2** to **Default** in your Azure resource. +::: + +1. Head over to the [Azure portal](https://portal.azure.com/) and create an **Azure OpenAI** resource. You'll need: + - **Resource name**: This becomes part of your API endpoint (`https://RESOURCE_NAME.openai.azure.com/`) + - **API key**: Either `KEY 1` or `KEY 2` from your resource + +2. Go to [Azure AI Foundry](https://ai.azure.com/) and deploy a model. + + :::note + The deployment name must match the model name for opencode to work properly. + ::: + +3. Run the `/connect` command and search for **Azure**. + + ```txt + /connect + ``` + +4. Enter your API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Set your resource name as an environment variable: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + Or add it to your bash profile: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. Run the `/models` command to select your deployed model. + + ```txt + /models + ``` + +--- + +### Azure Cognitive Services + +1. Head over to the [Azure portal](https://portal.azure.com/) and create an **Azure OpenAI** resource. You'll need: + - **Resource name**: This becomes part of your API endpoint (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) + - **API key**: Either `KEY 1` or `KEY 2` from your resource + +2. Go to [Azure AI Foundry](https://ai.azure.com/) and deploy a model. + + :::note + The deployment name must match the model name for opencode to work properly. + ::: + +3. Run the `/connect` command and search for **Azure Cognitive Services**. + + ```txt + /connect + ``` + +4. Enter your API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Set your resource name as an environment variable: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + Or add it to your bash profile: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. Run the `/models` command to select your deployed model. + + ```txt + /models + ``` + +--- + +### Baseten + +1. Head over to the [Baseten](https://app.baseten.co/), create an account, and generate an API key. + +2. Run the `/connect` command and search for **Baseten**. + + ```txt + /connect + ``` + +3. Enter your Baseten API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model. + + ```txt + /models + ``` + +--- + +### Cerebras + +1. Head over to the [Cerebras console](https://inference.cerebras.ai/), create an account, and generate an API key. + +2. Run the `/connect` command and search for **Cerebras**. + + ```txt + /connect + ``` + +3. Enter your Cerebras API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### Cloudflare AI Gateway + +Cloudflare AI Gateway lets you access models from OpenAI, Anthropic, Workers AI, and more through a unified endpoint. With [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) you don't need separate API keys for each provider. + +1. Head over to the [Cloudflare dashboard](https://dash.cloudflare.com/), navigate to **AI** > **AI Gateway**, and create a new gateway. + +2. Set your Account ID and Gateway ID as environment variables. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. Run the `/connect` command and search for **Cloudflare AI Gateway**. + + ```txt + /connect + ``` + +4. Enter your Cloudflare API token. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + Or set it as an environment variable. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. Run the `/models` command to select a model. + + ```txt + /models + ``` + + You can also add models through your opencode config. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### Cortecs + +1. Head over to the [Cortecs console](https://cortecs.ai/), create an account, and generate an API key. + +2. Run the `/connect` command and search for **Cortecs**. + + ```txt + /connect + ``` + +3. Enter your Cortecs API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### DeepSeek + +1. Head over to the [DeepSeek console](https://platform.deepseek.com/), create an account, and click **Create new API key**. + +2. Run the `/connect` command and search for **DeepSeek**. + + ```txt + /connect + ``` + +3. Enter your DeepSeek API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a DeepSeek model like _DeepSeek Reasoner_. + + ```txt + /models + ``` + +--- + +### Deep Infra + +1. Head over to the [Deep Infra dashboard](https://deepinfra.com/dash), create an account, and generate an API key. + +2. Run the `/connect` command and search for **Deep Infra**. + + ```txt + /connect + ``` + +3. Enter your Deep Infra API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model. + + ```txt + /models + ``` + +--- + +### Firmware + +1. Head over to the [Firmware dashboard](https://app.firmware.ai/signup), create an account, and generate an API key. + +2. Run the `/connect` command and search for **Firmware**. + + ```txt + /connect + ``` + +3. Enter your Firmware API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model. + + ```txt + /models + ``` + +--- + +### Fireworks AI + +1. Head over to the [Fireworks AI console](https://app.fireworks.ai/), create an account, and click **Create API Key**. + +2. Run the `/connect` command and search for **Fireworks AI**. + + ```txt + /connect + ``` + +3. Enter your Fireworks AI API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### GitLab Duo + +GitLab Duo provides AI-powered agentic chat with native tool calling capabilities through GitLab's Anthropic proxy. + +1. Run the `/connect` command and select GitLab. + + ```txt + /connect + ``` + +2. Choose your authentication method: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### Using OAuth (Recommended) + + Select **OAuth** and your browser will open for authorization. + + #### Using Personal Access Token + 1. Go to [GitLab User Settings > Access Tokens](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. Click **Add new token** + 3. Name: `OpenCode`, Scopes: `api` + 4. Copy the token (starts with `glpat-`) + 5. Enter it in the terminal + +3. Run the `/models` command to see available models. + + ```txt + /models + ``` + + Three Claude-based models are available: + - **duo-chat-haiku-4-5** (Default) - Fast responses for quick tasks + - **duo-chat-sonnet-4-5** - Balanced performance for most workflows + - **duo-chat-opus-4-5** - Most capable for complex analysis + +:::note +You can also specify 'GITLAB_TOKEN' environment variable if you don't want +to store token in opencode auth storage. +::: + +##### Self-Hosted GitLab + +:::note[compliance note] +OpenCode uses a small model for some AI tasks like generating the session title. +It is configured to use gpt-5-nano by default, hosted by Zen. To lock OpenCode +to only use your own GitLab-hosted instance, add the following to your +`opencode.json` file. It is also recommended to disable session sharing. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +For self-hosted GitLab instances: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +If your instance runs a custom AI Gateway: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +Or add to your bash profile: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +Your GitLab administrator must enable the following: + +1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) for the user, group, or instance +2. Feature flags (via Rails console): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### OAuth for Self-Hosted instances + +In order to make Oauth working for your self-hosted instance, you need to create +a new application (Settings → Applications) with the +callback URL `http://127.0.0.1:8080/callback` and following scopes: + +- api (Access the API on your behalf) +- read_user (Read your personal information) +- read_repository (Allows read-only access to the repository) + +Then expose application ID as environment variable: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +More documentation on [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth) homepage. + +##### Configuration + +Customize through `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API Tools (Optional, but highly recommended) + +To access GitLab tools (merge requests, issues, pipelines, CI/CD, etc.): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +Questo plugin offre funzionalita complete per la gestione dei repository GitLab, incluse revisioni delle MR, tracciamento dei problemi, monitoraggio delle pipeline e altro. + +--- + +### GitHub Copilot + +To use your GitHub Copilot subscription with opencode: + +:::note +Alcuni modelli potrebbero richiedere un [abbonamento Pro+](https://github.com/features/copilot/plans) per essere utilizzati. + +Some models need to be manually enabled in your [GitHub Copilot settings](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. Run the `/connect` command and search for GitHub Copilot. + + ```txt + /connect + ``` + +2. Navigate to [github.com/login/device](https://github.com/login/device) and enter the code. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. Now run the `/models` command to select the model you want. + + ```txt + /models + ``` + +--- + +### Google Vertex AI + +To use Google Vertex AI with OpenCode: + +1. Head over to the **Model Garden** in the Google Cloud Console and check the + models available in your region. + + :::note + You need to have a Google Cloud project with Vertex AI API enabled. + ::: + +2. Set the required environment variables: + - `GOOGLE_CLOUD_PROJECT`: Your Google Cloud project ID + - `VERTEX_LOCATION` (optional): The region for Vertex AI (defaults to `global`) + - Authentication (choose one): + - `GOOGLE_APPLICATION_CREDENTIALS`: Path to your service account JSON key file + - Authenticate using gcloud CLI: `gcloud auth application-default login` + + Set them while running opencode. + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + Or add them to your bash profile. + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::tip +The `global` region improves availability and reduces errors at no extra cost. Use regional endpoints (e.g., `us-central1`) for data residency requirements. [Learn more](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. Run the `/models` command to select the model you want. + + ```txt + /models + ``` + +--- + +### Groq + +1. Head over to the [Groq console](https://console.groq.com/), click **Create API Key**, and copy the key. + +2. Run the `/connect` command and search for Groq. + + ```txt + /connect + ``` + +3. Enter the API key for the provider. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select the one you want. + + ```txt + /models + ``` + +--- + +### Hugging Face + +[Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers) provides access to open models supported by 17+ providers. + +1. Head over to [Hugging Face settings](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) to create a token with permission to make calls to Inference Providers. + +2. Run the `/connect` command and search for **Hugging Face**. + + ```txt + /connect + ``` + +3. Enter your Hugging Face token. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _Kimi-K2-Instruct_ or _GLM-4.6_. + + ```txt + /models + ``` + +--- + +### Helicone + +[Helicone](https://helicone.ai) is an LLM observability platform that provides logging, monitoring, and analytics for your AI applications. The Helicone AI Gateway routes your requests to the appropriate provider automatically based on the model. + +1. Head over to [Helicone](https://helicone.ai), create an account, and generate an API key from your dashboard. + +2. Run the `/connect` command and search for **Helicone**. + + ```txt + /connect + ``` + +3. Enter your Helicone API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model. + + ```txt + /models + ``` + +For more providers and advanced features like caching and rate limiting, check the [Helicone documentation](https://docs.helicone.ai). + +#### Optional Configs + +In the event you see a feature or model from Helicone that isn't configured automatically through opencode, you can always configure it yourself. + +Here's [Helicone's Model Directory](https://helicone.ai/models), you'll need this to grab the IDs of the models you want to add. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### Custom Headers + +Helicone supports custom headers for features like caching, user tracking, and session management. Add them to your provider config using `options.headers`: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### Session tracking + +Helicone's [Sessions](https://docs.helicone.ai/features/sessions) feature lets you group related LLM requests together. Use the [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) plugin to automatically log each OpenCode conversation as a session in Helicone. + +```bash +npm install -g opencode-helicone-session +``` + +Add it to your config. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +The plugin injects `Helicone-Session-Id` and `Helicone-Session-Name` headers into your requests. In Helicone's Sessions page, you'll see each OpenCode conversation listed as a separate session. + +##### Common Helicone headers + +| Header | Description | +| -------------------------- | ------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | Enable response caching (`true`/`false`) | +| `Helicone-User-Id` | Track metrics by user | +| `Helicone-Property-[Name]` | Add custom properties (e.g., `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | Associate requests with prompt versions | + +See the [Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory) for all available headers. + +--- + +### llama.cpp + +You can configure opencode to use local models through [llama.cpp's](https://github.com/ggml-org/llama.cpp) llama-server utility + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +In this example: + +- `llama.cpp` is the custom provider ID. This can be any string you want. +- `npm` specifies the package to use for this provider. Here, `@ai-sdk/openai-compatible` is used for any OpenAI-compatible API. +- `name` is the display name for the provider in the UI. +- `options.baseURL` is the endpoint for the local server. +- `models` is a map of model IDs to their configurations. The model name will be displayed in the model selection list. + +--- + +### IO.NET + +IO.NET offers 17 models optimized for various use cases: + +1. Head over to the [IO.NET console](https://ai.io.net/), create an account, and generate an API key. + +2. Run the `/connect` command and search for **IO.NET**. + + ```txt + /connect + ``` + +3. Enter your IO.NET API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model. + + ```txt + /models + ``` + +--- + +### LM Studio + +You can configure opencode to use local models through LM Studio. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +In this example: + +- `lmstudio` is the custom provider ID. This can be any string you want. +- `npm` specifies the package to use for this provider. Here, `@ai-sdk/openai-compatible` is used for any OpenAI-compatible API. +- `name` is the display name for the provider in the UI. +- `options.baseURL` is the endpoint for the local server. +- `models` is a map of model IDs to their configurations. The model name will be displayed in the model selection list. + +--- + +### Moonshot AI + +To use Kimi K2 from Moonshot AI: + +1. Head over to the [Moonshot AI console](https://platform.moonshot.ai/console), create an account, and click **Create API key**. + +2. Run the `/connect` command and search for **Moonshot AI**. + + ```txt + /connect + ``` + +3. Enter your Moonshot API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select _Kimi K2_. + + ```txt + /models + ``` + +--- + +### MiniMax + +1. Head over to the [MiniMax API Console](https://platform.minimax.io/login), create an account, and generate an API key. + +2. Run the `/connect` command and search for **MiniMax**. + + ```txt + /connect + ``` + +3. Enter your MiniMax API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _M2.1_. + + ```txt + /models + ``` + +--- + +### Nebius Token Factory + +1. Head over to the [Nebius Token Factory console](https://tokenfactory.nebius.com/), create an account, and click **Add Key**. + +2. Run the `/connect` command and search for **Nebius Token Factory**. + + ```txt + /connect + ``` + +3. Enter your Nebius Token Factory API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Ollama + +You can configure opencode to use local models through Ollama. + +:::tip +Ollama can automatically configure itself for OpenCode. See the [Ollama integration docs](https://docs.ollama.com/integrations/opencode) for details. +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +In this example: + +- `ollama` is the custom provider ID. This can be any string you want. +- `npm` specifies the package to use for this provider. Here, `@ai-sdk/openai-compatible` is used for any OpenAI-compatible API. +- `name` is the display name for the provider in the UI. +- `options.baseURL` is the endpoint for the local server. +- `models` is a map of model IDs to their configurations. The model name will be displayed in the model selection list. + +:::tip +If tool calls aren't working, try increasing `num_ctx` in Ollama. Start around 16k - 32k. +::: + +--- + +### Ollama Cloud + +To use Ollama Cloud with OpenCode: + +1. Head over to [https://ollama.com/](https://ollama.com/) and sign in or create an account. + +2. Navigate to **Settings** > **Keys** and click **Add API Key** to generate a new API key. + +3. Copy the API key for use in OpenCode. + +4. Run the `/connect` command and search for **Ollama Cloud**. + + ```txt + /connect + ``` + +5. Enter your Ollama Cloud API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **Important**: Before using cloud models in OpenCode, you must pull the model information locally: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. Run the `/models` command to select your Ollama Cloud model. + + ```txt + /models + ``` + +--- + +### OpenAI + +We recommend signing up for [ChatGPT Plus or Pro](https://chatgpt.com/pricing). + +1. Once you've signed up, run the `/connect` command and select OpenAI. + + ```txt + /connect + ``` + +2. Here you can select the **ChatGPT Plus/Pro** option and it'll open your browser + and ask you to authenticate. + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. Now all the OpenAI models should be available when you use the `/models` command. + + ```txt + /models + ``` + +##### Using API keys + +If you already have an API key, you can select **Manually enter API Key** and paste it in your terminal. + +--- + +### OpenCode Zen + +OpenCode Zen is a list of tested and verified models provided by the OpenCode team. [Learn more](/docs/zen). + +1. Sign in to **OpenCode Zen** and click **Create API Key**. + +2. Run the `/connect` command and search for **OpenCode Zen**. + + ```txt + /connect + ``` + +3. Enter your OpenCode API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### OpenRouter + +1. Head over to the [OpenRouter dashboard](https://openrouter.ai/settings/keys), click **Create API Key**, and copy the key. + +2. Run the `/connect` command and search for OpenRouter. + + ```txt + /connect + ``` + +3. Enter the API key for the provider. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Many OpenRouter models are preloaded by default, run the `/models` command to select the one you want. + + ```txt + /models + ``` + + You can also add additional models through your opencode config. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. You can also customize them through your opencode config. Here's an example of specifying a provider + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP AI Core + +SAP AI Core provides access to 40+ models from OpenAI, Anthropic, Google, Amazon, Meta, Mistral, and AI21 through a unified platform. + +1. Go to your [SAP BTP Cockpit](https://account.hana.ondemand.com/), navigate to your SAP AI Core service instance, and create a service key. + + :::tip + The service key is a JSON object containing `clientid`, `clientsecret`, `url`, and `serviceurls.AI_API_URL`. You can find your AI Core instance under **Services** > **Instances and Subscriptions** in the BTP Cockpit. + ::: + +2. Run the `/connect` command and search for **SAP AI Core**. + + ```txt + /connect + ``` + +3. Enter your service key JSON. + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + Or set the `AICORE_SERVICE_KEY` environment variable: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + Or add it to your bash profile: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. Optionally set deployment ID and resource group: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::note + These settings are optional and should be configured according to your SAP AI Core setup. + ::: + +5. Run the `/models` command to select from 40+ available models. + + ```txt + /models + ``` + +--- + +### OVHcloud AI Endpoints + +1. Head over to the [OVHcloud panel](https://ovh.com/manager). Navigate to the `Public Cloud` section, `AI & Machine Learning` > `AI Endpoints` and in `API Keys` tab, click **Create a new API key**. + +2. Run the `/connect` command and search for **OVHcloud AI Endpoints**. + + ```txt + /connect + ``` + +3. Enter your OVHcloud AI Endpoints API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Scaleway + +To use [Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/) with Opencode: + +1. Head over to the [Scaleway Console IAM settings](https://console.scaleway.com/iam/api-keys) to generate a new API key. + +2. Run the `/connect` command and search for **Scaleway**. + + ```txt + /connect + ``` + +3. Enter your Scaleway API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _devstral-2-123b-instruct-2512_ or _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Together AI + +1. Head over to the [Together AI console](https://api.together.ai), create an account, and click **Add Key**. + +2. Run the `/connect` command and search for **Together AI**. + + ```txt + /connect + ``` + +3. Enter your Together AI API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Venice AI + +1. Head over to the [Venice AI console](https://venice.ai), create an account, and generate an API key. + +2. Run the `/connect` command and search for **Venice AI**. + + ```txt + /connect + ``` + +3. Enter your Venice AI API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _Llama 3.3 70B_. + + ```txt + /models + ``` + +--- + +### Vercel AI Gateway + +Vercel AI Gateway lets you access models from OpenAI, Anthropic, Google, xAI, and more through a unified endpoint. Models are offered at list price with no markup. + +1. Head over to the [Vercel dashboard](https://vercel.com/), navigate to the **AI Gateway** tab, and click **API keys** to create a new API key. + +2. Run the `/connect` command and search for **Vercel AI Gateway**. + + ```txt + /connect + ``` + +3. Enter your Vercel AI Gateway API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model. + + ```txt + /models + ``` + +You can also customize models through your opencode config. Here's an example of specifying provider routing order. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +Some useful routing options: + +| Option | Description | +| ------------------- | ---------------------------------------------------- | +| `order` | Provider sequence to try | +| `only` | Restrict to specific providers | +| `zeroDataRetention` | Only use providers with zero data retention policies | + +--- + +### xAI + +1. Head over to the [xAI console](https://console.x.ai/), create an account, and generate an API key. + +2. Run the `/connect` command and search for **xAI**. + + ```txt + /connect + ``` + +3. Enter your xAI API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _Grok Beta_. + + ```txt + /models + ``` + +--- + +### Z.AI + +1. Head over to the [Z.AI API console](https://z.ai/manage-apikey/apikey-list), create an account, and click **Create a new API key**. + +2. Run the `/connect` command and search for **Z.AI**. + + ```txt + /connect + ``` + + If you are subscribed to the **GLM Coding Plan**, select **Z.AI Coding Plan**. + +3. Enter your Z.AI API key. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Run the `/models` command to select a model like _GLM-4.7_. + + ```txt + /models + ``` + +--- + +### ZenMux + +1. Head over to the [ZenMux dashboard](https://zenmux.ai/settings/keys), click **Create API Key**, and copy the key. + +2. Run the `/connect` command and search for ZenMux. + + ```txt + /connect + ``` + +3. Enter the API key for the provider. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Many ZenMux models are preloaded by default, run the `/models` command to select the one you want. + + ```txt + /models + ``` + + You can also add additional models through your opencode config. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## Custom provider + +To add any **OpenAI-compatible** provider that's not listed in the `/connect` command: + +:::tip +You can use any OpenAI-compatible provider with opencode. Most modern AI providers offer OpenAI-compatible APIs. +::: + +1. Run the `/connect` command and scroll down to **Other**. + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. Enter a unique ID for the provider. + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note + Choose a memorable ID, you'll use this in your config file. + ::: + +3. Enter your API key for the provider. + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. Create or update your `opencode.json` file in your project directory: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + Here are the configuration options: + - **npm**: AI SDK package to use, `@ai-sdk/openai-compatible` for OpenAI-compatible providers + - **name**: Display name in UI. + - **models**: Available models. + - **options.baseURL**: API endpoint URL. + - **options.apiKey**: Optionally set the API key, if not using auth. + - **options.headers**: Optionally set custom headers. + + More on the advanced options in the example below. + +5. Run the `/models` command and your custom provider and models will appear in the selection list. + +--- + +##### Example + +Here's an example setting the `apiKey`, `headers`, and model `limit` options. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +Configuration details: + +- **apiKey**: Set using `env` variable syntax, [learn more](/docs/config#env-vars). +- **headers**: Custom headers sent with each request. +- **limit.context**: Maximum input tokens the model accepts. +- **limit.output**: Maximum tokens the model can generate. + +The `limit` fields allow OpenCode to understand how much context you have left. Standard providers pull these from models.dev automatically. + +--- + +## Troubleshooting + +If you are having trouble with configuring a provider, check the following: + +1. **Check the auth setup**: Run `opencode auth list` to see if the credentials + for the provider are added to your config. + + This doesn't apply to providers like Amazon Bedrock, that rely on environment variables for their auth. + +2. For custom providers, check the opencode config and: + - Make sure the provider ID used in the `/connect` command matches the ID in your opencode config. + - The right npm package is used for the provider. For example, use `@ai-sdk/cerebras` for Cerebras. And for all other OpenAI-compatible providers, use `@ai-sdk/openai-compatible`. + - Check correct API endpoint is used in the `options.baseURL` field. diff --git a/packages/web/src/content/docs/it/rules.mdx b/packages/web/src/content/docs/it/rules.mdx new file mode 100644 index 000000000..fba7d5873 --- /dev/null +++ b/packages/web/src/content/docs/it/rules.mdx @@ -0,0 +1,180 @@ +--- +title: Regole +description: Imposta istruzioni personalizzate per opencode. +--- + +Puoi fornire istruzioni personalizzate a opencode creando un file `AGENTS.md`. E' simile alle regole di Cursor. Contiene istruzioni che verranno incluse nel contesto dell'LLM per personalizzarne il comportamento per il tuo progetto. + +--- + +## Initialize + +Per creare un nuovo file `AGENTS.md`, puoi eseguire il comando `/init` in opencode. + +:::tip +Dovresti committare il file `AGENTS.md` del progetto in Git. +::: + +Questo scansiona il progetto e tutti i suoi contenuti per capire di cosa si tratta e generare un file `AGENTS.md`. Questo aiuta opencode a orientarsi meglio nel progetto. + +Se hai gia' un file `AGENTS.md` esistente, cerchera' di aggiungervi contenuti. + +--- + +## Example + +Puoi anche creare questo file manualmente. Ecco un esempio di alcune cose che puoi inserire in un file `AGENTS.md`. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +Qui stiamo aggiungendo istruzioni specifiche del progetto e saranno condivise con il tuo team. + +--- + +## Types + +opencode supporta anche la lettura del file `AGENTS.md` da piu' posizioni, e questo serve a scopi diversi. + +### Project + +Metti un `AGENTS.md` nella root del progetto per regole specifiche del progetto. Si applicano solo quando stai lavorando in questa directory o nelle sue sottodirectory. + +### Global + +Puoi anche avere regole globali in un file `~/.config/opencode/AGENTS.md`. Queste si applicano a tutte le sessioni di opencode. + +Dato che questo non viene committato in Git o condiviso con il team, consigliamo di usarlo per specificare regole personali che l'LLM deve seguire. + +### Claude Code Compatibility + +Per gli utenti che migrano da Claude Code, OpenCode supporta come fallback le convenzioni di file di Claude Code: + +- **Project rules**: `CLAUDE.md` in your project directory (used if no `AGENTS.md` exists) +- **Global rules**: `~/.claude/CLAUDE.md` (used if no `~/.config/opencode/AGENTS.md` exists) +- **Skills**: `~/.claude/skills/` — see [Agent Skills](/docs/skills/) for details + +Per disabilitare la compatibilita' con Claude Code, imposta una di queste variabili d'ambiente: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## Precedence + +Quando opencode si avvia, cerca i file di regole in questo ordine: + +1. **Local files** by traversing up from the current directory (`AGENTS.md`, `CLAUDE.md`) +2. **Global file** at `~/.config/opencode/AGENTS.md` +3. **Claude Code file** at `~/.claude/CLAUDE.md` (unless disabled) + +In ogni categoria vince il primo file corrispondente. Per esempio, se hai sia `AGENTS.md` sia `CLAUDE.md`, viene usato solo `AGENTS.md`. Allo stesso modo, `~/.config/opencode/AGENTS.md` ha priorita' su `~/.claude/CLAUDE.md`. + +--- + +## Custom Instructions + +Puoi specificare file di istruzioni personalizzati nel tuo `opencode.json` o nel globale `~/.config/opencode/opencode.json`. Questo permette a te e al tuo team di riusare regole esistenti invece di doverle duplicare in AGENTS.md. + +Example: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +You can also use remote URLs to load instructions from the web. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +Le istruzioni remote vengono recuperate con un timeout di 5 secondi. + +Tutti i file di istruzioni vengono combinati con i tuoi file `AGENTS.md`. + +--- + +## Referencing External Files + +Anche se opencode non interpreta automaticamente i riferimenti a file in `AGENTS.md`, puoi ottenere una funzionalita' simile in due modi: + +### Using opencode.json + +L'approccio consigliato e' usare il campo `instructions` in `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Manual Instructions in AGENTS.md + +Puoi insegnare a opencode a leggere file esterni fornendo istruzioni esplicite nel tuo `AGENTS.md`. Ecco un esempio pratico: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +Questo approccio ti permette di: + +- Create modular, reusable rule files +- Share rules across projects via symlinks or git submodules +- Keep AGENTS.md concise while referencing detailed guidelines +- Ensure opencode loads files only when needed for the specific task + +:::tip +Per monorepo o progetti con standard condivisi, usare `opencode.json` con pattern glob (come `packages/*/AGENTS.md`) e' piu' manutenibile rispetto alle istruzioni manuali. +::: diff --git a/packages/web/src/content/docs/it/sdk.mdx b/packages/web/src/content/docs/it/sdk.mdx new file mode 100644 index 000000000..9d8ab006f --- /dev/null +++ b/packages/web/src/content/docs/it/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: Client JS type-safe per il server opencode. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +L'SDK JS/TS di opencode fornisce un client type-safe per interagire con il server. +Usalo per creare integrazioni e controllare opencode in modo programmatico. + +[Scopri di piu](/docs/server) su come funziona il server. Per esempi, guarda i [progetti](/docs/ecosystem#projects) creati dalla comunita. + +--- + +## Installa + +Installa l'SDK da npm: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## Crea un client + +Crea un'istanza di opencode: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +Questo avvia sia un server sia un client + +#### Opzioni + +| Opzione | Tipo | Descrizione | Predefinito | +| ---------- | ------------- | ------------------------------ | ----------- | +| `hostname` | `string` | Hostname del server | `127.0.0.1` | +| `port` | `number` | Porta del server | `4096` | +| `signal` | `AbortSignal` | Segnale di abort per annullare | `undefined` | +| `timeout` | `number` | Timeout in ms per avvio server | `5000` | +| `config` | `Config` | Oggetto di configurazione | `{}` | + +--- + +## Configurazione + +Puoi passare un oggetto di configurazione per personalizzare il comportamento. L'istanza legge comunque `opencode.json`, ma puoi sovrascrivere o aggiungere configurazione inline: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## Solo client + +Se hai gia un'istanza di opencode in esecuzione, puoi creare un client per collegarti: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### Opzioni + +| Opzione | Tipo | Descrizione | Predefinito | +| --------------- | ---------- | ----------------------------------- | ----------------------- | +| `baseUrl` | `string` | URL del server | `http://localhost:4096` | +| `fetch` | `function` | Implementazione fetch custom | `globalThis.fetch` | +| `parseAs` | `string` | Metodo di parsing della risposta | `auto` | +| `responseStyle` | `string` | Stile di ritorno: `data` o `fields` | `fields` | +| `throwOnError` | `boolean` | Lancia errori invece di restituirli | `false` | + +--- + +## Tipi + +L'SDK include definizioni TypeScript per tutti i tipi API. Importale direttamente: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +Tutti i tipi sono generati dalla specifica OpenAPI del server e disponibili nel file dei tipi. + +--- + +## Errori + +L'SDK puo lanciare errori che puoi intercettare e gestire: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## API + +L'SDK espone tutte le API del server tramite un client type-safe. + +--- + +### Global + +| Metodo | Descrizione | Response | +| ----------------- | --------------------------------- | ------------------------------------ | +| `global.health()` | Controlla stato e versione server | `{ healthy: true, version: string }` | + +--- + +#### Esempi + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### App + +| Metodo | Descrizione | Response | +| -------------- | ----------------------- | ------------------------------------------- | +| `app.log()` | Scrive una voce di log | `boolean` | +| `app.agents()` | Elenca tutti gli agenti | Agent[] | + +--- + +#### Esempi + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### Project + +| Metodo | Descrizione | Response | +| ------------------- | ----------------- | --------------------------------------------- | +| `project.list()` | Elenca i progetti | Project[] | +| `project.current()` | Progetto corrente | Project | + +--- + +#### Esempi + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### Path + +| Metodo | Descrizione | Response | +| ------------ | ----------------- | ---------------------------------------- | +| `path.get()` | Percorso corrente | Path | + +--- + +#### Esempi + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### Config + +| Metodo | Descrizione | Response | +| -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` | Ottieni info config | Config | +| `config.providers()` | Elenca provider e modelli default | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +#### Esempi + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### Sessions + +| Metodo | Descrizione | Note | +| ---------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` | Elenca le sessioni | Returns Session[] | +| `session.get({ path })` | Ottieni una sessione | Returns Session | +| `session.children({ path })` | Elenca sessioni figlie | Returns Session[] | +| `session.create({ body })` | Crea una sessione | Returns Session | +| `session.delete({ path })` | Elimina una sessione | Returns `boolean` | +| `session.update({ path, body })` | Aggiorna proprieta della sessione | Returns Session | +| `session.init({ path, body })` | Analizza app e crea `AGENTS.md` | Returns `boolean` | +| `session.abort({ path })` | Interrompe una sessione in corso | Returns `boolean` | +| `session.share({ path })` | Condivide la sessione | Returns Session | +| `session.unshare({ path })` | Rimuove la condivisione | Returns Session | +| `session.summarize({ path, body })` | Riassume la sessione | Returns `boolean` | +| `session.messages({ path })` | Elenca i messaggi della sessione | Returns `{ info: `Message`, parts: `Part[]`}[]` | +| `session.message({ path })` | Ottieni dettagli di un messaggio | Returns `{ info: `Message`, parts: `Part[]`}` | +| `session.prompt({ path, body })` | Invia un prompt | `body.noReply: true` returns UserMessage (solo contesto). Di default ritorna AssistantMessage con risposta AI | +| `session.command({ path, body })` | Invia un comando alla sessione | Returns `{ info: `AssistantMessage`, parts: `Part[]`}` | +| `session.shell({ path, body })` | Esegue un comando shell | Returns AssistantMessage | +| `session.revert({ path, body })` | Ripristina un messaggio | Returns Session | +| `session.unrevert({ path })` | Ripristina messaggi revertiti | Returns Session | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | Risponde a una richiesta permessi | Returns `boolean` | + +--- + +#### Esempi + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### File + +| Metodo | Descrizione | Response | +| ------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------- | +| `find.text({ query })` | Cerca testo nei file | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `find.files({ query })` | Trova file e directory per nome | `string[]` (paths) | +| `find.symbols({ query })` | Trova simboli nel workspace | Symbol[] | +| `file.read({ query })` | Legge un file | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | Stato dei file tracciati | File[] | + +`find.files` supporta alcuni campi query opzionali: + +- `type`: `"file"` or `"directory"` +- `directory`: sovrascrive la root del progetto per la ricerca +- `limit`: risultati massimi (1–200) + +--- + +#### Esempi + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +| Metodo | Descrizione | Response | +| ------------------------------ | -------------------------- | --------- | +| `tui.appendPrompt({ body })` | Aggiunge testo al prompt | `boolean` | +| `tui.openHelp()` | Apre la finestra help | `boolean` | +| `tui.openSessions()` | Apre il selettore sessioni | `boolean` | +| `tui.openThemes()` | Apre il selettore temi | `boolean` | +| `tui.openModels()` | Apre il selettore modelli | `boolean` | +| `tui.submitPrompt()` | Invia il prompt corrente | `boolean` | +| `tui.clearPrompt()` | Pulisce il prompt | `boolean` | +| `tui.executeCommand({ body })` | Esegue un comando | `boolean` | +| `tui.showToast({ body })` | Mostra una notifica toast | `boolean` | + +--- + +#### Esempi + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### Auth + +| Metodo | Descrizione | Response | +| ------------------- | ------------------------ | --------- | +| `auth.set({ ... })` | Imposta credenziali auth | `boolean` | + +--- + +#### Esempi + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### Eventi + +| Metodo | Descrizione | Response | +| ------------------- | ---------------------------- | ---------------------------- | +| `event.subscribe()` | Stream di server-sent events | Stream di server-sent events | + +--- + +#### Esempi + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/it/server.mdx b/packages/web/src/content/docs/it/server.mdx new file mode 100644 index 000000000..3422206cb --- /dev/null +++ b/packages/web/src/content/docs/it/server.mdx @@ -0,0 +1,284 @@ +--- +title: Server +description: Interagisci con il server opencode via HTTP. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Il comando `opencode serve` avvia un server HTTP headless che espone un endpoint OpenAPI utilizzabile da un client opencode. + +--- + +### Utilizzo + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### Opzioni + +| Flag | Descrizione | Predefinito | +| --------------- | --------------------------------------- | ---------------- | +| `--port` | Porta su cui ascoltare | `4096` | +| `--hostname` | Hostname su cui ascoltare | `127.0.0.1` | +| `--mdns` | Abilita la scoperta mDNS | `false` | +| `--mdns-domain` | Nome di dominio personalizzato mDNS | `opencode.local` | +| `--cors` | Origin browser aggiuntive da permettere | `[]` | + +`--cors` puo essere passato piu volte: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### Autenticazione + +Imposta `OPENCODE_SERVER_PASSWORD` per proteggere il server con HTTP basic auth. Lo username predefinito e `opencode`, oppure imposta `OPENCODE_SERVER_USERNAME` per sovrascriverlo. Questo vale sia per `opencode serve` sia per `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### Come funziona + +Quando esegui `opencode` avvia una TUI e un server. La TUI e il client che parla col server. Il server espone un endpoint con specifica OpenAPI 3.1. Questo endpoint viene anche usato per generare un [SDK](/docs/sdk). + +:::tip +Usa il server opencode per interagire con opencode in modo programmatico. +::: + +Questa architettura permette a opencode di supportare piu client e di essere usato in modo programmatico. + +Puoi eseguire `opencode serve` per avviare un server standalone. Se la TUI di opencode e gia in esecuzione, `opencode serve` avviera un nuovo server. + +--- + +#### Connettersi a un server esistente + +Quando avvii la TUI assegna casualmente porta e hostname. In alternativa puoi passare i [flag](/docs/cli) `--hostname` e `--port` e poi usare questi valori per connetterti al suo server. + +L'endpoint [`/tui`](#tui) puo essere usato per pilotare la TUI tramite il server. Per esempio, puoi precompilare o eseguire un prompt. Questa configurazione e usata dai plugin [IDE](/docs/ide) di OpenCode. + +--- + +## Specifica + +Il server pubblica una specifica OpenAPI 3.1 visualizzabile su: + +``` +http://:/doc +``` + +Per esempio, `http://localhost:4096/doc`. Usa la spec per generare client o ispezionare i tipi di request/response, oppure visualizzala in uno Swagger explorer. + +--- + +## API + +Il server opencode espone le seguenti API. + +--- + +### Global + +| Metodo | Path | Descrizione | Response | +| ------ | ---------------- | --------------------------- | ------------------------------------ | +| `GET` | `/global/health` | Stato di salute e versione | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | Eventi globali (stream SSE) | Event stream | + +--- + +### Project + +| Metodo | Path | Descrizione | Response | +| ------ | ------------------ | ----------------------- | --------------------------------------------- | +| `GET` | `/project` | Elenca tutti i progetti | Project[] | +| `GET` | `/project/current` | Progetto corrente | Project | + +--- + +### Percorso e VCS + +| Metodo | Path | Descrizione | Response | +| ------ | ------- | --------------------------------- | ------------------------------------------- | +| `GET` | `/path` | Percorso corrente | Path | +| `GET` | `/vcs` | Info VCS per il progetto corrente | VcsInfo | + +--- + +### Instance + +| Metodo | Path | Descrizione | Response | +| ------ | ------------------- | --------------------------- | --------- | +| `POST` | `/instance/dispose` | Rilascia l'istanza corrente | `boolean` | + +--- + +### Configurazione + +| Metodo | Path | Descrizione | Response | +| ------- | ------------------- | --------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` | Info sulla config | Config | +| `PATCH` | `/config` | Aggiorna la config | Config | +| `GET` | `/config/providers` | Elenca provider e modelli default | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +### Provider + +| Metodo | Path | Descrizione | Response | +| ------ | -------------------------------- | ------------------------------- | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` | Elenca tutti i provider | `{ all: `Provider[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | Metodi auth dei provider | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | Autorizza un provider via OAuth | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | Gestisce callback OAuth | `boolean` | + +--- + +### Sessioni + +| Metodo | Path | Descrizione | Note | +| -------- | ---------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------- | +| `GET` | `/session` | Elenca tutte le sessioni | Returns Session[] | +| `POST` | `/session` | Crea una nuova sessione | body: `{ parentID?, title? }`, returns Session | +| `GET` | `/session/status` | Stato di tutte le sessioni | Returns `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | Dettagli di sessione | Returns Session | +| `DELETE` | `/session/:id` | Elimina una sessione e i suoi dati | Returns `boolean` | +| `PATCH` | `/session/:id` | Aggiorna proprieta sessione | body: `{ title? }`, returns Session | +| `GET` | `/session/:id/children` | Sessioni figlie | Returns Session[] | +| `GET` | `/session/:id/todo` | Todo list della sessione | Returns Todo[] | +| `POST` | `/session/:id/init` | Analizza app e crea `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returns `boolean` | +| `POST` | `/session/:id/fork` | Fork di sessione su un messaggio | body: `{ messageID? }`, returns Session | +| `POST` | `/session/:id/abort` | Interrompe una sessione in esecuzione | Returns `boolean` | +| `POST` | `/session/:id/share` | Condivide una sessione | Returns Session | +| `DELETE` | `/session/:id/share` | Annulla condivisione | Returns Session | +| `GET` | `/session/:id/diff` | Diff della sessione | query: `messageID?`, returns FileDiff[] | +| `POST` | `/session/:id/summarize` | Riassume la sessione | body: `{ providerID, modelID }`, returns `boolean` | +| `POST` | `/session/:id/revert` | Ripristina un messaggio | body: `{ messageID, partID? }`, returns `boolean` | +| `POST` | `/session/:id/unrevert` | Ripristina tutti i messaggi revertiti | Returns `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | Risponde a una richiesta permessi | body: `{ response, remember? }`, returns `boolean` | + +--- + +### Messaggi + +| Metodo | Path | Descrizione | Note | +| ------ | --------------------------------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` | Elenca messaggi in una sessione | query: `limit?`, returns `{ info: `Message`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` | Invia un messaggio e attende risposta | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, returns `{ info: `Message`, parts: `Part[]`}` | +| `GET` | `/session/:id/message/:messageID` | Dettagli messaggio | Returns `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/prompt_async` | Invia un messaggio in async (senza wait) | body: same as `/session/:id/message`, returns `204 No Content` | +| `POST` | `/session/:id/command` | Esegue un comando slash | body: `{ messageID?, agent?, model?, command, arguments }`, returns `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/shell` | Esegue un comando shell | body: `{ agent, model?, command }`, returns `{ info: `Message`, parts: `Part[]`}` | + +--- + +### Comandi + +| Metodo | Path | Descrizione | Response | +| ------ | ---------- | ---------------- | --------------------------------------------- | +| `GET` | `/command` | Elenca i comandi | Command[] | + +--- + +### File + +| Metodo | Path | Descrizione | Response | +| ------ | ------------------------ | ------------------------------- | ------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | Cerca testo nei file | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | Trova file e directory per nome | `string[]` (paths) | +| `GET` | `/find/symbol?query=` | Trova simboli workspace | Symbol[] | +| `GET` | `/file?path=` | Elenca file e directory | FileNode[] | +| `GET` | `/file/content?path=

` | Legge un file | FileContent | +| `GET` | `/file/status` | Stato dei file tracciati | File[] | + +#### `/find/file` query parameters + +- `query` (required) — stringa di ricerca (fuzzy match) +- `type` (optional) — limita i risultati a `"file"` o `"directory"` +- `directory` (optional) — sovrascrive la root del progetto per la ricerca +- `limit` (optional) — massimo risultati (1–200) +- `dirs` (optional) — flag legacy (`"false"` restituisce solo file) + +--- + +### Strumenti (sperimentale) + +| Metodo | Path | Descrizione | Response | +| ------ | ------------------------------------------- | ------------------------------------------ | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` | Elenca tutti i tool ID | ToolIDs | +| `GET` | `/experimental/tool?provider=

&model=` | Elenca tool con JSON schema per un modello | ToolList | + +--- + +### LSP, formatter e MCP + +| Metodo | Path | Descrizione | Response | +| ------ | ------------ | --------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | Stato server LSP | LSPStatus[] | +| `GET` | `/formatter` | Stato formatter | FormatterStatus[] | +| `GET` | `/mcp` | Stato server MCP | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | Aggiunge server MCP runtime | body: `{ name, config }`, returns MCP status object | + +--- + +### Agenti + +| Metodo | Path | Descrizione | Response | +| ------ | -------- | ----------------------- | ------------------------------------------- | +| `GET` | `/agent` | Elenca tutti gli agenti | Agent[] | + +--- + +### Log + +| Metodo | Path | Descrizione | Response | +| ------ | ------ | ------------------------------------------------------------------- | --------- | +| `POST` | `/log` | Scrive una voce di log. Body: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| Metodo | Path | Descrizione | Response | +| ------ | ----------------------- | -------------------------------------------------- | ---------------------- | +| `POST` | `/tui/append-prompt` | Aggiunge testo al prompt | `boolean` | +| `POST` | `/tui/open-help` | Apre il dialog help | `boolean` | +| `POST` | `/tui/open-sessions` | Apre il selettore sessioni | `boolean` | +| `POST` | `/tui/open-themes` | Apre il selettore temi | `boolean` | +| `POST` | `/tui/open-models` | Apre il selettore modelli | `boolean` | +| `POST` | `/tui/submit-prompt` | Invia il prompt corrente | `boolean` | +| `POST` | `/tui/clear-prompt` | Pulisce il prompt | `boolean` | +| `POST` | `/tui/execute-command` | Esegue un comando (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | Mostra toast (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | Attende la prossima richiesta di controllo | Control request object | +| `POST` | `/tui/control/response` | Risponde a una richiesta di controllo (`{ body }`) | `boolean` | + +--- + +### Autenticazione + +| Metodo | Path | Descrizione | Response | +| ------ | ----------- | -------------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | Imposta credenziali auth. Il body deve rispettare lo schema provider | `boolean` | + +--- + +### Eventi + +| Metodo | Path | Descrizione | Response | +| ------ | -------- | ----------------------------------------------------------- | ------------------------- | +| `GET` | `/event` | Stream SSE. Primo evento `server.connected`, poi eventi bus | Server-sent events stream | + +--- + +### Documentazione + +| Metodo | Path | Descrizione | Response | +| ------ | ------ | --------------------- | ---------------------------- | +| `GET` | `/doc` | Specifica OpenAPI 3.1 | Pagina HTML con spec OpenAPI | diff --git a/packages/web/src/content/docs/it/share.mdx b/packages/web/src/content/docs/it/share.mdx new file mode 100644 index 000000000..d78c8f982 --- /dev/null +++ b/packages/web/src/content/docs/it/share.mdx @@ -0,0 +1,127 @@ +--- +title: Condivisione +description: Condividi le tue conversazioni OpenCode. +--- + +La funzione di condivisione di OpenCode ti permette di creare link pubblici alle tue conversazioni, cosi puoi collaborare con i colleghi o chiedere aiuto ad altre persone. + +:::note +Le conversazioni condivise sono accessibili pubblicamente a chiunque abbia il link. +::: + +--- + +## Come funziona + +Quando condividi una conversazione, OpenCode: + +1. Crea un URL pubblico univoco per la sessione +2. Sincronizza la cronologia della conversazione sui nostri server +3. Rende la conversazione accessibile tramite il link condivisibile: `opncd.ai/s/` + +--- + +## Sharing + +OpenCode supporta tre modalita di condivisione che controllano come vengono condivise le conversazioni: + +--- + +### Manuale (predefinito) + +Per impostazione predefinita, OpenCode usa la condivisione manuale. Le sessioni non vengono condivise automaticamente, ma puoi condividerle manualmente con il comando `/share`: + +``` +/share +``` + +Questo genera un URL univoco che viene copiato negli appunti. + +Per impostare esplicitamente la modalita manuale nel tuo [file di config](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### Auto-share + +Puoi abilitare la condivisione automatica per tutte le nuove conversazioni impostando l'opzione `share` su `"auto"` nel tuo [file di config](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +Con la condivisione automatica attiva, ogni nuova conversazione verra condivisa automaticamente e verra generato un link. + +--- + +### Disabled + +Puoi disabilitare completamente la condivisione impostando l'opzione `share` su `"disabled"` nel tuo [file di config](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +Per applicarlo al tuo team in un progetto specifico, aggiungilo a `opencode.json` nel progetto e versionalo su Git. + +--- + +## Annullare la condivisione + +Per smettere di condividere una conversazione e rimuoverla dall'accesso pubblico: + +``` +/unshare +``` + +Questo rimuove il link di condivisione ed elimina i dati associati alla conversazione. + +--- + +## Privacy + +Ci sono alcune cose da tenere a mente quando condividi una conversazione. + +--- + +### Data retention + +Le conversazioni condivise restano accessibili finche non le annulli esplicitamente. Questo include: + +- La cronologia completa della conversazione +- Tutti i messaggi e le risposte +- I metadati della sessione + +--- + +### Recommendations + +- Condividi solo conversazioni che non contengono informazioni sensibili. +- Rivedi il contenuto della conversazione prima di condividerla. +- Annulla la condivisione quando la collaborazione e conclusa. +- Evita di condividere conversazioni con codice proprietario o dati riservati. +- Per progetti sensibili, disabilita completamente la condivisione. + +--- + +## Per le aziende + +Per deploy enterprise, la condivisione puo essere: + +- **Disabilitata** completamente per requisiti di conformita e sicurezza +- **Limitata** ai soli utenti autenticati tramite SSO +- **Self-hosted** sulla tua infrastruttura + +[Scopri di piu](/docs/enterprise) su come usare opencode nella tua organizzazione. diff --git a/packages/web/src/content/docs/it/skills.mdx b/packages/web/src/content/docs/it/skills.mdx new file mode 100644 index 000000000..824ea4054 --- /dev/null +++ b/packages/web/src/content/docs/it/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "Competenze dell'agente" +description: "Definisci comportamenti riutilizzabili tramite definizioni in SKILL.md" +--- + +Le skill degli agenti permettono a OpenCode di individuare istruzioni riutilizzabili dal tuo repo o dalla home directory. +Le skill vengono caricate on-demand tramite lo strumento nativo `skill`: gli agenti vedono le skill disponibili e possono caricarne il contenuto completo quando serve. + +--- + +## Posiziona i file + +Crea una cartella per ogni nome di skill e metti un `SKILL.md` al suo interno. +OpenCode cerca in queste posizioni: + +- Config di progetto: `.opencode/skills//SKILL.md` +- Config globale: `~/.config/opencode/skills//SKILL.md` +- Progetto compatibile con Claude: `.claude/skills//SKILL.md` +- Globale compatibile con Claude: `~/.claude/skills//SKILL.md` +- Progetto compatibile con agent: `.agents/skills//SKILL.md` +- Globale compatibile con agent: `~/.agents/skills//SKILL.md` + +--- + +## Comprendere la discovery + +Per i percorsi locali al progetto, OpenCode risale dalla directory di lavoro corrente finche' non raggiunge il worktree git. +Carica qualsiasi `skills/*/SKILL.md` corrispondente in `.opencode/` e qualsiasi `.claude/skills/*/SKILL.md` o `.agents/skills/*/SKILL.md` corrispondente lungo il percorso. + +Le definizioni globali vengono caricate anche da `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` e `~/.agents/skills/*/SKILL.md`. + +--- + +## Scrivi il frontmatter + +Ogni `SKILL.md` deve iniziare con frontmatter YAML. +Sono riconosciuti solo questi campi: + +- `name` (obbligatorio) +- `description` (obbligatorio) +- `license` (opzionale) +- `compatibility` (opzionale) +- `metadata` (opzionale, mappa stringa-a-stringa) + +I campi di frontmatter sconosciuti vengono ignorati. + +--- + +## Valida i nomi + +`name` deve: + +- Essere lungo 1-64 caratteri +- Essere alfanumerico minuscolo con separatori `-` singoli +- Non iniziare o finire con `-` +- Non contenere `--` consecutivi +- Corrispondere al nome della directory che contiene `SKILL.md` + +Regex equivalente: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## Rispetta le regole di lunghezza + +`description` deve essere lunga 1-1024 caratteri. +Tieni la descrizione abbastanza specifica da permettere all'agente di scegliere correttamente. + +--- + +## Usa un esempio + +Crea `.opencode/skills/git-release/SKILL.md` cosi': + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## Riconoscere la descrizione dello strumento + +OpenCode elenca le skill disponibili nella descrizione dello strumento `skill`. +Ogni voce include il nome della skill e la descrizione: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +L'agente carica una skill chiamando lo strumento: + +``` +skill({ name: "git-release" }) +``` + +--- + +## Configura i permessi + +Controlla a quali skill gli agenti possono accedere usando permessi basati su pattern in `opencode.json`: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Permesso | Comportamento | +| -------- | -------------------------------------------- | +| `allow` | La skill viene caricata immediatamente | +| `deny` | Skill nascosta all'agente, accesso negato | +| `ask` | L'utente viene invitato ad approvare il load | + +I pattern supportano wildcard: `internal-*` corrisponde a `internal-docs`, `internal-tools`, ecc. + +--- + +## Sovrascrivi per agente + +Dai ad agenti specifici permessi diversi dai default globali. + +**Per agenti personalizzati** (nel frontmatter dell'agente): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**Per agenti integrati** (in `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## Disabilita lo strumento skill + +Disabilita completamente le skill per agenti che non dovrebbero usarle: + +**Per agenti personalizzati**: + +```yaml +--- +tools: + skill: false +--- +``` + +**Per agenti integrati**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +Quando e' disabilitato, la sezione `` viene omessa completamente. + +--- + +## Risoluzione problemi di caricamento + +Se una skill non compare: + +1. Verifica che `SKILL.md` sia scritto in maiuscolo +2. Controlla che il frontmatter includa `name` e `description` +3. Assicurati che i nomi delle skill siano unici in tutte le posizioni +4. Controlla i permessi: le skill con `deny` vengono nascoste agli agenti diff --git a/packages/web/src/content/docs/it/themes.mdx b/packages/web/src/content/docs/it/themes.mdx new file mode 100644 index 000000000..6dfc3e125 --- /dev/null +++ b/packages/web/src/content/docs/it/themes.mdx @@ -0,0 +1,369 @@ +--- +title: Temi +description: Seleziona un tema integrato o definiscine uno tuo. +--- + +Con OpenCode puoi scegliere tra diversi temi integrati, usare un tema che si adatta al tema del tuo terminale oppure definire un tema personalizzato. + +Per impostazione predefinita, OpenCode usa il tema `opencode`. + +--- + +## Requisiti del terminale + +Per visualizzare correttamente i temi con l'intera palette, il terminale deve supportare **truecolor** (colore a 24 bit). La maggior parte dei terminali moderni lo supporta di default, ma potrebbe essere necessario abilitarlo: + +- **Verifica supporto**: esegui `echo $COLORTERM` - dovrebbe stampare `truecolor` o `24bit` +- **Abilita truecolor**: imposta la variabile d'ambiente `COLORTERM=truecolor` nel profilo della shell +- **Compatibilita del terminale**: assicurati che l'emulatore supporti il colore a 24 bit (la maggior parte dei terminali moderni come iTerm2, Alacritty, Kitty, Windows Terminal e le versioni recenti di GNOME Terminal) + +Senza truecolor, i temi potrebbero apparire con colori meno accurati oppure fare fallback alla migliore approssimazione a 256 colori. + +--- + +## Temi integrati + +OpenCode include diversi temi integrati. + +| Nome | Descrizione | +| ---------------------- | ------------------------------------------------------------------------- | +| `system` | Si adatta al colore di sfondo del terminale | +| `tokyonight` | Basato sul tema [Tokyonight](https://github.com/folke/tokyonight.nvim) | +| `everforest` | Basato sul tema [Everforest](https://github.com/sainnhe/everforest) | +| `ayu` | Basato sul tema scuro [Ayu](https://github.com/ayu-theme) | +| `catppuccin` | Basato sul tema [Catppuccin](https://github.com/catppuccin) | +| `catppuccin-macchiato` | Basato sul tema [Catppuccin](https://github.com/catppuccin) | +| `gruvbox` | Basato sul tema [Gruvbox](https://github.com/morhetz/gruvbox) | +| `kanagawa` | Basato sul tema [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | +| `nord` | Basato sul tema [Nord](https://github.com/nordtheme/nord) | +| `matrix` | Tema verde su nero in stile hacker | +| `one-dark` | Basato sul tema Dark [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) | + +E altri ancora: aggiungiamo costantemente nuovi temi. + +--- + +## Tema di sistema + +Il tema `system` e progettato per adattarsi automaticamente allo schema colori del tuo terminale. A differenza dei temi tradizionali con colori fissi, il tema _system_: + +- **Genera una scala di grigi**: crea una scala di grigi personalizzata in base al colore di sfondo del terminale, garantendo un contrasto ottimale. +- **Usa colori ANSI**: sfrutta i colori ANSI standard (0-15) per evidenziazione della sintassi ed elementi UI, rispettando la palette del terminale. +- **Preserva i default del terminale**: usa `none` per testo e sfondo per mantenere l'aspetto nativo del terminale. + +Il tema di sistema e pensato per chi: + +- Vuole che OpenCode corrisponda all'aspetto del terminale +- Usa schemi colori personalizzati del terminale +- Preferisce un aspetto coerente tra tutte le applicazioni da terminale + +--- + +## Usare un tema + +Puoi selezionare un tema aprendo la selezione temi con il comando `/theme`. In alternativa, puoi specificarlo nella tua [configurazione](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Temi personalizzati + +OpenCode supporta un sistema di temi flessibile basato su JSON che permette di creare e personalizzare temi facilmente. + +--- + +### Gerarchia + +I temi vengono caricati da piu directory nel seguente ordine, dove le directory successive sovrascrivono le precedenti: + +1. **Temi integrati** - incorporati nel binario +2. **Directory di configurazione utente** - in `~/.config/opencode/themes/*.json` o `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Directory root del progetto** - in `/.opencode/themes/*.json` +4. **Directory di lavoro corrente** - in `./.opencode/themes/*.json` + +Se piu directory contengono un tema con lo stesso nome, verra usato il tema della directory con priorita piu alta. + +--- + +### Creare un tema + +Per creare un tema personalizzato, crea un file JSON in una delle directory dei temi. + +Per temi a livello utente: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +E per temi specifici del progetto. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### Formato JSON + +I temi usano un formato JSON flessibile che supporta: + +- **Colori hex**: `"#ffffff"` +- **Colori ANSI**: `3` (0-255) +- **Riferimenti colore**: `"primary"` o definizioni personalizzate +- **Varianti scuro/chiaro**: `{"dark": "#000", "light": "#fff"}` +- **Nessun colore**: `"none"` - usa il colore predefinito del terminale o trasparente + +--- + +### Definizioni dei colori + +La sezione `defs` e opzionale e ti permette di definire colori riutilizzabili che possono essere referenziati nel tema. + +--- + +### Valori predefiniti del terminale + +Il valore speciale `"none"` puo essere usato per qualunque colore per ereditare il colore predefinito del terminale. E particolarmente utile per creare temi che si fondono con lo schema colori del terminale: + +- `"text": "none"` - usa il colore del testo predefinito del terminale +- `"background": "none"` - usa il colore di sfondo predefinito del terminale + +--- + +### Esempio + +Ecco un esempio di tema personalizzato: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/it/tools.mdx b/packages/web/src/content/docs/it/tools.mdx new file mode 100644 index 000000000..67a0640c7 --- /dev/null +++ b/packages/web/src/content/docs/it/tools.mdx @@ -0,0 +1,379 @@ +--- +title: Strumenti +description: Gestisci gli strumenti che un LLM puo' usare. +--- + +Gli strumenti permettono all'LLM di eseguire azioni nel tuo codebase. OpenCode include un set di strumenti integrati, ma puoi estenderlo con [strumenti personalizzati](/docs/custom-tools) o con [server MCP](/docs/mcp-servers). + +Di default, tutti gli strumenti sono **abilitati** e non richiedono permessi per essere eseguiti. Puoi controllare il comportamento degli strumenti tramite i [permessi](/docs/permissions). + +--- + +## Configura + +Usa il campo `permission` per controllare il comportamento degli strumenti. Puoi consentire, negare o richiedere approvazione per ciascuno. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +Puoi anche usare wildcard per controllare piu' strumenti insieme. Per esempio, per richiedere approvazione per tutti gli strumenti di un server MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[Scopri di piu'](/docs/permissions) su come configurare i permessi. + +--- + +## Integrati + +Ecco tutti gli strumenti integrati disponibili in OpenCode. + +--- + +### bash + +Esegui comandi di shell nel tuo ambiente di progetto. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +Questo strumento permette all'LLM di eseguire comandi da terminale come `npm install`, `git status` o qualunque altro comando di shell. + +--- + +### edit + +Modifica file esistenti usando sostituzioni esatte di stringhe. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Questo strumento esegue modifiche precise ai file sostituendo corrispondenze di testo esatte. E' il modo principale con cui l'LLM modifica il codice. + +--- + +### write + +Crea nuovi file o sovrascrive quelli esistenti. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Usalo per consentire all'LLM di creare nuovi file. Sovrascrivera' i file esistenti se sono gia' presenti. + +:::note +Lo strumento `write` e' controllato dal permesso `edit`, che copre tutte le modifiche ai file (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### read + +Leggi il contenuto dei file dal tuo codebase. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +Questo strumento legge i file e ne restituisce il contenuto. Supporta la lettura di intervalli di righe specifici per file grandi. + +--- + +### grep + +Cerca nel contenuto dei file usando espressioni regolari. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Ricerca rapida nel contenuto su tutto il codebase. Supporta la sintassi completa delle regex e il filtro per pattern di file. + +--- + +### glob + +Trova file tramite pattern matching. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +Cerca file usando pattern glob come `**/*.js` o `src/**/*.ts`. Restituisce i percorsi corrispondenti ordinati per data di modifica. + +--- + +### list + +Elenca file e directory in un percorso specifico. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +Questo strumento elenca il contenuto di una directory. Accetta pattern glob per filtrare i risultati. + +--- + +### lsp (experimental) + +Interagisci con i server LSP configurati per ottenere funzionalita' di code intelligence come definizioni, riferimenti, hover info e call hierarchy. + +:::note +Questo strumento e' disponibile solo quando `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (oppure `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +Le operazioni supportate includono `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` e `outgoingCalls`. + +Per configurare quali server LSP sono disponibili per il tuo progetto, vedi [LSP Servers](/docs/lsp). + +--- + +### patch + +Applica patch ai file. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Questo strumento applica file patch al tuo codebase. Utile per applicare diff e patch da varie fonti. + +:::note +Lo strumento `patch` e' controllato dal permesso `edit`, che copre tutte le modifiche ai file (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### skill + +Carica una [skill](/docs/skills) (un file `SKILL.md`) e ne restituisce il contenuto nella conversazione. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todowrite + +Gestisci todo list durante le sessioni di coding. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +Crea e aggiorna liste di task per tracciare i progressi durante operazioni complesse. L'LLM lo usa per organizzare attivita' multi-step. + +:::note +Questo strumento e' disabilitato per i subagenti di default, ma puoi abilitarlo manualmente. [Scopri di piu'](/docs/agents/#permissions) +::: + +--- + +### todoread + +Leggi le todo list esistenti. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +Legge lo stato corrente della todo list. Usato dall'LLM per tenere traccia di quali task sono in sospeso o completati. + +:::note +Questo strumento e' disabilitato per i subagenti di default, ma puoi abilitarlo manualmente. [Scopri di piu'](/docs/agents/#permissions) +::: + +--- + +### webfetch + +Recupera contenuti dal web. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +Permette all'LLM di recuperare e leggere pagine web. Utile per consultare documentazione o ricercare risorse online. + +--- + +### websearch + +Cerca informazioni sul web. + +:::note +Questo strumento e' disponibile solo quando usi il provider OpenCode o quando la variabile d'ambiente `OPENCODE_ENABLE_EXA` e' impostata a un valore truthy (ad esempio `true` o `1`). + +Per abilitarlo all'avvio di OpenCode: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Esegue ricerche web usando Exa AI per trovare informazioni rilevanti online. Utile per ricercare argomenti, trovare eventi attuali o raccogliere informazioni oltre il cutoff dei dati di addestramento. + +Non e' richiesta alcuna API key: lo strumento si connette direttamente al servizio MCP ospitato da Exa AI senza autenticazione. + +:::tip +Usa `websearch` quando devi trovare informazioni (discovery) e `webfetch` quando devi recuperare contenuti da un URL specifico (retrieval). +::: + +--- + +### question + +Fai domande all'utente durante l'esecuzione. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +Questo strumento permette all'LLM di porre domande all'utente durante un task. E' utile per: + +- Raccogliere preferenze o requisiti dell'utente +- Chiarire istruzioni ambigue +- Ottenere decisioni sulle scelte di implementazione +- Offrire opzioni su che direzione prendere + +Ogni domanda include un header, il testo della domanda e una lista di opzioni. Gli utenti possono selezionare dalle opzioni fornite o digitare una risposta personalizzata. Quando ci sono piu' domande, gli utenti possono navigare tra di esse prima di inviare tutte le risposte. + +--- + +## Strumenti personalizzati + +Gli strumenti personalizzati ti permettono di definire funzioni che l'LLM puo' chiamare. Sono definiti nel tuo file di configurazione e possono eseguire codice arbitrario. + +[Scopri di piu'](/docs/custom-tools) su come creare strumenti personalizzati. + +--- + +## Server MCP + +I server MCP (Model Context Protocol) permettono di integrare strumenti e servizi esterni. Questo include accesso a database, integrazioni API e servizi di terze parti. + +[Scopri di piu'](/docs/mcp-servers) su come configurare i server MCP. + +--- + +## Interni + +Internamente, strumenti come `grep`, `glob` e `list` usano [ripgrep](https://github.com/BurntSushi/ripgrep) sotto al cofano. Di default, ripgrep rispetta i pattern di `.gitignore`, quindi i file e le directory elencati in `.gitignore` vengono esclusi da ricerche ed elenchi. + +--- + +### Pattern di ignore + +Per includere file che normalmente verrebbero ignorati, crea un file `.ignore` nella root del progetto. Questo file puo' consentire esplicitamente certi path. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +Per esempio, questo file `.ignore` permette a ripgrep di cercare dentro `node_modules/`, `dist/` e `build/` anche se sono elencate in `.gitignore`. diff --git a/packages/web/src/content/docs/it/troubleshooting.mdx b/packages/web/src/content/docs/it/troubleshooting.mdx new file mode 100644 index 000000000..5f0ed3820 --- /dev/null +++ b/packages/web/src/content/docs/it/troubleshooting.mdx @@ -0,0 +1,299 @@ +--- +title: Risoluzione dei problemi +description: Problemi comuni e come risolverli. +--- + +Per diagnosticare problemi con OpenCode, inizia controllando i log e i dati locali che salva su disco. + +--- + +## Log + +I file di log vengono scritti in: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: premi `WIN+R` e incolla `%USERPROFILE%\.local\share\opencode\log` + +I file di log hanno nomi con timestamp (ad es. `2025-01-09T123456.log`) e vengono conservati i 10 file di log piu recenti. + +Puoi impostare il livello di log con l'opzione a riga di comando `--log-level` per ottenere informazioni di debug piu dettagliate. Per esempio: `opencode --log-level DEBUG`. + +--- + +## Archiviazione + +opencode salva i dati delle sessioni e altri dati dell'applicazione su disco in: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: premi `WIN+R` e incolla `%USERPROFILE%\.local\share\opencode` + +Questa directory contiene: + +- `auth.json` - dati di autenticazione come chiavi API, token OAuth +- `log/` - log dell'applicazione +- `project/` - dati specifici del progetto come dati di sessione e messaggi + - Se il progetto e dentro un repository Git, viene salvato in `.//storage/` + - Se non e un repository Git, viene salvato in `./global/storage/` + +--- + +## App desktop + +OpenCode Desktop esegue in background un server locale di OpenCode (il sidecar `opencode-cli`). La maggior parte dei problemi e causata da un plugin che si comporta male, da una cache corrotta o da un'impostazione del server errata. + +### Controlli rapidi + +- Chiudi completamente l'app e riaprila. +- Se l'app mostra una schermata di errore, fai clic su **Restart** e copia i dettagli dell'errore. +- Solo macOS: menu `OpenCode` -> **Reload Webview** (utile se l'interfaccia e vuota o bloccata). + +--- + +### Disabilita i plugin + +Se l'app desktop va in crash all'avvio, si blocca o si comporta in modo strano, inizia disabilitando i plugin. + +#### Controlla la configurazione globale + +Apri il tuo file di configurazione globale e cerca la chiave `plugin`. + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (or `~/.config/opencode/opencode.json`) +- **macOS/Linux** (older installs): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: premi `WIN+R` e incolla `%USERPROFILE%\.config\opencode\opencode.jsonc` + +Se hai plugin configurati, disabilitali temporaneamente rimuovendo la chiave o impostandola a un array vuoto: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### Controlla le directory dei plugin + +OpenCode puo anche caricare plugin locali dal disco. Spostali temporaneamente altrove (o rinomina la cartella) e riavvia l'app desktop: + +- **Plugin globali** + - **macOS/Linux**: `~/.config/opencode/plugins/` +- **Windows**: premi `WIN+R` e incolla `%USERPROFILE%\.config\opencode\plugins` +- **Plugin del progetto** (solo se usi una configurazione per progetto) + - `/.opencode/plugins/` + +Se l'app ricomincia a funzionare, riabilita i plugin uno alla volta per capire quale stia causando il problema. + +--- + +### Svuota la cache + +Se disabilitare i plugin non aiuta (o l'installazione di un plugin e bloccata), svuota la cache in modo che OpenCode possa ricostruirla. + +1. Quit OpenCode Desktop completely. +2. Elimina la directory della cache: + +- **macOS**: Finder -> `Cmd+Shift+G` -> paste `~/.cache/opencode` +- **Linux**: elimina `~/.cache/opencode` (oppure esegui `rm -rf ~/.cache/opencode`) +- **Windows**: premi `WIN+R` e incolla `%USERPROFILE%\.cache\opencode` + +3. Restart OpenCode Desktop. + +--- + +### Risolvi problemi di connessione al server + +OpenCode Desktop puo avviare il proprio server locale (predefinito) oppure connettersi a un URL server che hai configurato. + +Se vedi una finestra **"Connection Failed"** (o l'app non supera mai la schermata di avvio), controlla se hai impostato un URL server personalizzato. + +#### Cancella l'URL del server predefinito dell'app desktop + +Dalla schermata Home, fai clic sul nome del server (con il pallino di stato) per aprire il selettore dei server. Nella sezione **Default server**, fai clic su **Clear**. + +#### Rimuovi `server.port` / `server.hostname` dalla tua configurazione + +Se il tuo `opencode.json(c)` contiene una sezione `server`, rimuovila temporaneamente e riavvia l'app desktop. + +#### Controlla le variabili d'ambiente + +Se hai `OPENCODE_PORT` impostato nell'ambiente, l'app desktop provera a usare quella porta per il server locale. + +- Rimuovi `OPENCODE_PORT` (o scegli una porta libera) e riavvia. + +--- + +### Linux: problemi Wayland / X11 + +Su Linux, alcune configurazioni Wayland possono causare finestre vuote o errori del compositor. + +- Se sei su Wayland e l'app e vuota o va in crash, prova ad avviarla con `OC_ALLOW_WAYLAND=1`. +- Se peggiora la situazione, rimuovilo e prova invece ad avviare sotto una sessione X11. + +--- + +### Windows: runtime WebView2 + +Su Windows, OpenCode Desktop richiede **WebView2 Runtime** di Microsoft Edge. Se l'app si apre su una finestra vuota o non parte, installa/aggiorna WebView2 e riprova. + +--- + +### Windows: problemi generali di prestazioni + +Se riscontri prestazioni lente, problemi di accesso ai file o problemi del terminale su Windows, prova a usare [WSL (Windows Subsystem for Linux)](/docs/windows-wsl). WSL fornisce un ambiente Linux che funziona in modo piu fluido con le funzionalita di OpenCode. + +--- + +### Notifiche non visualizzate + +OpenCode Desktop mostra le notifiche di sistema solo quando: + +- le notifiche sono abilitate per OpenCode nelle impostazioni del sistema operativo, e +- la finestra dell'app non e in primo piano. + +--- + +### Reimposta lo stato dell'app desktop (ultima risorsa) + +Se l'app non si avvia e non riesci a ripulire le impostazioni dall'interfaccia, reimposta lo stato salvato dell'app desktop. + +1. Quit OpenCode Desktop. +2. Trova ed elimina questi file (si trovano nella directory dati dell'app OpenCode Desktop): + +- `opencode.settings.dat` (desktop default server URL) +- `opencode.global.dat` e `opencode.workspace.*.dat` (stato dell'interfaccia come server/progetti recenti) + +Per trovare rapidamente la directory: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (poi cerca i nomi file qui sopra) +- **Linux**: cerca sotto `~/.local/share` i nomi file qui sopra +- **Windows**: premi `WIN+R` -> `%APPDATA%` (poi cerca i nomi file qui sopra) + +--- + +## Ottenere aiuto + +Se riscontri problemi con OpenCode: + +1. **Segnala i problemi su GitHub** + + Il modo migliore per segnalare bug o richiedere funzionalita e tramite il nostro repository GitHub: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + Prima di creare una nuova issue, cerca tra quelle esistenti per vedere se il problema e gia stato segnalato. + +2. **Unisciti al nostro Discord** + + Per supporto in tempo reale e discussioni con la community, unisciti al nostro server Discord: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Problemi comuni + +Ecco alcuni problemi comuni e come risolverli. + +--- + +### OpenCode non si avvia + +1. Controlla i log per eventuali messaggi di errore +2. Prova a eseguire con `--print-logs` per vedere l'output nel terminale +3. Assicurati di avere l'ultima versione con `opencode upgrade` + +--- + +### Problemi di autenticazione + +1. Prova a riautenticarti con il comando `/connect` nella TUI +2. Controlla che le chiavi API siano valide +3. Assicurati che la rete permetta connessioni all'API del provider + +--- + +### Modello non disponibile + +1. Controlla di esserti autenticato con il provider +2. Verifica che il nome del modello nella configurazione sia corretto +3. Alcuni modelli potrebbero richiedere accessi o abbonamenti specifici + +Se incontri `ProviderModelNotFoundError`, probabilmente stai facendo riferimento a un modello in modo errato da qualche parte. +I modelli vanno indicati in questo formato: `/` + +Esempi: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +Per capire a quali modelli hai accesso, esegui `opencode models` + +--- + +### ProviderInitError + +Se incontri un ProviderInitError, probabilmente la tua configurazione e invalida o corrotta. + +Per risolvere: + +1. Per prima cosa, verifica che il provider sia configurato correttamente seguendo la [guida ai provider](/docs/providers) +2. Se il problema persiste, prova a cancellare la configurazione salvata: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + Su Windows, premi `WIN+R` ed elimina: `%USERPROFILE%\.local\share\opencode` + +3. Riautenticati con il provider usando il comando `/connect` nella TUI. + +--- + +### AI_APICallError e problemi dei pacchetti provider + +Se incontri errori nelle chiamate API, potrebbe dipendere da pacchetti provider non aggiornati. opencode installa dinamicamente i pacchetti provider (OpenAI, Anthropic, Google, ecc.) quando servono e li mette in cache localmente. + +Per risolvere problemi coi pacchetti provider: + +1. Svuota la cache dei pacchetti provider: + + ```bash + rm -rf ~/.cache/opencode + ``` + + Su Windows, premi `WIN+R` ed elimina: `%USERPROFILE%\.cache\opencode` + +2. Riavvia opencode per reinstallare i pacchetti provider piu recenti + +Questo forzera opencode a scaricare le versioni piu recenti dei pacchetti provider, cosa che spesso risolve problemi di compatibilita con parametri dei modelli e cambiamenti delle API. + +--- + +### Copy/paste not working on Linux + +Su Linux e necessario avere installata una delle seguenti utility per gli appunti affinche copia/incolla funzioni: + +**Per sistemi X11:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**Per sistemi Wayland:** + +```bash +apt install -y wl-clipboard +``` + +**Per ambienti headless:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode rilevera se stai usando Wayland e preferira `wl-clipboard`; altrimenti provera a trovare gli strumenti per gli appunti nell'ordine: `xclip` e `xsel`. diff --git a/packages/web/src/content/docs/it/tui.mdx b/packages/web/src/content/docs/it/tui.mdx new file mode 100644 index 000000000..f24612f46 --- /dev/null +++ b/packages/web/src/content/docs/it/tui.mdx @@ -0,0 +1,387 @@ +--- +title: TUI +description: Usa l'interfaccia utente da terminale (TUI) di OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode fornisce un'interfaccia interattiva da terminale (TUI) per lavorare sui tuoi progetti con un LLM. + +Eseguire OpenCode avvia la TUI per la directory corrente. + +```bash +opencode +``` + +Oppure puoi avviarla per una specifica working directory. + +```bash +opencode /path/to/project +``` + +Una volta nella TUI, puoi inviare un messaggio come prompt. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## Riferimenti ai file + +Puoi riferirti ai file nei messaggi usando `@`. Questo esegue una ricerca fuzzy dei file nella working directory corrente. + +:::tip +Puoi anche usare `@` per riferirti ai file nei messaggi. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +Il contenuto del file viene aggiunto automaticamente alla conversazione. + +--- + +## Comandi bash + +Inizia un messaggio con `!` per eseguire un comando shell. + +```bash frame="none" +!ls -la +``` + +L'output del comando viene aggiunto alla conversazione come risultato di uno strumento. + +--- + +## Comandi + +Quando usi la TUI di OpenCode, puoi digitare `/` seguito dal nome di un comando per eseguire rapidamente azioni. Per esempio: + +```bash frame="none" +/help +``` + +Molti comandi hanno anche una scorciatoia da tastiera che usa `ctrl+x` come tasto leader (predefinito). [Scopri di piu](/docs/keybinds). + +Ecco tutti i comandi slash disponibili: + +--- + +### connetti + +Aggiunge un provider a OpenCode. Ti permette di selezionare tra i provider disponibili e aggiungere le relative chiavi API. + +```bash frame="none" +/connect +``` + +--- + +### compatta + +Compatta la sessione corrente. _Alias_: `/summarize` + +```bash frame="none" +/compact +``` + +**Scorciatoia:** `ctrl+x c` + +--- + +### dettagli + +Attiva/disattiva i dettagli di esecuzione degli strumenti. + +```bash frame="none" +/details +``` + +**Scorciatoia:** `ctrl+x d` + +--- + +### editor + +Apre un editor esterno per comporre messaggi. Usa l'editor impostato nella variabile d'ambiente `EDITOR`. [Scopri di piu](#editor-setup). + +```bash frame="none" +/editor +``` + +**Scorciatoia:** `ctrl+x e` + +--- + +### esci + +Esce da OpenCode. _Alias_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Scorciatoia:** `ctrl+x q` + +--- + +### esporta + +Esporta la conversazione corrente in Markdown e la apre nell'editor predefinito. Usa l'editor impostato nella variabile d'ambiente `EDITOR`. [Scopri di piu](#editor-setup). + +```bash frame="none" +/export +``` + +**Scorciatoia:** `ctrl+x x` + +--- + +### aiuto + +Mostra la finestra di aiuto. + +```bash frame="none" +/help +``` + +**Scorciatoia:** `ctrl+x h` + +--- + +### inizializza + +Crea o aggiorna il file `AGENTS.md`. [Scopri di piu](/docs/rules). + +```bash frame="none" +/init +``` + +**Scorciatoia:** `ctrl+x i` + +--- + +### modelli + +Elenca i modelli disponibili. + +```bash frame="none" +/models +``` + +**Scorciatoia:** `ctrl+x m` + +--- + +### nuovo + +Avvia una nuova sessione. _Alias_: `/clear` + +```bash frame="none" +/new +``` + +**Scorciatoia:** `ctrl+x n` + +--- + +### rifai + +Rifai un messaggio precedentemente annullato. Disponibile solo dopo aver usato `/undo`. + +:::tip +Vengono ripristinate anche eventuali modifiche ai file. +::: + +Internamente usa Git per gestire le modifiche ai file. Quindi il progetto **deve essere un repository Git**. + +```bash frame="none" +/redo +``` + +**Scorciatoia:** `ctrl+x r` + +--- + +### sessioni + +Elenca e passa tra le sessioni. _Alias_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Scorciatoia:** `ctrl+x l` + +--- + +### condividi + +Condivide la sessione corrente. [Scopri di piu](/docs/share). + +```bash frame="none" +/share +``` + +**Scorciatoia:** `ctrl+x s` + +--- + +### temi + +Elenca i temi disponibili. + +```bash frame="none" +/theme +``` + +**Scorciatoia:** `ctrl+x t` + +--- + +### ragionamento + +Attiva/disattiva la visibilita dei blocchi thinking/reasoning nella conversazione. Quando abilitato, puoi vedere il ragionamento del modello per i modelli che supportano extended thinking. + +:::note +Questo comando controlla solo se i blocchi di thinking vengono **mostrati**: non abilita o disabilita le capacita di ragionamento del modello. Per cambiare le capacita di ragionamento effettive, usa `ctrl+t` per ciclare tra le varianti del modello. +::: + +```bash frame="none" +/thinking +``` + +--- + +### annulla + +Annulla l'ultimo messaggio nella conversazione. Rimuove l'ultimo messaggio utente, tutte le risposte successive e qualsiasi modifica ai file. + +:::tip +Vengono annullate anche eventuali modifiche ai file. +::: + +Internamente usa Git per gestire le modifiche ai file. Quindi il progetto **deve essere un repository Git**. + +```bash frame="none" +/undo +``` + +**Scorciatoia:** `ctrl+x u` + +--- + +### annulla condivisione + +Annulla la condivisione della sessione corrente. [Scopri di piu](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## Configurazione dell'editor + +Sia `/editor` sia `/export` usano l'editor specificato nella variabile d'ambiente `EDITOR`. + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + + Per renderlo permanente, aggiungilo al profilo della shell; + `~/.bashrc`, `~/.zshrc`, ecc. + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + + Per renderlo permanente, usa **System Properties** > **Environment Variables**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + + Per renderlo permanente, aggiungilo al profilo PowerShell. + + + + +Opzioni comuni per l'editor includono: + +- `code` - Visual Studio Code +- `cursor` - Cursor +- `windsurf` - Windsurf +- `nvim` - Neovim editor +- `vim` - Vim editor +- `nano` - Nano editor +- `notepad` - Windows Notepad +- `subl` - Sublime Text + +:::note +Alcuni editor come VS Code devono essere avviati con il flag `--wait`. +::: + +Alcuni editor richiedono argomenti da riga di comando per funzionare in modalita bloccante. Il flag `--wait` fa si che il processo dell'editor resti in attesa finche non viene chiuso. + +--- + +## Configura + +Puoi personalizzare il comportamento della TUI tramite il file di config di OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### Opzioni + +- `scroll_acceleration` - Abilita l'accelerazione di scroll in stile macOS per uno scorrimento fluido e naturale. Quando abilitata, la velocita aumenta con gesture rapide e resta precisa con movimenti lenti. **Questa impostazione ha precedenza su `scroll_speed` e lo sovrascrive quando attiva.** +- `scroll_speed` - Controlla la velocita di scorrimento della TUI quando usi i comandi di scroll (minimo: `1`). Default: `3`. **Nota: viene ignorata se `scroll_acceleration.enabled` e impostato a `true`.** + +--- + +## Personalizzazione + +Puoi personalizzare vari aspetti della vista TUI usando la palette dei comandi (`ctrl+x h` o `/help`). Queste impostazioni persistono tra i riavvii. + +--- + +#### Visualizzazione nome utente + +Attiva/disattiva se lo username appare nei messaggi della chat. Puoi farlo da: + +- Palette comandi: cerca "username" o "hide username" +- L'impostazione viene salvata automaticamente e ricordata tra le sessioni TUI diff --git a/packages/web/src/content/docs/it/web.mdx b/packages/web/src/content/docs/it/web.mdx new file mode 100644 index 000000000..bda4ba9c2 --- /dev/null +++ b/packages/web/src/content/docs/it/web.mdx @@ -0,0 +1,142 @@ +--- +title: Web +description: Usa OpenCode nel browser. +--- + +OpenCode puo funzionare come applicazione web nel browser, offrendo la stessa potente esperienza di coding AI senza bisogno di un terminale. + +![OpenCode Web - Nuova sessione](../../../assets/web/web-homepage-new-session.png) + +## Per iniziare + +Avvia l'interfaccia web eseguendo: + +```bash +opencode web +``` + +Questo avvia un server locale su `127.0.0.1` con una porta disponibile scelta a caso e apre automaticamente OpenCode nel browser predefinito. + +:::caution +Se `OPENCODE_SERVER_PASSWORD` non e impostata, il server non sara protetto. Va bene per l'uso locale, ma va impostata per l'accesso in rete. +::: + +:::tip[Utenti Windows] +Per la migliore esperienza, esegui `opencode web` da [WSL](/docs/windows-wsl) invece che da PowerShell. Questo garantisce accesso corretto al file system e integrazione col terminale. +::: + +--- + +## Configurazione + +Puoi configurare il server web con i flag della riga di comando o nel tuo [file di config](/docs/config). + +### Porta + +Per impostazione predefinita, OpenCode sceglie una porta disponibile. Puoi specificare una porta: + +```bash +opencode web --port 4096 +``` + +### Nome host + +Per impostazione predefinita, il server si lega a `127.0.0.1` (solo localhost). Per rendere OpenCode accessibile sulla rete: + +```bash +opencode web --hostname 0.0.0.0 +``` + +Usando `0.0.0.0`, OpenCode mostrera sia l'indirizzo locale sia quello di rete: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### Scoperta mDNS + +Abilita mDNS per rendere il server individuabile sulla rete locale: + +```bash +opencode web --mdns +``` + +Questo imposta automaticamente l'hostname a `0.0.0.0` e pubblicizza il server come `opencode.local`. + +Puoi personalizzare il nome di dominio mDNS per eseguire piu istanze sulla stessa rete: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +Per consentire domini aggiuntivi per CORS (utile per frontend personalizzati): + +```bash +opencode web --cors https://example.com +``` + +### Autenticazione + +Per proteggere l'accesso, imposta una password usando la variabile d'ambiente `OPENCODE_SERVER_PASSWORD`: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +Lo username predefinito e `opencode`, ma puo essere cambiato con `OPENCODE_SERVER_USERNAME`. + +--- + +## Usa l'interfaccia web + +Una volta avviata, l'interfaccia web ti da accesso alle tue sessioni OpenCode. + +### Sessioni + +Visualizza e gestisci le sessioni dalla homepage. Puoi vedere le sessioni attive e avviarne di nuove. + +![OpenCode Web - Sessione attiva](../../../assets/web/web-homepage-active-session.png) + +### Stato del server + +Fai clic su "See Servers" per vedere i server connessi e il loro stato. + +![OpenCode Web - See Servers](../../../assets/web/web-homepage-see-servers.png) + +--- + +## Collegare un terminale + +Puoi collegare una TUI da terminale a un server web gia in esecuzione: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +Questo ti permette di usare contemporaneamente interfaccia web e terminale, condividendo le stesse sessioni e lo stesso stato. + +--- + +## File di configurazione + +Puoi anche configurare le impostazioni del server nel file di config `opencode.json`: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +I flag della riga di comando hanno precedenza sulle impostazioni del file di config. diff --git a/packages/web/src/content/docs/it/windows-wsl.mdx b/packages/web/src/content/docs/it/windows-wsl.mdx new file mode 100644 index 000000000..a1a7aa4ef --- /dev/null +++ b/packages/web/src/content/docs/it/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: Esegui OpenCode su Windows con WSL per la migliore esperienza. +--- + +import { Steps } from "@astrojs/starlight/components" + +Anche se OpenCode puo essere eseguito direttamente su Windows, consigliamo di usare [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) per la migliore esperienza. WSL fornisce un ambiente Linux che funziona in modo ottimale con le funzionalita di OpenCode. + +:::tip[Perche WSL?] +WSL offre prestazioni migliori del file system, supporto completo del terminale e compatibilita con gli strumenti di sviluppo su cui OpenCode fa affidamento. +::: + +--- + +## Configurazione + + + +1. **Installa WSL** + + Se non l'hai ancora fatto, [installa WSL](https://learn.microsoft.com/en-us/windows/wsl/install) seguendo la guida ufficiale Microsoft. + +2. **Installa OpenCode in WSL** + + Dopo aver configurato WSL, apri il terminale WSL e installa OpenCode usando uno dei [metodi di installazione](/docs/). + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **Usa OpenCode da WSL** + + Vai nella directory del progetto (accedi ai file Windows tramite `/mnt/c/`, `/mnt/d/`, ecc.) ed esegui OpenCode. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## App desktop + server WSL + +Se preferisci usare l'app desktop di OpenCode ma vuoi eseguire il server in WSL: + +1. **Avvia il server in WSL** con `--hostname 0.0.0.0` per consentire connessioni esterne: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Collega l'app desktop** a `http://localhost:4096` + +:::note +Se `localhost` non funziona nella tua configurazione, usa l'indirizzo IP di WSL (da WSL: `hostname -I`) e collega `http://:4096`. +::: + +:::caution +Quando usi `--hostname 0.0.0.0`, imposta `OPENCODE_SERVER_PASSWORD` per proteggere il server. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Client web + WSL + +Per la migliore esperienza web su Windows: + +1. **Esegui `opencode web` nel terminale WSL** invece che in PowerShell: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Accedi dal browser Windows** su `http://localhost:` (OpenCode stampa l'URL) + +Eseguire `opencode web` da WSL garantisce accesso corretto al file system e integrazione del terminale, restando comunque accessibile dal browser Windows. + +--- + +## Accesso ai file Windows + +WSL puo accedere a tutti i file Windows tramite la directory `/mnt/`: + +- Unita `C:` → `/mnt/c/` +- Unita `D:` → `/mnt/d/` +- E cosi via... + +Esempio: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +Per un'esperienza piu fluida, valuta di clonare o copiare il repository nel file system di WSL (per esempio in `~/code/`) ed eseguire OpenCode li. +::: + +--- + +## Suggerimenti + +- Tieni OpenCode in esecuzione su WSL per i progetti salvati su unita Windows: l'accesso ai file e immediato +- Usa l'[estensione WSL di VS Code](https://code.visualstudio.com/docs/remote/wsl) insieme a OpenCode per un flusso di lavoro integrato +- Configurazione e sessioni di OpenCode sono salvate nell'ambiente WSL in `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/it/zen.mdx b/packages/web/src/content/docs/it/zen.mdx new file mode 100644 index 000000000..8ea628aee --- /dev/null +++ b/packages/web/src/content/docs/it/zen.mdx @@ -0,0 +1,236 @@ +--- +title: Zen +description: Lista curata di modelli fornita da OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen e una lista di modelli testati e verificati dal team di OpenCode. + +:::note +OpenCode Zen e attualmente in beta. +::: + +Zen funziona come qualunque altro provider in OpenCode. Accedi a OpenCode Zen e ottieni la tua chiave API. E **completamente opzionale**: non devi usarlo per usare OpenCode. + +--- + +## Contesto + +Ci sono moltissimi modelli, ma solo pochi funzionano bene come agenti di coding. Inoltre, la maggior parte dei provider e configurata in modo molto diverso, quindi prestazioni e qualita possono variare parecchio. + +:::tip +Abbiamo testato un gruppo selezionato di modelli e provider che funzionano bene con OpenCode. +::: + +Quindi, se usi un modello tramite qualcosa come OpenRouter, non puoi mai essere sicuro di ottenere la migliore versione del modello che vuoi. + +Per risolvere, abbiamo fatto alcune cose: + +1. Abbiamo testato un gruppo selezionato di modelli e parlato coi loro team su come eseguirli al meglio. +2. Poi abbiamo lavorato con alcuni provider per assicurarci che venissero serviti correttamente. +3. Infine, abbiamo fatto benchmark delle combinazioni modello/provider e creato una lista che ci sentiamo di raccomandare. + +OpenCode Zen e un gateway AI che ti da accesso a questi modelli. + +--- + +## Come funziona + +OpenCode Zen funziona come qualunque altro provider in OpenCode. + +1. Accedi a **OpenCode Zen**, aggiungi i dettagli di fatturazione e copia la chiave API. +2. Esegui il comando `/connect` nella TUI, seleziona OpenCode Zen e incolla la chiave API. +3. Esegui `/models` nella TUI per vedere la lista dei modelli che consigliamo. + +Paghi per richiesta e puoi aggiungere credito al tuo account. + +--- + +## Endpoint + +Puoi anche accedere ai nostri modelli tramite i seguenti endpoint API. + +| Modello | ID modello | Endpoint | Pacchetto AI SDK | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Free | minimax-m2.1-free | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Free | glm-4.7-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Free | kimi-k2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +Il [model id](/docs/config/#models) nella config di OpenCode usa il formato `opencode/`. Per esempio, per GPT 5.2 Codex useresti `opencode/gpt-5.2-codex` nella config. + +--- + +### Modelli + +Puoi recuperare la lista completa dei modelli disponibili e i relativi metadati da: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## Prezzi + +Supportiamo un modello pay-as-you-go. Qui sotto trovi i prezzi **per 1M token**. + +| Modello | Input | Output | Lettura in cache | Scrittura in cache | +| --------------------------------- | ------ | ------ | ---------------- | ------------------ | +| Big Pickle | Gratis | Gratis | Gratis | - | +| MiniMax M2.1 Free | Gratis | Gratis | Gratis | - | +| MiniMax M2.1 | $0.30 | $1.20 | $0.10 | - | +| GLM 4.7 Free | Gratis | Gratis | Gratis | - | +| GLM 4.7 | $0.60 | $2.20 | $0.10 | - | +| GLM 4.6 | $0.60 | $2.20 | $0.10 | - | +| Kimi K2.5 Free | Gratis | Gratis | Gratis | - | +| Kimi K2.5 | $0.60 | $3.00 | $0.08 | - | +| Kimi K2 Thinking | $0.40 | $2.50 | - | - | +| Kimi K2 | $0.40 | $2.50 | - | - | +| Qwen3 Coder 480B | $0.45 | $1.50 | - | - | +| Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | +| Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | +| Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | +| Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | +| Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | - | +| Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | - | +| Gemini 3 Flash | $0.50 | $3.00 | $0.05 | - | +| GPT 5.2 | $1.75 | $14.00 | $0.175 | - | +| GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | - | +| GPT 5.1 | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | - | +| GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | - | +| GPT 5 | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Nano | Gratis | Gratis | Gratis | - | + +Potresti notare _Claude Haiku 3.5_ nella cronologia d'uso. E un [modello a basso costo](/docs/config/#models) usato per generare i titoli delle sessioni. + +:::note +Le commissioni della carta di credito vengono ribaltate al costo (4.4% + $0.30 per transazione); non addebitiamo nulla oltre a questo. +::: + +I modelli gratuiti: + +- GLM 4.7 Free e disponibile su OpenCode per un periodo limitato. Il team usa questo tempo per raccogliere feedback e migliorare il modello. +- Kimi K2.5 Free e disponibile su OpenCode per un periodo limitato. Il team usa questo tempo per raccogliere feedback e migliorare il modello. +- MiniMax M2.1 Free e disponibile su OpenCode per un periodo limitato. Il team usa questo tempo per raccogliere feedback e migliorare il modello. +- Big Pickle e un modello stealth gratuito su OpenCode per un periodo limitato. Il team usa questo tempo per raccogliere feedback e migliorare il modello. + +Contattaci se hai domande. + +--- + +### Ricarica automatica + +Se il saldo scende sotto $5, Zen ricarica automaticamente $20. + +Puoi cambiare l'importo della ricarica automatica. Puoi anche disabilitare completamente l'auto-reload. + +--- + +### Limiti mensili + +Puoi anche impostare un limite mensile di utilizzo per l'intero workspace e per ogni membro del team. + +Per esempio, se imposti un limite mensile a $20, Zen non usera piu di $20 in un mese. Ma se hai l'auto-reload attivo, Zen potrebbe finire per addebitarti piu di $20 se il saldo scende sotto $5. + +--- + +## Privacy + +Tutti i nostri modelli sono ospitati negli US. I nostri provider seguono una policy di zero-retention e non usano i tuoi dati per training dei modelli, con le seguenti eccezioni: + +- Big Pickle: durante il periodo gratuito, i dati raccolti potrebbero essere usati per migliorare il modello. +- GLM 4.7 Free: durante il periodo gratuito, i dati raccolti potrebbero essere usati per migliorare il modello. +- Kimi K2.5 Free: durante il periodo gratuito, i dati raccolti potrebbero essere usati per migliorare il modello. +- MiniMax M2.1 Free: durante il periodo gratuito, i dati raccolti potrebbero essere usati per migliorare il modello. +- OpenAI APIs: le richieste vengono conservate per 30 giorni in conformita alle [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data). +- Anthropic APIs: le richieste vengono conservate per 30 giorni in conformita alle [Anthropic's Data Policies](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## Per i team + +Zen funziona benissimo anche per i team. Puoi invitare colleghi, assegnare ruoli, curare i modelli usati dal team e altro. + +:::note +I workspace sono attualmente gratuiti per i team come parte della beta. +::: + +Gestire il workspace e attualmente gratuito per i team come parte della beta. Condivideremo presto piu dettagli sul pricing. + +--- + +### Ruoli + +Puoi invitare colleghi nel workspace e assegnare ruoli: + +- **Admin**: gestisce modelli, membri, chiavi API e fatturazione +- **Member**: gestisce solo le proprie chiavi API + +Gli admin possono anche impostare limiti mensili di spesa per ogni membro per tenere i costi sotto controllo. + +--- + +### Accesso ai modelli + +Gli admin possono abilitare o disabilitare modelli specifici per il workspace. Le richieste verso un modello disabilitato restituiscono un errore. + +Questo e utile quando vuoi disabilitare l'uso di un modello che raccoglie dati. + +--- + +### Usa le tue chiavi + +Puoi usare le tue chiavi API OpenAI o Anthropic continuando ad accedere agli altri modelli in Zen. + +Quando usi le tue chiavi, i token vengono fatturati direttamente dal provider, non da Zen. + +Per esempio, la tua organizzazione potrebbe avere gia una chiave per OpenAI o Anthropic e vuoi usare quella invece di quella fornita da Zen. + +--- + +## Obiettivi + +Abbiamo creato OpenCode Zen per: + +1. Fare **benchmark** dei migliori modelli/provider per agenti di coding. +2. Dare accesso alle opzioni di **massima qualita** senza ridurre le prestazioni o instradare verso provider piu economici. +3. Trasferire eventuali **riduzioni di prezzo** vendendo al costo; l'unico markup copre le commissioni di elaborazione. +4. Evitare **lock-in** permettendoti di usarlo con qualunque altro agente di coding e lasciandoti sempre usare anche altri provider con OpenCode. diff --git a/packages/web/src/content/docs/ja/1-0.mdx b/packages/web/src/content/docs/ja/1-0.mdx new file mode 100644 index 000000000..3a77cc02e --- /dev/null +++ b/packages/web/src/content/docs/ja/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: 1.0 への移行 +description: OpenCode 1.0 の新機能。 +--- + +OpenCode 1.0 は TUI を完全に書き直したものです。 + +私たちは、パフォーマンスと機能に問題があった go+bubbletea ベースの TUI から、zig+solidjs で書かれた社内フレームワーク (OpenTUI) に移行しました。 + +新しい TUI は、同じオープンコード サーバーに接続するため、古い TUI と同様に機能します。 + +--- + +## アップグレード中 + +現在以前のバージョンを使用している場合は、1.0 に自動アップグレードしないでください。 +バージョン。ただし、OpenCode の一部の古いバージョンは常に最新のものを取得します。 + +手動でアップグレードするには、次を実行します + +```bash +$ opencode upgrade 1.0.0 +``` + +0.x にダウングレードするには、次を実行します。 + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## UXの変更 + +セッション履歴はより圧縮されており、編集および bash ツールの完全な詳細のみが表示されます。 + +ほぼすべての操作が実行できるコマンド バーを追加しました。 Ctrl+P を押すと、任意のコンテキストでそれが表示され、実行できるすべてのことが表示されます。 + +役立つ情報を含むセッション サイドバー (切り替え可能) を追加しました。 + +実際に誰も使用しているかどうかわからないいくつかの機能を削除しました。重要な点が欠けている場合は、問題を開いてください。すぐに追加します。 + +--- + +## 重大な変更 + +### キーバインドの名前が変更されました + +- メッセージを元に戻す -> メッセージを元に戻す +- スイッチエージェント -> エージェントサイクル +- スイッチ_エージェント_リバース -> エージェント_サイクル_リバース +- スイッチモード -> エージェントサイクル +- スイッチモードリバース -> エージェントサイクルリバース + +### キーバインドが削除されました + +- メッセージ_レイアウト_トグル +- メッセージ_次 +- メッセージ_前 +- file_diff_toggle +- ファイル検索 +- ファイル_閉じる +- ファイルリスト +- アプリヘルプ +- プロジェクト初期化 +- ツールの詳細 +- 思考ブロック diff --git a/packages/web/src/content/docs/ja/acp.mdx b/packages/web/src/content/docs/ja/acp.mdx new file mode 100644 index 000000000..80e03493b --- /dev/null +++ b/packages/web/src/content/docs/ja/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACPのサポート +description: ACP 互換エディターで OpenCode を使用します。 +--- + +OpenCode は [Agent Client Protocol](https://agentclientprotocol.com) または (ACP) をサポートしているため、互換性のあるエディターや IDE で直接使用できます。 + +:::ヒント +ACP をサポートするエディターとツールのリストについては、[ACP progress report](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP は、コード エディターと AI コーディング エージェント間の通信を標準化するオープン プロトコルです。 + +--- + +## 設定する + +ACP 経由で OpenCode を使用するには、`opencode acp` コマンドを実行するようにエディタを設定します。 + +このコマンドは、stdio 経由で JSON-RPC 経由でエディターと通信する ACP 互換のサブプロセスとして OpenCode を開始します。 + +以下は、ACP をサポートする一般的なエディタの例です。 + +--- + +### ゼッド + +[Zed](https://zed.dev) 構成 (`~/.config/zed/settings.json`) に追加します。 + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +これを開くには、**コマンド パレット**の `agent: new thread` アクションを使用します。 + +`keymap.json` を編集してキーボード ショートカットをバインドすることもできます。 + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### JetBrains IDE + +[documentation](https://www.jetbrains.com/help/ai-assistant/acp.html):] に従って、[JetBrains IDE](https://www.jetbrains.com/) acp.json] に追加します。 + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +これを開くには、AI Chat エージェント セレクターで新しい「OpenCode」エージェントを使用します。 + +--- + +### アバンテ.nvim + +[Avante.nvim](https://github.com/yetone/avante.nvim) 設定に追加: + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +環境変数を渡す必要がある場合: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +[CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) で OpenCode を ACP エージェントとして使用するには、以下を Neovim 構成に追加します。 + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +この構成は、OpenCode をチャットの ACP エージェントとして使用するように CodeCompanion をセットアップします。 + +環境変数 (`OPENCODE_API_KEY` など) を渡す必要がある場合、詳細については、CodeCompanion.nvim ドキュメントの「アダプターの構成: 環境変数 ](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key)」を参照してください。 + +## サポート + +OpenCode は、ACP 経由でもターミナル内で動作するのと同じように動作します。すべての機能がサポートされています。 + +:::注記 +`/undo` や `/redo` などの一部の組み込みスラッシュ コマンドは現在サポートされていません。 +::: + +- 組み込みツール (ファイル操作、ターミナルコマンドなど) +- カスタムツールとスラッシュコマンド +- OpenCode 構成で構成された MCP サーバー +- `AGENTS.md` のプロジェクト固有のルール +- カスタムフォーマッタとリンター +- エージェントと権限システム diff --git a/packages/web/src/content/docs/ja/agents.mdx b/packages/web/src/content/docs/ja/agents.mdx new file mode 100644 index 000000000..fe912c44e --- /dev/null +++ b/packages/web/src/content/docs/ja/agents.mdx @@ -0,0 +1,747 @@ +--- +title: エージェント +description: 特殊なエージェントを構成して使用します。 +--- + +エージェントは、特定のタスクやワークフロー向けに構成できる特殊な AI アシスタントです。これらを使用すると、カスタム プロンプト、モデル、ツール アクセスを備えた焦点を絞ったツールを作成できます。 + +:::ヒント +プラン エージェントを使用すると、コードを変更せずにコードを分析し、提案を確認できます。 +::: + +セッション中にエージェントを切り替えることも、`@` メンションを使用してエージェントを呼び出すこともできます。 + +--- + +## 種類 + +OpenCode には 2 種類のエージェントがあります。プライマリエージェントとサブエージェント。 + +--- + +### 主要エージェント + +プライマリ エージェントは、直接対話する主要なアシスタントです。 **Tab** キー、または設定した `switch_agent` キーバインドを使用して、それらを切り替えることができます。これらのエージェントが主な会話を処理します。ツールへのアクセスは権限によって構成されます。たとえば、Build ではすべてのツールが有効になっていますが、Plan は制限されています。 + +:::ヒント +**Tab** キーを使用して、セッション中にプライマリ エージェントを切り替えることができます。 +::: + +OpenCode には、**Build** と **Plan** という 2 つの組み込みプライマリ エージェントが付属しています。良い +以下を見てください。 + +--- + +### サブエージェント + +サブエージェントは、プライマリ エージェントが特定のタスクのために呼び出すことができる特殊なアシスタントです。メッセージ内で **@ メンション**することで、手動で呼び出すこともできます。 + +OpenCode には、**General** と **Explore** という 2 つの組み込みサブエージェントが付属しています。これについては以下で見ていきます。 + +--- + +## 内蔵 + +OpenCode には、2 つの組み込みプライマリ エージェントと 2 つの組み込みサブエージェントが付属しています。 + +--- + +### ビルドを使用する + +_モード_: `primary` + +ビルドは、すべてのツールが有効になっている **デフォルト** プライマリ エージェントです。これは、ファイル操作やシステム コマンドへの完全なアクセスが必要な開発作業用の標準エージェントです。 + +--- + +### 利用プラン + +_モード_: `primary` + +計画と分析のために設計された制限付きエージェント。より詳細な制御を提供し、意図しない変更を防ぐために、許可システムを使用しています。 +デフォルトでは、次のすべてが `ask` に設定されます。 + +- `file edits`: すべての書き込み、パッチ、および編集 +- `bash`: すべての bash コマンド + +このエージェントは、コードベースに実際の変更を加えずに LLM にコードの分析、変更の提案、または計画の作成を行わせたい場合に役立ちます。 + +--- + +### 一般的な使用 + +_モード_: `primary` + +複雑な質問を調査し、複数ステップのタスクを実行するための汎用エージェント。完全なツール アクセス権 (todo を除く) があるため、必要に応じてファイルを変更できます。これを使用して、複数の作業単位を並行して実行します。 + +--- + +### 探索を使用する + +_モード_: `primary` + +コードベースを探索するための高速な読み取り専用エージェント。ファイルを変更できません。これは、パターンでファイルをすばやく検索したり、コードでキーワードを検索したり、コードベースに関する質問に答えたりする必要がある場合に使用します。 + +--- + +### 圧縮を使用する + +_モード_: `primary` + +長いコンテキストを小さな要約に圧縮する隠しシステム エージェント。これは必要に応じて自動的に実行され、UI では選択できません。 + +--- + +### タイトルを使用する + +_モード_: `primary` + +短いセッション タイトルを生成する非表示のシステム エージェント。これは自動的に実行され、UI では選択できません。 + +--- + +### 使用概要 + +_モード_: `primary` + +セッション概要を作成する非表示のシステム エージェント。これは自動的に実行され、UI では選択できません。 + +--- + +## 使用法 + +1. プライマリ エージェントの場合は、セッション中に **Tab** キーを使用してエージェントを切り替えます。設定した `switch_agent` キーバインドを使用することもできます。 + +2. サブエージェントは次のように呼び出すことができます。 + - プライマリ エージェントによって、説明に基づいて特殊なタスクを **自動的に** 実行されます。 + - メッセージ内でサブエージェントを **@ メンション**することで手動で実行できます。例えば。 + + ```txt frame="none" + @general help me search for this function + ``` + +3. **セッション間のナビゲーション**: サブエージェントが独自の子セッションを作成する場合、以下を使用して親セッションとすべての子セッションの間を移動できます。 + - **\+Right** (または設定した `session_child_cycle` キーバインド) で、親 → 子 1 → 子 2 → ... → 親と順に循環します。 + - **\+Left** (または設定した `session_child_cycle_reverse` キーバインド) で、親 ← 子 1 ← 子 2 ← ... ← 親を逆方向に循環します。 + +これにより、メインの会話と専門的なサブエージェントの作業をシームレスに切り替えることができます。 + +--- + +## 設定する + +組み込みエージェントをカスタマイズしたり、構成を通じて独自のエージェントを作成したりできます。エージェントは次の 2 つの方法で構成できます。 + +--- + +### JSON + +`opencode.json` 構成ファイルでエージェントを構成します。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### マークダウン + +マークダウン ファイルを使用してエージェントを定義することもできます。それらを次の場所に置きます。 + +- グローバル: `~/.config/opencode/agents/` +- プロジェクトごと: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +マークダウンファイル名がエージェント名になります。たとえば、`review.md` は `review` エージェントを作成します。 + +--- + +## オプション + +これらの構成オプションを詳しく見てみましょう。 + +--- + +### 説明 + +`description` オプションを使用して、エージェントの機能とそれをいつ使用するかについての簡単な説明を提供します。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +これは**必須**の構成オプションです。 + +--- + +### 温度 + +`temperature` 設定を使用して、LLM の応答のランダム性と創造性を制御します。 + +値が低いほど、応答はより集中的かつ決定的になりますが、値が高いほど、創造性と変動性が高まります。 + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +通常、温度値の範囲は 0.0 ~ 1.0 です。 + +- **0.0-0.2**: 非常に焦点が絞られた決定的な応答。コード分析と計画に最適です。 +- **0.3-0.5**: 創造性を備えたバランスの取れた応答。一般的な開発タスクに適しています。 +- **0.6-1.0**: より創造的で多様な応答。ブレーンストーミングや探索に役立ちます。 + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +温度が指定されていない場合、OpenCode はモデル固有のデフォルトを使用します。通常、ほとんどのモデルでは 0、Qwen モデルでは 0.55 です。 + +--- + +### 最大ステップ数 + +エージェントが強制的にテキストのみで応答するまでに実行できるエージェントの反復の最大数を制御します。これにより、コストを管理したいユーザーは、エージェントのアクションに制限を設定できます。 + +これが設定されていない場合、エージェントは、モデルが停止を選択するか、ユーザーがセッションを中断するまで反復を続けます。 + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +制限に達すると、エージェントは、作業の概要と推奨される残りのタスクを応答するように指示する特別なシステム プロンプトを受け取ります。 + +:::注意 +従来の `maxSteps` フィールドは非推奨になりました。代わりに `steps` を使用してください。 +::: + +--- + +### 無効にする + +エージェントを無効にするには、`true` に設定します。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### プロンプト + +`prompt` 構成を使用して、このエージェントのカスタム システム プロンプト ファイルを指定します。プロンプト ファイルには、エージェントの目的に固有の指示が含まれている必要があります。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +このパスは、構成ファイルが配置されている場所に対する相対パスです。したがって、これはグローバルな OpenCode 構成とプロジェクト固有の構成の両方で機能します。 + +--- + +### モデル + +`model` 構成を使用して、このエージェントのモデルをオーバーライドします。さまざまなタスクに最適化されたさまざまなモデルを使用する場合に役立ちます。たとえば、計画にはより高速なモデルを、実装にはより有能なモデルを使用します。 + +:::ヒント +モデルを指定しない場合、プライマリ エージェントは [グローバルに設定されたモデル ](/docs/config#models) を使用し、サブエージェントはサブエージェントを呼び出したプライマリ エージェントのモデルを使用します。 +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +OpenCode 構成内のモデル ID は、`provider/model-id` という形式を使用します。たとえば、[OpenCode Zen](/docs/zen) を使用している場合、GPT 5.1 Codex には `opencode/gpt-5.1-codex` を使用します。 + +--- + +### ツール + +`tools` 構成を使用して、このエージェントで使用できるツールを制御します。特定のツールを `true` または `false` に設定することで、有効または無効にすることができます。 + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::注記 +エージェント固有の設定はグローバル設定をオーバーライドします。 +::: + +ワイルドカードを使用して複数のツールを一度に制御することもできます。たとえば、MCP サーバーからすべてのツールを無効にするには、次のようにします。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[tools](/docs/tools) について詳しくはこちらをご覧ください。 + +--- + +### 権限 + +権限を設定して、エージェントが実行できるアクションを管理できます。現在、`edit`、`bash`、および `webfetch` ツールの権限は次のように構成できます。 + +- `"ask"` — ツールを実行する前に承認を求めるプロンプトを表示する +- `"allow"` — 承認なしですべての操作を許可する +- `"deny"` — ツールを無効にする + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +これらの権限はエージェントごとにオーバーライドできます。 + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +Markdown エージェントで権限を設定することもできます。 + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +特定の bash コマンドに対するアクセス許可を設定できます。 + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +これにはグロブ パターンを使用できます。 + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +また、`*` ワイルドカードを使用して、すべてのコマンドの権限を管理することもできます。 +最後に一致したルールが優先されるため、`*` ワイルドカードを最初に置き、特定のルールを後に置きます。 + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[権限](/docs/permissions)について詳しくはこちらをご覧ください。 + +--- + +### モード + +`mode` 設定を使用してエージェントのモードを制御します。 `mode` オプションは、エージェントの使用方法を決定するために使用されます。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +`mode` オプションは、`primary`、`subagent`、または `all` に設定できます。 `mode` が指定されていない場合、デフォルトは `all` になります。 + +--- + +### 隠れた + +`hidden: true` を使用して、`@` オートコンプリート メニューからサブエージェントを非表示にします。他のエージェントによってタスク ツールを介してプログラム的にのみ呼び出す必要がある内部サブエージェントに役立ちます。 + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +これは、オートコンプリート メニューでのユーザーの表示にのみ影響します。権限が許可されていれば、非表示のエージェントをタスク ツール経由でモデルから呼び出すことができます。 + +:::注記 +`mode: subagent` エージェントにのみ適用されます。 +::: + +--- + +### タスクの権限 + +`permission.task` を使用して、エージェントがタスク ツール経由でどのサブエージェントを呼び出すことができるかを制御します。柔軟なマッチングのためにグロブ パターンを使用します。 + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +`deny` に設定すると、サブエージェントはタスク ツールの説明から完全に削除されるため、モデルはそれを呼び出そうとしません。 + +:::ヒント +ルールは順番に評価され、**最後に一致したルールが優先されます**。上記の例では、`orchestrator-planner` は `*` (拒否) と `orchestrator-*` (許可) の両方に一致しますが、`orchestrator-*` は `*` の後に来るため、結果は `allow` になります。 +::: + +:::ヒント +ユーザーは、エージェントのタスク権限が拒否する場合でも、`@` オートコンプリート メニューを介して、いつでもサブエージェントを直接呼び出すことができます。 +::: + +--- + +### 色 + +`color` オプションを使用して、UI でのエージェントの外観をカスタマイズします。これは、インターフェイスでのエージェントの表示方法に影響します。 + +有効な 16 進カラー (例: `#FF5733`) またはテーマカラー: `primary`、`secondary`、`accent`、`success`、`warning`、`error`、`info` を使用します。 + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### トップP + +`top_p` オプションで応答の多様性を制御します。ランダム性を制御するための温度の代替手段。 + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +値の範囲は 0.0 ~ 1.0 です。値が低いほど集中力が高まり、値が高いほど多様性が高まります。 + +--- + +### 追加 + +エージェント設定で指定したその他のオプションはすべて、モデル オプションとしてプロバイダーに**直接渡されます**。これにより、プロバイダー固有の機能とパラメーターを使用できるようになります。 + +たとえば、OpenAI の推論モデルを使用すると、推論の労力を制御できます。 + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +これらの追加オプションはモデルとプロバイダーに固有です。使用可能なパラメータについては、プロバイダのドキュメントを確認してください。 + +:::ヒント +`opencode models` を実行して、利用可能なモデルのリストを表示します。 +::: + +--- + +## エージェントの作成 + +次のコマンドを使用して、新しいエージェントを作成できます。 + +```bash +opencode agent create +``` + +この対話型コマンドは次のことを行います。 + +1. エージェントを保存する場所を尋ねます。グローバルまたはプロジェクト固有。 +2. エージェントが行うべきことの説明。 +3. 適切なシステム プロンプトと識別子を生成します。 +4. エージェントがアクセスできるツールを選択できます。 +5. 最後に、エージェント構成を含むマークダウン ファイルを作成します。 + +--- + +## ユースケース + +さまざまなエージェントの一般的な使用例をいくつか示します。 + +- **ビルド エージェント**: すべてのツールを有効にした完全な開発作業 +- **計画エージェント**: 変更を加えずに分析および計画を立てる +- **レビュー エージェント**: 読み取り専用アクセスとドキュメント ツールを備えたコード レビュー +- **デバッグ エージェント**: bash および読み取りツールを有効にして調査に重点を置きます +- **ドキュメント エージェント**: ファイル操作を使用してドキュメントを作成しますが、システム コマンドは使用しません + +--- + +## 例 + +以下に、役立つと思われるエージェントの例をいくつか示します。 + +:::ヒント +共有したいエージェントはいますか? [PR](https://github.com/anomalyco/opencode) を送信します。 +::: + +--- + +### 文書作成エージェント + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### セキュリティ監査人 + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/ja/cli.mdx b/packages/web/src/content/docs/ja/cli.mdx new file mode 100644 index 000000000..cea73f960 --- /dev/null +++ b/packages/web/src/content/docs/ja/cli.mdx @@ -0,0 +1,601 @@ +--- +title: CLI +description: OpenCode CLI のオプションとコマンド。 +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode CLI は、引数なしで実行すると、デフォルトで [TUI](/docs/tui) を開始します。 + +```bash +opencode +``` + +ただし、このページに記載されているようにコマンドも受け入れます。これにより、OpenCode をプログラム的に操作できるようになります。 + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### トゥイ + +OpenCode ターミナル ユーザー インターフェイスを開始します。 + +```bash +opencode [project] +``` + +#### フラグ + +|旗 |ショート |説明 | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` |最後のセッションを続行 | +| `--session` | `-s` |続行するセッション ID | +| `--prompt` | |使用のプロンプト | +| `--model` | `-m` |プロバイダー/モデルの形式で使用するモデル | +| `--agent` | |使用するエージェント | +| `--port` | |リッスンするポート | +| `--hostname` | |リッスンするホスト名 | + +--- + +## コマンド + +OpenCode CLI には次のコマンドもあります。 + +--- + +### エージェント + +OpenCode のエージェントを管理します。 + +```bash +opencode agent [command] +``` + +--- + +### 付ける + +`serve` または `web` コマンドを使用して起動された、すでに実行中の OpenCode バックエンド サーバーにターミナルを接続します。 + +```bash +opencode attach [url] +``` + +これにより、リモート OpenCode バックエンドで TUI を使用できるようになります。例えば: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### フラグ + +|旗 |ショート |説明 | +| ----------- | ----- | --------------------------------- | +| `--dir` | | TUI を開始する作業ディレクトリ | +| `--session` | `-s` |続行するセッション ID | + +--- + +#### 作成する + +カスタム構成で新しいエージェントを作成します。 + +```bash +opencode agent create +``` + +このコマンドは、カスタム システム プロンプトとツール構成を使用して新しいエージェントを作成する手順を示します。 + +--- + +#### リスト + +利用可能なエージェントをすべてリストします。 + +```bash +opencode agent list +``` + +--- + +### 認証 + +プロバイダーの資格情報とログインを管理するコマンド。 + +```bash +opencode auth [command] +``` + +--- + +#### ログイン + +OpenCode は [Models.dev](https://models.dev) のプロバイダー リストを利用しているため、`opencode auth login` を使用して、使用したいプロバイダーの API キーを構成できます。これは`~/.local/share/opencode/auth.json`に保存されます。 + +```bash +opencode auth login +``` + +OpenCode が起動すると、認証情報ファイルからプロバイダーがロードされます。また、環境またはプロジェクト内の `.env` ファイルで定義されたキーがあるかどうかも確認します。 + +--- + +#### リスト + +認証情報ファイルに保存されているすべての認証されたプロバイダーをリストします。 + +```bash +opencode auth list +``` + +またはショートバージョン。 + +```bash +opencode auth ls +``` + +--- + +#### ログアウト + +資格情報ファイルからプロバイダーをクリアすることで、プロバイダーからログアウトします。 + +```bash +opencode auth logout +``` + +--- + +### ギットハブ + +リポジトリ自動化のための GitHub エージェントを管理します。 + +```bash +opencode github [command] +``` + +--- + +#### インストール + +GitHub エージェントをリポジトリにインストールします。 + +```bash +opencode github install +``` + +これにより、必要な GitHub Actions ワークフローが設定され、構成プロセスがガイドされます。 [詳細はこちら](/docs/github)。 + +--- + +#### 走る + +GitHub エージェントを実行します。これは通常、GitHub Actions で使用されます。 + +```bash +opencode github run +``` + +##### フラグ + +|旗 |説明 | +| --------- | -------------------------------------- | +| `--event` |エージェントを実行するための GitHub モック イベント | +| `--token` | GitHub個人アクセストークン | + +--- + +### mcp + +モデル コンテキスト プロトコル サーバーを管理します。 + +```bash +opencode mcp [command] +``` + +--- + +#### 追加 + +MCP サーバーを構成に追加します。 + +```bash +opencode mcp add +``` + +このコマンドは、ローカルまたはリモートの MCP サーバーを追加する手順を示します。 + +--- + +#### リスト + +構成されているすべての MCP サーバーとその接続ステータスをリストします。 + +```bash +opencode mcp list +``` + +または、短いバージョンを使用してください。 + +```bash +opencode mcp ls +``` + +--- + +#### 認証 + +OAuth 対応の MCP サーバーで認証します。 + +```bash +opencode mcp auth [name] +``` + +サーバー名を指定しない場合は、利用可能な OAuth 対応サーバーから選択するように求められます。 + +OAuth 対応サーバーとその認証ステータスを一覧表示することもできます。 + +```bash +opencode mcp auth list +``` + +または、短いバージョンを使用してください。 + +```bash +opencode mcp auth ls +``` + +--- + +#### ログアウト + +MCP サーバーの OAuth 資格情報を削除します。 + +```bash +opencode mcp logout [name] +``` + +--- + +#### デバッグ + +MCP サーバーの OAuth 接続の問題をデバッグします。 + +```bash +opencode mcp debug +``` + +--- + +### モデル + +構成されたプロバイダーから利用可能なすべてのモデルをリストします。 + +```bash +opencode models [provider] +``` + +このコマンドは、構成されたプロバイダー全体で利用可能なすべてのモデルを `provider/model` の形式で表示します。 + +これは、config](/docs/config/) で使用する正確なモデル名を把握するのに役立ちます。 + +オプションでプロバイダー ID を渡して、そのプロバイダーによってモデルをフィルターできます。 + +```bash +opencode models anthropic +``` + +#### フラグ + +|旗 |説明 | +| ----------- | ------------------------------------------------------------ | +| `--refresh` | models.dev からモデル キャッシュを更新します。 +| `--verbose` |より詳細なモデル出力を使用します (コストなどのメタデータを含む) | + +`--refresh` フラグを使用して、キャッシュされたモデル リストを更新します。これは、新しいモデルがプロバイダーに追加され、それを OpenCode で確認したい場合に便利です。 + +```bash +opencode models --refresh +``` + +--- + +### 走る + +プロンプトを直接渡して、非対話モードでオープンコードを実行します。 + +```bash +opencode run [message..] +``` + +これは、スクリプト作成、自動化、または完全な TUI を起動せずに迅速な回答が必要な場合に便利です。例えば。 + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +実行中の `opencode serve` インスタンスにアタッチして、実行ごとの MCP サーバーのコールド ブート時間を回避することもできます。 + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### フラグ + +|旗 |ショート |説明 | +| ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | |実行するコマンド。引数には message を使用します。 +| `--continue` | `-c` |最後のセッションを続行 | +| `--session` | `-s` |続行するセッション ID | +| `--share` | |セッションを共有する | +| `--model` | `-m` |プロバイダー/モデルの形式で使用するモデル | +| `--agent` | |使用するエージェント | +| `--file` | `-f` |メッセージに添付するファイル | +| `--format` | |形式: デフォルト (フォーマット済み) または json (生の JSON イベント) | +| `--title` | |セッションのタイトル (値が指定されていない場合は、切り詰められたプロンプトが使用されます) | +| `--attach` | |実行中のオープンコードサーバー (http://localhost:4096 など) に接続します。 +| `--port` | |ローカルサーバーのポート (デフォルトはランダムポート) | + +--- + +### 仕える + +API アクセスのためにヘッドレス OpenCode サーバーを起動します。完全な HTTP インターフェイスについては、[server docs](/docs/server) を確認してください。 + +```bash +opencode serve +``` + +これにより、TUI インターフェイスを使用せずにオープンコード機能への API アクセスを提供する HTTP サーバーが起動します。 `OPENCODE_SERVER_PASSWORD` を設定して HTTP 基本認証を有効にします (ユーザー名のデフォルトは `opencode`)。 + +#### フラグ + +|旗 |説明 | +| ------------ | ------------------------------------------ | +| `--port` |リッスンするポート | +| `--hostname` |リッスンするホスト名 | +| `--mdns` | mDNS 検出を有効にする | +| `--cors` | CORS を許可する追加のブラウザーオリジン | + +--- + +### セッション + +OpenCode セッションを管理します。 + +```bash +opencode session [command] +``` + +--- + +#### リスト + +すべての OpenCode セッションをリストします。 + +```bash +opencode session list +``` + +##### フラグ + +|旗 |ショート |説明 | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` |最新のセッションを N 個に制限 | +| `--format` | |出力形式: テーブルまたは json (テーブル) | + +--- + +### 統計 + +OpenCode セッションのトークンの使用状況とコストの統計を表示します。 + +```bash +opencode stats +``` + +#### フラグ + +|旗 |説明 | +| ----------- | --------------------------------------------------------------------------- | +| `--days` |過去 N 日間の統計を表示 (すべての時間) | +| `--tools` |表示するツールの数 (すべて) | +| `--models` |モデルの使用状況の内訳を表示します (デフォルトでは非表示)。上位 N | を表示するには、数値を渡します。 +| `--project` |プロジェクトによるフィルター (すべてのプロジェクト、空の文字列: 現在のプロジェクト) | + +--- + +### 輸出 + +セッションデータをJSONとしてエクスポートします。 + +```bash +opencode export [sessionID] +``` + +セッション ID を指定しない場合は、利用可能なセッションから選択するように求められます。 + +--- + +### 輸入 + +JSON ファイルまたは OpenCode 共有 URL からセッション データをインポートします。 + +```bash +opencode import +``` + +ローカル ファイルまたは OpenCode 共有 URL からインポートできます。 + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### ウェブ + +Web インターフェイスを使用してヘッドレス OpenCode サーバーを起動します。 + +```bash +opencode web +``` + +これにより、HTTP サーバーが起動し、Web ブラウザが開き、Web インターフェイスを通じて OpenCode にアクセスします。 `OPENCODE_SERVER_PASSWORD` を設定して HTTP 基本認証を有効にします (ユーザー名のデフォルトは `opencode`)。 + +#### フラグ + +|旗 |説明 | +| ------------ | ------------------------------------------ | +| `--port` |リッスンするポート | +| `--hostname` |リッスンするホスト名 | +| `--mdns` | mDNS 検出を有効にする | +| `--cors` | CORS を許可する追加のブラウザーオリジン | + +--- + +### acp + +ACP (エージェント クライアント プロトコル) サーバーを起動します。 + +```bash +opencode acp +``` + +このコマンドは、nd-JSON を使用して stdin/stdout 経由で通信する ACP サーバーを起動します。 + +#### フラグ + +|旗 |説明 | +| ------------ | --------------------- | +| `--cwd` |作業ディレクトリ | +| `--port` |リッスンするポート | +| `--hostname` |リッスンするホスト名 | + +--- + +### アンインストールする + +OpenCode をアンインストールし、関連ファイルをすべて削除します。 + +```bash +opencode uninstall +``` + +#### フラグ + +|旗 |ショート |説明 | +| --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` |設定ファイルを保持する | +| `--keep-data` | `-d` |セッション データとスナップショットを保持する | +| `--dry-run` | | | を削除せずに削除されるものを表示します。 +| `--force` | `-f` |確認プロンプトをスキップする | + +--- + +### アップグレード + +オープンコードを最新バージョンまたは特定のバージョンに更新します。 + +```bash +opencode upgrade [target] +``` + +最新バージョンにアップグレードするには。 + +```bash +opencode upgrade +``` + +特定のバージョンにアップグレードするには。 + +```bash +opencode upgrade v0.1.48 +``` + +#### フラグ + +|旗 |ショート |説明 | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` |使用されたインストール方法。カール、npm、pnpm、バン、醸造 | + +--- + +## グローバルフラグ + +opencode CLI は次のグローバル フラグを受け取ります。 + +|旗 |ショート |説明 | +| -------------- | ----- | ------------------------------------ | +| `--help` | `-h` |ヘルプを表示 | +| `--version` | `-v` |バージョン番号を出力 | +| `--print-logs` | |ログを標準エラー出力に出力 | +| `--log-level` | |ログ レベル (DEBUG、INFO、WARN、ERROR) | + +--- + +## 環境変数 + +OpenCode は環境変数を使用して構成できます。 + +|変数 |タイプ |説明 | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` |ブール値 |セッションを自動的に共有する | +| `OPENCODE_GIT_BASH_PATH` |文字列 | Windows 上で実行可能な Git Bash へのパス | +| `OPENCODE_CONFIG` |文字列 |構成ファイルへのパス | +| `OPENCODE_CONFIG_DIR` |文字列 | config ディレクトリへのパス | +| `OPENCODE_CONFIG_CONTENT` |文字列 |インライン JSON 構成コンテンツ | +| `OPENCODE_DISABLE_AUTOUPDATE` |ブール値 |自動更新チェックを無効にする | +| `OPENCODE_DISABLE_PRUNE` |ブール値 |古いデータのプルーニングを無効にする | +| `OPENCODE_DISABLE_TERMINAL_TITLE` |ブール値 |端末タイトルの自動更新を無効にする | +| `OPENCODE_PERMISSION` |文字列 |インライン化された json 権限設定 | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` |ブール値 |デフォルトのプラグインを無効にする | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` |ブール値 | LSP サーバーの自動ダウンロードを無効にする | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` |ブール値 |実験モデルを有効にする | +| `OPENCODE_DISABLE_AUTOCOMPACT` |ブール値 |自動コンテキスト圧縮を無効にする | +| `OPENCODE_DISABLE_CLAUDE_CODE` |ブール値 | `.claude` からの読み取りを無効にする (プロンプト + スキル) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` |ブール値 | `~/.claude/CLAUDE.md` の読み取りを無効にする | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` |ブール値 | `.claude/skills` のロードを無効にする | +| `OPENCODE_DISABLE_MODELS_FETCH` |ブール値 |リモート ソースからのモデルの取得を無効にする | +| `OPENCODE_FAKE_VCS` |文字列 |テスト目的の偽の VCS プロバイダー | +| `OPENCODE_DISABLE_FILETIME_CHECK` |ブール値 |最適化のためにファイル時間チェックを無効にする | +| `OPENCODE_CLIENT` |文字列 |クライアント識別子 (デフォルトは `cli`) | +| `OPENCODE_ENABLE_EXA` |ブール値 | Exa Web 検索ツールを有効にする | +| `OPENCODE_SERVER_PASSWORD` |文字列 | `serve`/`web` の基本認証を有効にする | +| `OPENCODE_SERVER_USERNAME` |文字列 |基本認証ユーザー名 (デフォルト `opencode`) をオーバーライドします。 +| `OPENCODE_MODELS_URL` |文字列 |モデル設定を取得するためのカスタム URL | + +--- + +### 実験的 + +これらの環境変数により、変更または削除される可能性のある実験的な機能が有効になります。 + +|変数 |タイプ |説明 | +| ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` |ブール値 |すべての実験的機能を有効にする | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` |ブール値 |アイコン検出を有効にする | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` |ブール値 | TUI で選択時のコピーを無効にする | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` |番号 | bash コマンドのデフォルトのタイムアウト (ミリ秒) | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` |番号 | LLM 応答の最大出力トークン | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` |ブール値 |ディレクトリ全体のファイル監視を有効にする | +| `OPENCODE_EXPERIMENTAL_OXFMT` |ブール値 | oxfmt フォーマッタを有効にする | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` |ブール値 |実験的な LSP ツールを有効にする | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` |ブール値 |ファイルウォッチャーを無効にする | +| `OPENCODE_EXPERIMENTAL_EXA` |ブール値 |実験的な Exa 機能を有効にする | +| `OPENCODE_EXPERIMENTAL_LSP_TY` |ブール値 |実験的な LSP タイプ チェックを有効にする | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` |ブール値 |試験的なマークダウン機能を有効にする | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` |ブール値 |プランモードを有効にする | diff --git a/packages/web/src/content/docs/ja/commands.mdx b/packages/web/src/content/docs/ja/commands.mdx new file mode 100644 index 000000000..90c42199b --- /dev/null +++ b/packages/web/src/content/docs/ja/commands.mdx @@ -0,0 +1,323 @@ +--- +title: コマンド +description: 反復的なタスク用のカスタム コマンドを作成します。 +--- + +カスタム コマンドを使用すると、TUI でコマンドを実行するときに実行するプロンプトを指定できます。 + +```bash frame="none" +/my-command +``` + +カスタム コマンドは、`/init`、`/undo`、`/redo`、`/share`、`/help` などの組み込みコマンドに追加されます。 [詳細はこちら](/docs/tui#commands)。 + +--- + +## コマンドファイルの作成 + +カスタム コマンドを定義するには、`commands/` ディレクトリにマークダウン ファイルを作成します。 + +`.opencode/commands/test.md` を作成します。 + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +フロントマターはコマンドのプロパティを定義します。内容がテンプレートとなります。 + +`/` に続けてコマンド名を入力して、コマンドを使用します。 + +```bash frame="none" +"/test" +``` + +--- + +## 設定する + +カスタム コマンドは、OpenCode 構成を通じて、または `commands/` ディレクトリにマークダウン ファイルを作成することによって追加できます。 + +--- + +### JSON + +OpenCode で `command` オプションを使用します [config](/docs/config): + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +これで、TUI で次のコマンドを実行できるようになります。 + +```bash frame="none" +/test +``` + +--- + +### マークダウン + +マークダウン ファイルを使用してコマンドを定義することもできます。それらを次の場所に置きます。 + +- グローバル: `~/.config/opencode/agents/` +- プロジェクトごと: `.opencode/agents/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +マークダウンファイル名がコマンド名になります。たとえば、`test.md` を使用すると、 +あなたは実行します: + +```bash frame="none" +/test +``` + +--- + +## プロンプト構成 + +カスタム コマンドのプロンプトは、いくつかの特別なプレースホルダーと構文をサポートしています。 + +--- + +### 引数 + +`$ARGUMENTS` プレースホルダーを使用してコマンドに引数を渡します。 + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +引数を指定してコマンドを実行します。 + +```bash frame="none" +/component Button +``` + +そして、`$ARGUMENTS` は `Button` に置き換えられます。 + +位置パラメータを使用して個々の引数にアクセスすることもできます。 + +- `$1` - 最初の引数 +- `$2` - 2 番目の引数 +- `$3` - 3 番目の引数 +- 等々... + +例えば: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +次のコマンドを実行します。 + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +これは以下を置き換えます。 + +- `$1` と `config.json` +- `$1` と `config.json` +- `$1` と `config.json` + +--- + +### シェル出力 + +_!`command`_ を使用して、[bash command](/docs/tui#bash-commands) の出力をプロンプトに挿入します。 + +たとえば、テスト カバレッジを分析するカスタム コマンドを作成するには、次のようにします。 + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +または、最近の変更を確認するには: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +コマンドはプロジェクトのルート ディレクトリで実行され、その出力はプロンプトの一部になります。 + +--- + +### ファイル参照 + +`@` の後にファイル名を指定して、コマンドにファイルを含めます。 + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +ファイルの内容はプロンプトに自動的に含まれます。 + +--- + +## オプション + +構成オプションを詳しく見てみましょう。 + +--- + +### テンプレート + +`template` オプションは、コマンドの実行時に LLM に送信されるプロンプトを定義します。 + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +これは**必須**の構成オプションです。 + +--- + +### 説明 + +`description` オプションを使用して、コマンドの動作の簡単な説明を入力します。 + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +これは、コマンドを入力すると TUI に説明として表示されます。 + +--- + +### エージェント + +オプションで、`agent` 設定を使用して、このコマンドを実行する [agent](/docs/agents) を指定します。 +これが [subagent](/docs/agents/#subagents) の場合、コマンドはデフォルトでサブエージェントの呼び出しをトリガーします。 +この動作を無効にするには、`subtask` を `false` に設定します。 + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +これは**オプション**の構成オプションです。指定しない場合、デフォルトで現在のエージェントが使用されます。 + +--- + +### サブタスク + +`subtask` ブール値を使用して、コマンドが [subagent](/docs/agents/#subagents) 呼び出しを強制的にトリガーします。 +これは、コマンドがプライマリ コンテキストを汚染せず、エージェントがサブエージェントとして動作するように**強制**する場合に便利です。 +[agent](/docs/agents) 設定で `mode` が `primary` に設定されている場合でも。 + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +これは**オプション**の構成オプションです。 + +--- + +### モデル + +`model` 設定を使用して、このコマンドのデフォルト モデルをオーバーライドします。 + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +これは**オプション**の構成オプションです。 + +--- + +## 内蔵 + +opencode には、`/init`、`/undo`、`/redo`、`/share`、`/help` などのいくつかの組み込みコマンドが含まれています。 [詳細はこちら](/docs/tui#commands)。 + +:::注記 +カスタム コマンドは組み込みコマンドをオーバーライドできます。 +::: + +同じ名前のカスタム コマンドを定義すると、組み込みコマンドがオーバーライドされます。 diff --git a/packages/web/src/content/docs/ja/config.mdx b/packages/web/src/content/docs/ja/config.mdx new file mode 100644 index 000000000..abe906592 --- /dev/null +++ b/packages/web/src/content/docs/ja/config.mdx @@ -0,0 +1,685 @@ +--- +title: 構成 +description: OpenCode JSON 構成を使用します。 +--- + +JSON 構成ファイルを使用して OpenCode を構成できます。 + +--- + +## 形式 + +OpenCode は、**JSON** と **JSONC** (コメント付きの JSON) 形式の両方をサポートしています。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## 所在地 + +構成をいくつかの異なる場所に配置できます。 +優先順位が違う。 + +:::注記 +構成ファイルは置き換えられるのではなく、**マージ**されます。 +::: + +構成ファイルは置き換えられるのではなく、マージされます。次の構成場所の設定が結合されます。後の構成は、キーが競合する場合にのみ、以前の構成をオーバーライドします。すべての構成からの競合しない設定は保持されます。 + +たとえば、グローバル設定で `theme: "opencode"` と `autoupdate: true` が設定され、プロジェクト設定で `model: "anthropic/claude-sonnet-4-5"` が設定されている場合、最終的な設定には 3 つの設定がすべて含まれます。 + +--- + +### 優先順位 + +構成ソースは次の順序でロードされます (後のソースは前のソースをオーバーライドします)。 + +1. **リモート設定** (`.well-known/opencode` から) - 組織のデフォルト +2. **グローバル設定** (`~/.config/opencode/opencode.json`) - ユーザー設定 +3. **カスタム構成** (`OPENCODE_CONFIG` 環境変数) - カスタム オーバーライド +4. **プロジェクト構成** (プロジェクト内の`opencode.json`) - プロジェクト固有の設定 +5. **`.opencode` ディレクトリ** - エージェント、コマンド、プラグイン +6. **インライン構成** (`OPENCODE_CONFIG_CONTENT` 環境変数) - ランタイムオーバーライド + +つまり、プロジェクト構成はグローバルのデフォルトをオーバーライドでき、グローバル構成はリモート組織のデフォルトをオーバーライドできます。 + +:::注記 +`.opencode` および `~/.config/opencode` ディレクトリでは、サブディレクトリに **複数名** が使用されています: `agents/`、`commands/`、`modes/`、`plugins/`、`skills/`、`tools/`、および `themes/`。下位互換性のために、単数形の名前 (`agent/` など) もサポートされています。 +::: + +--- + +### リモート + +組織は、`.well-known/opencode` エンドポイント経由でデフォルト構成を提供できます。これは、それをサポートするプロバイダーで認証するときに自動的に取得されます。 + +リモート設定が最初にロードされ、基本層として機能します。他のすべての構成ソース (グローバル、プロジェクト) は、これらのデフォルトをオーバーライドできます。 + +たとえば、組織がデフォルトで無効になっている MCP サーバーを提供している場合: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +ローカル設定で特定のサーバーを有効にすることができます。 + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### グローバル + +グローバル OpenCode 構成を `~/.config/opencode/opencode.json` に配置します。テーマ、プロバイダー、キーバインドなどのユーザー全体の設定にはグローバル設定を使用します。 + +グローバル設定はリモート組織のデフォルトをオーバーライドします。 + +--- + +### プロジェクトごと + +プロジェクトのルートに `opencode.json` を追加します。プロジェクト構成は、標準構成ファイルの中で最も高い優先順位を持ち、グローバル構成とリモート構成の両方をオーバーライドします。 + +:::ヒント +プロジェクト固有の構成をプロジェクトのルートに配置します。 +::: + +OpenCode が起動すると、現在のディレクトリで構成ファイルを検索するか、最も近い Git ディレクトリまで移動します。 + +これは Git に安全にチェックインでき、グローバル スキーマと同じスキーマを使用します。 + +--- + +### カスタムパス + +`OPENCODE_CONFIG` 環境変数を使用してカスタム構成ファイルのパスを指定します。 + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +カスタム構成は、優先順位でグローバル構成とプロジェクト構成の間にロードされます。 + +--- + +### カスタムディレクトリ + +`OPENCODE_CONFIG_DIR` を使用してカスタム構成ディレクトリを指定します。 +環境変数。このディレクトリでは、エージェント、コマンド、 +モードとプラグインは標準の `.opencode` ディレクトリと同様であり、次のようにする必要があります。 +同じ構造に従います。 + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +カスタム ディレクトリはグローバル config ディレクトリと `.opencode` ディレクトリの後にロードされるため、それらの設定を**オーバーライド**できます。 + +--- + +## スキーマ + +構成ファイルには、[**`opencode.ai/config.json`**](https://opencode.ai/config.json). + +エディターはスキーマに基づいて検証し、オートコンプリートできる必要があります。 + +--- + +### トゥイ + +`tui` オプションを使用して TUI 固有の設定を構成できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +利用可能なオプション: + +- `scroll_acceleration.enabled` - macOS スタイルのスクロール アクセラレーションを有効にします。 **`scroll_speed` よりも優先されます。** +- `scroll_speed` - カスタムのスクロール速度乗数 (デフォルト: `3`、最小: `1`)。 `scroll_acceleration.enabled` が `true` の場合は無視されます。 +- `diff_style` - 差分レンダリングを制御します。 `"auto"` は端末の幅に適応し、`"stacked"` は常に 1 列を表示します。 + +[TUI の使用方法の詳細については、こちら](/docs/tui) をご覧ください。 + +--- + +### サーバ + +`server` オプションを使用して、`opencode serve` および `opencode web` コマンドのサーバー設定を構成できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +利用可能なオプション: + +- `port` - リッスンするポート。 +- `hostname` - リッスンするホスト名。 `mdns` が有効でホスト名が設定されていない場合、デフォルトは `0.0.0.0` になります。 +- `mdns` - mDNS サービス検出を有効にします。これにより、ネットワーク上の他のデバイスが OpenCode サーバーを検出できるようになります。 +- `mdnsDomain` - mDNS サービスのカスタム ドメイン名。デフォルトは `opencode.local` です。同じネットワーク上で複数のインスタンスを実行する場合に便利です。 +- `cors` - ブラウザベースのクライアントから HTTP サーバーを使用するときに CORS を許可する追加のオリジン。値は完全なオリジン (スキーム + ホスト + オプションのポート) である必要があります (例: `https://app.example.com`)。 + +[サーバーの詳細については、こちら](/docs/server)をご覧ください。 + +--- + +### ツール + +LLM が使用できるツールは、`tools` オプションを通じて管理できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[ツールの詳細については、こちらをご覧ください](/docs/tools)。 + +--- + +### モデル + +`provider`、`model`、および `small_model` オプションを使用して、OpenCode 構成で使用するプロバイダーとモデルを構成できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +`small_model` オプションは、タイトル生成などの軽量タスク用に別のモデルを構成します。デフォルトでは、OpenCode は、プロバイダーから安価なモデルが入手可能な場合は、より安価なモデルを使用しようとします。そうでない場合は、メイン モデルにフォールバックします。 + +プロバイダー オプションには、`timeout` および `setCacheKey` を含めることができます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - リクエストのタイムアウト (ミリ秒単位) (デフォルト: 300000)。無効にするには、`false` に設定します。 +- `setCacheKey` - 指定されたプロバイダーに対してキャッシュ キーが常に設定されていることを確認します。 + +[ローカルモデル](/docs/models#local). [詳細はこちら](/docs/models)。 + +--- + +#### プロバイダー固有のオプション + +一部のプロバイダーは、一般的な `timeout` および `apiKey` 設定を超える追加の構成オプションをサポートしています。 + +##### アマゾンの岩盤 + +Amazon Bedrock は、AWS 固有の構成をサポートしています。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - Bedrock の AWS リージョン (デフォルトは `AWS_REGION` 環境変数または `us-east-1`) +- `profile` - `~/.aws/credentials` からの AWS 名前付きプロファイル (デフォルトは `AWS_PROFILE` 環境変数) +- `endpoint` - VPC エンドポイントのカスタム エンドポイント URL。これは、AWS 固有の用語を使用した汎用 `baseURL` オプションのエイリアスです。両方を指定した場合は、`endpoint` が優先されます。 + +:::注記 +ベアラー トークン (`AWS_BEARER_TOKEN_BEDROCK` または `/connect`) は、プロファイルベースの認証より優先されます。詳細については、「認証優先順位](/docs/providers#authentication-precedence)」を参照してください。 +::: + +[Amazon Bedrock 構成 ](/docs/providers#amazon-bedrock) の詳細をご覧ください。 + +--- + +### テーマ + +`theme` オプションを使用して、OpenCode 構成で使用するテーマを構成できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[詳細はこちら](/docs/themes)。 + +--- + +### エージェント + +`agent` オプションを使用して、特定のタスクに特化したエージェントを構成できます。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +`~/.config/opencode/agents/` または `.opencode/agents/` のマークダウン ファイルを使用してエージェントを定義することもできます。 [詳細はこちら](/docs/agents)。 + +--- + +### デフォルトエージェント + +`default_agent` オプションを使用してデフォルトのエージェントを設定できます。これにより、明示的に何も指定されていない場合にどのエージェントが使用されるかが決まります。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +デフォルトのエージェントはプライマリ エージェントである必要があります (サブエージェントではありません)。これは、`"build"` や `"plan"` のような組み込みエージェント、または定義したカスタム Agent](/docs/agents) にすることができます。指定されたエージェントが存在しないか、サブエージェントである場合、OpenCode は警告とともに `"build"` にフォールバックします。 + +この設定は、TUI、CLI (`opencode run`)、デスクトップ アプリ、および GitHub Action のすべてのインターフェイスに適用されます。 + +--- + +### 共有 + +`share` オプションを使用して [share](/docs/share) 機能を設定できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +これには以下が必要です: + +- `"manual"` - コマンドによる手動共有を許可します (デフォルト) +- `"auto"` - 新しい会話を自動的に共有します +- `"disabled"` - 共有を完全に無効にする + +デフォルトでは、共有は手動モードに設定されており、`/share` コマンドを使用して会話を明示的に共有する必要があります。 + +--- + +### コマンド + +`command` オプションを使用して、反復タスク用のカスタム コマンドを構成できます。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +`~/.config/opencode/commands/` または `.opencode/commands/` のマークダウン ファイルを使用してコマンドを定義することもできます。 [詳細はこちら](/docs/commands)。 + +--- + +### キーバインド + +`keybinds` オプションを使用してキーバインドをカスタマイズできます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[詳細はこちら](/docs/themes)。 + +--- + +### 自動更新 + +OpenCode は起動時に新しいアップデートを自動的にダウンロードします。 `autoupdate` オプションを使用してこれを無効にできます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +更新は必要ないが、新しいバージョンが利用可能になったときに通知を受け取りたい場合は、`autoupdate` を `"notify"` に設定します。 +これは、Homebrew などのパッケージ マネージャーを使用してインストールされていない場合にのみ機能することに注意してください。 + +--- + +### フォーマッタ + +`formatter` オプションを使用してコード フォーマッタを設定できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[フォーマッタの詳細については、こちら](/docs/formatters) をご覧ください。 + +--- + +### 権限 + +デフォルトでは、opencode は明示的な承認を必要とせずに **すべての操作を許可**します。これは、`permission` オプションを使用して変更できます。 + +たとえば、`edit` ツールと `bash` ツールにユーザーの承認が必要であることを確認するには、次のようにします。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[権限の詳細については、こちら](/docs/permissions)をご覧ください。 + +--- + +### 圧縮 + +`compaction` オプションを使用してコンテキストの圧縮動作を制御できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - コンテキストがいっぱいのときにセッションを自動的に圧縮します (デフォルト: `true`)。 +- `prune` - 古いツールの出力を削除してトークンを保存します (デフォルト: `true`)。 + +--- + +### ウォッチャー + +`watcher` オプションを使用して、ファイル ウォッチャーの無視パターンを構成できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +パターンは glob 構文に従います。これを使用して、ノイズの多いディレクトリをファイル監視から除外します。 + +--- + +### MCPサーバー + +`mcp` オプションを使用して、使用する MCP サーバーを構成できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[詳細はこちら](/docs/themes)。 + +--- + +### プラグイン + +[Plugins](/docs/plugins) は、カスタム ツール、フック、統合を使用して OpenCode を拡張します。 + +プラグインファイルを`.opencode/plugins/`または`~/.config/opencode/plugins/`に配置します。 `plugin` オプションを使用して npm からプラグインをロードすることもできます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[詳細はこちら](/docs/themes)。 + +--- + +### 説明書 + +`instructions` オプションを使用して、使用しているモデルの命令を構成できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +これは、命令ファイルへのパスとグロブ パターンの配列を受け取ります。 [もっと詳しく知る +ルールについてはこちら](/docs/rules)。 + +--- + +### 無効なプロバイダー + +`disabled_providers` オプションを使用して、自動的にロードされるプロバイダーを無効にすることができます。これは、認証情報が利用可能な場合でも、特定のプロバイダーが読み込まれないようにしたい場合に便利です。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::注記 +`disabled_providers` は `enabled_providers` よりも優先されます。 +::: + +`disabled_providers` オプションは、プロバイダー ID の配列を受け入れます。プロバイダーが無効になっている場合: + +- 環境変数を設定してもロードされません。 +- `/connect` コマンドで API キーを設定してもロードされません。 +- プロバイダーのモデルはモデル選択リストに表示されません。 + +--- + +### 有効なプロバイダー + +`enabled_providers` オプションを使用してプロバイダーの許可リストを指定できます。設定すると、指定されたプロバイダーのみが有効になり、その他はすべて無視されます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +これは、OpenCode を 1 つずつ無効にするのではなく、特定のプロバイダーのみを使用するように制限したい場合に便利です。 + +:::注記 +`disabled_providers` は `enabled_providers` よりも優先されます。 +::: + +プロバイダーが `enabled_providers` と `disabled_providers` の両方に表示される場合、下位互換性のために `disabled_providers` が優先されます。 + +--- + +### 実験的 + +`experimental` キーには、現在開発中のオプションが含まれています。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::注意 +実験的なオプションは安定していません。予告なく変更または削除される場合があります。 +::: + +--- + +## 変数 + +構成ファイル内で変数置換を使用して、環境変数とファイルの内容を参照できます。 + +--- + +### 環境変数 + +`{env:VARIABLE_NAME}` を使用して環境変数を置き換えます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +環境変数が設定されていない場合は、空の文字列に置き換えられます。 + +--- + +### ファイル + +`{file:path/to/file}` を使用してファイルの内容を置き換えます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +ファイル パスは次のとおりです。 + +- 設定ファイルのディレクトリからの相対パス +- または、`/` または `~` で始まる絶対パス + +これらは次の場合に役立ちます。 + +- API キーなどの機密データを別のファイルに保存します。 +- 構成を乱雑にすることなく、大きな命令ファイルを含めることができます。 +- 複数の構成ファイル間で共通の構成スニペットを共有します。 diff --git a/packages/web/src/content/docs/ja/custom-tools.mdx b/packages/web/src/content/docs/ja/custom-tools.mdx new file mode 100644 index 000000000..1a996f716 --- /dev/null +++ b/packages/web/src/content/docs/ja/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: カスタムツール +description: LLM がオープンコードで呼び出すことができるツールを作成します。 +--- + +カスタム ツールは、会話中に LLM が呼び出すことができる作成した関数です。これらは、opencode の組み込みツール ](/docs/tools) (`read`、`write`、`bash` など) と連携して動作します。 + +--- + +## ツールの作成 + +ツールは **TypeScript** または **JavaScript** ファイルとして定義されます。ただし、ツール定義では**任意の言語**で記述されたスクリプトを呼び出すことができます。TypeScript または JavaScript はツール定義自体にのみ使用されます。 + +--- + +### 位置 + +それらは次のように定義できます。 + +- ローカルでは、プロジェクトの `.opencode/tools/` ディレクトリに配置します。 +- または、グローバルに、それらを `~/.config/opencode/tools/` に配置します。 + +--- + +### 構造 + +ツールを作成する最も簡単な方法は、タイプ セーフティと検証を提供する `tool()` ヘルパーを使用することです。 + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +**ファイル名**は**ツール名**になります。上記により `database` ツールが作成されます。 + +--- + +#### ファイルごとに複数のツール + +単一のファイルから複数のツールをエクスポートすることもできます。各エクスポートは **`_`** という名前の **別のツール** になります。 + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +これにより、`math_add` と `math_multiply` という 2 つのツールが作成されます。 + +--- + +### 引数 + +引数の型を定義するには、`tool.schema` (つまり [Zod](https://zod.dev)) を使用できます。 + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +[Zod](https://zod.dev) を直接インポートしてプレーン オブジェクトを返すこともできます。 + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### コンテクスト + +ツールは現在のセッションに関するコンテキストを受け取ります。 + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +セッション作業ディレクトリには `context.directory` を使用します。 +git ワークツリー ルートには `context.worktree` を使用します。 + +--- + +## 例 + +### Python でツールを作成する + +ツールは任意の言語で作成できます。以下は、Python を使用して 2 つの数値を加算する例です。 + +まず、ツールを Python スクリプトとして作成します。 + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +次に、それを呼び出すツール定義を作成します。 + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +ここでは、[`Bun.$`](https://bun.com/docs/runtime/shell) ユーティリティを使用して Python スクリプトを実行しています。 diff --git a/packages/web/src/content/docs/ja/ecosystem.mdx b/packages/web/src/content/docs/ja/ecosystem.mdx new file mode 100644 index 000000000..e9bff9dfe --- /dev/null +++ b/packages/web/src/content/docs/ja/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: 生態系 +description: OpenCode で構築されたプロジェクトと統合。 +--- + +OpenCode に基づいて構築されたコミュニティ プロジェクトのコレクション。 + +:::注記 +OpenCode 関連プロジェクトをこのリストに追加したいですか? PRを送信してください。 +::: + +エコシステムとコミュニティを集約したコミュニティ [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) および [opencode.cafe](https://opencode.cafe) もチェックしてください。 + +--- + +## プラグイン + +|名前 |説明 | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | git sync とライブ プレビューを使用して、隔離された Daytona サンドボックスで OpenCode セッションを自動的に実行します。 +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) |リクエストのグループ化のために Helicone セッション ヘッダーを自動的に挿入する | +| [opencode-type-in​​ject](https://github.com/nick-vi/opencode-type-inject) |ルックアップ ツールを使用して TypeScript/Svelte 型をファイル読み取りに自動挿入する | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | API クレジットの代わりに ChatGPT Plus/Pro サブスクリプションを使用する | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | API 課金の代わりに既存の Gemini プランを使用する | +| [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | API 課金の代わりに Antigravity の無料モデルを使用する | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) |浅いクローンと自動割り当てポートを使用したマルチブランチ devcontainer の分離 | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Antigravity OAuth プラグイン、Google 検索のサポート、およびより堅牢な API 処理 | +| [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) |古いツールの出力を削除してトークンの使用を最適化する | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Google ベースのスタイルでサポートされているプロバイダーにネイティブ Web 検索サポートを追加 | +| [オープンコード-pty](https://github.com/shekohex/opencode-pty.git) | AI エージェントが PTY でバックグラウンド プロセスを実行し、インタラクティブな入力を送信できるようにします。 | +| [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) |非対話型シェル コマンドの手順 - TTY に依存する操作によるハングの防止 | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | wakatime で OpenCode の使用状況を追跡する | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | LLM によって生成されたマークダウン テーブルをクリーンアップする | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | Morph Fast apply API と遅延編集マーカーにより 10 倍高速なコード編集 | +| [オーマイオープンコード](https://github.com/code-yeongyu/oh-my-opencode) |バックグラウンド エージェント、事前構築された LSP/AST/MCP ツール、厳選されたエージェント、Claude Code 互換 | +| [opencode-notificator](https://github.com/panta82/opencode-notificator) | OpenCode セッションのデスクトップ通知とサウンド アラート | +| [opencode-notifier](https://github.com/mohak34/opencode-notifier) |許可、完了、エラー イベントのデスクトップ通知とサウンド アラート | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | OpenCode コンテキストに基づいた AI による自動 Zellij セッション命名 | +| [オープンコードスキル](https://github.com/zenobi-us/opencode-skillful) | OpenCode エージェントがスキルの検出と挿入を使用してオンデマンドでプロンプトを遅延ロードできるようにする | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) |スーパーメモリを使用したセッション間での永続メモリ | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) |視覚的な注釈とプライベート/オフライン共有による対話型の計画レビュー | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) |オープンコード/コマンドをきめ細かいフロー制御を備えた強力なオーケストレーション システムに拡張 | +| [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | launchd (Mac) または systemd (Linux) を cron 構文で使用して、定期的なジョブをスケジュールする | +| [ミコード](https://github.com/vtemian/micode) |構造化されたブレインストーミング → 計画 → セッション継続性のあるワークフローの実装 | +| [octto](https://github.com/vtemian/octto) |複数の質問フォームを使用した AI ブレインストーミング用のインタラクティブなブラウザ UI | +| [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) |非同期委任とコンテキスト永続性を備えた Claude Code スタイルのバックグラウンド エージェント | +| [opencode-notify](https://github.com/kdcokenny/opencode-notify) | OpenCode のネイティブ OS 通知 – タスクがいつ完了したかを知る | +| [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) |バンドルされたマルチエージェント オーケストレーション ハーネス – 16 コンポーネント、1 回のインストール | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | OpenCode 用のゼロフリクション Git ワークツリー | + +--- + +## プロジェクト + +|名前 |説明 | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | SDK 上に構築された OpenCode セッションを制御する Discord ボット | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | API に基づいて構築された、エディター対応プロンプト用の Neovim プラグイン | +| [ポータル](https://github.com/hosenur/portal) | Tailscale/VPN 上の OpenCode 向けモバイルファースト Web UI | +| [opencode プラグイン テンプレート ](https://github.com/zenobi-us/opencode-plugin-template/) | OpenCode プラグインを構築するためのテンプレート | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Neovim オープンコード用フロントエンド - ターミナルベースの AI コーディング エージェント | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | @opencode-ai/sdk 経由で OpenCode を使用するための Vercel AI SDK プロバイダー | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | OpenCode 用の Web/デスクトップ アプリと VS Code 拡張機能 | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Obsidian の UI に OpenCode を埋め込む Obsidian プラグイン | +| [OpenWork](https://github.com/different-ai/openwork) | OpenCode を利用した、Claude Cowork に代わるオープンソース | +| [ocx](https://github.com/kdcokenny/ocx) |移植可能な独立したプロファイルを備えた OpenCode 拡張機能マネージャー。 | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | OpenCode 用のデスクトップ、Web、モバイル、およびリモート クライアント アプリ | + +--- + +## エージェント + +|名前 |説明 | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [Agentic](https://github.com/Cluster444/agentic) |構造化開発のためのモジュール型 AI エージェントとコマンド | +| [opencode-agents](https://github.com/darrenhinde/opencode-agents) |強化されたワークフローのための構成、プロンプト、エージェント、およびプラグイン | diff --git a/packages/web/src/content/docs/ja/enterprise.mdx b/packages/web/src/content/docs/ja/enterprise.mdx new file mode 100644 index 000000000..c9a257b4c --- /dev/null +++ b/packages/web/src/content/docs/ja/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: 企業 +description: 組織内で OpenCode を安全に使用します。 +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise は、コードとデータがインフラストラクチャから決して流出しないようにしたい組織を対象としています。これは、SSO および内部 AI ゲートウェイと統合された一元化された構成を使用することで実現できます。 + +:::注記 +OpenCode は、コードやコンテキスト データを一切保存しません。 +::: + +OpenCode Enterprise を始めるには: + +1. チーム内でトライアルを実施してください。 +2. 価格や実装オプションについては、**お問い合わせ**ください。 + +--- + +## トライアル + +OpenCode はオープン ソースであり、コードやコンテキスト データは一切保存されないため、開発者は簡単に [開始してトライアルを実行できます。 + +--- + +### データの取り扱い + +**OpenCode はコードやコンテキスト データを保存しません。** すべての処理はローカルで、または AI プロバイダーへの直接 API 呼び出しを通じて行われます。 + +つまり、信頼できるプロバイダー、または内部プロバイダーを使用している限り、 +AIゲートウェイならOpenCodeを安全に利用できます。 + +ここでの唯一の注意点は、オプションの `/share` 機能です。 + +--- + +#### 会話を共有する + +ユーザーが `/share` 機能を有効にすると、会話とそれに関連付けられたデータが、opencode.ai でこれらの共有ページをホストするために使用されるサービスに送信されます。 + +現在、データは CDN のエッジ ネットワークを通じて提供され、ユーザーの近くのエッジにキャッシュされます。 + +試用版ではこれを無効にすることをお勧めします。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[sharing](/docs/share) について詳しくはこちらをご覧ください。 + +--- + +### コードの所有権 + +**OpenCode によって生成されたすべてのコードはお客様が所有します。** ライセンスの制限や所有権の主張はありません。 + +--- + +## 価格設定 + +OpenCode Enterprise ではシートごとのモデルを使用します。独自の LLM ゲートウェイをお持ちの場合、使用されたトークンに対して料金はかかりません。価格と実装オプションの詳細については、**お問い合わせください**。 + +--- + +## 導入 + +トライアルが完了し、OpenCode を使用する準備が整ったら、 +貴組織の場合は、**お問い合わせ**してご相談ください。 +価格設定と実装オプション。 + +--- + +### 中央構成 + +組織全体で単一の中央構成を使用するように OpenCode をセットアップできます。 + +この一元化された構成は SSO プロバイダーと統合でき、すべてのユーザーが内部 AI ゲートウェイのみにアクセスできるようにします。 + +--- + +### SSOの統合 + +中央の構成を通じて、OpenCode は認証のために組織の SSO プロバイダーと統合できます。 + +これにより、OpenCode は既存の ID 管理システムを通じて内部 AI ゲートウェイの認証情報を取得できるようになります。 + +--- + +### 社内AIゲートウェイ + +中央構成を使用すると、内部 AI ゲートウェイのみを使用するように OpenCode を構成することもできます。 + +他のすべての AI プロバイダーを無効にして、すべてのリクエストが組織の承認されたインフラストラクチャを通過するようにすることもできます。 + +--- + +### セルフホスティング + +データが流出しないように共有ページを無効にすることをお勧めします +貴社のインフラストラクチャ上でセルフホストすることもお手伝いします。 + +これは現在ロードマップに載っています。ご興味がございましたら、**お知らせください**。 + +--- + +## よくある質問 + +

+What is OpenCode Enterprise? + +OpenCode Enterprise は、コードとデータがインフラストラクチャから決して流出しないようにしたい組織を対象としています。これは、SSO および内部 AI ゲートウェイと統合された一元化された構成を使用することで実現できます。 + +
+ +
+How do I get started with OpenCode Enterprise? + +まずはチームの内部トライアルから始めてください。 OpenCode はデフォルトでコードやコンテキスト データを保存しないため、簡単に開始できます。 + +その後、**お問い合わせ**いただき、価格や実装オプションについてご相談ください。 + +
+ +
+How does enterprise pricing work? + +エンタープライズ価格はシートごとに提供されます。独自の LLM ゲートウェイをお持ちの場合、使用されたトークンに対して料金はかかりません。詳細については、組織のニーズに基づいたカスタム見積もりをご希望の場合は、**お問い合わせください**。 + +
+ +
+Is my data secure with OpenCode Enterprise? + +はい。 OpenCode はコードやコンテキスト データを保存しません。すべての処理はローカルで、または AI プロバイダーへの直接 API 呼び出しを通じて行われます。一元的な構成と SSO の統合により、データは組織のインフラストラクチャ内で安全に保たれます。 + +
+ +
+Can we use our own private NPM registry? + +OpenCode は、Bun のネイティブ `.npmrc` ファイル サポートを通じてプライベート npm レジストリをサポートします。組織が JFrog Artifactory、Nexus などのプライベート レジストリを使用している場合は、OpenCode を実行する前に開発者が認証されていることを確認してください。 + +プライベート レジストリを使用して認証を設定するには、次の手順を実行します。 + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +これにより、認証の詳細を含む `~/.npmrc` が作成されます。 OpenCode は自動的に +これを拾ってください。 + +:::注意 +OpenCode を実行する前に、プライベート レジストリにログインする必要があります。 +::: + +あるいは、`.npmrc` ファイルを手動で構成することもできます。 + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +開発者は、エンタープライズ レジストリからパッケージを確実にインストールできるように、OpenCode を実行する前にプライベート レジストリにログインする必要があります。 + +
diff --git a/packages/web/src/content/docs/ja/formatters.mdx b/packages/web/src/content/docs/ja/formatters.mdx new file mode 100644 index 000000000..46f05ecdb --- /dev/null +++ b/packages/web/src/content/docs/ja/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: フォーマッタ +description: OpenCode は言語固有のフォーマッタを使用します。 +--- + +OpenCode は、言語固有のフォーマッタを使用してファイルを作成または編集した後、ファイルを自動的にフォーマットします。これにより、生成されるコードがプロジェクトのコード スタイルに従っていることが保証されます。 + +--- + +## 内蔵 + +OpenCode には、一般的な言語およびフレームワーク用のいくつかの組み込みフォーマッタが付属しています。以下は、フォーマッタ、サポートされているファイル拡張子、および必要なコマンドまたは構成オプションのリストです。 + +|フォーマッタ |拡張機能 |要件 | +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +|ゴーフムト | .go | `gofmt` コマンドが利用可能 | +|ミックス | .ex、.exs、.eex、.heex、.leex、.neex、.sface | `mix` コマンドが利用可能 | +|よりきれい | .js、.jsx、.ts、.tsx、.html、.css、.md、.json、.yaml、および [more](https://prettier.io/docs/en/index.html) | `package.json` における `prettier` の依存関係 | +|バイオーム | .js、.jsx、.ts、.tsx、.html、.css、.md、.json、.yaml、および [more](https://biomejs.dev/) | `biome.json(c)` 設定ファイル | +|ジグ | .zig、.zon | `zig` コマンドが利用可能 | +|クラン形式 | .c、.cpp、.h、.hpp、.ino、および [more](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` 設定ファイル | +|クトリント | .kt、.kts | `ktlint` コマンドが利用可能 | +|ラフ | .py、.pyi | `ruff` コマンドは config | で使用可能です。 +|さびと.rs | `rustfmt` コマンドが利用可能 | +|カーゴフムト | .rs | `cargo fmt` コマンドが利用可能 | +|紫外線 | .py、.pyi | `uv` コマンドが利用可能 | +|ロボコップ | .rb、.rake、.gemspec、.ru | `rubocop` コマンドが利用可能 | +|標準RB | .rb、.rake、.gemspec、.ru | `standardrb` コマンドが利用可能 | +| htmlビューティー | .erb、.html.erb | `htmlbeautifier` コマンドが利用可能 | +|空気 | .R | `air` コマンドが利用可能 | +|ダーツ | .ダーツ | `dart` コマンドが利用可能 | +| ocaml形式 | .ml、.mli |利用可能な `ocamlformat` コマンドと `.ocamlformat` 設定ファイル | +|テラフォーム | .tf、.tfvars | `terraform` コマンドが利用可能 | +|輝く.gleam | `gleam` コマンドが利用可能 | +|ニクスフムト | .nix | `nixfmt` コマンドが利用可能 | +|シュフムト | .sh、.bash | `shfmt` コマンドが利用可能 | +|パイント | .php | `composer.json` における `laravel/pint` の依存関係 | +| oxfmt (実験的) | .js、.jsx、.ts、.tsx | `package.json` の `oxfmt` 依存関係と [実験用環境変数 flag](/docs/cli/#experimental) | +|オルモル | .hs | `ormolu` コマンドが利用可能 | + +したがって、プロジェクトの `package.json` に `prettier` が含まれている場合、OpenCode は自動的にそれを使用します。 + +--- + +## 仕組み + +OpenCode がファイルを書き込んだり編集したりすると、次のことが行われます。 + +1. 有効なすべてのフォーマッタに対してファイル拡張子をチェックします。 +2. ファイルに対して適切なフォーマッタ コマンドを実行します。 +3. 書式の変更を自動的に適用します。 + +このプロセスはバックグラウンドで実行されるため、手動の手順を行わなくてもコード スタイルが維持されます。 + +--- + +## 設定する + +OpenCode 構成の `formatter` セクションを通じてフォーマッタをカスタマイズできます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +各フォーマッタ設定は以下をサポートします。 + +|プロパティ |タイプ |説明 | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` |ブール値 |フォーマッタを無効にするには、これを `true` に設定します。 +| `command` |文字列[] |フォーマットのために実行するコマンド | +| `environment` |オブジェクト |フォーマッタの実行時に設定する環境変数 | +| `extensions` |文字列[] |このフォーマッタが処理するファイル拡張子 | + +いくつかの例を見てみましょう。 + +--- + +### フォーマッタの無効化 + +**すべて**のフォーマッタをグローバルに無効にするには、`formatter` を `false` に設定します。 + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +**特定**のフォーマッタを無効にするには、`disabled` を `true` に設定します。 + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### カスタムフォーマッタ + +コマンド、環境変数、ファイル拡張子を指定することで、組み込みフォーマッタをオーバーライドしたり、新しいフォーマッタを追加したりできます。 + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +コマンド内の **`$FILE` プレースホルダー** は、フォーマットされるファイルへのパスに置き換えられます。 diff --git a/packages/web/src/content/docs/ja/github.mdx b/packages/web/src/content/docs/ja/github.mdx new file mode 100644 index 000000000..989e71b87 --- /dev/null +++ b/packages/web/src/content/docs/ja/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: GitHub の問題とプルリクエストで OpenCode を使用します。 +--- + +OpenCode は GitHub ワークフローと統合します。コメントで `/opencode` または `/oc` に言及すると、OpenCode が GitHub Actions ランナー内でタスクを実行します。 + +--- + +## 特徴 + +- **問題のトリアージ**: OpenCode に問題を調べて説明してもらいます。 +- **修正と実装**: OpenCode に問題の修正または機能の実装を依頼します。そして、新しいブランチで動作し、すべての変更を含む PR を送信します。 +- **安全**: OpenCode は GitHub のランナー内で実行されます。 + +--- + +## インストール + +GitHub リポジトリにあるプロジェクトで次のコマンドを実行します。 + +```bash +opencode github install +``` + +ここでは、GitHub アプリのインストール、ワークフローの作成、シークレットの設定について説明します。 + +--- + +### 手動セットアップ + +または、手動で設定することもできます。 + +1. **GitHub アプリをインストールします** + +[**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent) にアクセスしてください。ターゲット リポジトリにインストールされていることを確認してください。 + +2. **ワークフローを追加** + +次のワークフロー ファイルをリポジトリの `.github/workflows/opencode.yml` に追加します。適切な `model` と必要な API キーを `env` に設定してください。 + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **API キーをシークレットに保存します** + +組織またはプロジェクトの**設定**で、左側の**シークレットと変数**を展開し、**アクション**を選択します。そして、必要な API キーを追加します。 + +--- + +## 構成 + +- `model`: OpenCode で使用するモデル。 `provider/model` の形式をとります。これは**必須**です。 +- `agent`: 使用するエージェント。プライマリ エージェントである必要があります。見つからない場合は、設定から `default_agent` にフォールバックするか、`"build"` にフォールバックします。 +- `share`: OpenCode セッションを共有するかどうか。パブリック リポジトリのデフォルトは **true** です。 +- `prompt`: デフォルトの動作をオーバーライドするためのオプションのカスタム プロンプト。これを使用して、OpenCode がリクエストを処理する方法をカスタマイズします。 +- `token`: コメントの作成、変更のコミット、プル リクエストのオープンなどの操作を実行するためのオプションの GitHub アクセス トークン。デフォルトでは、OpenCode は OpenCode GitHub アプリからのインストール アクセス トークンを使用するため、コミット、コメント、プル リクエストはアプリからのものとして表示されます。 + +あるいは、OpenCode GitHub アプリをインストールせずに、GitHub Action ランナーの [組み込み `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) を使用することもできます。ワークフローで必要な権限を必ず付与してください。 + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + +必要に応じて、[パーソナル アクセス トークン](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) を使用することもできます。 + +--- + +## サポートされているイベント + +OpenCode は、次の GitHub イベントによってトリガーできます。 + +|イベントの種類 |きっかけ |詳細 | +| ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` |問題または PR についてコメントする |コメントで `/opencode` または `/oc` について言及してください。 OpenCode はコンテキストを読み取り、ブランチを作成したり、PR を開いたり、返信したりできます。 | +| `pull_request_review_comment` | PR 内の特定のコード行にコメントする |コードをレビューするときに、`/opencode` または `/oc` について言及します。 OpenCode は、ファイル パス、行番号、および diff コンテキストを受け取ります。 | +| `issues` |問題がオープンまたは編集されました |問題が作成または変更されると、OpenCode が自動的にトリガーされます。 `prompt` 入力が必要です。 | +| `pull_request` | PR がオープンまたは更新されました | PR が開かれる、同期される、または再度開かれるときに、OpenCode を自動的にトリガーします。自動レビューに役立ちます。 | +| `schedule` | Cron ベースのスケジュール |スケジュールに従って OpenCode を実行します。 `prompt` 入力が必要です。出力はログと PR に送られます (コメントする問題はありません)。 | +| `workflow_dispatch` | GitHub UI からの手動トリガー | [アクション] タブから OpenCode をオンデマンドでトリガーします。 `prompt` 入力が必要です。出力はログと PR に送られます。 | + +### スケジュール例 + +スケジュールに従って OpenCode を実行し、自動化されたタスクを実行します。 + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +スケジュールされたイベントの場合、指示を抽出するためのコメントがないため、`prompt` 入力は **必須** です。スケジュールされたワークフローは、権限チェックのためのユーザー コンテキストなしで実行されるため、OpenCode がブランチまたは PR を作成することが予想される場合、ワークフローは `contents: write` および `pull-requests: write` を付与する必要があります。 + +--- + +### プルリクエストの例 + +PR が開かれるか更新されるときに、PR を自動的にレビューします。 + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +`pull_request` イベントの場合、`prompt` が指定されていない場合、OpenCode はデフォルトでプル リクエストをレビューします。 + +--- + +### 問題のトリアージの例 + +新しい問題を自動的に優先順位付けします。この例では、スパムを減らすために 30 日より古いアカウントにフィルターを適用します。 + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +`issues` イベントの場合、指示を抽出するためのコメントがないため、`prompt` 入力は **必須** です。 + +--- + +## カスタムプロンプト + +デフォルトのプロンプトをオーバーライドして、ワークフローに合わせて OpenCode の動作をカスタマイズします。 + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +これは、プロジェクトに関連する特定のレビュー基準、コーディング標準、または重点分野を強制するのに役立ちます。 + +--- + +## 例 + +GitHub で OpenCode を使用する方法の例をいくつか示します。 + +- **問題の説明** + +このコメントを GitHub の問題に追加します。 + + ``` + /opencode explain this issue + ``` + +OpenCode は、すべてのコメントを含むスレッド全体を読み取り、明確な説明を返信します。 + +- **問題を修正** + +GitHub の問題で次のように言います。 + + ``` + /opencode fix this + ``` + +そして、OpenCode は新しいブランチを作成し、変更を実装し、変更を含む PR を開きます。 + +- **PR を確認して変更を加える** + +GitHub PR に次のコメントを残してください。 + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + +OpenCode は要求された変更を実装し、同じ PR にコミットします。 + +- **特定のコード行を確認してください** + +PR の「ファイル」タブのコード行に直接コメントを残します。 OpenCode は、ファイル、行番号、および diff コンテキストを自動的に検出して、正確な応答を提供します。 + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + +特定の行にコメントすると、OpenCode は以下を受け取ります。 + - レビューされている正確なファイル + - コードの特定の行 + - 周囲の差分コンテキスト + - 行番号情報 + +これにより、ファイル パスや行番号を手動で指定する必要がなく、よりターゲットを絞ったリクエストが可能になります。 diff --git a/packages/web/src/content/docs/ja/gitlab.mdx b/packages/web/src/content/docs/ja/gitlab.mdx new file mode 100644 index 000000000..9c74105e1 --- /dev/null +++ b/packages/web/src/content/docs/ja/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: GitLab の問題とマージリクエストで OpenCode を使用します。 +--- + +OpenCode は、GitLab CI/CD パイプラインまたは GitLab Duo を通じて GitLab ワークフローと統合します。 + +どちらの場合も、OpenCode は GitLab ランナー上で実行されます。 + +--- + +## GitLab CI + +OpenCode は通常の GitLab パイプラインで動作します。 [CI コンポーネント](https://docs.gitlab.com/ee/ci/components/) としてパイプラインに組み込むことができます。 + +ここでは、コミュニティが作成した OpenCode 用の CI/CD コンポーネント — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### 特徴 + +- **ジョブごとにカスタム構成を使用する**: カスタム構成ディレクトリ (`./config/#custom-directory` など) を使用して OpenCode を構成し、OpenCode の呼び出しごとに機能を有効または無効にします。 +- **最小限のセットアップ**: CI コンポーネントはバックグラウンドで OpenCode をセットアップします。必要なのは、OpenCode 構成と初期プロンプトを作成することだけです。 +- **柔軟性**: CI コンポーネントは、動作をカスタマイズするための複数の入力をサポートしています。 + +--- + +### 設定 + +1. OpenCode 認証 JSON をファイル タイプ CI 環境変数として [**設定**] > [**CI/CD**] > [**変数**] に保存します。必ず「マスクして非表示」としてマークしてください。 +2. 以下を `.gitlab-ci.yml` ファイルに追加します。 + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +さらに多くの入力と使用例については、このコンポーネントの docs](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) をチェックしてください。 + +--- + +## GitLab デュオ + +OpenCode は GitLab ワークフローと統合します。 +コメントで `@opencode` に言及すると、OpenCode が GitLab CI パイプライン内でタスクを実行します。 + +--- + +### 特徴 + +- **問題のトリアージ**: OpenCode に問題を調べて説明してもらいます。 +- **修正と実装**: OpenCode に問題の修正または機能の実装を依頼します。 +新しいブランチを作成し、変更を加えたマージリクエストを発行します。 +- **安全**: OpenCode は GitLab ランナー上で実行されます。 + +--- + +### 設定 + +OpenCode は GitLab CI/CD パイプラインで実行されます。セットアップするには次のものが必要です。 + +:::ヒント +最新の手順については、[**GitLab ドキュメント**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) を参照してください。 +::: + +1. GitLab 環境を構成する +2. CI/CD のセットアップ +3. AI モデル プロバイダー API キーを取得する +4. サービスアカウントを作成する +5. CI/CD変数を構成する +6. フロー構成ファイルを作成します。例を次に示します。 + +
+ + Flow configuration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +詳細な手順については、「GitLab CLI エージェント docs](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/)」を参照してください。 + +--- + +### 例 + +GitLab で OpenCode を使用する方法の例をいくつか示します。 + +:::ヒント +`@opencode` とは異なるトリガー フレーズを使用するように設定できます。 +::: + +- **問題の説明** + +このコメントを GitLab の問題に追加します。 + + ``` + @opencode explain this issue + ``` + +OpenCode は問題を読み、明確な説明を返信します。 + +- **問題を修正** + +GitLab の問題では、次のように言います。 + + ``` + @opencode fix this + ``` + +OpenCode は新しいブランチを作成し、変更を実装し、変更を含むマージ リクエストを開きます。 + +- **マージリクエストを確認する** + +GitLab マージ リクエストに次のコメントを残してください。 + + ``` + @opencode review this merge request + ``` + +OpenCode はマージ リクエストをレビューし、フィードバックを提供します。 diff --git a/packages/web/src/content/docs/ja/ide.mdx b/packages/web/src/content/docs/ja/ide.mdx new file mode 100644 index 000000000..2005565e1 --- /dev/null +++ b/packages/web/src/content/docs/ja/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: VS Code、Cursor、およびその他の IDE 用の OpenCode 拡張機能 +--- + +OpenCode は、VS Code、Cursor、またはターミナルをサポートする任意の IDE と統合します。開始するには、ターミナルで `opencode` を実行するだけです。 + +--- + +## 使用法 + +- **クイック起動**: `Cmd+Esc` (Mac) または `Ctrl+Esc` (Windows/Linux) を使用して、分割ターミナル ビューで OpenCode を開くか、既存のターミナル セッションが既に実行されている場合はそれにフォーカスします。 +- **新しいセッション**: すでに開いている場合でも、`Cmd+Shift+Esc` (Mac) または `Ctrl+Shift+Esc` (Windows/Linux) を使用して、新しい OpenCode ターミナル セッションを開始します。 UI の [OpenCode] ボタンをクリックすることもできます。 +- **コンテキスト認識**: 現在の選択またはタブを OpenCode と自動的に共有します。 +- **ファイル参照のショートカット**: ファイル参照を挿入するには、`Cmd+Option+K` (Mac) または `Alt+Ctrl+K` (Linux/Windows) を使用します。たとえば、`@File#L37-42`。 + +--- + +## インストール + +OpenCode を VS Code および Cursor、Windsurf、VSCodium などの一般的なフォークにインストールするには: + +1. VS コードを開く +2. 統合ターミナルを開きます +3. `opencode` を実行します - 拡張機能は自動的にインストールされます + +一方、TUI から `/editor` または `/export` を実行するときに独自の IDE を使用したい場合は、`export EDITOR="code --wait"` を設定する必要があります。 [詳細はこちら](/docs/tui/#editor-setup)。 + +--- + +### 手動インストール + +Extension Marketplace で **OpenCode** を検索し、**インストール** をクリックします。 + +--- + +### トラブルシューティング + +拡張機能が自動的にインストールされない場合: + +- 統合ターミナルで `opencode` を実行していることを確認してください。 +- IDE の CLI がインストールされていることを確認します。 + - VS コードの場合: `code` コマンド + - カーソルの場合: `cursor` コマンド + - ウィンドサーフィンの場合: `windsurf` コマンド + - VSCodium の場合: `codium` コマンド + - そうでない場合は、`Cmd+Shift+P` (Mac) または `Ctrl+Shift+P` (Windows/Linux) を実行し、「Shell Command: Install 'code' command in PATH」(または IDE の同等のコマンド) を検索します。 +- VS Code に拡張機能をインストールする権限があることを確認してください diff --git a/packages/web/src/content/docs/ja/index.mdx b/packages/web/src/content/docs/ja/index.mdx new file mode 100644 index 000000000..514b8a2bb --- /dev/null +++ b/packages/web/src/content/docs/ja/index.mdx @@ -0,0 +1,359 @@ +--- +title: イントロ +description: OpenCode を始めましょう。 +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) は、オープンソースの AI コーディング エージェントです。これは、ターミナルベースのインターフェイス、デスクトップ アプリ、または IDE 拡張機能として利用できます。 + +![オープンコードテーマ](../../../assets/lander/screenshot.png)を使用したOpenCode TUI + +始めましょう。 + +--- + +#### 前提条件 + +ターミナルで OpenCode を使用するには、次のものが必要です。 + +1. 次のような最新のターミナル エミュレータ: + - [WezTerm](https://wezterm.org)、クロスプラットフォーム + - [Alacritty](https://alacritty.org)、クロスプラットフォーム + - [Ghostty](https://ghostty.org)、Linux および macOS + - [Kitty](https://sw.kovidgoyal.net/kitty/)、Linux および macOS + +2. 使用する LLM プロバイダーの API キー。 + +--- + +## インストール + +OpenCode をインストールする最も簡単な方法は、インストール スクリプトを使用することです。 + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +次のコマンドを使用してインストールすることもできます。 + +- **Node.js の使用** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **macOS および Linux での Homebrew の使用** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > 最新のリリースには OpenCode タップを使用することをお勧めします。公式の `brew install opencode` 式は Homebrew チームによって維持されており、更新頻度は低くなります。 + +- **Arch Linux での Paru の使用** + + ```bash + paru -S opencode-bin + ``` + +#### 窓 + +:::tip[推奨: WSL を使用する] +Windows で最高のエクスペリエンスを得るには、[Windows Subsystem for Linux (WSL)](/docs/windows-wsl) を使用することをお勧めします。これにより、パフォーマンスが向上し、OpenCode の機能との完全な互換性が提供されます。 +::: + +- **Chocolatey の使用** + + ```bash + choco install opencode + ``` + +- **スクープの使用** + + ```bash + scoop install opencode + ``` + +- **NPM の使用** + + ```bash + npm install -g opencode-ai + ``` + +- **ミセの使い方** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **Docker の使用** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +Bun を使用して Windows に OpenCode をインストールするためのサポートは現在進行中です。 + +[Releases](https://github.com/anomalyco/opencode/releases). + +--- + +## 設定する + +OpenCode を使用すると、API キーを構成することで任意の LLM プロバイダーを使用できます。 + +LLM プロバイダーを初めて使用する場合は、[OpenCode Zen](/docs/zen). +これは、OpenCode によってテストおよび検証されたモデルの厳選されたリストです。 +team. + +1. TUI で `/connect` コマンドを実行し、opencode を選択して、[opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. サインインし、お支払いの詳細を追加し、API キーをコピーします。 + +3. API キーを貼り付けます。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +あるいは、他のプロバイダーのいずれかを選択することもできます。 [詳細はこちら](/docs/providers#directory)。 + +--- + +## 初期化する + +プロバイダーを構成したので、次のプロジェクトに移動できます。 +取り組みたいと考えています。 + +```bash +cd /path/to/project +``` + +そしてOpenCodeを実行します。 + +```bash +opencode +``` + +次に、次のコマンドを実行して、プロジェクトの OpenCode を初期化します。 + +```bash frame="none" +/init +``` + +これにより、OpenCode がプロジェクトを分析し、`AGENTS.md` ファイルを作成します。 +プロジェクトのルート。 + +:::ヒント +プロジェクトの `AGENTS.md` ファイルを Git にコミットする必要があります。 +::: + +これは、OpenCode がプロジェクトの構造とコーディング パターンを理解するのに役立ちます。 +used. + +--- + +## 使用法 + +これで、OpenCode を使用してプロジェクトに取り組む準備が整いました。お気軽にお尋ねください +何でも! + +AI コーディング エージェントを初めて使用する場合は、次の例を参考にしてください。 +help. + +--- + +### 質問する + +OpenCode にコードベースの説明を依頼できます。 + +:::ヒント +プロジェクト内のファイルをあいまい検索するには、`@` キーを使用します。 +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +これは、コードベースに作業していない部分がある場合に役立ちます。 + +--- + +### 機能を追加する + +OpenCode に新しい機能をプロジェクトに追加するよう依頼できます。ただし、最初は計画の作成を依頼することをお勧めします。 + +1. **計画を作成する** + +OpenCode には、変更を加える機能を無効にする _Plan モード_ があり、 +代わりに、その機能を_どのように_実装するかを提案してください。 + +**Tab** キーを使用してそれに切り替えます。右下隅にこれを示すインジケーターが表示されます。 + + ```bash frame="none" title="Switch to Plan mode" + + ``` + +では、何をしたいのかを説明しましょう。 + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + +自分が何を望んでいるのかを理解するために、OpenCode に十分な詳細を提供したいと考えています。役に立ちます +チームの若手開発者と話しているように話すことができます。 + +:::ヒント +OpenCode に多くのコンテキストと例を提供して、意図する内容を理解できるようにします。 + want. + ::: + +2. **計画を反復する** + +計画が示されたら、フィードバックを送信したり、詳細を追加したりできます。 + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + +:::ヒント +画像をターミナルにドラッグ アンド ドロップして、プロンプトに追加します。 + ::: + +OpenCode は、指定された画像をスキャンしてプロンプトに追加できます。あなたはできる +これを行うには、画像をターミナルにドラッグ アンド ドロップします。 + +3. **機能を構築する** + +計画に慣れたら、_Build モード_に戻ります。 +**Tab** キーをもう一度押します。 + + ```bash frame="none" + + ``` + +そして変更を加えるように依頼します。 + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### 変更を加える + +より単純な変更については、OpenCode に直接ビルドするよう依頼できます。 +最初に計画を見直す必要はありません。 + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +OpenCode が適切な情報を提供できるように、十分な量の詳細を確実に提供する必要があります。 +changes. + +--- + +### 変更を元に戻す + +OpenCode にいくつかの変更を依頼するとします。 + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +しかし、それは自分が望んでいたものではないことに気づきます。変更は **元に戻すことができます** +`/undo` コマンドを使用します。 + +```bash frame="none" +/undo +``` + +OpenCode は加えた変更を元に戻し、元のメッセージを表示します。 +again. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +ここからプロンプトを調整し、OpenCode に再試行を依頼できます。 + +:::ヒント +`/undo` を複数回実行すると、複数の変更を元に戻すことができます。 +::: + +または、`/redo` コマンドを使用して変更を**やり直す**こともできます。 + +```bash frame="none" +/redo +``` + +--- + +## 共有 + +OpenCode との会話は [他のユーザーと共有できます] +チーム](/docs/share)。 + +```bash frame="none" +/share +``` + +これにより、現在の会話へのリンクが作成され、クリップボードにコピーされます。 + +:::注記 +会話はデフォルトでは共有されません。 +::: + +これは [OpenCode を使用した会話 ](https://opencode.ai/s/4XP1fce5) の例です。 + +--- + +## カスタマイズ + +それで終わりです!これであなたは OpenCode の使い方のプロになりました。 + +独自のものにするには、[テーマ](/docs/themes) を選択する、[キーバインドをカスタマイズする ](/docs/keybinds)、[コード フォーマッタ ](/docs/formatters) を設定する、[カスタム コマンド ](/docs/commands) を作成する]、または [OpenCode config](/docs/config) を試してみる] ことをお勧めします。 diff --git a/packages/web/src/content/docs/ja/keybinds.mdx b/packages/web/src/content/docs/ja/keybinds.mdx new file mode 100644 index 000000000..598c5a406 --- /dev/null +++ b/packages/web/src/content/docs/ja/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: キーバインド +description: キーバインドをカスタマイズします。 +--- + +OpenCode には、OpenCode 設定を通じてカスタマイズできるキーバインドのリストがあります。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## リーダーキー + +OpenCode は、ほとんどのキーバインドに `leader` キーを使用します。これにより、端末での競合が回避されます。 + +デフォルトでは、`ctrl+x` がリーダー キーであり、ほとんどの操作では、最初にリーダー キーを押してからショートカットを押す必要があります。たとえば、新しいセッションを開始するには、まず `ctrl+x` を押してから、`n` を押します。 + +キーバインドにリーダー キーを使用する必要はありませんが、そうすることをお勧めします。 + +--- + +## キーバインドを無効にする + +キーバインドを無効にするには、値「none」を指定してキーを構成に追加します。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## デスクトッププロンプトのショートカット + +OpenCode デスクトップ アプリのプロンプト入力は、テキストを編集するための一般的な Readline/Emacs スタイルのショートカットをサポートしています。これらは組み込みであり、現在 `opencode.json` を介して構成することはできません。 + +|ショートカット |アクション | +| -------- | ---------------------------------------- | +| `ctrl+a` |現在の行の先頭に移動 | +| `ctrl+e` |現在の行の末尾に移動 | +| `ctrl+b` |カーソルを 1 文字前に移動 | +| `ctrl+f` |カーソルを 1 文字前に移動 | +| `alt+b` |カーソルを 1 単語前に移動 | +| `alt+f` |カーソルを 1 単語前に移動 | +| `ctrl+d` |カーソル下の文字を削除 | +| `ctrl+k` |行末まで強制終了 | +| `ctrl+u` |行の先頭までキル | +| `ctrl+w` |前の単語を削除 | +| `alt+d` |次の単語を削除 | +| `ctrl+t` |文字を入れ替える | +| `ctrl+g` |ポップオーバーをキャンセル/実行中の応答を中止する | + +--- + +## Shift+Enter + +一部の端末では、デフォルトでは Enter キーを使用して修飾キーを送信しません。エスケープ シーケンスとして `Shift+Enter` を送信するように端末を設定する必要がある場合があります。 + +### Windowsターミナル + +次の場所で `settings.json` を開きます。 + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +これをルートレベルの `actions` 配列に追加します。 + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +これをルートレベルの `actions` 配列に追加します。 + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +ファイルを保存し、Windows ターミナルを再起動するか、新しいタブを開きます。 diff --git a/packages/web/src/content/docs/ja/lsp.mdx b/packages/web/src/content/docs/ja/lsp.mdx new file mode 100644 index 000000000..555df3e2f --- /dev/null +++ b/packages/web/src/content/docs/ja/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: LSPサーバー +description: OpenCode は LSP サーバーと統合します。 +--- + +OpenCode は言語サーバー プロトコル (LSP) と統合して、LLM がコードベースと対話できるようにします。診断を使用して LLM にフィードバックを提供します。 + +--- + +## 内蔵 + +OpenCode には、一般的な言語用のいくつかの組み込み LSP サーバーが付属しています。 + +| LSPサーバー |拡張機能 |要件 | +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +|アストロ | .astro | Astro プロジェクトの自動インストール | +|バッシュ | .sh、.bash、.zsh、.ksh | bash-lang-server を自動インストールします。 +|クランド | .c、.cpp、.cc、.cxx、.c++、.h、.hpp、.hh、.hxx、.h++ | C/C++ プロジェクトの自動インストール | +|シーシャープ | .cs | `.NET SDK` がインストールされました | +| clojure-lsp | .clj、.cljs、.cljc、.edn | `clojure-lsp` コマンドが利用可能 | +|ダーツ | .ダーツ | `dart` コマンドが利用可能 | +|デノ | .ts、.tsx、.js、.jsx、.mjs | `deno` コマンドが利用可能 (deno.json/deno.jsonc を自動検出) | +|エリクサーLS | .ex、.exs | `elixir` コマンドが利用可能 | +|エスリント | .ts、.tsx、.js、.jsx、.mjs、.cjs、.mts、.cts、.vue |プロジェクト内の `eslint` 依存関係 | +|フシャープ | .fs、.fsi、.fsx、.fsscript | `.NET SDK` がインストールされました | +|輝く.gleam | `gleam` コマンドが利用可能 | +|ゴップル | .go | `go` コマンドが利用可能 | +| HLS | .hs、.lhs | `haskell-language-server-wrapper` コマンドが利用可能 | +| jdtls | .java | `Java SDK (version 21+)` がインストールされました | +| kotlin-ls | .kt、.kts | Kotlin プロジェクトの自動インストール | +|ルアール | .lua | Lua プロジェクトの自動インストール | +|ニクスド | .nix | `nixd` コマンドが利用可能 | +| ocaml-lsp | .ml、.mli | `ocamllsp` コマンドが利用可能 | +|オックスリント | .ts、.tsx、.js、.jsx、.mjs、.cjs、.mts、.cts、.vue、.astro、.svelte |プロジェクト内の `oxlint` 依存関係 | +| php インテルフェンス | .php | PHP プロジェクトの自動インストール | +|プリズマ | .プリズム | `prisma` コマンドが利用可能 | +|著作権 | .py、.pyi | `pyright` 依存関係がインストールされました | +| Ruby-LSP (ルボコップ) | .rb、.rake、.gemspec、.ru | `ruby` および `gem` コマンドが利用可能 | +|さび | .rs | `rust-analyzer` コマンドが利用可能 | +|ソースキット-lsp | .swift、.objc、.objcpp | `swift` がインストールされています (macOS では `xcode`)。 +|細い | .svelte | Svelte プロジェクトの自動インストール | +|テラフォーム | .tf、.tfvars | GitHub リリースからの自動インストール | +|タイニーミスト | .typ、.typc | GitHub リリースからの自動インストール | +|タイプスクリプト | .ts、.tsx、.js、.jsx、.mjs、.cjs、.mts、.cts |プロジェクト内の `typescript` 依存関係 | +|ビュー | .vue | Vue プロジェクトの自動インストール | +| yaml-ls | .yaml、.yml | Red Hat yaml-lang-server を自動インストールします。 +| zls | .zig、.zon | `zig` コマンドが利用可能 | + +上記のファイル拡張子のいずれかが検出され、要件が満たされると、LSP サーバーは自動的に有効になります。 + +:::注記 +`OPENCODE_DISABLE_LSP_DOWNLOAD` 環境変数を `true` に設定すると、LSP サーバーの自動ダウンロードを無効にできます。 +::: + +--- + +## 仕組み + +opencode がファイルを開くと、次のようになります。 + +1. 有効なすべての LSP サーバーに対してファイル拡張子をチェックします。 +2. 適切な LSP サーバーがまだ実行されていない場合は開始します。 + +--- + +## 設定する + +Opencode 構成の `lsp` セクションを通じて LSP サーバーをカスタマイズできます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +各 LSP サーバーは以下をサポートします。 + +|プロパティ |タイプ |説明 | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` |ブール値 | LSP サーバーを無効にするには、これを `true` に設定します。 +| `command` |文字列[] | LSP サーバーを起動するコマンド | +| `extensions` |文字列[] |この LSP サーバーが処理するファイル拡張子 | +| `env` |オブジェクト |サーバーの起動時に設定する環境変数 | +| `initialization` |オブジェクト | LSP サーバーに送信する初期化オプション | + +いくつかの例を見てみましょう。 + +--- + +### 環境変数 + +LSP サーバーの起動時に `env` プロパティを使用して環境変数を設定します。 + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### 初期化オプション + +`initialization` プロパティを使用して、初期化オプションを LSP サーバーに渡します。これらは、LSP `initialize` リクエスト中に送信されるサーバー固有の設定です。 + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::注記 +初期化オプションは LSP サーバーによって異なります。利用可能なオプションについては、LSP サーバーのドキュメントを確認してください。 +::: + +--- + +### LSPサーバーの無効化 + +**すべて** LSP サーバーをグローバルに無効にするには、`lsp` を `false` に設定します。 + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +**特定** LSP サーバーを無効にするには、`disabled` を `true` に設定します。 + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### カスタムLSPサーバー + +コマンドとファイル拡張子を指定して、カスタム LSP サーバーを追加できます。 + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## 追加情報 + +### PHP インテリフェンス + +PHP Intelephense は、ライセンス キーを通じてプレミアム機能を提供します。ライセンス キーを指定するには、次の場所にあるテキスト ファイルにキー (のみ) を配置します。 + +- macOS/Linux の場合: `$HOME/intelephense/licence.txt` +- Windows の場合: `%USERPROFILE%/intelephense/licence.txt` + +ファイルにはライセンス キーのみが含まれており、追加のコンテンツは含まれていません。 diff --git a/packages/web/src/content/docs/ja/mcp-servers.mdx b/packages/web/src/content/docs/ja/mcp-servers.mdx new file mode 100644 index 000000000..76a0559c0 --- /dev/null +++ b/packages/web/src/content/docs/ja/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: MCPサーバー +description: ローカルおよびリモートの MCP ツールを追加します。 +--- + +_Model Context Protocol_ (MCP) を使用して、OpenCode に外部ツールを追加できます。 OpenCode は、ローカル サーバーとリモート サーバーの両方をサポートします。 + +MCP ツールを追加すると、組み込みツールとともに LLM で自動的に使用できるようになります。 + +--- + +#### 注意事項 + +MCP サーバーを使用すると、コンテキストが追加されます。多くのツールがある場合、これはすぐに増加する可能性があります。したがって、使用する MCP サーバーには注意することをお勧めします。 + +:::ヒント +MCP サーバーはコンテキストに追加されるため、どのサーバーを有効にするかには注意してください。 +::: + +GitHub MCP サーバーなどの特定の MCP サーバーは、大量のトークンを追加する傾向があり、コンテキスト制限を簡単に超える可能性があります。 + +--- + +## 有効にする + +MCP サーバーは、`mcp` の下の [OpenCode Config](https://opencode.ai/docs/config/) で定義できます。各 MCP を一意の名前で追加します。 LLM にプロンプ​​トを表示するときに、その MCP を名前で参照できます。 + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +`enabled` を `false` に設定してサーバーを無効にすることもできます。これは、サーバーを構成から削除せずに一時的に無効にする場合に便利です。 + +--- + +### リモートのデフォルトを上書きする + +組織は、`.well-known/opencode` エンドポイント経由でデフォルトの MCP サーバーを提供できます。これらのサーバーはデフォルトで無効になっている場合があり、ユーザーは必要なサーバーにオプトインできます。 + +組織のリモート構成から特定のサーバーを有効にするには、`enabled: true` を使用してローカル構成に追加します。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +ローカルの設定値はリモートのデフォルト値をオーバーライドします。詳細については、「config precedence](/docs/config#precedence-order)」を参照してください。 + +--- + +## 地元 + +MCP オブジェクト内の `type` から `"local"` を使用してローカル MCP サーバーを追加します。 + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +このコマンドは、ローカル MCP サーバーの起動方法を示します。環境変数のリストを渡すこともできます。 + +たとえば、テスト [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP サーバー] を追加する方法は次のとおりです。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +これを使用するには、プロンプトに `use the mcp_everything tool` を追加します。 + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### オプション + +ここでは、ローカル MCP サーバーを構成するためのすべてのオプションを示します。 + +|オプション |タイプ |必須 |説明 | +| ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` |文字列 |や | MCP サーバー接続のタイプは、`"local"` である必要があります。 | +| `command` |配列 |や | MCP サーバーを実行するためのコマンドと引数。 | +| `environment` |オブジェクト | |サーバーの実行時に設定する環境変数。 | +| `enabled` |ブール値 | |起動時に MCP サーバーを有効または無効にします。 | +| `timeout` |番号 | | MCP サーバーからツールを取得する際のタイムアウト (ミリ秒)。デフォルトは 5000 (5 秒) です。 | + +--- + +## リモート + +`type` を `"remote"` に設定して、リモート MCP サーバーを追加します。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` はリモート MCP サーバーの URL で、`headers` オプションを使用するとヘッダーのリストを渡すことができます。 + +--- + +#### オプション + +|オプション |タイプ |必須 |説明 | +| --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` |文字列 |や | MCP サーバー接続のタイプは、`"remote"` である必要があります。 | +| `url` |文字列 |や |リモート MCP サーバーの URL。 | +| `enabled` |ブール値 | |起動時に MCP サーバーを有効または無効にします。 | +| `headers` |オブジェクト | |リクエストとともに送信するヘッダー。 | +| `oauth` |オブジェクト | | OAuth認証構成。以下の「OAuth](#oauth)」セクションを参照してください。 | +| `timeout` |番号 | | MCP サーバーからツールを取得する際のタイムアウト (ミリ秒)。デフォルトは 5000 (5 秒) です。 | + +--- + +## OAuth + +OpenCode は、リモート MCP サーバーの OAuth 認証を自動的に処理します。サーバーが認証を必要とする場合、OpenCode は次のことを行います。 + +1. 401 応答を検出し、OAuth フローを開始します。 +2. サーバーでサポートされている場合は **動的クライアント登録 (RFC 7591)** を使用します +3. 今後のリクエストに備えてトークンを安全に保管する + +--- + +### 自動 + +ほとんどの OAuth 対応 MCP サーバーでは、特別な構成は必要ありません。リモートサーバーを設定するだけです。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +サーバーが認証を必要とする場合、OpenCode を初めて使用しようとすると、認証を求めるプロンプトが表示されます。そうでない場合は、`opencode mcp auth ` を使用して flow](#authenticating) を手動でトリガーできます。 + +--- + +### 事前登録済み + +MCP サーバープロバイダーからクライアント認証情報を取得している場合は、それらを構成できます。 + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### 認証中 + +手動で認証をトリガーしたり、資格情報を管理したりできます。 + +特定の MCP サーバーで認証します。 + +```bash +opencode mcp auth my-oauth-server +``` + +すべての MCP サーバーとその認証ステータスをリストします。 + +```bash +opencode mcp list +``` + +保存されている認証情報を削除します。 + +```bash +opencode mcp logout my-oauth-server +``` + +`mcp auth` コマンドは、認証のためにブラウザを開きます。承認後、OpenCode はトークンを `~/.local/share/opencode/mcp-auth.json` に安全に保存します。 + +--- + +#### OAuthの無効化 + +サーバー (代わりに API キーを使用するサーバーなど) の自動 OAuth を無効にする場合は、`oauth` を `false` に設定します。 + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### OAuth オプション + +|オプション |タイプ |説明 | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` |オブジェクト \|偽 | OAuth 構成オブジェクト、または `false` を使用して OAuth 自動検出を無効にします。 | +| `clientId` |文字列 | OAuth クライアント ID。指定しない場合は、動的クライアント登録が試行されます。 | +| `clientSecret` |文字列 | OAuth クライアント シークレット (認可サーバーで必要な場合)。 | +| `scope` |文字列 |認可中にリクエストする OAuth スコープ。 | + +#### デバッグ + +リモート MCP サーバーが認証に失敗した場合は、次の方法で問題を診断できます。 + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +`mcp debug` コマンドは、現在の認証ステータスを表示し、HTTP 接続をテストし、OAuth 検出フローを試行します。 + +--- + +## 管理 + +MCP は、組み込みツールと並んで、OpenCode のツールとして利用できます。したがって、他のツールと同様に、OpenCode config を通じてそれらを管理できます。 + +--- + +### グローバル + +これは、それらをグローバルに有効または無効にできることを意味します。 + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +グロブ パターンを使用して、一致するすべての MCP を無効にすることもできます。 + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +ここでは、グロブ パターン `my-mcp*` を使用して、すべての MCP を無効にしています。 + +--- + +### エージェントごと + +多数の MCP サーバーがある場合は、エージェントごとにのみ有効にし、グローバルに無効にすることができます。これを行うには: + +1. ツールとしてグローバルに無効にします。 +2. [エージェント config](/docs/agents#tools) で、MCP サーバーをツールとして有効にします。 + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### グロブパターン + +グロブ パターンでは、単純な正規表現のグロブ パターンを使用します。 + +- `*` は 0 個以上の任意の文字に一致します (例: `"my-mcp*"` は `my-mcp_search`、`my-mcp_list` などに一致します)。 +- `?` は 1 つの文字に正確に一致します +- 他のすべての文字は文字通り一致します + +:::注記 +MCP サーバー ツールはサーバー名をプレフィックスとして登録されているため、サーバーのすべてのツールを無効にするには、次のコマンドを使用するだけです。 + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## 例 + +以下に、一般的な MCP サーバーの例をいくつか示します。他のサーバーを文書化したい場合は、PR を送信できます。 + +--- + +### セントリー + +[Sentry MCP サーバー ](https://mcp.sentry.dev) を追加して、Sentry プロジェクトや問題と対話します。 + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +構成を追加した後、Sentry で認証します。 + +```bash +opencode mcp auth sentry +``` + +これにより、ブラウザ ウィンドウが開き、OAuth フローが完了し、OpenCode が Sentry アカウントに接続されます。 + +認証が完了すると、プロンプトで Sentry ツールを使用して、問題、プロジェクト、エラー データをクエリできるようになります。 + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### コンテキスト7 + +ドキュメントを検索するために [Context7 MCP server](https://github.com/upstash/context7) を追加します。 + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +無料アカウントにサインアップしている場合は、API キーを使用して、より高いレート制限を取得できます。 + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +ここでは、`CONTEXT7_API_KEY` 環境変数が設定されていることを前提としています。 + +Context7 MCP サーバーを使用するには、プロンプトに `use context7` を追加します。 + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +あるいは、次のようなものを [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Vercel による Grep + +GitHub 上のコード スニペットを検索するには、[Grep by Vercel](https://grep.app) MCP サーバーを追加します。 + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +MCP サーバーに `gh_grep` という名前を付けたので、プロンプトに `use the gh_grep tool` を追加して、エージェントにそれを使用させることができます。 + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +あるいは、次のようなものを [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/ja/models.mdx b/packages/web/src/content/docs/ja/models.mdx new file mode 100644 index 000000000..b596c6d90 --- /dev/null +++ b/packages/web/src/content/docs/ja/models.mdx @@ -0,0 +1,223 @@ +--- +title: モデル +description: LLM プロバイダーとモデルを構成します。 +--- + +OpenCode は [AI SDK](https://ai-sdk.dev/) および [Models.dev](https://models.dev) を使用して **75 以上の LLM プロバイダー** をサポートし、ローカル モデルの実行をサポートします。 + +--- + +## プロバイダー + +最も一般的なプロバイダーはデフォルトでプリロードされています。 `/connect` コマンドを使用してプロバイダーの資格情報を追加した場合は、OpenCode を開始するときにそれらの資格情報を使用できるようになります。 + +[プロバイダー](/docs/providers). + +--- + +## モデルを選択してください + +プロバイダーを構成したら、次のように入力して必要なモデルを選択できます。 + +```bash frame="none" +/models +``` + +--- + +## 推奨機種 + +たくさんのモデルがあり、毎週のように新しいモデルが登場します。 + +:::ヒント +当社が推奨するモデルのいずれかの使用を検討してください。 +::: + +ただし、コードの生成とツールの呼び出しの両方に優れているものはほんのわずかです。 + +ここでは、OpenCode で適切に動作するいくつかのモデルを順不同で示します。 (これは完全なリストではなく、必ずしも最新であるとは限りません): + +- GPT5.2 +- GPT 5.1 コーデックス +- クロード 作品4.5 +- クロード・ソネット 4.5 +- ミニマックス M2.1 +- ジェミニ 3 プロ + +--- + +## デフォルトを設定する + +これらのいずれかをデフォルトのモデルとして設定するには、`model` キーを +OpenCodeの設定。 + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +ここでの完全な ID は `provider_id/model_id` です。たとえば、[OpenCode Zen](/docs/zen) を使用している場合、GPT 5.1 Codex には `opencode/gpt-5.1-codex` を使用します。 + +[カスタムプロバイダー](/docs/providers#custom) を構成している場合、`provider_id` は構成の `provider` 部分のキーであり、`model_id` は `provider.models` のキーです。 + +--- + +## モデルの構成 + +config を通じてモデルのオプションをグローバルに設定できます。 + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +ここでは、2 つの組み込みモデル (`openai` プロバイダー経由でアクセスする場合は `gpt-5`、`anthropic` プロバイダー経由でアクセスする場合は `claude-sonnet-4-20250514`) のグローバル設定を構成しています。 +組み込みプロバイダーとモデル名は、[Models.dev](https://models.dev). + +使用しているエージェントに対してこれらのオプションを構成することもできます。ここでエージェント設定はグローバル オプションをオーバーライドします。 [詳細はこちら](/docs/agents/#additional)。 + +組み込みバリアントを拡張するカスタム バリアントを定義することもできます。バリアントを使用すると、重複したエントリを作成せずに、同じモデルに対して異なる設定を構成できます。 + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## バリエーション + +多くのモデルは、異なる構成の複数のバリアントをサポートしています。 OpenCode には、一般的なプロバイダーのデフォルトのバリアントが組み込まれています。 + +### 組み込みバリアント + +OpenCode には、多くのプロバイダーのデフォルトのバリアントが付属しています。 + +**人間的**: + +- `high` - 高度な思考予算 (デフォルト) +- `max` - 最大の思考予算 + +**OpenAI**: + +モデルによって異なりますが、おおよそ次のとおりです。 + +- `none` - 理由はありません +- `minimal` - 最小限の推論努力 +- `low` - 推論の労力が少ない +- `medium` - 中程度の推論努力 +- `high` - 高い推論努力 +- `xhigh` - 非常に高い推論努力 + +**グーグル**: + +- `low` - 労力/トークン予算の削減 +- `high` - より高い労力/トークン予算 + +:::ヒント +このリストは包括的なものではありません。他の多くのプロバイダーにもデフォルトが組み込まれています。 +::: + +### カスタムバリアント + +既存のバリアントをオーバーライドすることも、独自のバリアントを追加することもできます。 + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### サイクルのバリエーション + +キーバインド `variant_cycle` を使用すると、バリアントをすばやく切り替えることができます。 [詳細はこちら](/docs/keybinds)。 + +--- + +## モデルのロード + +OpenCode が起動すると、次の優先順位でモデルがチェックされます。 + +1. `--model` または `-m` コマンド ライン フラグ。形式は構成ファイルと同じです: `provider_id/model_id`。 + +2. OpenCode 構成内のモデルのリスト。 + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + +ここでの形式は `provider/model` です。 + +3. 最後に使用されたモデル。 + +4. 内部優先を使用した最初のモデル。 diff --git a/packages/web/src/content/docs/ja/modes.mdx b/packages/web/src/content/docs/ja/modes.mdx new file mode 100644 index 000000000..79025e281 --- /dev/null +++ b/packages/web/src/content/docs/ja/modes.mdx @@ -0,0 +1,331 @@ +--- +title: モード +description: さまざまなユースケースに応じたさまざまなモード。 +--- + +:::注意 +モードは、opencode config の `agent` オプションを通じて設定されるようになりました。の +`mode` オプションは非推奨になりました。 [詳細はこちら](/docs/agents)。 +::: + +opencode のモードを使用すると、さまざまなユースケースに合わせて動作、ツール、プロンプトをカスタマイズできます。 + +**ビルド** と **プラン** という 2 つの組み込みモードが付属しています。カスタマイズできます +これらを使用するか、opencode config を通じて独自の設定を行います。 + +セッション中にモードを切り替えることも、構成ファイルでモードを構成することもできます。 + +--- + +## 内蔵 + +opencode には 2 つの組み込みモードが付属しています。 + +--- + +### 建てる + +ビルドは、すべてのツールが有効になっている **デフォルト** モードです。これは、ファイル操作やシステム コマンドへのフル アクセスが必要な開発作業の標準モードです。 + +--- + +### プラン + +計画と分析のために設計された制限付きモード。プラン モードでは、次のツールはデフォルトで無効になっています。 + +- `write` - 新しいファイルを作成できません +- `edit` - 計画自体の詳細を示す `.opencode/plans/*.md` にあるファイルを除き、既存のファイルを変更できません +- `patch` - パッチを適用できません +- `bash` - シェルコマンドを実行できません + +このモードは、コードベースに実際の変更を加えずに、AI にコードを分析させたり、変更を提案したり、計画を作成させたい場合に便利です。 + +--- + +## スイッチング + +セッション中に _Tab_ キーを使用してモードを切り替えることができます。または、設定された `switch_mode` キーバインド。 + +参照: [コードのフォーマット構成については、Formatters](/docs/formatters)。 + +--- + +## 設定する + +組み込みモードをカスタマイズしたり、構成を通じて独自のモードを作成したりできます。モードは次の 2 つの方法で設定できます。 + +### JSON構成 + +`opencode.json` 構成ファイルでモードを構成します。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### マークダウン構成 + +マークダウン ファイルを使用してモードを定義することもできます。それらを次の場所に置きます。 + +- グローバル: `~/.config/opencode/agents/` +- プロジェクト: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +マークダウン ファイル名はモード名になります (例: `review.md` は `review` モードを作成します)。 + +これらの構成オプションを詳しく見てみましょう。 + +--- + +### モデル + +`model` 設定を使用して、このモードのデフォルト モデルをオーバーライドします。さまざまなタスクに最適化されたさまざまなモデルを使用する場合に役立ちます。たとえば、計画にはより高速なモデルを、実装にはより有能なモデルを使用します。 + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### 温度 + +`temperature` 構成を使用して、AI の応答のランダム性と創造性を制御します。値が低いほど、応答はより集中的かつ決定的になりますが、値が高いほど、創造性と変動性が高まります。 + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +通常、温度値の範囲は 0.0 ~ 1.0 です。 + +- **0.0-0.2**: 非常に焦点が絞られた決定的な応答。コード分析と計画に最適です。 +- **0.3-0.5**: 創造性を備えたバランスの取れた応答。一般的な開発タスクに適しています。 +- **0.6-1.0**: より創造的で多様な応答。ブレーンストーミングや探索に役立ちます。 + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +温度が指定されていない場合、opencode はモデル固有のデフォルトを使用します (通常、ほとんどのモデルでは 0、Qwen モデルでは 0.55)。 + +--- + +### プロンプト + +`prompt` 構成を使用して、このモードのカスタム システム プロンプト ファイルを指定します。プロンプト ファイルには、モードの目的に固有の指示が含まれている必要があります。 + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +このパスは、構成ファイルが配置されている場所に対する相対パスです。したがって、これは次の場合に機能します +グローバルなオープンコード構成とプロジェクト固有の構成の両方。 + +--- + +### ツール + +`tools` 設定を使用して、このモードでどのツールを使用できるかを制御します。特定のツールを `true` または `false` に設定することで、有効または無効にすることができます。 + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +ツールが指定されていない場合は、すべてのツールがデフォルトで有効になります。 + +--- + +#### 利用可能なツール + +ここでは、モード設定を通じて制御できるすべてのツールを示します。 + +|ツール |説明 | +| ----------- | ----------------------- | +| `bash` |シェルコマンドを実行する | +| `edit` |既存のファイルを変更する | +| `write` |新しいファイルを作成する | +| `read` |ファイルの内容を読み取る | +| `grep` |ファイルの内容を検索 | +| `glob` |パターンでファイルを検索 | +| `list` |ディレクトリの内容をリストする | +| `patch` |ファイルにパッチを適用する | +| `todowrite` | ToDo リストを管理する | +| `todoread` | ToDo リストを読む | +| `webfetch` | Web コンテンツを取得する | + +--- + +## カスタムモード + +構成に追加することで、独自のカスタム モードを作成できます。両方のアプローチを使用した例を次に示します。 + +### JSON設定の使用 + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### マークダウンファイルの使用 + +モード ファイルをプロジェクト固有モードの場合は `.opencode/modes/` に、グローバル モードの場合は `~/.config/opencode/modes/` に作成します。 + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### ユースケース + +さまざまなモードの一般的な使用例をいくつか示します。 + +- **ビルド モード**: すべてのツールを有効にした完全な開発作業 +- **計画モード**: 変更を加えずに分析および計画を立てる +- **レビュー モード**: 読み取り専用アクセスとドキュメント ツールによるコード レビュー +- **デバッグ モード**: bash および読み取りツールを有効にして調査に重点を置きます +- **ドキュメント モード**: ファイル操作を使用してドキュメントを作成しますが、システム コマンドは使用しません + +また、さまざまなユースケースにさまざまなモデルが適していることがわかるかもしれません。 diff --git a/packages/web/src/content/docs/ja/network.mdx b/packages/web/src/content/docs/ja/network.mdx new file mode 100644 index 000000000..44fed17fd --- /dev/null +++ b/packages/web/src/content/docs/ja/network.mdx @@ -0,0 +1,57 @@ +--- +title: ネットワーク +description: プロキシとカスタム証明書を構成します。 +--- + +OpenCode は、エンタープライズ ネットワーク環境の標準プロキシ環境変数とカスタム証明書をサポートしています。 + +--- + +## プロキシ + +OpenCode は標準のプロキシ環境変数を尊重します。 + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::注意 +TUI はローカル HTTP サーバーと通信します。ルーティング ループを防ぐには、この接続のプロキシをバイパスする必要があります。 +::: + +サーバーのポートとホスト名は、[CLI flags](/docs/cli#run). + +--- + +### 認証する + +プロキシで基本認証が必要な場合は、URL に資格情報を含めます。 + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::注意 +パスワードのハードコーディングは避けてください。環境変数または安全な認証情報ストレージを使用します。 +::: + +NTLM や Kerberos などの高度な認証を必要とするプロキシの場合は、認証方法をサポートする LLM ゲートウェイの使用を検討してください。 + +--- + +## カスタム証明書 + +企業が HTTPS 接続にカスタム CA を使用している場合は、それらを信頼するように OpenCode を構成します。 + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +これは、プロキシ接続と直接 API アクセスの両方で機能します。 diff --git a/packages/web/src/content/docs/ja/permissions.mdx b/packages/web/src/content/docs/ja/permissions.mdx new file mode 100644 index 000000000..16f0cac89 --- /dev/null +++ b/packages/web/src/content/docs/ja/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: 権限 +description: どのアクションの実行に承認が必要かを制御します。 +--- + +OpenCode は `permission` 構成を使用して、特定のアクションを自動的に実行するか、プロンプトを表示するか、ブロックするかを決定します。 + +`v1.1.1` の時点で、従来の `tools` ブール値設定は非推奨となり、`permission` にマージされました。古い `tools` 構成は、下位互換性のために引き続きサポートされています。 + +--- + +## アクション + +各権限ルールは次のいずれかに解決されます。 + +- `"allow"` — 承認なしで実行します +- `"ask"` — 承認を求めるプロンプト +- `"deny"` — アクションをブロックする + +--- + +## 構成 + +権限をグローバルに (`*` を使用して) 設定し、特定のツールをオーバーライドできます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +すべての権限を一度に設定することもできます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## 詳細なルール (オブジェクト構文) + +ほとんどの権限では、オブジェクトを使用して、ツール入力に基づいてさまざまなアクションを適用できます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +ルールはパターン マッチによって評価され、**最後に一致したルールが優先されます**。一般的なパターンは、キャッチオール `"*"` ルールを最初に置き、その後により具体的なルールを置くことです。 + +### ワイルドカード + +許可パターンでは、単純なワイルドカード マッチングを使用します。 + +- `*` は 0 個以上の任意の文字と一致します +- `?` は 1 つの文字に正確に一致します +- 他のすべての文字は文字通り一致します + +### ホームディレクトリの拡張 + +パターンの先頭で `~` または `$HOME` を使用して、ホーム ディレクトリを参照できます。これは、[`external_directory`](#external-directories) ルールに特に役立ちます。 + +- `~/projects/*` -> `/Users/username/projects/*` +- `~/projects/*` -> `/Users/username/projects/*` +- `~/projects/*` -> `/Users/username/projects/*` + +### 外部ディレクトリ + +`external_directory` を使用して、OpenCode が開始された作業ディレクトリの外部のパスに触れるツール呼び出しを許可します。これは、パスを入力として受け取るすべてのツール (`read`、`edit`、`list`、`glob`、`grep`、および多くの `bash` コマンドなど) に適用されます。 + +ホーム拡張 (`~/...` など) は、パターンの記述方法にのみ影響します。外部パスは現在のワークスペースの一部にはならないため、作業ディレクトリの外部のパスも `external_directory` 経由で許可する必要があります。 + +たとえば、これにより、`~/projects/personal/` の下にあるすべてのものへのアクセスが許可されます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +ここで許可されるディレクトリはすべて、現在のワークスペースと同じデフォルトを継承します。 [`read` のデフォルトは `allow`](#defaults) であるため、オーバーライドされない限り、`external_directory` の下のエントリの読み取りも許可されます。読み取りを保持しながら編集をブロックするなど、ツールをこれらのパスで制限する必要がある場合は、明示的なルールを追加します。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +信頼できるパスに重点を置いたリストを維持し、他のツール (`bash` など) の必要に応じて追加の許可または拒否ルールを追加します。 + +--- + +## 利用可能な権限 + +OpenCode のアクセス許可は、ツール名に加えて、いくつかの安全対策によってキー化されます。 + +- `read` — ファイルの読み取り (ファイルパスと一致) +- `edit` — すべてのファイル変更 (`edit`、`write`、`patch`、`multiedit` をカバー) +- `glob` — ファイルのグロビング (グロブパターンと一致) +- `grep` — コンテンツ検索 (正規表現パターンと一致) +- `list` — ディレクトリ内のファイルのリスト (ディレクトリ パスと一致) +- `bash` — シェルコマンドの実行 (`git status --porcelain` などの解析されたコマンドと一致します) +- `task` — サブエージェントの起動 (サブエージェントのタイプと一致) +- `skill` — スキルをロードしています(スキル名と一致します) +- `lsp` — LSP クエリの実行 (現在は非細分性) +- `todoread`、`todowrite` — ToDo リストの読み取り/更新 +- `webfetch` — URL を取得します (URL と一致します) +- `websearch`、`codesearch` — Web/コード検索 (クエリと一致) +- `external_directory` — ツールがプロジェクトの作業ディレクトリ外のパスにアクセスするとトリガーされます。 +- `doom_loop` — 同じ入力で同じツール呼び出しが 3 回繰り返されたときにトリガーされます。 + +--- + +## デフォルト + +何も指定しない場合、OpenCode は許容的なデフォルトから開始します。 + +- ほとんどの権限はデフォルトで `"allow"` に設定されます。 +- `doom_loop` と `external_directory` のデフォルトは `"ask"` です。 +- `read` は `"allow"` ですが、`.env` ファイルはデフォルトで拒否されます。 + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## 「尋ねる」ということ + +OpenCode が承認を求めるプロンプトを表示すると、UI は 3 つの結果を提供します。 + +- `once` — このリクエストのみを承認します +- `always` — 提案されたパターンに一致する今後のリクエストを承認します(現在の OpenCode セッションの残りの部分) +- `reject` — リクエストを拒否します + +`always` が承認するパターンのセットは、ツールによって提供されます (たとえば、bash の承認では通常、`git status*` のような安全なコマンド プレフィックスがホワイトリストに登録されます)。 + +--- + +## エージェント + +エージェントごとに権限をオーバーライドできます。エージェントの権限はグローバル設定とマージされ、エージェント ルールが優先されます。 [エージェントの権限について詳しくは、](/docs/agents#permissions) をご覧ください。 + +:::注記 +パターン マッチングの詳細な例については、上記の「粒度ルール (オブジェクト構文)](#granular-rules-object-syntax)」セクションを参照してください。 +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +マークダウンでエージェントの権限を構成することもできます。 + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::ヒント +引数のあるコマンドにはパターン マッチングを使用します。 `"grep *"` は `grep pattern file.txt` を許可しますが、`"grep"` だけではブロックされます。 `git status` のようなコマンドはデフォルトの動作で機能しますが、引数を渡すときに明示的な許可 (`"git status *"` など) が必要です。 +::: diff --git a/packages/web/src/content/docs/ja/plugins.mdx b/packages/web/src/content/docs/ja/plugins.mdx new file mode 100644 index 000000000..e83b41103 --- /dev/null +++ b/packages/web/src/content/docs/ja/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: プラグイン +description: OpenCode を拡張する独自のプラグインを作成します。 +--- + +プラグインを使用すると、さまざまなイベントにフックして動作をカスタマイズすることで OpenCode を拡張できます。プラグインを作成して、新しい機能を追加したり、外部サービスと統合したり、OpenCode のデフォルトの動作を変更したりできます。 + +たとえば、コミュニティによって作成された [plugins](/docs/ecosystem#plugins) をチェックしてください。 + +--- + +## プラグインを使用する + +プラグインをロードするには 2 つの方法があります。 + +--- + +### ローカルファイルから + +JavaScript または TypeScript ファイルをプラグイン ディレクトリに配置します。 + +- `.opencode/plugins/` - プロジェクトレベルのプラグイン +- `~/.config/opencode/plugins/` - グローバルプラグイン + +これらのディレクトリ内のファイルは起動時に自動的にロードされます。 + +--- + +### npmから + +構成ファイルで npm パッケージを指定します。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +通常の npm パッケージとスコープ指定された npm パッケージの両方がサポートされています。 + +[ecosystem](/docs/ecosystem#plugins). + +--- + +### プラグインのインストール方法 + +**npm プラグイン** は、起動時に Bun を使用して自動的にインストールされます。パッケージとその依存関係は `~/.cache/opencode/node_modules/` にキャッシュされます。 + +**ローカル プラグイン**は、プラグイン ディレクトリから直接ロードされます。外部パッケージを使用するには、config ディレクトリ内に `package.json` を作成するか ([Dependency](#dependencies) を参照)、プラグインを npm に公開して [config](/docs/config#plugins) に追加する] 必要があります。 + +--- + +### ロード順序 + +プラグインはすべてのソースからロードされ、すべてのフックが順番に実行されます。ロード順序は次のとおりです。 + +1. グローバル構成 (`~/.config/opencode/opencode.json`) +2. プロジェクト構成 (`opencode.json`) +3. グローバルプラグインディレクトリ (`~/.config/opencode/plugins/`) +4. プロジェクトプラグインディレクトリ (`.opencode/plugins/`) + +同じ名前とバージョンを持つ重複した npm パッケージは 1 回ロードされます。ただし、似た名前のローカル プラグインと npm プラグインは両方とも別々にロードされます。 + +--- + +## プラグインを作成する + +プラグインは、1 つ以上のプラグインをエクスポートする **JavaScript/TypeScript モジュール**です +機能。各関数はコンテキスト オブジェクトを受け取り、フック オブジェクトを返します。 + +--- + +### 依存関係 + +ローカル プラグインとカスタム ツールは外部の npm パッケージを使用できます。必要な依存関係を含む `package.json` を config ディレクトリに追加します。 + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode は起動時に `bun install` を実行してこれらをインストールします。プラグインとツールはそれらをインポートできるようになります。 + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### 基本構造 + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +プラグイン関数は以下を受け取ります。 + +- `project`: 現在のプロジェクト情報。 +- `directory`: 現在の作業ディレクトリ。 +- `worktree`: git ワークツリーのパス。 +- `client`: AI と対話するためのオープンコード SDK クライアント。 +- `$`: Bun の [コマンドを実行するためのシェル API](https://bun.com/docs/runtime/shell)。 + +--- + +### TypeScript のサポート + +TypeScript プラグインの場合、プラグイン パッケージから型をインポートできます。 + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### イベント + +以下の「例」セクションに示すように、プラグインはイベントをサブスクライブできます。利用可能なさまざまなイベントのリストは次のとおりです。 + +#### コマンドイベント + +- `command.executed` + +#### ファイルイベント + +- `command.executed` +- `command.executed` + +#### インストールイベント + +- `command.executed` + +#### LSPイベント + +- `command.executed` +- `command.executed` + +#### メッセージイベント + +- `command.executed` +- `command.executed` +- `command.executed` +- `command.executed` + +#### 許可イベント + +- `command.executed` +- `command.executed` + +#### サーバーイベント + +- `command.executed` + +#### セッションイベント + +- `command.executed` +- `command.executed` +- `command.executed` +- `command.executed` +- `command.executed` +- `command.executed` +- `command.executed` +- `command.executed` + +#### Todoイベント + +- `command.executed` + +#### シェルイベント + +- `command.executed` + +#### ツールイベント + +- `command.executed` +- `command.executed` + +#### TUIイベント + +- `command.executed` +- `command.executed` +- `command.executed` + +--- + +## 例 + +ここでは、オープンコードを拡張するために使用できるプラグインの例をいくつか示します。 + +--- + +### 通知を送信する + +特定のイベントが発生したときに通知を送信します。 + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +macOS 上で AppleScript を実行するために `osascript` を使用しています。ここでは通知を送信するために使用しています。 + +:::注記 +OpenCode デスクトップ アプリを使用している場合は、応答の準備ができたとき、またはセッション エラーが発生したときにシステム通知を自動的に送信できます。 +::: + +--- + +### .env 保護 + +opencode が `.env` ファイルを読み取らないようにします。 + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### 環境変数を挿入する + +すべてのシェル実行 (AI ツールとユーザー端末) に環境変数を挿入します。 + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### カスタムツール + +プラグインはオープンコードにカスタム ツールを追加することもできます。 + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +`tool` ヘルパーは、opencode が呼び出すことができるカスタム ツールを作成します。 Zod スキーマ関数を受け取り、次のようなツール定義を返します。 + +- `description`: ツールの機能 +- `args`: ツールの引数の Zod スキーマ +- `execute`: ツールが呼び出されたときに実行される関数 + +カスタム ツールは、組み込みツールと並行してオープンコードに使用できます。 + +--- + +### ロギング + +構造化ログには `console.log` の代わりに `client.app.log()` を使用します。 + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +レベル: `debug`、`info`、`warn`、`error`。詳細については、[SDK ドキュメント](https://opencode.ai/docs/sdk) を参照してください。 + +--- + +### 圧縮フック + +セッションが圧縮されたときに含まれるコンテキストをカスタマイズします。 + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +`experimental.session.compacting` フックは、LLM が継続概要を生成する前に起動します。これを使用して、デフォルトの圧縮プロンプトでは見逃されるドメイン固有のコンテキストを挿入します。 + +`output.prompt` を設定することで、圧縮プロンプトを完全に置き換えることもできます。 + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +`output.prompt` を設定すると、デフォルトの圧縮プロンプトが完全に置き換えられます。この場合、`output.context` 配列は無視されます。 diff --git a/packages/web/src/content/docs/ja/providers.mdx b/packages/web/src/content/docs/ja/providers.mdx new file mode 100644 index 000000000..8ac371358 --- /dev/null +++ b/packages/web/src/content/docs/ja/providers.mdx @@ -0,0 +1,1895 @@ +--- +title: プロバイダー +description: OpenCode で LLM プロバイダーを使用する。 +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode は [AI SDK](https://ai-sdk.dev/) および [Models.dev](https://models.dev) を使用して **75 以上の LLM プロバイダー** をサポートし、ローカル モデルの実行をサポートします。 + +プロバイダーを追加するには、次のことを行う必要があります。 + +1. `/connect` コマンドを使用して、プロバイダーの API キーを追加します。 +2. OpenCode 構成でプロバイダーを構成します。 + +--- + +### 資格 + +`/connect` コマンドを使用してプロバイダーの API キーを追加すると、それらは保存されます +`~/.local/share/opencode/auth.json`で。 + +--- + +### 構成 + +OpenCode の `provider` セクションを通じてプロバイダーをカスタマイズできます。 +config. + +--- + +#### ベース URL + +`baseURL` オプションを設定することで、任意のプロバイダーのベース URL をカスタマイズできます。これは、プロキシ サービスまたはカスタム エンドポイントを使用する場合に便利です。 + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen は、OpenCode チームが提供するモデルのリストです。 +OpenCode で適切に動作することがテストおよび検証されています。 [詳細はこちら](/docs/zen)。 + +:::ヒント +初めての方は、OpenCode Zen から始めることをお勧めします。 +::: + +1. TUI で `/connect` コマンドを実行し、opencode を選択して、[opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. サインインし、お支払いの詳細を追加し、API キーをコピーします。 + +3. API キーを貼り付けます。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. TUI で `/models` を実行すると、推奨されるモデルのリストが表示されます。 + + ```txt + /models + ``` + +これは OpenCode の他のプロバイダーと同様に機能し、使用は完全にオプションです。 + +--- + +## ディレクトリ + +いくつかのプロバイダーを詳しく見てみましょう。プロバイダーを追加したい場合は、 +リストにある場合は、お気軽に PR を開いてください。 + +:::注記 +ここにプロバイダーが表示されない場合は、 PRを送信してください。 +::: + +--- + +### 302.AI + +1. [302.AI console](https://302.ai/) に移動し、アカウントを作成し、API キーを生成します。 + +2. `/connect` コマンドを実行し、**302.AI** を検索します。 + + ```txt + /connect + ``` + +3. 302.AI API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行してモデルを選択します。 + + ```txt + /models + ``` + +--- + +### アマゾンの岩盤 + +OpenCode で Amazon Bedrock を使用するには: + +1. Amazon Bedrock コンソールの **モデル カタログ** に移動してリクエストします。 + 必要なモデルにアクセスします。 + +:::ヒント +Amazon Bedrock で必要なモデルにアクセスできる必要があります。 +::: + +2. **次のいずれかの方法を使用して認証を構成します**。 + + #### 環境変数 (クイック スタート) + +opencode の実行中に次の環境変数のいずれかを設定します。 + +```bash +# Option 1: Using AWS access keys +AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + +# Option 2: Using named AWS profile +AWS_PROFILE=my-profile opencode + +# Option 3: Using Bedrock bearer token +AWS_BEARER_TOKEN_BEDROCK=XXX opencode +``` + +または、それらを bash プロファイルに追加します。 + +```bash title="~/.bash_profile" +export AWS_PROFILE=my-dev-profile +export AWS_REGION=us-east-1 +``` + +#### 設定ファイル (推奨) + +プロジェクト固有の構成または永続的な構成の場合は、`opencode.json` を使用します。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } +} +``` + +**利用可能なオプション:** + +- `region` - AWS リージョン (例: `us-east-1`、`eu-west-1`) +- `profile` - `~/.aws/credentials` からの AWS 名前付きプロファイル +- `endpoint` - VPC エンドポイントのカスタム エンドポイント URL (汎用 `baseURL` オプションのエイリアス) + +:::ヒント +構成ファイルのオプションは環境変数より優先されます。 +::: + +#### 上級: VPC エンドポイント + +Bedrock の VPC エンドポイントを使用している場合: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +:::注記 +`endpoint` オプションは、AWS 固有の用語を使用した汎用の `baseURL` オプションのエイリアスです。 `endpoint` と `baseURL` の両方が指定された場合は、`endpoint` が優先されます。 +::: + +#### 認証方法 + +- **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: IAM ユーザーを作成し、AWS コンソールでアクセス キーを生成します。 +- **`AWS_PROFILE`**: `~/.aws/credentials` の名前付きプロファイルを使用します。最初に `aws configure --profile my-profile` または `aws sso login` を設定します +- **`AWS_BEARER_TOKEN_BEDROCK`**: Amazon Bedrock コンソールから長期 API キーを生成します +- **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: EKS IRSA (サービス アカウントの IAM ロール) または OIDC フェデレーションを備えた他の Kubernetes 環境の場合。これらの環境変数は、サービス アカウント アノテーションを使用するときに Kubernetes によって自動的に挿入されます。 + +#### 認証の優先順位 + +Amazon Bedrock は次の認証優先度を使用します。 + +1. **ベアラー トークン** - `AWS_BEARER_TOKEN_BEDROCK` 環境変数または `/connect` コマンドからのトークン +2. **AWS 認証情報チェーン** - プロファイル、アクセス キー、共有認証情報、IAM ロール、Web ID トークン (EKS IRSA)、インスタンス メタデータ + +:::注記 +ベアラー トークンが (`/connect` または `AWS_BEARER_TOKEN_BEDROCK` 経由で) 設定されると、設定されたプロファイルを含むすべての AWS 認証情報方法よりも優先されます。 +::: + +3. `/models` コマンドを実行して、必要なモデルを選択します。 + + ```txt + /models + ``` + +:::注記 +カスタム推論プロファイルの場合、キーでモデルとプロバイダー名を使用し、`id` プロパティを arn に設定します。これにより、正しいキャッシュが保証されます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### 人間的 + +1. サインアップしたら、`/connect` コマンドを実行し、[Anthropic] を選択します。 + + ```txt + /connect + ``` + +2. ここで **Claude Pro/Max** オプションを選択すると、ブラウザが開きます + そして認証を求められます。 + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. これで、`/models` コマンドを使用すると、すべての人智モデルが利用できるようになります。 + + ```txt + /models + ``` + +:::情報 +OpenCode での Claude Pro/Max サブスクリプションの使用は、[Anthropic](https://anthropic.com). +::: + +##### APIキーの使用 + +Pro/Max サブスクリプションをお持ちでない場合は、[**API キーの作成**] を選択することもできます。また、ブラウザが開き、Anthropic にログインするよう求められ、端末に貼り付けるコードが表示されます。 + +または、すでに API キーをお持ちの場合は、[**API キーを手動で入力**] を選択してターミナルに貼り付けることができます。 + +--- + +### Azure OpenAI + +:::注記 +「申し訳ありませんが、そのリクエストには対応できません」エラーが発生した場合は、Azure リソースのコンテンツ フィルターを **DefaultV2** から **Default** に変更してみてください。 +::: + +1. [Azure portal](https://portal.azure.com/) に移動し、**Azure OpenAI** リソースを作成します。必要なものは次のとおりです。 + - **リソース名**: これは API エンドポイント (`https://RESOURCE_NAME.openai.azure.com/`) の一部になります。 + - **API キー**: リソースの `KEY 1` または `KEY 2` のいずれか + +2. [Azure AI Foundry](https://ai.azure.com/) に移動し、モデルをデプロイします。 + +:::注記 +オープンコードが正しく動作するには、デプロイメント名がモデル名と一致する必要があります。 +::: + +3. `/connect` コマンドを実行し、**Azure** を検索します。 + + ```txt + /connect + ``` + +4. API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. リソース名を環境変数として設定します。 + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + +または、bash プロファイルに追加します。 + +```bash title="~/.bash_profile" +export AZURE_RESOURCE_NAME=XXX +``` + +6. `/models` コマンドを実行して、デプロイされたモデルを選択します。 + + ```txt + /models + ``` + +--- + +### Azure コグニティブ サービス + +1. [Azure portal](https://portal.azure.com/) に移動し、**Azure OpenAI** リソースを作成します。必要なものは次のとおりです。 + - **リソース名**: これは API エンドポイント (`https://RESOURCE_NAME.openai.azure.com/`) の一部になります。 + - **API キー**: リソースの `KEY 1` または `KEY 2` のいずれか + +2. [Azure AI Foundry](https://ai.azure.com/) に移動し、モデルをデプロイします。 + +:::注記 +オープンコードが正しく動作するには、デプロイメント名がモデル名と一致する必要があります。 +::: + +3. `/connect` コマンドを実行し、**Azure Cognitive Services** を検索します。 + + ```txt + /connect + ``` + +4. API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. リソース名を環境変数として設定します。 + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + +または、bash プロファイルに追加します。 + +```bash title="~/.bash_profile" +export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX +``` + +6. `/models` コマンドを実行して、デプロイされたモデルを選択します。 + + ```txt + /models + ``` + +--- + +### ベーステン + +1. [Baseten](https://app.baseten.co/) に移動し、アカウントを作成し、API キーを生成します。 + +2. `/connect` コマンドを実行し、**Baseten** を検索します。 + + ```txt + /connect + ``` + +3. Baseten API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行してモデルを選択します。 + + ```txt + /models + ``` + +--- + +### 大脳 + +1. [Cerebras console](https://inference.cerebras.ai/) に移動し、アカウントを作成し、API キーを生成します。 + +2. `/connect` コマンドを実行し、**Cerebras** を検索します。 + + ```txt + /connect + ``` + +3. Cerebras API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_Qwen 3 Coder 480B_ のようなモデルを選択します。 + + ```txt + /models + ``` + +--- + +### Cloudflare AI ゲートウェイ + +Cloudflare AI Gatewayを使用すると、統合エンドポイントを通じてOpenAI、Anthropic、Workers AIなどのモデルにアクセスできます。 [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) を使用すると、プロバイダーごとに個別の API キーは必要ありません。 + +1. [Cloudflare ダッシュボード ](https://dash.cloudflare.com/) に移動し、**AI** > **AI ゲートウェイ** に移動し、新しいゲートウェイを作成します。 + +2. アカウント ID とゲートウェイ ID を環境変数として設定します。 + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. `/connect` コマンドを実行し、**Cloudflare AI Gateway** を検索します。 + + ```txt + /connect + ``` + +4. Cloudflare API トークンを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +または環境変数として設定します。 + +```bash title="~/.bash_profile" +export CLOUDFLARE_API_TOKEN=your-api-token +``` + +5. `/models` コマンドを実行してモデルを選択します。 + + ```txt + /models + ``` + +オープンコード構成を通じてモデルを追加することもできます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } +} +``` + +--- + +### コルテックス + +1. [Cortecs console](https://cortecs.ai/) に移動し、アカウントを作成し、API キーを生成します。 + +2. `/connect` コマンドを実行し、**Cortecs** を検索します。 + + ```txt + /connect + ``` + +3. Cortecs API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_Kimi K2 Instruct_ のようなモデルを選択します。 + + ```txt + /models + ``` + +--- + +### ディープシーク + +1. [DeepSeek コンソール ](https://platform.deepseek.com/) に移動し、アカウントを作成し、**新しい API キーの作成** をクリックします。 + +2. `/connect` コマンドを実行し、**DeepSeek** を検索します。 + + ```txt + /connect + ``` + +3. DeepSeek API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_DeepSeek Reasoner_ のような DeepSeek モデルを選択します。 + + ```txt + /models + ``` + +--- + +### ディープインフラ + +1. [Deep Infra ダッシュボード](https://deepinfra.com/dash) に移動し、アカウントを作成し、API キーを生成します。 + +2. `/connect` コマンドを実行し、**Deep Infra** を検索します。 + + ```txt + /connect + ``` + +3. Deep Infra API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行してモデルを選択します。 + + ```txt + /models + ``` + +--- + +### ファームウェア + +1. [ファームウェア ダッシュボード](https://app.firmware.ai/signup) に移動し、アカウントを作成し、API キーを生成します。 + +2. `/connect` コマンドを実行し、**ファームウェア**を検索します。 + + ```txt + /connect + ``` + +3. ファームウェア API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行してモデルを選択します。 + + ```txt + /models + ``` + +--- + +### 花火AI + +1. [Fireworks AI コンソール ](https://app.fireworks.ai/) に移動し、アカウントを作成し、**API キーの作成** をクリックします。 + +2. `/connect` コマンドを実行し、**Fireworks AI** を検索します。 + + ```txt + /connect + ``` + +3. Fireworks AI API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_Kimi K2 Instruct_ のようなモデルを選択します。 + + ```txt + /models + ``` + +--- + +### GitLab デュオ + +GitLab Duo は、GitLab の Anthropic プロキシを介したネイティブ ツール呼び出し機能を備えた AI を活用したエージェント チャットを提供します。 + +1. `/connect` コマンドを実行し、GitLab を選択します。 + + ```txt + /connect + ``` + +2. 認証方法を選択してください: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### OAuthの使用(推奨) + +**OAuth** を選択すると、認証のためにブラウザが開きます。 + +#### パーソナルアクセストークンの使用 + +1. [GitLab ユーザー設定 > アクセス Tokens](https://gitlab.com/-/user_settings/personal_access_tokens) に移動します。 +2. **新しいトークンを追加** をクリックします +3. 名前: `OpenCode`、スコープ: `api` +4. トークンをコピーします(`glpat-`で始まる) +5. ターミナルに入力してください + +6. `/models` コマンドを実行して、利用可能なモデルを確認します。 + + ```txt + /models + ``` + +3 つのクロードベースのモデルが利用可能です。 + +- **duo-chat-haiku-4-5** (デフォルト) - 素早いタスクに対する素早い応答 +- **duo-chat-sonnet-4-5** - ほとんどのワークフローでバランスの取れたパフォーマンス +- **duo-chat-opus-4-5** - 複雑な分析に最も適した能力 + +:::注記 +必要がない場合は、「GITLAB_TOKEN」環境変数を指定することもできます。 +トークンをオープンコード認証ストレージに保存します。 +::: + +##### 自己ホスト型 GitLab + +:::note[コンプライアンスメモ] +OpenCode は、セッション タイトルの生成などの一部の AI タスクに小規模なモデルを使用します。 +デフォルトでは、Zen によってホストされる gpt-5-nano を使用するように構成されています。 OpenCodeをロックするには +自分の GitLab でホストされているインスタンスのみを使用するには、次の行を +`opencode.json` ファイル。セッション共有を無効にすることもお勧めします。 + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +セルフホスト型 GitLab インスタンスの場合: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +インスタンスがカスタム AI ゲートウェイを実行している場合: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +または、bash プロファイルに追加します。 + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::注記 +GitLab 管理者は以下を有効にする必要があります。 + +1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) (ユーザー、グループ、またはインスタンス用) +2. 機能フラグ (Rails コンソール経由): + - `command.executed` + - `command.executed` + ::: + +##### セルフホスト型インスタンスの OAuth + +自己ホスト型インスタンスで Oauth を機能させるには、以下を作成する必要があります。 +新しいアプリケーション ([設定] → [アプリケーション]) で、 +コールバック URL `http://127.0.0.1:8080/callback` と次のスコープ: + +- api (あなたの代わりに API にアクセスします) +- read_user (個人情報の読み取り) +- read_repository (リポジトリへの読み取り専用アクセスを許可します) + +次に、アプリケーション ID を環境変数として公開します。 + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +詳細については、[opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth) ホームページ。 + +##### 構成 + +`opencode.json` を通じてカスタマイズします。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API ツール (オプションですが強く推奨) + +GitLab ツール (マージ リクエスト、問題、パイプライン、CI/CD など) にアクセスするには: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +このプラグインは、MR レビュー、問題追跡、パイプライン監視などを含む、包括的な GitLab リポジトリ管理機能を提供します。 + +--- + +### GitHub コパイロット + +GitHub Copilot サブスクリプションをオープンコードで使用するには: + +:::注記 +一部のモデルでは [Pro+] が必要になる場合があります。 +subscription](https://github.com/features/copilot/plans) を使用します。 + +一部のモデルは、[GitHub Copilot settings](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. `/connect` コマンドを実行し、GitHub Copilot を検索します。 + + ```txt + /connect + ``` + +2. [github.com/login/device](https://github.com/login/device) に移動し、コードを入力します。 + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. 次に、`/models` コマンドを実行して、必要なモデルを選択します。 + + ```txt + /models + ``` + +--- + +### Google バーテックス AI + +OpenCode で Google Vertex AI を使用するには: + +1. Google Cloud Console の **Model Garden** に移動し、 + お住まいの地域で利用可能なモデル。 + +:::注記 +Vertex AI API が有効になっている Google Cloud プロジェクトが必要です。 +::: + +2. 必要な環境変数を設定します。 + - `GOOGLE_CLOUD_PROJECT`: Google Cloud プロジェクト ID + - `VERTEX_LOCATION` (オプション): Vertex AI の領域 (デフォルトは `global`) + - 認証 (1 つ選択): + - `GOOGLE_APPLICATION_CREDENTIALS`: サービス アカウントの JSON キー ファイルへのパス + - gcloud CLI を使用して認証する: `gcloud auth application-default login` + +opencode の実行中に設定します。 + +```bash +GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode +``` + +または、それらを bash プロファイルに追加します。 + +```bash title="~/.bash_profile" +export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json +export GOOGLE_CLOUD_PROJECT=your-project-id +export VERTEX_LOCATION=global +``` + +:::ヒント +`global` 領域は、追加コストなしで可用性を向上させ、エラーを削減します。データ常駐要件には、リージョン エンドポイント (`us-central1` など) を使用します。 [詳細はこちら](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. `/models` コマンドを実行して、必要なモデルを選択します。 + + ```txt + /models + ``` + +--- + +### グロク + +1. [Groq console](https://console.groq.com/) に移動し、[**API キーの作成**] をクリックして、キーをコピーします。 + +2. `/connect` コマンドを実行し、Groq を検索します。 + + ```txt + /connect + ``` + +3. プロバイダーの API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、必要なものを選択します。 + + ```txt + /models + ``` + +--- + +### ハグフェイス + +[ハグ顔推論プロバイダー ](https://huggingface.co/docs/inference-providers) は、17 を超えるプロバイダーがサポートするオープン モデルへのアクセスを提供します。 + +1. [Hugging Face settings](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) に移動して、推論プロバイダーを呼び出す権限を持つトークンを作成します。 + +2. `/connect` コマンドを実行し、**Hugging Face** を検索します。 + + ```txt + /connect + ``` + +3. ハグフェイストークンを入力してください。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_Kimi-K2-Instruct_ や _GLM-4.6_ などのモデルを選択します。 + + ```txt + /models + ``` + +--- + +### ヘリコン + +[Helicone](https://helicone.ai) は、AI アプリケーションのロギング、監視、分析を提供する LLM 可観測性プラットフォームです。 Helicone AI ゲートウェイは、モデルに基づいてリクエストを適切なプロバイダーに自動的にルーティングします。 + +1. [Helicone](https://helicone.ai) に移動し、アカウントを作成し、ダッシュボードから API キーを生成します。 + +2. `/connect` コマンドを実行し、**Helicone** を検索します。 + + ```txt + /connect + ``` + +3. Helicone API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行してモデルを選択します。 + + ```txt + /models + ``` + +その他のプロバイダーや、キャッシュやレート制限などの高度な機能については、[Helicone ドキュメント ](https://docs.helicone.ai). + +#### オプションの構成 + +オープンコードを通じて自動的に構成されていない Helicone の機能またはモデルを見つけた場合は、いつでも自分で構成できます。 + +これは [Helicone のモデル ディレクトリ ](https://helicone.ai/models) です。追加するモデルの ID を取得するためにこれが必要になります。 + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### カスタムヘッダー + +Helicone は、キャッシュ、ユーザー追跡、セッション管理などの機能のカスタム ヘッダーをサポートしています。 `options.headers` を使用してプロバイダー構成に追加します。 + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### セッション追跡 + +Helicone の [Sessions](https://docs.helicone.ai/features/sessions) 機能を使用すると、関連する LLM リクエストをグループ化できます。 [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) プラグインを使用して、各 OpenCode 会話を Helicone のセッションとして自動的に記録します。 + +```bash +npm install -g opencode-helicone-session +``` + +それを構成に追加します。 + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +プラグインは、リクエストに `Helicone-Session-Id` ヘッダーと `Helicone-Session-Name` ヘッダーを挿入します。 Helicone のセッション ページでは、OpenCode の各会話が個別のセッションとしてリストされています。 + +##### 一般的なヘリコーンヘッダー + +| ヘッダー | 説明 | +| -------------------------- | ----------------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | 応答キャッシュを有効にする (`true`/`false`) | +| `Helicone-User-Id` | ユーザーごとにメトリクスを追跡する | +| `Helicone-Property-[Name]` | カスタム プロパティを追加します (例: `Helicone-Property-Environment`)。 | +| `Helicone-Prompt-Id` | リクエストをプロンプト バージョンに関連付ける | + +利用可能なすべてのヘッダーについては、[Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory) を参照してください。 + +--- + +### ラマ.cpp + +[llama.cpp の s](https://github.com/ggml-org/llama.cpp) llama-server ユーティリティ] を通じて、ローカル モデルを使用するようにオープンコードを構成できます。 + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +この例では: + +- `llama.cpp` はカスタムプロバイダー ID です。これには任意の文字列を指定できます。 +- `npm` は、このプロバイダーに使用するパッケージを指定します。ここで、`@ai-sdk/openai-compatible` は OpenAI 互換 API に使用されます。 +- `name` は、UI でのプロバイダーの表示名です。 +- `options.baseURL` はローカル サーバーのエンドポイントです。 +- `models` は、モデル ID とその構成のマップです。機種選択リストに機種名が表示されます。 + +--- + +### IO.NET + +IO.NET は、さまざまなユースケースに最適化された 17 のモデルを提供します。 + +1. [IO.NET console](https://ai.io.net/) に移動し、アカウントを作成し、API キーを生成します。 + +2. `/connect` コマンドを実行し、**IO.NET** を検索します。 + + ```txt + /connect + ``` + +3. IO.NET API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行してモデルを選択します。 + + ```txt + /models + ``` + +--- + +### LMスタジオ + +LM Studio を通じてローカル モデルを使用するようにオープンコードを構成できます。 + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +この例では: + +- `llama.cpp` はカスタムプロバイダー ID です。これには任意の文字列を指定できます。 +- `npm` は、このプロバイダーに使用するパッケージを指定します。ここで、`@ai-sdk/openai-compatible` は OpenAI 互換 API に使用されます。 +- `name` は、UI でのプロバイダーの表示名です。 +- `options.baseURL` はローカル サーバーのエンドポイントです。 +- `models` は、モデル ID とその構成のマップです。機種選択リストに機種名が表示されます。 + +--- + +### ムーンショットAI + +Moonshot AI の Kim K2 を使用するには: + +1. [Moonshot AI console](https://platform.moonshot.ai/console) に移動し、アカウントを作成し、[**API キーの作成**] をクリックします。 + +2. `/connect` コマンドを実行し、**Moonshot AI** を検索します。 + + ```txt + /connect + ``` + +3. Moonshot API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_Kimi K2_ を選択します。 + + ```txt + /models + ``` + +--- + +### ミニマックス + +1. [MiniMax API Console](https://platform.minimax.io/login) に移動し、アカウントを作成し、API キーを生成します。 + +2. `/connect` コマンドを実行し、**MiniMax** を検索します。 + + ```txt + /connect + ``` + +3. MiniMax API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_M2.1_ のようなモデルを選択します。 + + ```txt + /models + ``` + +--- + +### ネビウストークンファクトリー + +1. [Nebius Token Factory console](https://tokenfactory.nebius.com/) に移動し、アカウントを作成し、[**キーの追加**] をクリックします。 + +2. `/connect` コマンドを実行し、**Nebius Token Factory** を検索します。 + + ```txt + /connect + ``` + +3. Nebius Token Factory API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_Kimi K2 Instruct_ のようなモデルを選択します。 + + ```txt + /models + ``` + +--- + +### オラマ + +Ollama を通じてローカル モデルを使用するようにオープンコードを構成できます。 + +:::ヒント +Ollama は OpenCode 用に自動的に構成できます。詳細については、「Ollama 統合 docs](https://docs.ollama.com/integrations/opencode)」を参照してください。 +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +この例では: + +- `llama.cpp` はカスタムプロバイダー ID です。これには任意の文字列を指定できます。 +- `npm` は、このプロバイダーに使用するパッケージを指定します。ここで、`@ai-sdk/openai-compatible` は OpenAI 互換 API に使用されます。 +- `name` は、UI でのプロバイダーの表示名です。 +- `options.baseURL` はローカル サーバーのエンドポイントです。 +- `models` は、モデル ID とその構成のマップです。機種選択リストに機種名が表示されます。 + +:::ヒント +ツール呼び出しが機能しない場合は、Ollama の `num_ctx` を増やしてみてください。 16k〜32kあたりから始めてください。 +::: + +--- + +### オラマ・クラウド + +OpenCode で Ollama Cloud を使用するには: + +1. [https://ollama.com/](https://ollama.com/) にアクセスしてサインインするか、アカウントを作成します。 + +2. [**設定**] > [キー**] に移動し、[**API キーの追加**] をクリックして新しい API キーを生成します。 + +3. OpenCode で使用するために API キーをコピーします。 + +4. `/connect` コマンドを実行し、**Ollama Cloud** を検索します。 + + ```txt + /connect + ``` + +5. Ollama Cloud API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **重要**: OpenCode でクラウド モデルを使用する前に、モデル情報をローカルに取得する必要があります。 + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. `/models` コマンドを実行して、Ollama Cloud モデルを選択します。 + + ```txt + /models + ``` + +--- + +### OpenAI + +[ChatGPT Plus または Pro](https://chatgpt.com/pricing) にサインアップすることをお勧めします。 + +1. サインアップしたら、`/connect` コマンドを実行し、OpenAI を選択します。 + + ```txt + /connect + ``` + +2. ここで **ChatGPT Plus/Pro** オプションを選択すると、ブラウザが開きます。 + そして認証を求められます。 + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. これで、`/models` コマンドを使用すると、すべての OpenAI モデルが利用できるようになります。 + + ```txt + /models + ``` + +##### APIキーの使用 + +すでに API キーをお持ちの場合は、**API キーを手動で入力** を選択し、ターミナルに貼り付けることができます。 + +--- + +### OpenCode Zen + +OpenCode Zen は、OpenCode チームによって提供される、テストおよび検証されたモデルのリストです。 [詳細はこちら](/docs/zen)。 + +1. **OpenCode Zen** にサインインし、**API キーの作成** をクリックします。 + +2. `/connect` コマンドを実行し、**OpenCode Zen** を検索します。 + + ```txt + /connect + ``` + +3. OpenCode API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_Qwen 3 Coder 480B_ のようなモデルを選択します。 + + ```txt + /models + ``` + +--- + +### オープンルーター + +1. [OpenRouter ダッシュボード](https://openrouter.ai/settings/keys) に移動し、[**API キーの作成**] をクリックして、キーをコピーします。 + +2. `/connect` コマンドを実行し、OpenRouter を検索します。 + + ```txt + /connect + ``` + +3. プロバイダーの API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 多くの OpenRouter モデルはデフォルトでプリロードされており、`/models` コマンドを実行して必要なモデルを選択します。 + + ```txt + /models + ``` + +オープンコード構成を通じて追加のモデルを追加することもできます。 + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } +} +``` + +5. オープンコード設定を通じてカスタマイズすることもできます。プロバイダーを指定する例を次に示します。 + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP AI コア + +SAP AI コアは、統合プラットフォームを通じて、OpenAI、Anthropic、Google、Amazon、Meta、Mistral、AI21 の 40 以上のモデルへのアクセスを提供します。 + +1. [SAP BTP Cockpit](https://account.hana.ondemand.com/) に移動し、SAP AI コア サービス インスタンスに移動して、サービス キーを作成します。 + +:::ヒント +サービス キーは、`clientid`、`clientsecret`、`url`、および `serviceurls.AI_API_URL` を含む JSON オブジェクトです。 AI コア インスタンスは、BTP コックピットの **サービス** > **インスタンスとサブスクリプション** で見つかります。 +::: + +2. `/connect` コマンドを実行し、**SAP AI Core** を検索します。 + + ```txt + /connect + ``` + +3. サービス キーの JSON を入力します。 + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + +または、`AICORE_SERVICE_KEY` 環境変数を設定します。 + +```bash +AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode +``` + +または、bash プロファイルに追加します。 + +```bash title="~/.bash_profile" +export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' +``` + +4. 必要に応じて、デプロイメント ID とリソース グループを設定します。 + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + +:::注記 +これらの設定はオプションであり、SAP AI コアのセットアップに従って構成する必要があります。 +::: + +5. `/models` コマンドを実行して、40 以上の利用可能なモデルから選択します。 + + ```txt + /models + ``` + +--- + +### OVHcloud AI エンドポイント + +1. [OVHcloud パネル](https://ovh.com/manager) に移動します。 `Public Cloud` セクション、`AI & Machine Learning` > `AI Endpoints` に移動し、`API Keys` タブで **新しい API キーの作成** をクリックします。 + +2. `/connect` コマンドを実行し、**OVHcloud AI エンドポイント**を検索します。 + + ```txt + /connect + ``` + +3. OVHcloud AI エンドポイント API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_gpt-oss-120b_ のようなモデルを選択します。 + + ```txt + /models + ``` + +--- + +### スケールウェイ + +[Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/) を Opencode で使用するには: + +1. [Scaleway Console IAM settings](https://console.scaleway.com/iam/api-keys) に移動して、新しい API キーを生成します。 + +2. `/connect` コマンドを実行し、**Scaleway** を検索します。 + + ```txt + /connect + ``` + +3. Scaleway API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_devstral-2-123b-instruct-2512_ や _gpt-oss-120b_ などのモデルを選択します。 + + ```txt + /models + ``` + +--- + +### 一緒にAI + +1. [Together AI console](https://api.together.ai) に移動し、アカウントを作成し、[**キーの追加**] をクリックします。 + +2. `/connect` コマンドを実行し、**Together AI** を検索します。 + + ```txt + /connect + ``` + +3. Together AI API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_Kimi K2 Instruct_ のようなモデルを選択します。 + + ```txt + /models + ``` + +--- + +### ヴェニス AI + +1. [Venice AI console](https://venice.ai) に移動し、アカウントを作成し、API キーを生成します。 + +2. `/connect` コマンドを実行し、**Venice AI** を検索します。 + + ```txt + /connect + ``` + +3. Venice AI API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_Llama 3.3 70B_ のようなモデルを選択します。 + + ```txt + /models + ``` + +--- + +### Vercel AI ゲートウェイ + +Vercel AI Gateway を使用すると、統合エンドポイントを通じて OpenAI、Anthropic、Google、xAI などのモデルにアクセスできます。モデルは値上げなしの定価で提供されます。 + +1. [Vercel ダッシュボード ](https://vercel.com/) に移動し、**AI ゲートウェイ** タブに移動し、**API キー** をクリックして新しい API キーを作成します。 + +2. `/connect` コマンドを実行し、**Vercel AI Gateway** を検索します。 + + ```txt + /connect + ``` + +3. Vercel AI Gateway API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行してモデルを選択します。 + + ```txt + /models + ``` + +オープンコード構成を通じてモデルをカスタマイズすることもできます。プロバイダーのルーティング順序を指定する例を次に示します。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +いくつかの便利なルーティング オプション: + +| オプション | 説明 | +| ------------------- | ---------------------------------------------------- | +| `order` | 試行するプロバイダー シーケンス | +| `only` | 特定のプロバイダーに制限する | +| `zeroDataRetention` | データ保持ポリシーがゼロのプロバイダーのみを使用する | + +--- + +### xAI + +1. [xAI console](https://console.x.ai/) に移動し、アカウントを作成し、API キーを生成します。 + +2. `/connect` コマンドを実行し、**xAI** を検索します。 + + ```txt + /connect + ``` + +3. xAI API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_Grok Beta_ のようなモデルを選択します。 + + ```txt + /models + ``` + +--- + +### Z.AI + +1. [Z.AI API コンソール ](https://z.ai/manage-apikey/apikey-list) に移動し、アカウントを作成し、**新しい API キーの作成** をクリックします。 + +2. `/connect` コマンドを実行し、**Z.AI** を検索します。 + + ```txt + /connect + ``` + +**GLM コーディング プラン**に加入している場合は、**Z.AI コーディング プラン**を選択します。 + +3. Z.AI API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` コマンドを実行して、_GLM-4.7_ のようなモデルを選択します。 + + ```txt + /models + ``` + +--- + +### ZenMux + +1. [ZenMux ダッシュボード](https://zenmux.ai/settings/keys) に移動し、[**API キーの作成**] をクリックして、キーをコピーします。 + +2. `/connect` コマンドを実行し、ZenMux を検索します。 + + ```txt + /connect + ``` + +3. プロバイダーの API キーを入力します。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 多くの ZenMux モデルはデフォルトでプリロードされており、`/models` コマンドを実行して必要なモデルを選択します。 + + ```txt + /models + ``` + +オープンコード構成を通じて追加のモデルを追加することもできます。 + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } +} +``` + +--- + +## カスタムプロバイダー + +`/connect` コマンドにリストされていない **OpenAI 互換**プロバイダーを追加するには: + +:::ヒント +OpenAI と互換性のある任意のプロバイダーをオープンコードで使用できます。最新の AI プロバイダーのほとんどは、OpenAI 互換の API を提供しています。 +::: + +1. `/connect` コマンドを実行し、**その他**まで下にスクロールします。 + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. プロバイダーの一意の ID を入力します。 + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + +:::注記 +覚えやすい ID を選択してください。これを構成ファイルで使用します。 +::: + +3. プロバイダーの API キーを入力します。 + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. プロジェクト ディレクトリで `opencode.json` ファイルを作成または更新します。 + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + +構成オプションは次のとおりです。 + +- **npm**: 使用する AI SDK パッケージ、OpenAI 互換プロバイダーの場合は `@ai-sdk/openai-compatible` +- **name**: UI での表示名。 +- **モデル**: 利用可能なモデル。 +- **options.baseURL**: API エンドポイント URL。 +- **options.apiKey**: 認証を使用しない場合は、オプションで API キーを設定します。 +- **options.headers**: 必要に応じてカスタム ヘッダーを設定します。 + +詳細オプションの詳細については、以下の例を参照してください。 + +5. `/models` コマンドを実行すると、カスタム プロバイダーとモデルが選択リストに表示されます。 + +--- + +##### 例 + +次に、`apiKey`、`headers`、およびモデル `limit` オプションを設定する例を示します。 + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +構成の詳細: + +- **apiKey**: `env` 変数構文を使用して設定します。[詳細については ](/docs/config#env-vars). +- **headers**: 各リクエストとともに送信されるカスタム ヘッダー。 +- **limit.context**: モデルが受け入れる最大入力トークン。 +- **limit.output**: モデルが生成できる最大トークン。 + +`limit` フィールドを使用すると、OpenCode はコンテキストがどのくらい残っているかを理解できます。標準プロバイダーは、これらを models.dev から自動的に取得します。 + +--- + +## トラブルシューティング + +プロバイダーの構成で問題が発生した場合は、次の点を確認してください。 + +1. **認証設定を確認します**: `opencode auth list` を実行して、資格情報が正しいかどうかを確認します。 + プロバイダー用のものが構成に追加されます。 + +これは、認証に環境変数に依存する Amazon Bedrock のようなプロバイダーには当てはまりません。 + +2. カスタム プロバイダーの場合は、opencode 構成を確認し、次のことを行います。 + - `/connect` コマンドで使用されるプロバイダー ID が、opencode 構成内の ID と一致することを確認してください。 + - プロバイダーには適切な npm パッケージが使用されます。たとえば、Cerebras には `@ai-sdk/cerebras` を使用します。他のすべての OpenAI 互換プロバイダーの場合は、`@ai-sdk/openai-compatible` を使用します。 + - `options.baseURL` フィールドで正しい API エンドポイントが使用されていることを確認してください。 diff --git a/packages/web/src/content/docs/ja/rules.mdx b/packages/web/src/content/docs/ja/rules.mdx new file mode 100644 index 000000000..40a219a71 --- /dev/null +++ b/packages/web/src/content/docs/ja/rules.mdx @@ -0,0 +1,180 @@ +--- +title: ルール +description: オープンコードのカスタム命令を設定します。 +--- + +`AGENTS.md` ファイルを作成することで、opencode にカスタム命令を提供できます。これは Cursor のルールと似ています。これには、特定のプロジェクトに合わせて LLM の動作をカスタマイズするために LLM のコンテキストに含まれる命令が含まれています。 + +--- + +## 初期化する + +新しい `AGENTS.md` ファイルを作成するには、opencode で `/init` コマンドを実行します。 + +:::ヒント +プロジェクトの `AGENTS.md` ファイルを Git にコミットする必要があります。 +::: + +これにより、プロジェクトとそのすべてのコンテンツがスキャンされ、プロジェクトの内容が理解され、それを含む `AGENTS.md` ファイルが生成されます。これは、opencode がプロジェクトをより適切にナビゲートするのに役立ちます。 + +既存の `AGENTS.md` ファイルがある場合、これはそれに追加しようとします。 + +--- + +## 例 + +このファイルを手動で作成することもできます。以下は、`AGENTS.md` ファイルに含めることができるいくつかの例です。 + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +ここにプロジェクト固有の手順を追加します。これはチーム全体で共有されます。 + +--- + +## 種類 + +opencode は、複数の場所からの `AGENTS.md` ファイルの読み取りもサポートしています。そして、これはさまざまな目的に役立ちます。 + +### プロジェクト + +プロジェクト固有のルールのために、プロジェクト ルートに `AGENTS.md` を配置します。これらは、このディレクトリまたはそのサブディレクトリで作業している場合にのみ適用されます。 + +### グローバル + +`~/.config/opencode/AGENTS.md` ファイルにグローバル ルールを含めることもできます。これは、すべてのオープンコード セッションに適用されます。 + +これは Git にコミットされておらず、チームと共有されていないため、LLM が従うべき個人ルールを指定するためにこれを使用することをお勧めします。 + +### クロードコードの互換性 + +Claude Code から移行するユーザーのために、OpenCode はフォールバックとして Claude Code のファイル規則をサポートしています。 + +- **プロジェクト ルール**: プロジェクト ディレクトリ内の `CLAUDE.md` (`AGENTS.md` が存在しない場合に使用されます) +- **グローバル ルール**: `~/.claude/CLAUDE.md` (`~/.config/opencode/AGENTS.md` が存在しない場合に使用) +- **スキル**: `~/.claude/skills/` — 詳細については、[エージェント スキル ](/docs/skills/) を参照してください。 + +クロード コードの互換性を無効にするには、次の環境変数のいずれかを設定します。 + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## 優先順位 + +opencode が開始されると、次の順序でルール ファイルが検索されます。 + +1. **ローカル ファイル** (現在のディレクトリから上に移動) (`AGENTS.md`、`CLAUDE.md`) +2. **グローバル ファイル** (`~/.config/opencode/AGENTS.md`) +3. **クロード コード ファイル** (`~/.claude/CLAUDE.md` にあります) (無効になっていない限り) + +最初に一致したファイルが各カテゴリで優勝します。たとえば、`AGENTS.md` と `CLAUDE.md` の両方がある場合、`AGENTS.md` のみが使用されます。同様に、`~/.config/opencode/AGENTS.md` は `~/.claude/CLAUDE.md` よりも優先されます。 + +--- + +## カスタム指示 + +`opencode.json` またはグローバル `~/.config/opencode/opencode.json` でカスタム命令ファイルを指定できます。これにより、あなたとあなたのチームは、既存のルールを AGENTS.md に複製するのではなく、再利用することができます。 + +例: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +リモート URL を使用して Web から命令をロードすることもできます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +リモート命令は 5 秒のタイムアウトでフェッチされます。 + +すべての命令ファイルは `AGENTS.md` ファイルと結合されます。 + +--- + +## 外部ファイルの参照 + +opencode は `AGENTS.md` のファイル参照を自動的に解析しませんが、次の 2 つの方法で同様の機能を実現できます。 + +### opencode.json の使用 + +推奨されるアプローチは、`opencode.json` の `instructions` フィールドを使用することです。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### AGENTS.md のマニュアル手順 + +`AGENTS.md` で明示的な命令を指定することで、オープンコードに外部ファイルを読み取るように教えることができます。実際の例を次に示します。 + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +このアプローチにより、次のことが可能になります。 + +- モジュール式の再利用可能なルール ファイルを作成する +- シンボリックリンクまたは git サブモジュールを介してプロジェクト間でルールを共有する +- 詳細なガイドラインを参照しながら、AGENTS.md を簡潔に保ちます +- opencode が特定のタスクに必要な場合にのみファイルをロードするようにする + +:::ヒント +モノリポジトリまたは共有標準を使用するプロジェクトの場合、グロブ パターン (`packages/*/AGENTS.md` など) で `opencode.json` を使用する方が、手動で指示するよりも保守しやすくなります。 +::: diff --git a/packages/web/src/content/docs/ja/sdk.mdx b/packages/web/src/content/docs/ja/sdk.mdx new file mode 100644 index 000000000..f9f21b329 --- /dev/null +++ b/packages/web/src/content/docs/ja/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: オープンコードサーバー用のタイプセーフな JS クライアント。 +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +opencode JS/TS SDK は、サーバーと対話するためのタイプセーフなクライアントを提供します。 +これを使用して、統合を構築し、オープンコードをプログラムで制御します。 + +[サーバーの仕組みについて詳しくは、](/docs/server) をご覧ください。たとえば、コミュニティによって構築された [projects](/docs/ecosystem#projects) をチェックしてください。 + +--- + +## インストール + +npm から SDK をインストールします。 + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## クライアントの作成 + +オープンコードのインスタンスを作成します。 + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +これにより、サーバーとクライアントの両方が起動します + +#### オプション + +|オプション |タイプ |説明 |デフォルト | +| ---------- | ------------- | ------------------------------ | ----------- | +| `hostname` | `string` |サーバーのホスト名 |うーん +| `port` | `number` |サーバーポート |うーん +| `signal` | `AbortSignal` |キャンセルのためのアボート信号 |うーん +| `timeout` | `number` |サーバー起動のタイムアウト (ミリ秒) |うーん +| `config` | `Config` |構成オブジェクト |うーん + +--- + +## 構成 + +構成オブジェクトを渡して動作をカスタマイズできます。インスタンスは引き続き `opencode.json` を取得しますが、設定をインラインでオーバーライドまたは追加することができます。 + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## クライアントのみ + +すでに実行中のオープンコードのインスタンスがある場合は、それに接続するためのクライアント インスタンスを作成できます。 + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### オプション + +|オプション |タイプ |説明 |デフォルト | +| --------------- | ---------- | -------------------------------- | ----------------------- | +| `baseUrl` | `string` |サーバーの URL |うーん +| `fetch` | `function` |カスタムフェッチの実装 |うーん +| `parseAs` | `string` |応答解析方法 |うーん +| `responseStyle` | `string` |戻り値のスタイル: `data` または `fields` |認証済み +| `throwOnError` | `boolean` | | を返す代わりにエラーをスローします。うーん + +--- + +## 種類 + +SDK には、すべての API タイプの TypeScript 定義が含まれています。それらを直接インポートします。 + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +すべてのタイプはサーバーの OpenAPI 仕様から生成され、タイプ ファイル で使用できます。 + +--- + +## エラー + +SDK は、キャッチして処理できるエラーをスローできます。 + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## API + +SDK は、タイプセーフなクライアントを通じてすべてのサーバー API を公開します。 + +--- + +### グローバル + +|方法 |説明 |応答 | +| ----------------- | ------------------------------- | ------------------------------------ | +| `global.health()` |サーバーの健全性とバージョンを確認する | `{ healthy: true, version: string }` | + +--- + +#### 例 + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### アプリ + +|方法 |説明 |応答 | +| -------------- | ------------------------- | ------------------------------------------- | +| `app.log()` |ログエントリを書き込む | `boolean` | +| `app.agents()` |利用可能なすべてのエージェントをリストする | エージェント[] | + +--- + +#### 例 + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### プロジェクト + +|方法 |説明 |応答 | +| ------------------- | ------------------- | --------------------------------------------- | +| `project.list()` |すべてのプロジェクトをリストする | プロジェクト[] | +| `project.current()` |現在のプロジェクトを取得 | プロジェクト | + +--- + +#### 例 + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### パス + +|方法 |説明 |応答 | +| ------------ | ---------------- | ---------------------------------------- | +| `path.get()` |現在のパスを取得 | パス | + +--- + +#### 例 + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### 構成 + +|方法 |説明 |応答 | +| -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` |構成情報を取得する | 構成 | +| `config.providers()` |プロバイダーとデフォルトのモデルをリストする | `{ providers: `プロバイダ[]`, default: { [key: string]: string } }` | + +--- + +#### 例 + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### セッション + +|方法 |説明 |メモ | +| ---------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` |セッションをリストする |戻り値 セッション[] | +| `session.get({ path })` |セッションを取得 |戻り値 セッション | +| `session.children({ path })` |子セッションをリストする |戻り値 セッション[] | +| `session.create({ body })` |セッションの作成 |戻り値 セッション | +| `session.delete({ path })` |セッションを削除 |戻り値 `boolean` | +| `session.update({ path, body })` |セッションのプロパティを更新する |戻り値 セッション | +| `session.init({ path, body })` |アプリを分析して `AGENTS.md` を作成する |戻り値 `boolean` | +| `session.abort({ path })` |実行中のセッションを中止する |戻り値 `boolean` | +| `session.share({ path })` |セッションを共有する |戻り値 セッション | +| `session.unshare({ path })` |セッションの共有を解除 |戻り値 セッション | +| `session.summarize({ path, body })` |セッションを要約する |戻り値 `boolean` | +| `session.messages({ path })` |セッション内のメッセージをリストする |戻り値 `{ info: `メッセージ`, parts: `Part[]`}[]` | +| `session.message({ path })` |メッセージの詳細を取得する |戻り値 `{ info: `メッセージ`, parts: `Part[]`}` | +| `session.prompt({ path, body })` |プロンプトメッセージを送信する | `body.noReply: true` は UserMessage (コンテキストのみ) を返します。デフォルトでは、AI 応答を含む AssistantMessage を返します。 +| `session.command({ path, body })` |コマンドをセッションに送信 |戻り値 `{ info: `AssistantMessage`, parts: `Part[]`}` | +| `session.shell({ path, body })` |シェルコマンドを実行する |戻り値 AssistantMessage | +| `session.revert({ path, body })` |メッセージを元に戻す |戻り値 セッション | +| `session.unrevert({ path })` |元に戻したメッセージを復元する |戻り値 セッション | +| `postSessionByIdPermissionsByPermissionId({ path, body })` |許可リクエストに応答する |戻り値 `boolean` | + +--- + +#### 例 + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### ファイル + +|方法 |説明 |応答 | +| ------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `find.text({ query })` |ファイル内のテキストを検索 | `path`、`lines`、`line_number`、`absolute_offset`、`submatches` の一致オブジェクトの配列 | +| `find.files({ query })` |ファイルとディレクトリを名前で検索する | `string[]` (パス) | +| `find.symbols({ query })` |ワークスペースのシンボルを検索する | シンボル[] | +| `file.read({ query })` |ファイルを読む | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` |追跡されたファイルのステータスを取得する | ファイル[] | + +`find.files` は、いくつかのオプションのクエリ フィールドをサポートしています。 + +- `type`: `"file"` または `"directory"` +- `directory`: 検索用のプロジェクト ルートをオーバーライドします。 +- `limit`: 最大結果 (1 ~ 200) + +--- + +#### 例 + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### トゥイ + +|方法 |説明 |応答 | +| ------------------------------ | ------------------------- | --------- | +| `tui.appendPrompt({ body })` |プロンプトにテキストを追加します | `boolean` | +| `tui.openHelp()` |ヘルプダイアログを開く | `boolean` | +| `tui.openSessions()` |セッションセレクターを開く | `boolean` | +| `tui.openThemes()` |テーマセレクターを開く | `boolean` | +| `tui.openModels()` |モデルセレクターを開く | `boolean` | +| `tui.submitPrompt()` |現在のプロンプトを送信します | `boolean` | +| `tui.clearPrompt()` |プロンプトをクリア | `boolean` | +| `tui.executeCommand({ body })` |コマンドを実行する | `boolean` | +| `tui.showToast({ body })` |トースト通知を表示 | `boolean` | + +--- + +#### 例 + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### 認証 + +|方法 |説明 |応答 | +| ------------------- | ------------------------------ | --------- | +| `auth.set({ ... })` |認証資格情報を設定する | `boolean` | + +--- + +#### 例 + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### イベント + +|方法 |説明 |応答 | +| ------------------- | ------------------------- | ------------------------- | +| `event.subscribe()` |サーバー送信イベント ストリーム |サーバー送信イベント ストリーム | + +--- + +#### 例 + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/ja/server.mdx b/packages/web/src/content/docs/ja/server.mdx new file mode 100644 index 000000000..b950e30c6 --- /dev/null +++ b/packages/web/src/content/docs/ja/server.mdx @@ -0,0 +1,287 @@ +--- +title: サーバ +description: HTTP 経由でオープンコード サーバーと通信します。 +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +`opencode serve` コマンドは、オープンコード クライアントが使用できる OpenAPI エンドポイントを公開するヘッドレス HTTP サーバーを実行します。 + +--- + +### 使用法 + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### オプション + +|旗 |説明 |デフォルト | +| --------------- | ----------------------------------- | ---------------- | +| `--port` |リッスンするポート | `4096` | +| `--hostname` |リッスンするホスト名 | `127.0.0.1` | +| `--mdns` | mDNS 検出を有効にする | `false` | +| `--mdns-domain` | mDNS サービスのカスタム ドメイン名 | `opencode.local` | +| `--cors` |許可する追加のブラウザーオリジン | `[]` | + +`--cors` は複数回渡すことができます。 + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### 認証 + +HTTP 基本認証でサーバーを保護するには、`OPENCODE_SERVER_PASSWORD` を設定します。ユーザー名はデフォルトで `opencode` になるか、`OPENCODE_SERVER_USERNAME` を設定してオーバーライドします。これは、`opencode serve` と `opencode web` の両方に当てはまります。 + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### 仕組み + +`opencode` を実行すると、TUI とサーバーが起動します。 TUI の場所 +サーバーと通信するクライアント。サーバーは OpenAPI 3.1 仕様を公開します +終点。このエンドポイントは、[SDK](/docs/sdk). + +:::ヒント +opencode サーバーを使用して、プログラムで opencode と対話します。 +::: + +このアーキテクチャにより、オープンコードで複数のクライアントをサポートできるようになり、プログラムでオープンコードと対話できるようになります。 + +`opencode serve` を実行してスタンドアロン サーバーを起動できます。持っている場合は、 +opencode TUI を実行すると、`opencode serve` が新しいサーバーを起動します。 + +--- + +#### 既存のサーバーに接続する + +TUI を起動すると、ポートとホスト名がランダムに割り当てられます。代わりに、`--hostname` と `--port` [flags](/docs/cli).次に、これを使用してサーバーに接続します。 + +[`/tui`](#tui) エンドポイントは、サーバー経由で TUI を駆動するために使用できます。たとえば、プロンプトを事前入力したり、実行したりできます。この設定は、OpenCode [IDE](/docs/ide) プラグイン] によって使用されます。 + +--- + +## スペック + +サーバーは、次の場所で閲覧できる OpenAPI 3.1 仕様を公開しています。 + +``` +http://:/doc +``` + +たとえば、`http://localhost:4096/doc`。この仕様を使用して、クライアントを生成したり、要求と応答のタイプを検査したりできます。または、Swagger エクスプローラーで表示します。 + +--- + +## API + +opencode サーバーは次の API を公開します。 + +--- + +### グローバル + +|方法 |パス |説明 |応答 | +| ------ | ---------------- | ------------------------------ | ------------------------------------ | +| `GET` | `/global/health` |サーバーの健全性とバージョンを取得する |うーん +| `GET` | `/global/event` |グローバル イベントの取得 (SSE ストリーム) |イベントストリーム | + +--- + +### プロジェクト + +|方法 |パス |説明 |応答 | +| ------ | ------------------ | ----------------------- | --------------------------------------------- | +| `GET` | `/project` |すべてのプロジェクトをリストする | プロジェクト[] | +| `GET` | `/project/current` |現在のプロジェクトを取得 | プロジェクト | + +--- + +### パスと VCS + +|方法 |パス |説明 |応答 | +| ------ | ------- | ------------------------------------ | ------------------------------------------- | +| `GET` | `/path` |現在のパスを取得する | パス | +| `GET` | `/vcs` |現在のプロジェクトの VCS 情報を取得する | VcsInfo | + +--- + +### 実例 + +|方法 |パス |説明 |応答 | +| ------ | ------------------- | ---------------------------- | --------- | +| `POST` | `/instance/dispose` |現在のインスタンスを破棄する |うーん + +--- + +### 構成 + +|方法 |パス |説明 |応答 | +| ------- | ------------------- | --------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` |構成情報を取得する | 構成 | +| `PATCH` | `/config` |構成を更新する | 構成 | +| `GET` | `/config/providers` |プロバイダーとデフォルトのモデルをリストする | `{ providers: `プロバイダ[]`, default: { [key: string]: string } }` | + +--- + +### プロバイダー + +|方法 |パス |説明 |応答 | +| ------ | -------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` |すべてのプロバイダーをリストする | `{ all: `プロバイダ[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` |プロバイダーの認証方法を取得する | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | OAuth を使用してプロバイダーを認証する | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` |プロバイダーの OAuth コールバックを処理する |うーん + +--- + +### セッション + +|方法 |パス |説明 |メモ | +| -------- | ---------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------- | +| `GET` | `/session` |すべてのセッションをリストする |戻り値 セッション[] | +| `POST` | `/session` |新しいセッションを作成する |本文: `{ parentID?, title? }`、セッション を返します。 +| `GET` | `/session/status` |すべてのセッションのセッション ステータスを取得する |戻り値 `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` |セッションの詳細を取得する |戻り値 セッション | +| `DELETE` | `/session/:id` |セッションとそのすべてのデータを削除する |戻り値 `boolean` | +| `PATCH` | `/session/:id` |セッションのプロパティを更新する |本文: `{ title? }`、セッション を返します。 +| `GET` | `/session/:id/children` |セッションの子セッションを取得する |戻り値 セッション[] | +| `GET` | `/session/:id/todo` |セッションの ToDo リストを取得する |戻り値 Todo[] | +| `POST` | `/session/:id/init` |アプリを分析して `AGENTS.md` を作成する |本文: `{ messageID, providerID, modelID }`、`boolean` を返します。 +| `POST` | `/session/:id/fork` |メッセージで既存のセッションをフォークする |本文: `{ messageID? }`、セッション を返します。 +| `POST` | `/session/:id/abort` |実行中のセッションを中止する |戻り値 `boolean` | +| `POST` | `/session/:id/share` |セッションを共有する |戻り値 セッション | +| `DELETE` | `/session/:id/share` |セッションの共有を解除する |戻り値 セッション | +| `GET` | `/session/:id/diff` |このセッションの差分を取得する |クエリ: `messageID?`、FileDiff[] を返します。 +| `POST` | `/session/:id/summarize` |セッションを要約する |本文: `{ providerID, modelID }`、`boolean` を返します。 +| `POST` | `/session/:id/revert` |メッセージを元に戻す |本文: `{ messageID, partID? }`、`boolean` を返します。 +| `POST` | `/session/:id/unrevert` |元に戻したすべてのメッセージを復元する |戻り値 `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` |許可リクエストに応答する |本文: `{ response, remember? }`、`boolean` を返します。 + +--- + +### メッセージ + +|方法 |パス |説明 |メモ | +| ------ | --------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` |セッション内のメッセージをリストする |クエリ: `limit?`、`{ info: `メッセージを返します。`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` |メッセージを送信して応答を待ちます |本文: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`、`{ info: `メッセージを返します`, parts: `Part[]`}` | +| `GET` | `/session/:id/message/:messageID` |メッセージの詳細を取得する |戻り値 `{ info: `メッセージ`, parts: `Part[]`}` | +| `POST` | `/session/:id/prompt_async` |メッセージを非同期に送信する (待機なし) | body: `/session/:id/message` と同じ、`204 No Content` を返します。 +| `POST` | `/session/:id/command` |スラッシュコマンドを実行します |本文: `{ messageID?, agent?, model?, command, arguments }`、`{ info: `メッセージを返します`, parts: `Part[]`}` | +| `POST` | `/session/:id/shell` |シェルコマンドを実行する |本文: `{ agent, model?, command }`、`{ info: `メッセージを返します`, parts: `Part[]`}` | + +--- + +### コマンド + +|方法 |パス |説明 |応答 | +| ------ | ---------- | ----------------- | --------------------------------------------- | +| `GET` | `/command` |すべてのコマンドをリストする | コマンド[] | + +--- + +### ファイル + +|方法 |パス |説明 |応答 | +| ------ | ------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` |ファイル内のテキストを検索 | `path`、`lines`、`line_number`、`absolute_offset`、`submatches` と一致するオブジェクトの配列 | +| `GET` | `/find/file?query=` |ファイルとディレクトリを名前で検索する | `string[]` (パス) | +| `GET` | `/find/symbol?query=` |ワークスペースのシンボルを検索する | シンボル[] | +| `GET` | `/file?path=` |ファイルとディレクトリをリストする | FileNode[] | +| `GET` | `/file/content?path=

` |ファイルを読む | ファイルコンテンツ | +| `GET` | `/file/status` |追跡されたファイルのステータスを取得する | ファイル[] | + +#### `/find/file` クエリパラメータ + +- `query` (必須) — 検索文字列 (あいまい一致) +- `type` (オプション) — 結果を `"file"` または `"directory"` に制限します +- `directory` (オプション) — 検索用のプロジェクト ルートをオーバーライドします。 +- `limit` (オプション) — 最大結果 (1 ~ 200) +- `dirs` (オプション) — 従来のフラグ (`"false"` はファイルのみを返します) + +--- + +### ツール (実験的) + +|方法 |パス |説明 |応答 | +| ------ | ------------------------------------------- | ---------------------------------------- | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` |すべてのツール ID をリストする | ツール ID | +| `GET` | `/experimental/tool?provider=

&model=` |モデルの JSON スキーマを含むツールをリストする | ツールリスト | + +--- + +### LSP、フォーマッタ、MCP + +|方法 |パス |説明 |応答 | +| ------ | ------------ | -------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | LSP サーバーのステータスを取得 | LSPStatus[] | +| `GET` | `/formatter` |フォーマッタのステータスを取得する | FormatterStatus[] | +| `GET` | `/mcp` | MCP サーバーのステータスを取得する | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | MCP サーバーを動的に追加する |本文: `{ name, config }`、MCP ステータス オブジェクトを返します。 + +--- + +### エージェント + +|方法 |パス |説明 |応答 | +| ------ | -------- | ------------------------- | ------------------------------------------- | +| `GET` | `/agent` |利用可能なすべてのエージェントをリストする | エージェント[] | + +--- + +### ロギング + +|方法 |パス |説明 |応答 | +| ------ | ------ | ------------------------------------------------------------ | --------- | +| `POST` | `/log` |ログエントリを書き込みます。本体:`{ service, level, message, extra? }` |うーん + +--- + +### トゥイ + +|方法 |パス |説明 |応答 | +| ------ | ----------------------- | ------------------------------------------- | ---------------------- | +| `POST` | `/tui/append-prompt` |プロンプトにテキストを追加します |うーん +| `POST` | `/tui/open-help` |ヘルプダイアログを開く |うーん +| `POST` | `/tui/open-sessions` |セッションセレクターを開く |うーん +| `POST` | `/tui/open-themes` |テーマセレクターを開く |うーん +| `POST` | `/tui/open-models` |モデルセレクターを開く |うーん +| `POST` | `/tui/submit-prompt` |現在のプロンプトを送信します |うーん +| `POST` | `/tui/clear-prompt` |プロンプトをクリア |うーん +| `POST` | `/tui/execute-command` |コマンドを実行する (`{ command }`) |うーん +| `POST` | `/tui/show-toast` |トーストを表示 (`{ title?, message, variant }`) |うーん +| `GET` | `/tui/control/next` |次の制御リクエストを待ちます |コントロールリクエストオブジェクト | +| `POST` | `/tui/control/response` |制御リクエストに応答する (`{ body }`) |うーん + +--- + +### 認証 + +|方法 |パス |説明 |応答 | +| ------ | ----------- | --------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` |認証資格情報を設定します。本文はプロバイダーのスキーマと一致する必要があります |うーん + +--- + +### イベント + +|方法 |パス |説明 |応答 | +| ------ | -------- | ----------------------------------------------------------------------------- | ------------------------- | +| `GET` | `/event` |サーバーから送信されたイベント ストリーム。最初のイベントは `server.connected` で、次にバス イベントです。サーバー送信イベント ストリーム | + +--- + +### ドキュメント + +|方法 |パス |説明 |応答 | +| ------ | ------ | ------------------------- | --------------------------- | +| `GET` | `/doc` | OpenAPI 3.1 仕様 | OpenAPI 仕様を備えた HTML ページ | diff --git a/packages/web/src/content/docs/ja/share.mdx b/packages/web/src/content/docs/ja/share.mdx new file mode 100644 index 000000000..90a7227c8 --- /dev/null +++ b/packages/web/src/content/docs/ja/share.mdx @@ -0,0 +1,128 @@ +--- +title: 共有 +description: OpenCode での会話を共有します。 +--- + +OpenCode の共有機能を使用すると、OpenCode の会話への公開リンクを作成できるため、チームメイトと共同作業したり、他の人から助けを得ることができます。 + +:::注記 +共有された会話は、リンクを知っている人なら誰でも公開してアクセスできます。 +::: + +--- + +## 仕組み + +会話を共有するとき、OpenCode は次のことを行います。 + +1. セッション用の一意のパブリック URL を作成します +2. 会話履歴をサーバーに同期します +3. 共有可能なリンク — `opncd.ai/s/` を介して会話にアクセスできるようにします + +--- + +## 共有 + +OpenCode は、会話の共有方法を制御する 3 つの共有モードをサポートしています。 + +--- + +### 手動(デフォルト) + +デフォルトでは、OpenCode は手動共有モードを使用します。セッションは自動的には共有されませんが、`/share` コマンドを使用して手動で共有できます。 + +``` +/share +``` + +これにより、クリップボードにコピーされる一意の URL が生成されます。 + +[config file](/docs/config):] で手動モードを明示的に設定するには: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### 自動共有 + +[config file](/docs/config):] で `share` オプションを `"auto"` に設定することで、すべての新しい会話の自動共有を有効にできます。 + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +自動共有を有効にすると、すべての新しい会話が自動的に共有され、リンクが生成されます。 + +--- + +### 無効 + +[config file](/docs/config):] で `share` オプションを `"disabled"` に設定することで、共有を完全に無効にすることができます。 + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +これを特定のプロジェクトのチーム全体に強制するには、それをプロジェクトの `opencode.json` に追加し、Git にチェックインします。 + +--- + +## 共有を解除する + +会話の共有を停止し、パブリック アクセスから削除するには: + +``` +/unshare +``` + +これにより、共有リンクが削除され、会話に関連するデータが削除されます。 + +--- + +## プライバシー + +会話を共有する際には、留意すべき点がいくつかあります。 + +--- + +### データの保持 + +共有された会話は、明示的に共有を解除するまでアクセス可能なままになります。これ +以下が含まれます: + +- 完全な会話履歴 +- すべてのメッセージと応答 +- セッションメタデータ + +--- + +### 推奨事項 + +- 機密情報を含まない会話のみを共有してください。 +- 共有する前に会話の内容を確認してください。 +- コラボレーションが完了したら、会話の共有を解除します。 +- 独自のコードや機密データを含む会話を共有することは避けてください。 +- 機密性の高いプロジェクトの場合は、共有を完全に無効にします。 + +--- + +## 企業向け + +エンタープライズ展開の場合、共有機能は次のようになります。 + +- **セキュリティコンプライアンスのため完全に無効** +- **SSO を通じて認証されたユーザーのみに制限** +- 独自のインフラストラクチャで **セルフホスト** + +[組織内でのオープンコードの使用について詳しくは、](/docs/enterprise) をご覧ください。 diff --git a/packages/web/src/content/docs/ja/skills.mdx b/packages/web/src/content/docs/ja/skills.mdx new file mode 100644 index 000000000..67e3bcec1 --- /dev/null +++ b/packages/web/src/content/docs/ja/skills.mdx @@ -0,0 +1,222 @@ +--- +title: 「エージェントスキル」 +description: 「SKILL.md定義による再利用可能な動作の定義」 +--- + +エージェント スキルにより、OpenCode はリポジトリまたはホーム ディレクトリから再利用可能な命令を検出できます。 +スキルはネイティブの `skill` ツールを介してオンデマンドでロードされます。エージェントは利用可能なスキルを確認し、必要に応じて完全なコンテンツをロードできます。 + +--- + +## ファイルを配置する + +スキル名ごとにフォルダーを 1 つ作成し、その中に `SKILL.md` を置きます。 +OpenCode は次の場所を検索します。 + +- プロジェクト構成: `.opencode/skills//SKILL.md` +- グローバル構成: `~/.config/opencode/skills//SKILL.md` +- Project Claude互換: `.claude/skills//SKILL.md` +- グローバルクロード互換: `~/.claude/skills//SKILL.md` +- プロジェクトエージェント互換: `.agents/skills//SKILL.md` +- グローバルエージェント互換: `~/.agents/skills//SKILL.md` + +--- + +## 発見を理解する + +プロジェクトのローカル パスの場合、OpenCode は現在の作業ディレクトリから git ワークツリーに到達するまで進みます。 +途中で、一致する `skills/*/SKILL.md` を `.opencode/` に読み込み、一致する `.claude/skills/*/SKILL.md` または `.agents/skills/*/SKILL.md` を読み込みます。 + +グローバル定義は、`~/.config/opencode/skills/*/SKILL.md`、`~/.claude/skills/*/SKILL.md`、および `~/.agents/skills/*/SKILL.md` からもロードされます。 + +--- + +## 前付を書く + +各 `SKILL.md` は YAML フロントマターで始まる必要があります。 +次のフィールドのみが認識されます。 + +- `name` (必須) +- `name` (必須) +- `license` (オプション) +- `license` (オプション) +- `metadata` (オプション、文字列間のマップ) + +不明なフロントマターフィールドは無視されます。 + +--- + +## 名前を検証する + +`name` は次のことを行う必要があります。 + +- 1 ~ 64 文字であること +- 単一のハイフンで区切られた小文字の英数字であること +- `-` で開始または終了しない +- 連続した `--` を含まない +- `SKILL.md` を含むディレクトリ名と一致する + +同等の正規表現: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## 長さのルールに従ってください + +`description` は 1 ~ 1024 文字である必要があります。 +エージェントが正しく選択できるように、十分具体的な内容にしてください。 + +--- + +## 例を使用する + +次のように `.opencode/skills/git-release/SKILL.md` を作成します。 + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## ツールの説明を認識する + +OpenCode では、`skill` ツールの説明に利用可能なスキルがリストされています。 +各エントリにはスキル名と説明が含まれます。 + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +エージェントはツールを呼び出してスキルをロードします。 + +``` +skill({ name: "git-release" }) +``` + +--- + +## 権限の構成 + +`opencode.json` のパターンベースの権限を使用して、エージェントがアクセスできるスキルを制御します。 + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +|許可 |行動 | +| ---------- | ----------------------------------------- | +| `allow` |スキルはすぐにロードされます | +| `deny` |スキルはエージェントから隠蔽され、アクセスは拒否されました | +| `ask` |ロードする前にユーザーに承認を求めるメッセージが表示される | + +パターンはワイルドカードをサポートしています: `internal-*` は `internal-docs`、`internal-tools` などに一致します。 + +--- + +## エージェントごとに上書きする + +特定のエージェントにグローバルのデフォルトとは異なる権限を与えます。 + +**カスタム エージェントの場合** (エージェント フロントマター内): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**組み込みエージェントの場合** (`opencode.json` 内): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## スキルツールを無効にする + +スキルを使用すべきではないエージェントのスキルを完全に無効にします。 + +**カスタム エージェントの場合**: + +```yaml +--- +tools: + skill: false +--- +``` + +**組み込みエージェントの場合**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +無効にすると、`` セクションが完全に省略されます。 + +--- + +## 読み込みのトラブルシューティング + +スキルが表示されない場合: + +1. `SKILL.md` のスペルがすべて大文字であることを確認してください +2. フロントマターに `name` と `description` が含まれていることを確認します +3. スキル名がすべての場所で一意であることを確認する +4. 権限を確認してください - `deny` のスキルはエージェントから非表示になります diff --git a/packages/web/src/content/docs/ja/themes.mdx b/packages/web/src/content/docs/ja/themes.mdx new file mode 100644 index 000000000..09d435f02 --- /dev/null +++ b/packages/web/src/content/docs/ja/themes.mdx @@ -0,0 +1,369 @@ +--- +title: テーマ +description: 組み込みのテーマを選択するか、独自のテーマを定義します。 +--- + +OpenCode を使用すると、いくつかの組み込みテーマから 1 つを選択したり、端末のテーマに適合するテーマを使用したり、独自のカスタム テーマを定義したりできます。 + +デフォルトでは、OpenCode は独自の `opencode` テーマを使用します。 + +--- + +## 端末要件 + +テーマをフルカラー パレットで正しく表示するには、端末が **truecolor** (24 ビット カラー) をサポートしている必要があります。最新の端末のほとんどはデフォルトでこれをサポートしていますが、有効にする必要がある場合があります。 + +- **サポートを確認してください**: `echo $COLORTERM` を実行します - `truecolor` または `24bit` が出力されるはずです +- **トゥルーカラーを有効にする**: シェル プロファイルで環境変数 `COLORTERM=truecolor` を設定します。 +- **ターミナルの互換性**: ターミナル エミュレータが 24 ビット カラーをサポートしていることを確認してください (iTerm2、Alacritty、Kitty、Windows ターミナル、および GNOME ターミナルの最新バージョンなどのほとんどの最新のターミナルはサポートしています)。 + +トゥルーカラーのサポートがないと、テーマの色の精度が低下したり、最も近い 256 色の近似値に戻ったりする可能性があります。 + +--- + +## 組み込みのテーマ + +OpenCode にはいくつかの組み込みテーマが付属しています。 + +|名前 |説明 | +| ---------------------- | ---------------------------------------------------------------------------- | +| `system` |端末の背景色に適応します | +| `tokyonight` | 【Tokyonight](https://github.com/folke/tokyonight.nvim)テーマ | +| `everforest` | [Everforest](https://github.com/sainnhe/everforest) テーマ | +| `ayu` | [Ayu](https://github.com/ayu-theme) ダークテーマ | ベース] +| `catppuccin` | [Catppuccin](https://github.com/catppuccin) テーマ | +| `catppuccin-macchiato` | [Catppuccin](https://github.com/catppuccin) テーマ | +| `gruvbox` | [Gruvbox](https://github.com/morhetz/gruvbox) テーマ | +| `kanagawa` | 【神奈川](https://github.com/rebelot/kanagawa.nvim)テーマ | +| `nord` | [Nord](https://github.com/nordtheme/nord) テーマ | +| `matrix` |ハッカースタイルの黒地に緑のテーマ | +| `one-dark` | [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) Dark テーマ | Atom One](https://github.com/Th3Whit3Wolf/one-nvim) Dark テーマ | + +さらに、新しいテーマも常に追加されています。 + +--- + +## システムテーマ + +`system` テーマは、端末のカラースキームに自動的に適応するように設計されています。固定色を使用する従来のテーマとは異なり、_system_ テーマは次のようになります。 + +- **グレー スケールを生成**: 端末の背景色に基づいてカスタム グレー スケールを作成し、最適なコントラストを確保します。 +- **ANSI カラーを使用**: 構文の強調表示と UI 要素に標準の ANSI カラー (0 ~ 15) を利用し、端末のカラー パレットを尊重します。 +- **端末のデフォルトを維持**: テキストと背景の色に `none` を使用して、端末のネイティブの外観を維持します。 + +システム テーマは、次のようなユーザーを対象としています。 + +- OpenCode を端末の外観と一致させたい +- カスタム端末のカラースキームを使用する +- すべての端末アプリケーションにわたって一貫した外観を好む + +--- + +## テーマの使用 + +テーマを選択するには、`/theme` コマンドでテーマ選択を表示します。または、[config](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## カスタムテーマ + +OpenCode は、ユーザーがテーマを簡単に作成およびカスタマイズできる柔軟な JSON ベースのテーマ システムをサポートしています。 + +--- + +### 階層 + +テーマは複数のディレクトリから次の順序でロードされ、後のディレクトリが前のディレクトリをオーバーライドします。 + +1. **組み込みテーマ** - これらはバイナリに埋め込まれています +2. **ユーザー設定ディレクトリ** - `~/.config/opencode/themes/*.json` または `$XDG_CONFIG_HOME/opencode/themes/*.json` で定義されます +3. **プロジェクトのルート ディレクトリ** - `/.opencode/themes/*.json` で定義されます。 +4. **現在の作業ディレクトリ** - `./.opencode/themes/*.json` で定義 + +複数のディレクトリに同じ名前のテーマが含まれている場合は、優先度の高いディレクトリのテーマが使用されます。 + +--- + +### テーマの作成 + +カスタム テーマを作成するには、テーマ ディレクトリの 1 つに JSON ファイルを作成します。 + +ユーザー全体のテーマの場合: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +そしてプロジェクト固有のテーマについても。 + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON形式 + +テーマは、以下をサポートする柔軟な JSON 形式を使用します。 + +- **16 進数の色**: `"#ffffff"` +- **ANSI カラー**: `3` (0-255) +- **色の参照**: `"primary"` またはカスタム定義 +- **ダーク/ライトのバリエーション**: `{"dark": "#000", "light": "#fff"}` +- **色なし**: `"none"` - 端末のデフォルトの色または透明を使用します。 + +--- + +### 色の定義 + +`defs` セクションはオプションであり、テーマ内で参照できる再利用可能な色を定義できます。 + +--- + +### 端末のデフォルト + +特別な値 `"none"` を任意の色に使用して、端末のデフォルトの色を継承できます。これは、端末の配色とシームレスに融合するテーマを作成する場合に特に便利です。 + +- `"text": "none"` - 端末のデフォルトの前景色を使用します +- `"background": "none"` - 端末のデフォルトの背景色を使用します + +--- + +### 例 + +カスタム テーマの例を次に示します。 + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/ja/tools.mdx b/packages/web/src/content/docs/ja/tools.mdx new file mode 100644 index 000000000..e4857fd1e --- /dev/null +++ b/packages/web/src/content/docs/ja/tools.mdx @@ -0,0 +1,379 @@ +--- +title: ツール +description: LLM が使用できるツールを管理します。 +--- + +ツールを使用すると、LLM がコードベースでアクションを実行できるようになります。 OpenCode には一連の組み込みツールが付属していますが、[カスタム ツール](/docs/custom-tools) または [MCP サーバー](/docs/mcp-servers). + +デフォルトでは、すべてのツールは**有効**になっており、実行するための権限は必要ありません。 [permissions](/docs/permissions). + +--- + +## 設定する + +`permission` フィールドを使用してツールの動作を制御します。各ツールを許可、拒否、または承認を要求することができます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +ワイルドカードを使用して複数のツールを一度に制御することもできます。たとえば、MCP サーバーからのすべてのツールの承認を要求するには、次のようにします。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[アクセス許可の構成について詳しくは、](/docs/permissions) をご覧ください。 + +--- + +## 内蔵 + +OpenCode で利用可能なすべての組み込みツールを次に示します。 + +--- + +### バッシュ + +プロジェクト環境でシェル コマンドを実行します。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +このツールを使用すると、LLM は `npm install`、`git status`、またはその他のシェル コマンドなどの端末コマンドを実行できます。 + +--- + +### 編集 + +正確な文字列置換を使用して既存のファイルを変更します。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +このツールは、完全に一致するテキストを置き換えることにより、ファイルを正確に編集します。これは、LLM がコードを変更する主な方法です。 + +--- + +### 書く + +新しいファイルを作成するか、既存のファイルを上書きします。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +これを使用して、LLM が新しいファイルを作成できるようにします。既存のファイルがすでに存在する場合は上書きされます。 + +:::注記 +`write` ツールは、すべてのファイル変更 (`edit`、`write`、`patch`、`multiedit`) をカバーする `edit` 権限によって制御されます。 +::: + +--- + +### 読む + +コードベースからファイルの内容を読み取ります。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +このツールはファイルを読み取り、その内容を返します。大きなファイルの特定の行範囲の読み取りをサポートします。 + +--- + +### grep + +正規表現を使用してファイルの内容を検索します。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +コードベース全体での高速コンテンツ検索。完全な正規表現構文とファイル パターン フィルタリングをサポートします。 + +--- + +### グロブ + +パターンマッチングによりファイルを検索します。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +`**/*.js` や `src/**/*.ts` などの glob パターンを使用してファイルを検索します。一致するファイル パスを変更時間順に並べて返します。 + +--- + +### リスト + +指定されたパス内のファイルとディレクトリを一覧表示します。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +このツールはディレクトリの内容を一覧表示します。結果をフィルタリングするための glob パターンを受け入れます。 + +--- + +### lsp (実験的) + +構成された LSP サーバーと対話して、定義、参照、ホバー情報、呼び出し階層などのコード インテリジェンス機能を取得します。 + +:::注記 +このツールは、`OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (または `OPENCODE_EXPERIMENTAL=true`) の場合にのみ使用できます。 +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +サポートされている操作には、`goToDefinition`、`findReferences`、`hover`、`documentSymbol`、`workspaceSymbol`、`goToImplementation`、`prepareCallHierarchy`、`incomingCalls`、および `outgoingCalls` が含まれます。 + +プロジェクトで使用できる LSP サーバーを構成するには、「LSP Servers](/docs/lsp). + +--- + +### パッチ + +ファイルにパッチを適用します。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +このツールは、コードベースにパッチ ファイルを適用します。さまざまなソースからの差分やパッチを適用するのに役立ちます。 + +:::注記 +`write` ツールは、すべてのファイル変更 (`edit`、`write`、`patch`、`multiedit`) をカバーする `edit` 権限によって制御されます。 +::: + +--- + +### スキル + +[skill](/docs/skills) (`SKILL.md` ファイル) をロードし、会話でその内容を返します。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todowrite + +コーディング セッション中に ToDo リストを管理します。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +タスク リストを作成および更新して、複雑な操作中の進行状況を追跡します。 LLM はこれを使用して、複数ステップのタスクを整理します。 + +:::注記 +このツールはデフォルトではサブエージェントに対して無効になっていますが、手動で有効にすることができます。 [詳細はこちら](/docs/agents/#permissions) +::: + +--- + +### トドリード + +既存の ToDo リストを読み取ります。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +現在の Todo リストの状態を読み取ります。どのタスクが保留中または完了しているかを追跡するために LLM によって使用されます。 + +:::注記 +このツールはデフォルトではサブエージェントに対して無効になっていますが、手動で有効にすることができます。 [詳細はこちら](/docs/agents/#permissions) +::: + +--- + +### ウェブフェッチ + +Web コンテンツを取得します。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +LLM が Web ページをフェッチして読み取ることを許可します。ドキュメントの検索やオンライン リソースの調査に役立ちます。 + +--- + +### ウェブ検索 + +ウェブで情報を検索してください。 + +:::注記 +このツールは、OpenCode プロバイダーを使用している場合、または `OPENCODE_ENABLE_EXA` 環境変数が真実の値 (`true` または `1` など) に設定されている場合にのみ使用できます。 + +OpenCode の起動時に有効にするには: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Exa AI を使用して Web 検索を実行し、オンラインで関連情報を見つけます。トピックの調査、最新のイベントの検索、またはトレーニング データのカットオフを超えた情報の収集に役立ちます。 + +API キーは必要ありません。ツールは認証なしで Exa AI のホストされた MCP サービスに直接接続します。 + +:::ヒント +情報を見つける必要がある場合 (検出)、`websearch` を使用し、特定の URL からコンテンツを取得する必要がある場合 (取得) は `webfetch` を使用します。 +::: + +--- + +### 質問 + +実行中にユーザーに質問します。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +このツールを使用すると、LLM はタスク中にユーザーに質問できるようになります。これは次の場合に役立ちます。 + +- ユーザーの好みや要件を収集する +- 曖昧な指示を明確にする +- 実装の選択肢について決定を下す +- どの方向に進むべきかについての選択肢を提供する + +各質問には、ヘッダー、質問テキスト、およびオプションのリストが含まれます。ユーザーは、提供されたオプションから選択するか、カスタムの回答を入力できます。複数の質問がある場合、ユーザーはすべての回答を送信する前に質問間を移動できます。 + +--- + +## カスタムツール + +カスタム ツールを使用すると、LLM が呼び出すことができる独自の関数を定義できます。これらは構成ファイルで定義されており、任意のコードを実行できます。 + +[カスタム ツールの作成について詳しくは、](/docs/custom-tools) をご覧ください。 + +--- + +## MCPサーバー + +MCP (Model Context Protocol) サーバーを使用すると、外部ツールとサービスを統合できます。これには、データベース アクセス、API 統合、サードパーティ サービスが含まれます。 + +[MCP サーバーの構成について詳しくは、](/docs/mcp-servers) をご覧ください。 + +--- + +## 内部構造 + +内部的には、`grep`、`glob`、`list` などのツールは内部で [ripgrep](https://github.com/BurntSushi/ripgrep) を使用します。デフォルトでは、ripgrep は `.gitignore` パターンを尊重します。つまり、`.gitignore` にリストされているファイルとディレクトリは検索とリストから除外されます。 + +--- + +### パターンを無視する + +通常は無視されるファイルを含めるには、プロジェクトのルートに `.ignore` ファイルを作成します。このファイルでは、特定のパスを明示的に許可できます。 + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +たとえば、この `.ignore` ファイルを使用すると、ripgrep は、`.gitignore` にリストされている場合でも、`node_modules/`、`dist/`、および `build/` ディレクトリ内を検索できます。 diff --git a/packages/web/src/content/docs/ja/troubleshooting.mdx b/packages/web/src/content/docs/ja/troubleshooting.mdx new file mode 100644 index 000000000..1772d9882 --- /dev/null +++ b/packages/web/src/content/docs/ja/troubleshooting.mdx @@ -0,0 +1,300 @@ +--- +title: トラブルシューティング +description: よくある問題とその解決方法。 +--- + +OpenCode の問題をデバッグするには、まず、ディスク上に保存されているログとローカル データを確認します。 + +--- + +## ログ + +ログ ファイルは次の場所に書き込まれます。 + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: `WIN+R` を押して `%USERPROFILE%\.local\share\opencode\log` を貼り付けます + +ログ ファイルにはタイムスタンプ付きの名前が付けられ (例: `2025-01-09T123456.log`)、最新の 10 個のログ ファイルが保存されます。 + +`--log-level` コマンドライン オプションを使用してログ レベルを設定すると、より詳細なデバッグ情報を取得できます。たとえば、`opencode --log-level DEBUG`。 + +--- + +## ストレージ + +opencode は、セッション データとその他のアプリケーション データをディスク上の次の場所に保存します。 + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: `WIN+R` を押して `%USERPROFILE%\.local\share\opencode\log` を貼り付けます + +このディレクトリには次のものが含まれます。 + +- `auth.json` - API キー、OAuth トークンなどの認証データ +- `log/` - アプリケーションログ +- `project/` - セッション データやメッセージ データなどのプロジェクト固有のデータ + - プロジェクトが Git リポジトリ内にある場合は、`.//storage/` に保存されます + - Git リポジトリではない場合は、`./global/storage/` に保存されます + +--- + +## デスクトップアプリ + +OpenCode Desktop は、ローカル OpenCode サーバー (`opencode-cli` サイドカー) をバックグラウンドで実行します。ほとんどの問題は、誤動作するプラグイン、破損したキャッシュ、または不正なサーバー設定によって発生します。 + +### クイックチェック + +- アプリを完全に終了して再起動します。 +- アプリにエラー画面が表示された場合は、**再起動** をクリックしてエラーの詳細をコピーします。 +- macOS のみ: `OpenCode` メニュー -> **Webview を再ロード** (UI が空白またはフリーズしている場合に役立ちます)。 + +--- + +### プラグインを無効にする + +デスクトップ アプリが起動時にクラッシュしたり、ハングしたり、異常な動作をしたりする場合は、まずプラグインを無効にしてください。 + +#### グローバル設定を確認してください + +グローバル設定ファイルを開き、`plugin` キーを探します。 + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (または `~/.config/opencode/opencode.json`) +- **macOS/Linux** (古いインストール): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: `WIN+R` を押して `%USERPROFILE%\.local\share\opencode\log` を貼り付けます + +プラグインを構成している場合は、キーを削除するか空の配列に設定して、プラグインを一時的に無効にします。 + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### プラグインのディレクトリを確認する + +OpenCode はディスクからローカル プラグインをロードすることもできます。これらを一時的に邪魔にならない場所に移動し (またはフォルダーの名前を変更し)、デスクトップ アプリを再起動します。 + +- **グローバル プラグイン** + - **macOS/Linux**: `~/.local/share/opencode/log/` + - **Windows**: `WIN+R` を押して `%USERPROFILE%\.local\share\opencode\log` を貼り付けます +- **プロジェクト プラグイン** (プロジェクトごとの構成を使用する場合のみ) + - `command.executed` + +アプリが再び動作し始めた場合は、プラグインを 1 つずつ再度有効にして、問題の原因となっているプラ​​グインを特定します。 + +--- + +### キャッシュをクリアする + +プラグインを無効にしても解決しない場合 (またはプラグインのインストールが停止した場合)、OpenCode がキャッシュを再構築できるようにキャッシュをクリアします。 + +1. OpenCode Desktop を完全に終了します。 +2. キャッシュ ディレクトリを削除します。 + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/.cache/opencode` を貼り付け +- **Linux**: `~/.cache/opencode` を削除します (または `rm -rf ~/.cache/opencode` を実行します)。 +- **Windows**: `WIN+R` を押して `%USERPROFILE%\.local\share\opencode\log` を貼り付けます + +3. OpenCode デスクトップを再起動します。 + +--- + +### サーバー接続の問題を修正する + +OpenCode Desktop は、独自のローカル サーバー (デフォルト) を起動することも、構成したサーバー URL に接続することもできます。 + +**「接続に失敗しました」** ダイアログが表示された場合 (またはアプリがスプラッシュ画面を通過できない場合)、カスタム サーバー URL を確認してください。 + +#### デスクトップのデフォルトのサーバー URL をクリアします + +ホーム画面でサーバー名 (ステータス ドット付き) をクリックしてサーバー ピッカーを開きます。 [**デフォルト サーバー**] セクションで、[**クリア**] をクリックします。 + +#### 設定から `server.port` / `server.hostname` を削除します + +`opencode.json(c)` に `server` セクションが含まれている場合は、それを一時的に削除し、デスクトップ アプリを再起動します。 + +#### 環境変数を確認する + +環境に `OPENCODE_PORT` が設定されている場合、デスクトップ アプリはローカル サーバーにそのポートを使用しようとします。 + +- `OPENCODE_PORT` の設定を解除して (または空きポートを選択して)、再起動します。 + +--- + +### Linux: Wayland / X11 の問題 + +Linux では、一部の Wayland セットアップにより、空白のウィンドウやコンポジター エラーが発生する可能性があります。 + +- Wayland を使用していて、アプリが空白またはクラッシュしている場合は、`OC_ALLOW_WAYLAND=1` で起動してみてください。 +- これにより状況が悪化する場合は、それを削除し、代わりに X11 セッションで起動してみてください。 + +--- + +### Windows: WebView2 ランタイム + +Windows では、OpenCode Desktop には Microsoft Edge **WebView2 ランタイム**が必要です。アプリが空白のウィンドウで開くか、起動しない場合は、WebView2 をインストールまたは更新して、もう一度試してください。 + +--- + +### Windows: 一般的なパフォーマンスの問題 + +Windows でパフォーマンスの低下、ファイル アクセスの問題、またはターミナルの問題が発生している場合は、[WSL (Windows Subsystem for Linux)](/docs/windows-wsl) を使用してみてください。 WSL は、OpenCode の機能とよりシームレスに連携する Linux 環境を提供します。 + +--- + +### 通知が表示されない + +OpenCode Desktop では、次の場合にのみシステム通知が表示されます。 + +- OS 設定で OpenCode の通知が有効になっており、 +- アプリウィンドウにフォーカスがありません。 + +--- + +### デスクトップ アプリのストレージをリセットする (最後の手段) + +アプリが起動せず、UI 内から設定をクリアできない場合は、デスクトップ アプリの保存された状態をリセットします。 + +1. OpenCode デスクトップを終了します。 +2. これらのファイルを見つけて削除します (これらのファイルは OpenCode デスクトップ アプリのデータ ディレクトリにあります)。 + +- `opencode.settings.dat` (デスクトップのデフォルトサーバー URL) +- `opencode.global.dat` および `opencode.workspace.*.dat` (最近のサーバー/プロジェクトなどの UI 状態) + +ディレクトリをすばやく見つけるには: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (その後、上記のファイル名を検索します) +- **Linux**: 上記のファイル名を `~/.local/share` で検索します。 +- **Windows**: `WIN+R` -> `%APPDATA%` を押します (その後、上記のファイル名を検索します)。 + +--- + +## 助けを求める + +OpenCode で問題が発生している場合: + +1. **GitHub で問題を報告してください** + +バグを報告したり、機能をリクエストしたりする最良の方法は、GitHub リポジトリを使用することです。 + +[**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + +新しい問題を作成する前に、既存の問題を検索して、問題がすでに報告されているかどうかを確認してください。 + +2. **Discord に参加してください** + +リアルタイムのヘルプやコミュニティのディスカッションについては、Discord サーバーに参加してください。 + +[**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## よくある問題 + +ここでは、いくつかの一般的な問題とその解決方法を示します。 + +--- + +### OpenCodeが起動しない + +1. ログでエラー メッセージを確認する +2. `--print-logs` で実行して、ターミナルに出力を確認してください。 +3. `opencode upgrade` を含む最新バージョンを使用していることを確認してください + +--- + +### 認証の問題 + +1. TUI で `/connect` コマンドを使用して再認証を試みます +2. API キーが有効であることを確認してください +3. ネットワークでプロバイダーの API への接続が許可されていることを確認してください + +--- + +### モデルがありません + +1. プロバイダーで認証されていることを確認してください +2. 構成内のモデル名が正しいことを確認してください +3. 一部のモデルでは、特定のアクセスまたはサブスクリプションが必要な場合があります + +`ProviderModelNotFoundError` が表示された場合は、間違いがある可能性が高くなります。 +どこかのモデルを参照しています。 +モデルは次のように参照する必要があります: `/` + +例: + +- `command.executed` +- `command.executed` +- `command.executed` + +どのモデルにアクセスできるかを確認するには、`opencode models` を実行します。 + +--- + +### ProviderInitError + +ProviderInitError が発生した場合は、構成が無効または破損している可能性があります。 + +これを解決するには: + +1. まず、[プロバイダー ガイド](/docs/providers) に従って、プロバイダーが正しく設定されていることを確認します。 +2. 問題が解決しない場合は、保存されている構成をクリアしてみてください。 + + ```bash + rm -rf ~/.local/share/opencode + ``` + +Windows では、`WIN+R` を押して、`%USERPROFILE%\.local\share\opencode` を削除します。 + +3. TUI の `/connect` コマンドを使用して、プロバイダーで再認証します。 + +--- + +### AI_APICallError とプロバイダー パッケージの問題 + +API 呼び出しエラーが発生した場合は、プロバイダー パッケージが古いことが原因である可能性があります。 opencode は、必要に応じてプロバイダー パッケージ (OpenAI、Anthropic、Google など) を動的にインストールし、ローカルにキャッシュします。 + +プロバイダー パッケージの問題を解決するには: + +1. プロバイダー パッケージのキャッシュをクリアします。 + + ```bash + rm -rf ~/.cache/opencode + ``` + +Windows では、`WIN+R` を押して、`%USERPROFILE%\.local\share\opencode` を削除します。 + +2. オープンコードを再起動して最新のプロバイダー パッケージを再インストールします + +これにより、オープンコードはプロバイダー パッケージの最新バージョンを強制的にダウンロードすることになり、多くの場合、モデル パラメーターや API の変更に関する互換性の問題が解決されます。 + +--- + +### Linux ではコピー/ペーストが機能しない + +Linux ユーザーがコピー/ペースト機能を動作させるには、次のクリップボード ユーティリティのいずれかがインストールされている必要があります。 + +**X11 システムの場合:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**Wayland システムの場合:** + +```bash +apt install -y wl-clipboard +``` + +**ヘッドレス環境の場合:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode は、Wayland を使用していて `wl-clipboard` を優先しているかどうかを検出します。そうでない場合は、`xclip` および `xsel` の順序でクリップボード ツールを検索しようとします。 diff --git a/packages/web/src/content/docs/ja/tui.mdx b/packages/web/src/content/docs/ja/tui.mdx new file mode 100644 index 000000000..af8468037 --- /dev/null +++ b/packages/web/src/content/docs/ja/tui.mdx @@ -0,0 +1,390 @@ +--- +title: トゥイ +description: OpenCode ターミナル ユーザー インターフェイスの使用。 +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode は、LLM を使用してプロジェクトを作業するための対話型ターミナル インターフェイスまたは TUI を提供します。 + +OpenCode を実行すると、現在のディレクトリの TUI が開始されます。 + +```bash +opencode +``` + +または、特定の作業ディレクトリに対して起動することもできます。 + +```bash +opencode /path/to/project +``` + +TUI に入ったら、メッセージを表示することができます。 + +```text +Give me a quick summary of the codebase. +``` + +--- + +## ファイル参照 + +`@` を使用してメッセージ内のファイルを参照できます。これにより、現在の作業ディレクトリ内であいまいなファイル検索が行われます。 + +:::ヒント +`@` を使用してメッセージ内のファイルを参照することもできます。 +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +ファイルの内容は会話に自動的に追加されます。 + +--- + +## Bash コマンド + +メッセージを `!` で開始して、シェル コマンドを実行します。 + +```bash frame="none" +!ls -la +``` + +コマンドの出力は、ツールの結果として会話に追加されます。 + +--- + +## コマンド + +OpenCode TUI を使用する場合、「`/`」に続いてコマンド名を入力すると、アクションをすばやく実行できます。例えば: + +```bash frame="none" +/help +``` + +ほとんどのコマンドには、`ctrl+x` をリーダー キーとして使用するキーバインドもあります。`ctrl+x` がデフォルトのリーダー キーです。 [詳細はこちら](/docs/keybinds)。 + +利用可能なすべてのスラッシュ コマンドは次のとおりです。 + +--- + +### 接続する + +OpenCode にプロバイダーを追加します。利用可能なプロバイダーから選択し、その API キーを追加できます。 + +```bash frame="none" +/connect +``` + +--- + +### コンパクト + +現在のセッションを圧縮します。 _別名_: `/summarize` + +```bash frame="none" +/compact +``` + +**キーバインド:** `ctrl+x c` + +--- + +### 詳細 + +ツール実行の詳細を切り替えます。 + +```bash frame="none" +/details +``` + +**キーバインド:** `ctrl+x c` + +--- + +### エディタ + +メッセージを作成するために外部エディタを開きます。 `EDITOR` 環境変数に設定されたエディタを使用します。 [詳細はこちら](#editor-setup)。 + +```bash frame="none" +/editor +``` + +**キーバインド:** `ctrl+x c` + +--- + +### 出口 + +OpenCodeを終了します。 _エイリアス_: `/quit`、`/q` + +```bash frame="none" +/exit +``` + +**キーバインド:** `ctrl+x c` + +--- + +### 輸出 + +現在の会話を Markdown にエクスポートし、デフォルトのエディターで開きます。 `EDITOR` 環境変数に設定されたエディタを使用します。 [詳細はこちら](#editor-setup)。 + +```bash frame="none" +/export +``` + +**キーバインド:** `ctrl+x c` + +--- + +### ヘルプ + +ヘルプダイアログを表示します。 + +```bash frame="none" +/help +``` + +**キーバインド:** `ctrl+x c` + +--- + +### 初期化 + +`AGENTS.md` ファイルを作成または更新します。 [詳細はこちら](/docs/rules)。 + +```bash frame="none" +/init +``` + +**キーバインド:** `ctrl+x c` + +--- + +### モデル + +利用可能なモデルをリストします。 + +```bash frame="none" +/models +``` + +**キーバインド:** `ctrl+x c` + +--- + +### 新しい + +新しいセッションを開始します。 _別名_: `/clear` + +```bash frame="none" +/new +``` + +**キーバインド:** `ctrl+x c` + +--- + +### やり直し + +以前に取り消したメッセージをやり直します。 `/undo` を使用した後にのみ使用できます。 + +:::ヒント +ファイルの変更も復元されます。 +::: + +内部的には、Git を使用してファイルの変更を管理します。したがって、あなたのプロジェクトは ** する必要があります +Git リポジトリ** であること。 + +```bash frame="none" +/redo +``` + +**キーバインド:** `ctrl+x c` + +--- + +### セッション + +セッションを一覧表示して切り替えます。 _エイリアス_: `/resume`、`/continue` + +```bash frame="none" +/sessions +``` + +**キーバインド:** `ctrl+x c` + +--- + +### 共有 + +現在のセッションを共有します。 [詳細はこちら](/docs/share)。 + +```bash frame="none" +/share +``` + +**キーバインド:** `ctrl+x c` + +--- + +### テーマ + +利用可能なテーマをリストします。 + +```bash frame="none" +/theme +``` + +**キーバインド:** `ctrl+x c` + +--- + +### 考え + +会話内の思考/推論ブロックの表示を切り替えます。有効にすると、拡張思考をサポートするモデルの推論プロセスを確認できます。 + +:::注記 +このコマンドは、思考ブロックを**表示**するかどうかのみを制御します。モデルの推論機能を有効または無効にすることはありません。実際の推論機能を切り替えるには、`ctrl+t` を使用してモデル バリアントを循環させます。 +::: + +```bash frame="none" +/thinking +``` + +--- + +### 元に戻す + +会話の最後のメッセージを元に戻します。最新のユーザー メッセージ、その後のすべての応答、およびファイルの変更を削除します。 + +:::ヒント +加えられたファイルの変更も元に戻されます。 +::: + +内部的には、Git を使用してファイルの変更を管理します。したがって、あなたのプロジェクトは ** する必要があります +Git リポジトリ** であること。 + +```bash frame="none" +/undo +``` + +**キーバインド:** `ctrl+x c` + +--- + +### 共有を解除する + +現在のセッションの共有を解除します。 [詳細はこちら](/docs/share#un-sharing)。 + +```bash frame="none" +/unshare +``` + +--- + +## エディターのセットアップ + +`/editor` および `/export` コマンドはどちらも、`EDITOR` 環境変数で指定されたエディターを使用します。 + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + +これを永続的にするには、これをシェル プロファイルに追加します。 +`~/.bashrc`、`~/.zshrc`など + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + +これを永続的にするには、**システム プロパティ** > **環境を使用します。 +変数**。 + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + +これを永続的にするには、これを PowerShell プロファイルに追加します。 + + + + +一般的なエディター オプションには次のものがあります。 + +- `code` - Visual Studio コード +- `cursor` - カーソル +- `windsurf` - ウィンドサーフィン +- `nvim` - Neovim エディター +- `vim` - Vim エディター +- `nano` - ナノエディター +- `notepad` - Windows メモ帳 +- `subl` - 崇高なテキスト + +:::注記 +VS Code などの一部のエディターは、`--wait` フラグを使用して起動する必要があります。 +::: + +一部のエディターは、ブロッキング モードで実行するためにコマンドライン引数が必要です。 `--wait` フラグにより​​、エディターは閉じられるまでプロセスをブロックします。 + +--- + +## 設定する + +OpenCode 構成ファイルを通じて TUI の動作をカスタマイズできます。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### オプション + +- `scroll_acceleration` - macOS スタイルのスクロール アクセラレーションを有効にして、スムーズで自然なスクロールを実現します。有効にすると、高速スクロール ジェスチャではスクロール速度が向上し、ゆっくりとした動きでは正確なままになります。 **この設定は `scroll_speed` よりも優先され、有効になっている場合は上書きされます。** +- `scroll_speed` - スクロール コマンドを使用するときに TUI がスクロールする速度を制御します (最小: `1`)。デフォルトは `3` です。 **注: `scroll_acceleration.enabled` が `true` に設定されている場合、これは無視されます。** + +--- + +## カスタマイズ + +コマンド パレット (`ctrl+x h` または `/help`) を使用して、TUI ビューのさまざまな側面をカスタマイズできます。これらの設定は再起動後も維持されます。 + +--- + +#### ユーザー名の表示 + +チャット メッセージにユーザー名を表示するかどうかを切り替えます。これには次の方法でアクセスします。 + +- コマンドパレット:「ユーザー名」または「ユーザー名を隠す」を検索します。 +- 設定は自動的に保持され、TUI セッション全体で記憶されます。 diff --git a/packages/web/src/content/docs/ja/web.mdx b/packages/web/src/content/docs/ja/web.mdx new file mode 100644 index 000000000..9a42ee8cb --- /dev/null +++ b/packages/web/src/content/docs/ja/web.mdx @@ -0,0 +1,142 @@ +--- +title: ウェブ +description: ブラウザで OpenCode を使用する。 +--- + +OpenCode はブラウザーで Web アプリケーションとして実行でき、ターミナルを必要とせずに同じ強力な AI コーディング エクスペリエンスを提供します。 + +![OpenCode Web - 新しいセッション](../../../assets/web/web-homepage-new-session.png) + +## はじめる + +以下を実行して Web インターフェースを開始します。 + +```bash +opencode web +``` + +これにより、利用可能なランダムなポートを使用して `127.0.0.1` でローカル サーバーが起動され、デフォルトのブラウザで OpenCode が自動的に開きます。 + +:::注意 +`OPENCODE_SERVER_PASSWORD` が設定されていない場合、サーバーは保護されません。これはローカルで使用する場合には問題ありませんが、ネットワーク アクセス用に設定する必要があります。 +::: + +:::tip[Windows ユーザー] +最高のエクスペリエンスを得るには、PowerShell ではなく [WSL](/docs/windows-wsl) から `opencode web` を実行します。これにより、ファイル システムへの適切なアクセスと端末の統合が保証されます。 +::: + +--- + +## 構成 + +コマンド ライン フラグを使用するか、[config file](/docs/config).config ファイル] で Web サーバーを設定できます。 + +### ポート + +デフォルトでは、OpenCode は使用可能なポートを選択します。ポートを指定できます。 + +```bash +opencode web --port 4096 +``` + +### ホスト名 + +デフォルトでは、サーバーは `127.0.0.1` (localhost のみ) にバインドされます。ネットワーク上で OpenCode にアクセスできるようにするには: + +```bash +opencode web --hostname 0.0.0.0 +``` + +`0.0.0.0` を使用すると、OpenCode はローカル アドレスとネットワーク アドレスの両方を表示します。 + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### mDNS ディスカバリー + +mDNS を有効にして、ローカル ネットワーク上でサーバーを検出できるようにします。 + +```bash +opencode web --mdns +``` + +これにより、ホスト名が自動的に `0.0.0.0` に設定され、サーバーが `opencode.local` としてアドバタイズされます。 + +mDNS ドメイン名をカスタマイズして、同じネットワーク上で複数のインスタンスを実行できます。 + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### コルス + +CORS の追加ドメインを許可するには (カスタム フロントエンドに便利): + +```bash +opencode web --cors https://example.com +``` + +### 認証 + +アクセスを保護するには、`OPENCODE_SERVER_PASSWORD` 環境変数を使用してパスワードを設定します。 + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +ユーザー名のデフォルトは `opencode` ですが、`OPENCODE_SERVER_USERNAME` で変更できます。 + +--- + +## Web インターフェースの使用 + +開始すると、Web インターフェイスから OpenCode セッションにアクセスできるようになります。 + +### セッション + +ホームページからセッションを表示および管理します。アクティブなセッションを確認したり、新しいセッションを開始したりできます。 + +![OpenCode Web - アクティブなセッション](../../../assets/web/web-homepage-active-session.png) + +### サーバーステータス + +「サーバーを表示」をクリックすると、接続されているサーバーとそのステータスが表示されます。 + +![OpenCode Web - Servers](../../../assets/web/web-homepage-see-servers.png) を参照 + +--- + +## 端子の取り付け + +実行中の Web サーバーにターミナル TUI を接続できます。 + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +これにより、Web インターフェイスとターミナルの両方を同時に使用し、同じセッションと状態を共有できるようになります。 + +--- + +## 設定ファイル + +`opencode.json` 構成ファイルでサーバー設定を構成することもできます。 + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +コマンド ライン フラグは、構成ファイルの設定よりも優先されます。 diff --git a/packages/web/src/content/docs/ja/windows-wsl.mdx b/packages/web/src/content/docs/ja/windows-wsl.mdx new file mode 100644 index 000000000..c968654bb --- /dev/null +++ b/packages/web/src/content/docs/ja/windows-wsl.mdx @@ -0,0 +1,119 @@ +--- +title: Windows (WSL) +description: WSL を使って Windows で OpenCode を使う。 +--- + +import { Steps } from "@astrojs/starlight/components" + +OpenCode は Windows で直接実行できますが、より快適に使うには [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) の利用をおすすめします。WSL は OpenCode の機能とスムーズに連携する Linux 環境を提供します。 + +:::tip[WSL を使う理由] +WSL を使うと、ファイルシステム性能、端末サポート、OpenCode が依存する開発ツールとの互換性が向上します。 +::: + +--- + +## セットアップ + + + +1. **WSL をインストールする** + + まだの場合は、Microsoft 公式ガイドを使って [WSL をインストール](https://learn.microsoft.com/en-us/windows/wsl/install) します。 + +2. **WSL で OpenCode をインストールする** + + WSL の準備ができたら WSL のターミナルを開き、[インストール方法](/docs/) のいずれかで OpenCode をインストールします。 + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **WSL から OpenCode を使う** + + プロジェクトディレクトリに移動し(Windows ファイルは `/mnt/c/` や `/mnt/d/` などからアクセス)、OpenCode を実行します。 + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## デスクトップアプリ + WSL サーバー + +OpenCode Desktop アプリを使いつつ、サーバーは WSL で動かしたい場合は次の手順です。 + +1. **WSL でサーバーを起動する** + + 外部接続を許可するため、`--hostname 0.0.0.0` を付けて起動します。 + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Desktop アプリを接続する** + + `http://localhost:4096` に接続します。 + +:::note +環境によって `localhost` が使えない場合は、WSL 側で `hostname -I` を実行して IP アドレスを確認し、`http://:4096` に接続してください。 +::: + +:::caution +`--hostname 0.0.0.0` を使う場合は、`OPENCODE_SERVER_PASSWORD` を設定してサーバーを保護してください。 + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Web クライアント + WSL + +Windows で Web 利用を快適にするには: + +1. **PowerShell ではなく WSL ターミナルで `opencode web` を実行する** + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Windows のブラウザーからアクセスする** + + `http://localhost:` にアクセスします(URL は OpenCode が表示します)。 + +WSL から `opencode web` を実行すると、適切なファイルシステムアクセスとターミナル統合を維持したまま、Windows ブラウザーから利用できます。 + +--- + +## Windows ファイルへのアクセス + +WSL からは `/mnt/` ディレクトリ経由で Windows ファイルにアクセスできます。 + +- `C:` drive → `/mnt/c/` +- `D:` drive → `/mnt/d/` +- そのほかのドライブも同様です + +例: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +よりスムーズに使うには、リポジトリを WSL のファイルシステム(例: `~/code/`)にクローンまたはコピーして、そこで OpenCode を実行することをおすすめします。 +::: + +--- + +## ヒント + +- Windows ドライブ上のプロジェクトでも、OpenCode は WSL で実行するとファイルアクセスがスムーズです +- OpenCode と一緒に VS Code の [WSL 拡張](https://code.visualstudio.com/docs/remote/wsl) を使うと統合的な開発フローを構築できます +- OpenCode の設定とセッションは WSL 環境内の `~/.local/share/opencode/` に保存されます diff --git a/packages/web/src/content/docs/ja/zen.mdx b/packages/web/src/content/docs/ja/zen.mdx new file mode 100644 index 000000000..c01011c56 --- /dev/null +++ b/packages/web/src/content/docs/ja/zen.mdx @@ -0,0 +1,254 @@ +--- +title: 禅 +description: OpenCode によって提供されるモデルの厳選されたリスト。 +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen は、OpenCode チームによって提供される、テストおよび検証されたモデルのリストです。 + +:::注記 +OpenCode Zen は現在ベータ版です。 +::: + +Zen は OpenCode の他のプロバイダーと同様に機能します。 OpenCode Zen にログインすると、 +API キー。これは **完全にオプション** であり、使用するために使用する必要はありません。 +OpenCode. + +--- + +## 背景 + +モデルはたくさんありますが、そのうちのほんの一部です +これらのモデルはコーディング エージェントとしてうまく機能します。さらに、ほとんどのプロバイダーは、 +構成が大きく異なります。したがって、まったく異なるパフォーマンスと品質が得られます。 + +:::ヒント +私たちは、OpenCode で適切に動作するモデルとプロバイダーの選択されたグループをテストしました。 +::: + +したがって、OpenRouter などを通じてモデルを使用している場合は、決してそうすることはできません。 +必要なモデルの最高のバージョンを入手しているかどうかを確認してください。 + +これを修正するために、いくつかのことを行いました。 + +1. 私たちは選択したモデルのグループをテストし、その方法についてチームと話し合いました。 +それらを実行するのが最善です。 +2. その後、いくつかのプロバイダーと協力して、これらが確実に提供されるようにしました。 + correctly. +3. 最後に、モデルとプロバイダーの組み合わせをベンチマークし、次の結果を導き出しました。 +私たちが自信を持ってお勧めするリストをご紹介します。 + +OpenCode Zen は、これらのモデルへのアクセスを可能にする AI ゲートウェイです。 + +--- + +## 仕組み + +OpenCode Zen は、OpenCode の他のプロバイダーと同様に機能します。 + +1. **OpenCode Zen** にログインし、請求内容を追加します +詳細を確認し、API キーをコピーします。 +2. TUI で `/connect` コマンドを実行し、OpenCode Zen を選択して API キーを貼り付けます。 +3. TUI で `/models` を実行すると、推奨されるモデルのリストが表示されます。 + +リクエストごとに料金が請求され、アカウントにクレジットを追加できます。 + +--- + +## エンドポイント + +次の API エンドポイントを通じてモデルにアクセスすることもできます。 + +|モデル |モデルID |エンドポイント | AI SDK パッケージ | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 コーデックス | gpt-5.2-コーデックス | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 コーデックス | gpt-5.1-コーデックス | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 コーデックス マックス | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 コーデックス ミニ | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 コーデックス | gpt-5-コーデックス | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT5ナノ | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +|クロード・ソネット 4.5 |クロード・ソネット-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|クロード・ソネット 4 |クロード・ソネット4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|クロード俳句 4.5 |クロード俳句-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|クロード俳句 3.5 |クロード-3-5-俳句 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|クロード作品4.6 |クロード作品4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|クロード作品4.5 |クロード作品4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|クロード作品4.1 |クロード-作品-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|ジェミニ 3 プロ |ジェミニ-3-プロ | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +|ジェミニ 3 フラッシュ |ジェミニ-3-フラッシュ | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +|ミニマックス M2.1 |ミニマックス-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 無料 |ミニマックス-m2.1-無料 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 無料 | glm-4.7-無料 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +|キミK2.5 |きみk2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +|キミ K2.5 無料 | kimi-k2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +|キミ K2 思考 | kimi-k2-思考 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +|キミ K2 |きみk2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3 コーダー 480B | qwen3 コーダー | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +|ビッグピクルス |ビッグピクルス | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +OpenCode 設定の [model id](/docs/config/#models) +`opencode/` 形式を使用します。たとえば、GPT 5.2 Codex の場合は、次のようになります。 +設定で `opencode/gpt-5.2-codex` を使用してください。 + +--- + +### モデル + +利用可能なモデルとそのメタデータの完全なリストは、次から取得できます。 + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## 価格設定 + +当社は従量課金制モデルをサポートしています。以下は **100 万トークンあたりの価格**です。 + +|モデル |入力 |出力 |キャッシュされた読み取り |キャッシュされた書き込み | +| --------------------------------- | ------ | ------ | ----------- | ------------ | +|ビッグピクルス |無料 |無料 |無料 | - | +| MiniMax M2.1 無料 |無料 |無料 |無料 | - | +|ミニマックス M2.1 | $0.30 | $1.20 | $0.10 | - | +| GLM 4.7 無料 |無料 |無料 |無料 | - | +| GLM 4.7 | $0.60 | $2.20 | $0.10 | - | +| GLM 4.6 | $0.60 | $2.20 | $0.10 | - | +|キミ K2.5 無料 |無料 |無料 |無料 | - | +|キミK2.5 | $0.60 | $3.00 | $0.08 | - | +|キミ K2 思考 | $0.40 | $2.50 | - | - | +|キミK2 | $0.40 | $2.50 | - | - | +| Qwen3 コーダー 480B | $0.45 | $1.50 | - | - | +|クロード・ソネット 4.5 (≤ 200K トークン) | $3.00 | $15.00 | $0.30 | $3.75 | +|クロード・ソネット 4.5 (> 200K トークン) | $6.00 | $22.50 | $0.60 | $7.50 | +|クロード・ソネット 4 (≤ 200K トークン) | $3.00 | $15.00 | $0.30 | $3.75 | +|クロード・ソネット 4 (> 200K トークン) | $6.00 | $22.50 | $0.60 | $7.50 | +|クロード俳句 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | +|クロード俳句 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | +|クロード オーパス 4.6 (≤ 200K トークン) | $5.00 | $25.00 | $0.50 | $6.25 | +|クロード オーパス 4.6 (> 200K トークン) | $10.00 | $37.50 | $1.00 | $12.50 | +|クロード作品4.5 | $5.00 | $25.00 | $0.50 | $6.25 | +|クロード作品4.1 | $15.00 | $75.00 | $1.50 | $18.75 | +| Gemini 3 Pro (≤ 200K トークン) | $2.00 | $12.00 | $0.20 | - | +| Gemini 3 Pro (> 200K トークン) | $4.00 | $18.00 | $0.40 | - | +|ジェミニ 3 フラッシュ | $0.50 | $3.00 | $0.05 | - | +| GPT5.2 | $1.75 | $14.00 | $0.175 | - | +| GPT 5.2 コーデックス | $1.75 | $14.00 | $0.175 | - | +| GPT5.1 | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 コーデックス | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 コーデックス マックス | $1.25 | $10.00 | $0.125 | - | +| GPT 5.1 コーデックス ミニ | $0.25 | $2.00 | $0.025 | - | +| GPT5 | $1.07 | $8.50 | $0.107 | - | +| GPT 5 コーデックス | $1.07 | $8.50 | $0.107 | - | +| GPT5ナノ |無料 |無料 |無料 | - | + +使用履歴に _Claude Haiku 3.5_ が表示されるかもしれません。これは [セッションのタイトルを生成するために使用される低コスト モデル ](/docs/config/#models) です。 + +:::注記 +クレジット カード手数料は実費で引き継がれます (4.4% + 取引ごとに 0.30 ドル)。それ以上の料金はかかりません。 +::: + +無料モデル: + +- GLM 4.7 Free は期間限定で OpenCode で入手できます。チームはこの時間を利用してフィードバックを収集し、モデルを改善します。 +- Kim K2.5 Free は OpenCode で期間限定で利用可能です。チームはこの時間を利用してフィードバックを収集し、モデルを改善します。 +- MiniMax M2.1 Free は期間限定で OpenCode で入手できます。チームはこの時間を利用してフィードバックを収集し、モデルを改善します。 +- Big Pickle は、期間限定で OpenCode で無料で利用できるステルス モデルです。チームはこの時間を利用してフィードバックを収集し、モデルを改善します。 + +ご質問がございましたら、お問い合わせください。 + +--- + +### 自動リロード + +残高が 5 ドルを下回ると、Zen は自動的に 20 ドルをリロードします。 + +自動リロード量を変更できます。自動リロードを完全に無効にすることもできます。 + +--- + +### 月ごとの制限 + +ワークスペース全体およびワークスペースごとに月ごとの使用制限を設定することもできます。 +あなたのチームのメンバー。 + +たとえば、毎月の使用制限を 20 ドルに設定したとします。Zen は使用しません。 +月に20ドル以上。ただし、自動リロードを有効にしている場合、Zen が終了する可能性があります。 +残高が 5 ドルを下回ると、20 ドル以上の請求が行われます。 + +--- + +## プライバシー + +すべてのモデルは米国でホストされています。当社のプロバイダーはゼロ保持ポリシーに従い、次の例外を除いて、モデルのトレーニングにデータを使用しません。 + +- Big Pickle: 無料期間中に、収集されたデータはモデルの改善に使用される場合があります。 +- GLM 4.7 無料: 無料期間中、収集されたデータはモデルを改善するために使用される場合があります。 +- Kimi K2.5 Free: 無料期間中、収集されたデータはモデルの改善に使用される場合があります。 +- MiniMax M2.1 無料: 無料期間中、収集されたデータはモデルを改善するために使用される場合があります。 +- OpenAI API: リクエストは [OpenAI のデータ ポリシー ](https://platform.openai.com/docs/guides/your-data). +- Anthropic API: リクエストは、[Anthropic のデータ ポリシー ](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## チーム向け + +Zen はチームにも効果的です。チームメイトを招待し、役割を割り当て、キュレートすることができます +チームが使用するモデルなど。 + +:::注記 +ワークスペースは現在、ベータ版の一部としてチームに無料で提供されています。 +::: + +現在、チームはベータ版の一部としてワークスペースの管理を無料で行うことができます。私たちはそうなります +価格の詳細については近日中にお知らせします。 + +--- + +### 役割 + +チームメイトをワークスペースに招待し、役割を割り当てることができます。 + +- **管理者**: モデル、メンバー、API キー、請求を管理します。 +- **メンバー**: 自分の API キーのみを管理します + +管理者は、コストを管理するために各メンバーの毎月の支出制限を設定することもできます。 + +--- + +### モデルアクセス + +管理者は、ワークスペースの特定のモデルを有効または無効にすることができます。無効なモデルに対してリクエストを行うと、エラーが返されます。 + +これは、モデルの使用を無効にしたい場合に便利です。 +データを収集します。 + +--- + +### 自分の鍵を持参してください + +Zen の他のモデルにアクセスしながら、独自の OpenAI または Anthropic API キーを使用できます。 + +独自のキーを使用する場合、トークンは Zen ではなくプロバイダーによって直接請求されます。 + +たとえば、組織はすでに OpenAI または Anthropic のキーを持っている可能性があります。 +Zen が提供するものの代わりにそれを使用したいとします。 + +--- + +## 目標 + +私たちは次の目的で OpenCode Zen を作成しました。 + +1. **ベンチマーク** コーディング エージェントに最適なモデル/プロバイダー。 +2. **最高品質**のオプションにアクセスでき、パフォーマンスをダウングレードしたり、より安価なプロバイダーにルートしたりする必要はありません。 +3. 原価で販売することで**価格下落**を転嫁します。したがって、唯一のマークアップは処理手数料をカバーすることです。 +4. 他のコーディング エージェントとの併用を許可することで、**ロックイン**がなくなります。また、常に OpenCode で他のプロバイダーも使用できるようにします。 diff --git a/packages/web/src/content/docs/ko/1-0.mdx b/packages/web/src/content/docs/ko/1-0.mdx new file mode 100644 index 000000000..f8366d5d3 --- /dev/null +++ b/packages/web/src/content/docs/ko/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: Migrating to 1.0 +description: What's new in OpenCode 1.0. +--- + +OpenCode 1.0은 TUI의 완전한 재쓰기입니다. + +우리는 zig+solidjs에서 작성된 사내 프레임 워크 (OpenTUI)에 성능과 기능 문제가있는 go+bubbletea 기반 TUI에서 이동했습니다. + +새로운 TUI는 같은 오픈 코드 서버에 연결하기 때문에 오래된 것 같이 작동합니다. + +--- + +## 업그레이드 + +현재 이전을 사용하는 경우 현재 1.0로 autoupgraded 할 수 없습니다. +버전. 그러나 OpenCode의 이전 버전은 항상 최신을 잡아. + +수동으로 업그레이드하려면 실행 + +```bash +$ opencode upgrade 1.0.0 +``` + +0.x로 다운 그레이드, 실행 + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## UX 변경 + +세션 역사는 더 많은 압축, 편집 및 bash 도구의 전체 세부 사항을 보여주는. + +우리는 거의 모든 것을 통해 흐르는 명령 줄을 추가했습니다. ctrl+p를 눌러 모든 컨텍스트에서 가져 와서 할 수있는 모든 것을 볼 수 있습니다. + +유용한 정보로 세션 사이드바(Toggled)를 추가했습니다. + +우리는 우리가 실제로 사용되었던 어떤 기능을 제거했습니다. 뭔가 중요하지 않은 경우 문제가 열리고 신속하게 추가됩니다. + +--- + +## 파손 변화 + +## Keybinds 이름 변경 + +- message revert -> 메시지 undo +- switch agent -> 에이전트 사이클 +- switch agent reverse -> 에이전트 cycle reverse +- switch mode -> 에이전트 cycle +- switch mode reverse -> 에이전트 cycle reverse + +## Keybinds 제거 + +- 메시지 layout toggle +- 메시지 +- 메시지 +- 파일 diff toggle +- 파일 search +- 파일 닫기 +- 파일 list +- 앱 help +- 프로젝트 init +- 툴 details +- 사고 blocks diff --git a/packages/web/src/content/docs/ko/acp.mdx b/packages/web/src/content/docs/ko/acp.mdx new file mode 100644 index 000000000..9accc06d2 --- /dev/null +++ b/packages/web/src/content/docs/ko/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACP Support +description: Use OpenCode in any ACP-compatible editor. +--- + +OpenCode는 [Agent Client Protocol](https://agentclientprotocol.com) 또는 (ACP)을 지원하며, 호환 편집기 및 IDE에서 직접 사용할 수 있습니다. + +:::tip +ACP를 지원하는 편집기 및 도구 목록의 경우 [ACP 진행 보고서](https://zed.dev/blog/acp-progress-report#available-now)를 확인하십시오. +::: + +ACP는 코드 편집기와 AI 코딩 에이전트 간의 통신을 표준화하는 개방형 프로토콜입니다. + +--- + +## 구성 + +ACP를 통해 OpenCode를 사용하려면 `opencode acp` 명령을 실행하려면 편집기를 구성하십시오. + +명령은 OpenCode를 실행하여 JSON-RPC를 통해 편집기와 통신하는 ACP 호환 하위 프로세스로 시작합니다. + +아래는 ACP를 지원하는 인기있는 편집기의 예입니다. + +--- + +# # # # # Zed를 + +[Zed] (https://zed.dev) 구성 (`~/.config/zed/settings.json`)에 추가 : + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +그것을 열려면 **Command Palette **에서 `agent: new thread` 동작을 사용하십시오. + +`keymap.json`를 편집하여 키보드 단축키도 결합할 수 있습니다. + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +# # # # JetBrains IDEs의 특징 + +[JetBrains IDE]에 추가하십시오 (https://www.jetbrains.com/) [documentation]에 따라 acp.json (https://www.jetbrains.com/help/ai-assistant/acp.html): + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +그것을 열려면 AI Chat Agent selector의 새로운 'OpenCode' 에이전트를 사용하십시오. + +--- + +# # # # Avante.nvim의 + +[Avante.nvim] (https://github.com/yetone/avante.nvim) 구성에 추가하십시오: + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +환경 변수를 전달해야 하는 경우: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +# # # # CodeCompanion.nvim의 + +OpenCode를 [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim)에서 ACP 에이전트로 사용하려면 Neovim config에 다음을 추가하십시오. + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +이 구성은 CodeCompanion을 설정하여 채팅을 위한 ACP 에이전트로 OpenCode를 사용합니다. + +환경 변수 (`OPENCODE_API_KEY`와 같은)를 전달해야하는 경우, CodeCompanion.nvim 문서에서 [Configuring Adapters: Environment variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key)를 참조하십시오. + +## 지원 + +OpenCode는 터미널에서 같은 ACP를 통해 작동합니다. 모든 기능은 지원됩니다: + +:::note +`/undo` 및 `/redo`와 같은 일부 내장 슬래시 명령은 현재 지원되지 않습니다. +::: + +- 내장 도구 (파일 작업, 터미널 명령 등) +- 사용자 정의 도구 및 슬래시 명령 +- OpenCode config에서 설정된 MCP 서버 +- `AGENTS.md`의 프로젝트 별 규칙 +- 사용자 정의 포맷 및 라이터 +- 에이전트 및 권한 시스템 diff --git a/packages/web/src/content/docs/ko/agents.mdx b/packages/web/src/content/docs/ko/agents.mdx new file mode 100644 index 000000000..d7c69140b --- /dev/null +++ b/packages/web/src/content/docs/ko/agents.mdx @@ -0,0 +1,747 @@ +--- +title: Agents +description: Configure and use specialized agents. +--- + +에이전트는 특정 작업과 워크플로우를 구성할 수 있는 AI 보조를 전문으로 합니다. 사용자 정의 프롬프트, 모델 및 도구 액세스와 초점을 맞춘 도구를 만들 수 있습니다. + +:::tip +코드를 분석하고 코드 변경없이 제안을 검토 할 계획 에이전트를 사용합니다. +::: + +세션 중에 에이전트를 전환하거나 `@` 언급으로 호출 할 수 있습니다. + +--- + +## 유형 + +OpenCode의 두 가지 유형이 있습니다; 기본 에이전트와 시약. + +--- + +### 1 차적인 대리인 + +1 차적인 대리인은 당신이 직접 상호 작용하는 주요 조수입니다. **Tab** 키 또는 설정된 `switch_agent` keybind를 사용하여 주기 할 수 있습니다. 이 대리인은 당신의 주요 대화를 취급합니다. 도구 액세스는 권한을 통해 구성된다 — 예를 들어, 빌드는 계획이 제한되는 동안 모든 도구를 사용할 수 있습니다. + +:::tip +세션 중에 기본 에이전트를 전환하는 **Tab** 키를 사용할 수 있습니다. +::: + +OpenCode는 두 개의 내장 기본 에이전트, **Build** 및 **Plan**와 함께 제공됩니다. 우리는 +아래에서 보기. + +--- + +## # 시약 + +Subagents는 기본 에이전트가 특정 작업을 위해 호출 할 수있는 전문 보조입니다. 또한 수동으로 그들을 호출 할 수 있습니다 ** @ 언급 ** 메시지에서 그들. + +OpenCode는 두 개의 내장 하위 시약, ** 일반 ** 및 ** 익스플로러 **. 아래에서 볼 수 있습니다. + +--- + +## 내장 + +OpenCode는 기본 에이전트와 두 개의 내장 하위 시약으로 제공됩니다. + +--- + +### 사용 빌드 + +모드 : `primary` + +Build는 **default** 모든 도구가 활성화된 기본 에이전트입니다. 이것은 당신이 파일 가동 및 체계 명령에 가득 차있는 접근을 필요로 하는 발달 일을 위한 표준 대리인입니다. + +--- + +### 사용 계획 + +모드 : `primary` + +계획 및 분석을 위해 설계된 제한된 대리인. 우리는 더 많은 통제를 주고 무인화한 변화를 방지하기 위하여 허가 체계를 이용합니다. +기본적으로, 뒤에 오는 전부는 `ask`로 놓입니다: + +- `file edits`: 모든 쓰기, 패치 및 편집 +- `bash`: 모든 bash 명령 + +이 에이전트는 코드를 분석 할 LLM을 원할 때 유용합니다, 변경을 제안하거나 코드베이스에 실제 수정없이 계획을 만들 수 있습니다. + +--- + +### 사용 일반 + +모드 : `subagent` + +복잡한 질문을 연구하고 다중 단계 작업을 실행하기위한 범용 에이전트. 전체 도구 액세스 (todo 제외), 그래서 필요할 때 파일 변경을 만들 수 있습니다. 평행한에 있는 일의 다수 단위를 달리기 위하여 이것을 사용하십시오. + +--- + +### 사용 탐구 + +모드 : `subagent` + +Codebases를 탐구하는 빠르고, 읽기 전용 에이전트. 파일을 수정할 수 없습니다. 이 작업을 사용하면 패턴, 키워드 검색 코드, 또는 codebase에 대한 질문에 신속하게 파일을 찾을 수 있습니다. + +--- + +### 사용 컴팩트 + +모드 : `primary` + +더 작은 요약으로 긴 맥락을 압축하는 숨겨진 시스템 에이전트. 필요한 경우 자동으로 실행되며 UI에서 선택할 수 없습니다. + +--- + +### 사용 제목 + +모드 : `primary` + +짧은 세션 타이틀을 생성하는 숨겨진 시스템 에이전트. 그것은 자동으로 실행하고 UI에서 선택할 수 없습니다. + +--- + +### 사용 요약 + +모드 : `primary` + +세션 summaries를 만드는 숨겨진 시스템 에이전트. 그것은 자동으로 실행하고 UI에서 선택할 수 없습니다. + +--- + +## 사용법 + +1. 1 차적인 대리인을 위해, **Tab ** 열쇠를 사용하여 세션 도중 주기. 구성 된 `switch_agent` keybind도 사용할 수 있습니다. + +2. 시약은 invoked 일 수 있습니다: +-**Automatically** 그들의 설명에 근거를 둔 특화된 업무를 위한 1 차적인 대리인에 의하여. +- 메시지에 대한 하위 시약**. 예를 들어. + + ```txt frame="none" + @general help me search for this function + ``` + +3. ** 세션 간의 편차 **: 하위 시약은 자신의 자녀 세션을 만들 때, 부모 세션과 모든 어린이 세션을 사용하여 탐색 할 수 있습니다. +- **\+Right** (또는 부모 → Child1 → Child2 →를 통해 전달하기 위해 설정된 `session_child_cycle` keybind) +- **\+Left** (또는 `session_child_cycle_reverse` keybind) 부모를 통해 돌아 가기 위해 ← child1 ← child2 ← ... ← 부모 + +이로 인해 주요 대화와 특이한 시약 작업을 원활하게 전환할 수 있습니다. + +--- + +## 구성 + +내장 에이전트를 사용자 정의하거나 구성을 통해 자신의 만들 수 있습니다. 에이전트는 두 가지 방법으로 구성 될 수 있습니다: + +--- + +### JSON 태그 + +`opencode.json` config 파일에 에이전트 구성: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### 마크다운 + +Markdown 파일을 사용하여 에이전트를 정의 할 수 있습니다. 그들에 게: + +- 글로벌: `~/.config/opencode/agents/` +- 프로젝트: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +markdown 파일 이름은 대리인 이름입니다. 예를 들어, `review.md`는 `review` 대리인을 만듭니다. + +--- + +## 옵션 + +이 구성 옵션을 자세히 살펴봅시다. + +--- + +### 묘사 + +`description` 옵션을 사용하여 에이전트가 작동하고 사용할 때의 간단한 설명을 제공합니다. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +** config 옵션이 필요합니다. + +--- + +### 온도 + +`temperature` config와 LLM의 응답의 임의성과 창의성을 제어합니다. + +더 낮은 값은 더 집중하고 세심한 응답을 만듭니다. 더 높은 값은 창의력과 가변성을 증가하면서. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +온도 값은 일반적으로 0.0에서 1.0에 배열합니다: + +- **0.0-0.2**: 매우 집중하고 신중한 응답, 코드 분석 및 계획에 이상 +-**0.3-0.5**: 일부 창의력과 균형 잡힌 응답, 일반 개발 작업에 좋은 +- **0.6-1.0**: 더 창조적이고 다양한 응답, 뇌하수 및 탐험에 유용한 + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +온도가 지정되지 않은 경우, OpenCode는 모델 별 기본을 사용합니다. 일반적으로 대부분의 모델의 경우 0, Qwen 모델의 경우 0.55. + +--- + +## 최대 단계 + +대리인의 최대 수를 통제하는 대리인은 원본과 반응하기 전에 실행할 수 있습니다. 이 사용자는 에이전트 행동에 제한을 설정하는 비용을 제어 할 수 있습니다. + +이 설정되지 않은 경우, 에이전트는 모델이 중지하거나 사용자가 세션을 중단하도록 선택할 때까지 계속됩니다. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +제한이 도달되면, 에이전트는 특별한 시스템을 신속하게 작업의 요약과 권장되는 나머지 작업에 응답하도록 지시합니다. + +:::caution +레거시 `maxSteps` 필드는 deprecated. 대신 `steps`를 사용하십시오. +::: + +--- + +# # # # 비활성화 + +`true`로 에이전트를 비활성화합니다. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +# # # # 프롬프트 + +`prompt` config를 가진 이 대리인을 위한 주문 체계 신속한 파일을 지정하십시오. 신속한 파일은 에이전트의 목적에 따라 지시를 포함해야합니다. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +이 경로는 config 파일이 있는 곳에 관계됩니다. 그래서 이것은 글로벌 OpenCode 구성과 프로젝트 특정 구성 모두를 위해 작동합니다. + +--- + +### 모형 + +`model` config를 사용하여이 에이전트에 대한 모델을 삭제합니다. 다른 작업에 최적화 된 다른 모델을 사용하는 데 유용합니다. 예를 들어, 계획을위한 빠른 모델, 구현을위한 더 많은 모델. + +:::tip +모델을 지정하지 않는 경우, 기본 에이전트는 [model globallyconfig](/docs/config#models)를 사용하며, subagents는 subagent를 호출하는 1차 에이전트의 모델을 사용합니다. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +OpenCode config의 모델 ID는 `provider/model-id` 형식을 사용합니다. 예를 들어, [OpenCode Zen](/docs/zen)을 사용한다면, GPT 5.1 Codex에 `opencode/gpt-5.1-codex`를 사용할 수 있습니다. + +--- + +## 도구 + +`tools` config로 이 에이전트에서 사용할 수있는 제어. `true` 또는 `false`로 설정하여 특정 도구를 활성화하거나 비활성화 할 수 있습니다. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +에이전트 별 구성 overrides 글로벌 구성. +::: + +한 번에 여러 도구를 제어 할 와일드 카드를 사용할 수 있습니다. 예를 들어, MCP 서버에서 모든 도구를 비활성화하려면: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[공구에 대해 더 알아보기](/docs/tools). + +--- + +## # 권한 + +에이전트가 수행 할 수있는 작업을 관리 할 수있는 권한을 구성 할 수 있습니다. 현재 `edit`, `bash` 및 `webfetch` 도구에 대한 권한은 다음과 같습니다. + +- `"ask"` - 도구 실행하기 전에 승인을위한 Prompt +- `"allow"` - 승인없이 모든 작업을 허용 +- `"deny"` - 도구 비활성화 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +당신은 에이전트 당이 허가를 override 할 수 있습니다. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +Markdown 에이전트에서 권한을 설정할 수 있습니다. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +특정 bash 명령에 대한 권한을 설정할 수 있습니다. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +이것은 glob 본을 가지고 갈 수 있습니다. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +또한 `*` 와일드 카드를 사용하여 모든 명령에 대한 권한을 관리 할 수 있습니다. +마지막 일치 규칙이 우선적으로 걸리기 때문에, `*` 와일드카드를 첫번째로 두고 특정 규칙을 후에 두십시오. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[허가에 대해 더 알아보기](/docs/permissions). + +--- + +### 형태 + +`mode` config로 에이전트 모드를 제어합니다. `mode` 선택권은 대리인이 사용될 수 있는 방법을 결정하기 위하여 이용됩니다. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +`mode` 선택권은 `primary`, `subagent`, 또는 `all`에 놓일 수 있습니다. `mode`가 지정되지 않은 경우 `all`로 기본값입니다. + +--- + +## #숨겨진 + +`@` 자동 완성 메뉴에서 시약을 숨깁니다. 작업 도구를 통해 다른 에이전트에 의해 invoked programmatically 있어야하는 내부 시약에 유용합니다. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +자동 완성 메뉴의 사용자 가시에만 영향을 미칩니다. 숨겨진 에이전트는 여전히 작업 도구를 통해 모델에 의해 호출 될 수 있습니다 권한 허용. + +:::note +`mode: subagent` 대리인에서만 적용합니다. +::: + +--- + +## 작업 권한 + +에이전트가 `permission.task`와 작업 도구를 통해 호출 할 수있는 제어. 유연한 일치를 위한 glob 본을 사용합니다. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +`deny`로 설정할 때, Subagent는 작업 도구 설명에서 완전히 제거됩니다. 그래서 모델은 그것을 호출하려고하지 않습니다. + +:::tip +규칙은 순서로 평가되고, **마지막 일치 규칙은**를 이깁니다. 위의 예에서 `orchestrator-planner`는 `*` (deny)와 `orchestrator-*` (allow) 모두 일치하지만 `orchestrator-*`가 `*` 후 제공되므로 결과는 `allow`입니다. +::: + +:::tip +사용자는 `@` 자동 완성 메뉴를 통해 직접 어떤 subagent를 호출 할 수 있습니다. 에이전트의 작업 허가가 거부 할 경우에도. +::: + +--- + +### 색깔 + +`color` 옵션과 UI에서 에이전트의 시각적 외관을 사용자 정의합니다. 이것은 어떻게 에이전트가 인터페이스에 나타납니다. + +유효한 hex 색깔을 사용하십시오 (예를들면, `#FF5733`) 또는 주제 색깔: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### 정상 P + +`top_p` 선택권을 가진 응답 다양성을 통제하십시오. 무작위 통제를 위한 온도에 대안. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +가치는 0.0에서 1.0에 배열합니다. 더 낮은 가치는 더 집중되고, 더 높은 가치는 더 다양합니다. + +--- + +### 추가 + +에이전트 구성에 지정하는 다른 옵션은 ** 직접 통과 ** 모델 옵션으로 공급자. 이 공급자 별 기능 및 매개 변수를 사용할 수 있습니다. + +예를 들어, OpenAI의 이유 모델과 함께, 당신은 이유를 제어 할 수 있습니다 노력: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +이 추가 옵션은 모델과 공급자 별입니다. 공급자의 문서 확인 가능 매개 변수. + +:::tip +`opencode models`를 실행하여 사용 가능한 모델 목록을 볼 수 있습니다. +::: + +--- + +## 에이전트 만들기 + +다음 명령을 사용하여 새로운 에이전트를 만들 수 있습니다: + +```bash +opencode agent create +``` + +이 대화 형 명령은: + +1. 대리인을 저장하는 곳에게; 세계적인 프로젝트 별. +2. 대리인이 해야 하는 무슨의 묘사. +3. 적절한 시스템 프롬프트 및 식별자를 생성한다. +4. 당신은 대리인이 접근할 수 있는 어떤 공구를 선정하자. +5. 마지막으로, 대리인 윤곽을 가진 markdown 파일을 창조하십시오. + +--- + +## 사용 사례 + +다른 대리인을 위한 몇몇 일반적인 사용 사례는 여기 있습니다. + +- **빌딩 에이전트**: 모든 도구와 함께 전체 개발 작업 +- ** 플랜 에이전트**: 변화없이 분석 및 계획 +- **리뷰 에이전트**: Code review with read-only access plus 문서 도구 +- ** 디버그 에이전트**: bash 및 읽기 도구와 함께 조사에 집중 +- **Docs 대리인 **: 파일 작업과 문서 작성하지만 시스템 명령 없음 + +--- + +## 예제 + +여기에 유용 할 수있는 몇 가지 예 에이전트가 있습니다. + +:::tip +당신은 공유하고 싶은 대리인이 있습니까? [PR](https://github.com/anomalyco/opencode). +::: + +--- + +### 문서 에이전트 + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +## 보안 감사 + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/ko/cli.mdx b/packages/web/src/content/docs/ko/cli.mdx new file mode 100644 index 000000000..f8caebfad --- /dev/null +++ b/packages/web/src/content/docs/ko/cli.mdx @@ -0,0 +1,601 @@ +--- +title: CLI +description: OpenCode CLI options and commands. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +기본적으로 OpenCode CLI는 어떤 인수 없이 실행할 때 [TUI](/docs/tui)를 시작합니다. + +```bash +opencode +``` + +그러나이 페이지에서 문서로 명령을받습니다. OpenCode programmatically와 상호 작용할 수 있습니다. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### 튜이 + +OpenCode 터미널 사용자 인터페이스를 시작합니다. + +```bash +opencode [project] +``` + +#### 플래그 + +| 간선 | 간선 | Description | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | 마지막 세션 | +| `--session` | `-s` | 세션 ID| +| `--prompt` | | | 사용 허가 | +| `--model` | `-m` | `-m`의 형태로 사용 가능 | +| `--agent` | | 에이전트 | +| `--port` |||꾸라 안내| +| `--hostname` | | 들러 주세요 | + +--- + +## 명령 + +OpenCode CLI에는 다음과 같은 명령이 있습니다. + +--- + +## 대리인 + +OpenCode에 대한 에이전트 관리. + +```bash +opencode agent [command] +``` + +--- + +### 첨부 + +`serve` 또는 `web` 명령을 통해 이미 실행되는 OpenCode 백엔드 서버에 터미널을 첨부합니다. + +```bash +opencode attach [url] +``` + +리모트 OpenCode 백엔드를 사용하여 TUI를 사용할 수 있습니다. 예를 들면: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### 플래그 + +| 간선 | 간선 | Description | +| ----------- | ----- | --------------------------------- | +| `--dir` | | TUI를 시작하는 작업 디렉토리 | +| `--session` | `-s` | 세션 ID| + +--- + +#### 생성 + +사용자 정의 구성으로 새로운 에이전트를 만듭니다. + +```bash +opencode agent create +``` + +이 명령은 사용자 정의 시스템 프롬프트 및 도구 구성으로 새로운 에이전트를 만들기 위해 안내합니다. + +--- + +#### 리스트 + +모든 사용 가능한 에이전트 목록. + +```bash +opencode agent list +``` + +--- + +## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +credentials 및 로그인을 관리하는 명령. + +```bash +opencode auth [command] +``` + +--- + +#### 로그인 + +OpenCode는 [Models.dev](https://models.dev)의 공급자 목록에 의해 구동되므로 `opencode auth login`를 사용하여 사용하려는 모든 공급자의 API 키를 구성할 수 있습니다. 이것은 `~/.local/share/opencode/auth.json`에서 저장됩니다. + +```bash +opencode auth login +``` + +OpenCode가 시작하면 credentials 파일에서 공급자를로드합니다. 그리고 프로젝트에 있는 환경 또는 `.env` 파일에서 정의된 키가 있다면. + +--- + +#### 리스트 + +credentials 파일에 저장 한 모든 인증 된 제공 업체를 나열합니다. + +```bash +opencode auth list +``` + +또는 짧은 버전. + +```bash +opencode auth ls +``` + +--- + +### 로그아웃 + +credentials 파일에서 삭제하여 공급자에서 로그. + +```bash +opencode auth logout +``` + +--- + +# # # # github에 + +저장소 자동화를 위한 GitHub 에이전트 관리. + +```bash +opencode github [command] +``` + +--- + +### 설치 + +저장소에 GitHub 에이전트를 설치합니다. + +```bash +opencode github install +``` + +필요한 GitHub Actions 워크플로우를 설정하고 구성 프로세스를 통해 안내합니다. [더 알아보기](/docs/github). + +--- + +#### 실행 + +GitHub 에이전트를 실행합니다. 이것은 일반적으로 GitHub Actions에서 사용됩니다. + +```bash +opencode github run +``` + +##### 플래그 + +| 플래그 | 설명 | +| --------- | -------------------------------------- | +| `--event` | GitHub 모의 이벤트 | +| `--token` | GitHub 개인 액세스 토큰 | + +--- + +# # # # mcp를 + +Model Context Protocol 서버 관리 + +```bash +opencode mcp [command] +``` + +--- + +#### 추가 + +MCP 서버를 구성에 추가합니다. + +```bash +opencode mcp add +``` + +이 명령은 로컬 또는 원격 MCP 서버를 추가하여 안내합니다. + +--- + +#### 리스트 + +모든 구성 MCP 서버와 연결 상태를 나열합니다. + +```bash +opencode mcp list +``` + +또는 짧은 버전을 사용합니다. + +```bash +opencode mcp ls +``` + +--- + +# # # # # # # 오 + +OAuth-enabled MCP 서버 인증 + +```bash +opencode mcp auth [name] +``` + +서버 이름을 제공하지 않으면 OAuth-capable 서버에서 선택할 수 있습니다. + +OAuth-capable 서버와 인증 상태를 나열할 수 있습니다. + +```bash +opencode mcp auth list +``` + +또는 짧은 버전을 사용합니다. + +```bash +opencode mcp auth ls +``` + +--- + +### 로그아웃 + +MCP 서버의 OAuth 자격 제거. + +```bash +opencode mcp logout [name] +``` + +--- + +### 디버그 + +MCP 서버의 OAuth 연결 문제. + +```bash +opencode mcp debug +``` + +--- + +## 모델 + +구성 공급자에서 모든 가능한 모델을 나열합니다. + +```bash +opencode models [provider] +``` + +이 명령은 `provider/model` 형식으로 구성된 제공 업체에서 사용할 수있는 모든 모델을 표시합니다. + +이것은 [your config](/docs/config/)에서 사용하는 정확한 모델 이름을 파악하는 데 유용합니다. + +선택적으로 공급자 ID를 필터 모델로 전달할 수 있습니다. + +```bash +opencode models anthropic +``` + +#### 플래그 + +| 플래그 | 설명 | +| ----------- | ------------------------------------------------------------ | +| `--refresh` | 모델 캐시를 모델에서 새로 고침 | +| `--verbose` | 더 많은 verbose 모델 출력 사용(비용과 같은 메타데이터 포함) | + +`--refresh` 플래그를 사용하여 캐시 모델 목록을 업데이트합니다. 이것은 새로운 모델이 공급자에 추가되었을 때 유용합니다. OpenCode에서 그들을보고 싶습니다. + +```bash +opencode models --refresh +``` + +--- + +### 실행 + +직접 프롬프트를 통과하여 비동기 모드에서 opencode를 실행합니다. + +```bash +opencode run [message..] +``` + +이것은 스크립트, 자동화 또는 전체 TUI를 실행하지 않고 빠른 응답을 원할 때 유용합니다. 예를 들어. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +`opencode serve` 인스턴스를 실행하여 MCP 서버 콜드 부팅 시간을 각 실행할 수 있습니다. + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### 플래그 + +| 간선 | 간선 | Description | +| ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | 실행중인 명령, args의 메시지 사용 | +| `--continue` | `-c` | 마지막 세션 | +| `--session` | `-s` | 세션 ID| +| `--share` | 세션 공유 | +| `--model` | `-m` | `-m`의 형태로 사용 가능 | +| `--agent` | | 에이전트 | +| `--file` | `-f` | 메시지 첨부 파일| +| `--format` | 체재: 기본(formatted) 또는 json(raw JSON 이벤트) | +| `--title` | | 세션의 제목(제공되지 않은 경우 truncated prompt 사용) | +| `--attach` | | 운영 개시 서버(예: http://localhost:4096) | +| `--port` | | 현지 서버 포트| + +--- + +## 서비스 + +API 액세스를 위한 headless OpenCode 서버를 시작합니다. 완전한 HTTP 인터페이스를 위해 [server docs](/docs/server)를 체크하십시오. + +```bash +opencode serve +``` + +TUI 인터페이스없이 API 액세스를 제공하는 HTTP 서버를 시작합니다. `OPENCODE_SERVER_PASSWORD`를 설정하여 HTTP 기본 auth (`opencode`에 기본적으로 이름을 지정합니다). + +#### 플래그 + +| 플래그 | 설명 | +| ------------ | ------------------------------------------ | +| `--port` | 즐거운 항구 | +| `--hostname` | 듣고 싶은 이름 | +| `--mdns` | 엔터블 mDNS 검색 | +| `--cors` | CORS를 허용하는 추가 브라우저 기원 | + +--- + +### 세션 + +OpenCode 세션 관리. + +```bash +opencode session [command] +``` + +--- + +#### 리스트 + +모든 OpenCode 세션 목록. + +```bash +opencode session list +``` + +##### 플래그 + +| 간선 | 간선 | Description | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` | 최근 세션에 제한 | +| `--format` | 산출 체재: 테이블 또는 json (테이블) | + +--- + +### 통계 + +OpenCode 세션에 대한 토큰 사용 및 비용 통계를 표시합니다. + +```bash +opencode stats +``` + +#### 플래그 + +| 플래그 | 설명 | +| ----------- | --------------------------------------------------------------------------- | +| `--days` | 지난 N일간의 통계를 보여 주세요(모든 시간) | +| `--tools` | 쇼의 도구 수 | +| `--models` | 모델 사용 내역(기본적으로 숨겨져 있음) 상단 N을 표시할 수 있는 번호| +| `--project` | 프로젝트별 필터링(모든 프로젝트, 빈 문자열: 현재 프로젝트) | + +--- + +### 수출 + +JSON으로 세션 데이터를 내보내기. + +```bash +opencode export [sessionID] +``` + +세션 ID를 제공하지 않는 경우 사용 가능한 세션에서 선택할 수 있습니다. + +--- + +### 가져오기 + +JSON 파일 또는 OpenCode 공유 URL에서 세션 데이터를 가져옵니다. + +```bash +opencode import +``` + +로컬 파일 또는 OpenCode 공유 URL에서 가져올 수 있습니다. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +# # # # 웹 + +웹 인터페이스로 headless OpenCode 서버를 시작합니다. + +```bash +opencode web +``` + +HTTP 서버를 시작하고 웹 인터페이스를 통해 OpenCode에 액세스하는 웹 브라우저를 엽니 다. `OPENCODE_SERVER_PASSWORD`를 설정하여 HTTP 기본 auth (`opencode`에 기본적으로 이름을 지정합니다). + +#### 플래그 + +| 플래그 | 설명 | +| ------------ | ------------------------------------------ | +| `--port` | 즐거운 항구 | +| `--hostname` | 듣고 싶은 이름 | +| `--mdns` | 엔터블 mDNS 검색 | +| `--cors` | CORS를 허용하는 추가 브라우저 기원 | + +--- + +# # # # 아프 + +ACP(Agent Client Protocol) 서버를 시작합니다. + +```bash +opencode acp +``` + +이 명령은 nd-JSON을 사용하여 stdin/stdout을 통해 통신하는 ACP 서버를 시작합니다. + +#### 플래그 + +| 플래그 | 설명 | +| ------------ | --------------------- | +| `--cwd` | 작업 디렉토리 | +| `--port` | 즐거운 항구 | +| `--hostname` | 듣고 싶은 이름 | + +--- + +## 제거 + +OpenCode 제거하고 관련 파일을 제거합니다. + +```bash +opencode uninstall +``` + +#### 플래그 + +| 간선 | 간선 | Description | +| --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` | 구성 파일 유지 | +| `--keep-data` | `-d` | 세션 데이터 및 스냅샷 유지 | +| `--dry-run` | | 제거하지 않고 제거하는 것 +| `--force` | `-f`|확인 프롬프트| + +--- + +### 업그레이드 + +업데이트 opencode 최신 버전 또는 특정 버전. + +```bash +opencode upgrade [target] +``` + +최신 버전으로 업그레이드하십시오. + +```bash +opencode upgrade +``` + +특정 버전으로 업그레이드하십시오. + +```bash +opencode upgrade v0.1.48 +``` + +#### 플래그 + +| 간선 | 간선 | Description | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` | 사용중인 설치 방법; 컬, npm, pnpm, bun, brew | + +--- + +## 글로벌 플래그 + +opencode CLI는 다음의 글로벌 플래그를 사용합니다. + +| 간선 | 간선 | Description | +| -------------- | ----- | ------------------------------------ | +| `--help` | `-h` | 디스플레이 도움말 | +| `--version` | `-v` | 인쇄판 번호 | +| `--print-logs` | | 스터디로 로그인 | +| `--log-level` | 로그 레벨(DEBUG, INFO, WARN, ERROR) | + +--- + +## 환경 변수 + +OpenCode는 환경 변수를 사용하여 구성할 수 있습니다. + +| 변하기 쉬운 | 유형 | 묘사 | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | 불린 | 자동 공유 세션 | +| `OPENCODE_GIT_BASH_PATH` | string | Windows에서 실행되는 Git Bash 경로 | +| `OPENCODE_CONFIG` | string | 설정파일 경로 | +| `OPENCODE_CONFIG_DIR` | string | 구성 디렉토리 경로 | +| `OPENCODE_CONFIG_CONTENT` | 문자열 | 인라인 json 구성 내용 | +| `OPENCODE_DISABLE_AUTOUPDATE` | 불린 | 자동 업데이트 체크 아웃 | +| `OPENCODE_DISABLE_PRUNE` | boolean | 오래된 자료의 무능 | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | 불린 | 자동 단말 제목 업데이트 | +| `OPENCODE_PERMISSION` | 문자열 | 인라인 json 권한 설정 | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | 불린 | 기본 플러그인 비활성화 | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | 불린 | 자동 LSP 서버 다운로드 | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | 불린 | 실험 모델| +| `OPENCODE_DISABLE_AUTOCOMPACT` | boolean | 자동 컨텍스트 컴팩트 | +| `OPENCODE_DISABLE_CLAUDE_CODE` | boolean | `.claude`(prompt + Skill)의 읽을 수 있음 | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | 불린 | `~/.claude/CLAUDE.md`를 읽을 수 있습니다 | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | 불린 | `.claude/skills` 적재 가능 | +| `OPENCODE_DISABLE_MODELS_FETCH` | boolean | 리모트 소스에서 모델에 익숙하지 않은 모델 | +| `OPENCODE_FAKE_VCS` | string | 시험용 VCS 제공업체 | +| `OPENCODE_DISABLE_FILETIME_CHECK` | boolean | 최적화를 위한 파일 시간 검사 | +| `OPENCODE_CLIENT` | string | 클라이언트 식별자(`cli`와 동일) | +| `OPENCODE_ENABLE_EXA` | 불린 | 엑다 웹 검색 도구 | +| `OPENCODE_SERVER_PASSWORD` | string | `serve`/`web`에 대한 기본 요점 | +| `OPENCODE_SERVER_USERNAME` | string | 기본 사용자 이름(기본 `opencode`) | +| `OPENCODE_MODELS_URL` | string | 모델 구성의 맞춤 URL | + +--- + +### 실험 + +이 환경변수는 변화하거나 제거될 수 있는 실험적인 특징을 가능하게 합니다. + +| 변하기 쉬운 | 유형 | 묘사 | +| ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | 불린 | 모든 실험적인 특징 | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | boolean | 아이콘 검색 | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | 불린 | TUI의 선택 해제 +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | 번호 | ms에서 bash 명령의 기본 시간 | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | 번호 | LLM 응답을 위한 최대 출력 토큰 | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | boolean | 전체 디디터용 파일워커 | +| `OPENCODE_EXPERIMENTAL_OXFMT` | 불린 | 엔블 oxfmt 형식 | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | 불린 | 실험적인 LSP 도구 | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | boolean | 사용 가능한 파일워커 | +| `OPENCODE_EXPERIMENTAL_EXA` | boolean | 실험용 Exa 기능 | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | 불린 | 실험적인 LSP형 검사 | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | boolean | 실험용 마운팅 기능 | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | 불린 | 플랜 모드 | diff --git a/packages/web/src/content/docs/ko/commands.mdx b/packages/web/src/content/docs/ko/commands.mdx new file mode 100644 index 000000000..4da513a2a --- /dev/null +++ b/packages/web/src/content/docs/ko/commands.mdx @@ -0,0 +1,323 @@ +--- +title: Commands +description: Create custom commands for repetitive tasks. +--- + +사용자 지정 명령은 TUI에서 실행될 때 실행할 때 실행해야 합니다. + +```bash frame="none" +/my-command +``` + +사용자 정의 명령은 `/init`, `/undo`, `/redo`, `/share`, `/share`, `/help`와 같은 내장된 명령 이외에 있습니다. [더 알아보기](/docs/tui#commands). + +--- + +## 명령 파일 생성 + +사용자 지정 명령을 정의하려면 `commands/` 디렉토리의 Markdown 파일을 만듭니다. + +`.opencode/commands/test.md` 만들기: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +frontmatter 명령 속성을 정의합니다. 콘텐츠는 템플릿이 됩니다. + +명령명에 따라 `/`를 입력하여 명령을 사용하십시오. + +```bash frame="none" +"/test" +``` + +--- + +## 구성 + +OpenCode config를 통해 사용자 지정 명령을 추가하거나 `commands/` 디렉토리에 있는 Markdown 파일을 만들 수 있습니다. + +--- + +### JSON 태그 + +OpenCode [config](/docs/config)에서 `command` 옵션을 사용하십시오: + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +이제 TUI에서이 명령을 실행할 수 있습니다. + +```bash frame="none" +/test +``` + +--- + +### 마크다운 + +Markdown 파일을 사용하여 명령을 정의할 수 있습니다. 그들에 게: + +- 글로벌: `~/.config/opencode/commands/` +- 프로젝트: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +markdown 파일 이름은 명령 이름입니다. 예를 들어, `test.md` lets +당신은 실행: + +```bash frame="none" +/test +``` + +--- + +## Prompt 구성 + +사용자 정의 명령에 대한 프롬프트는 몇 가지 특별한 placeholders 및 구문을 지원합니다. + +--- + +# # # # 가격 + +`$ARGUMENTS` placeholder를 사용하여 명령을 전달합니다. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +인수로 명령을 실행: + +```bash frame="none" +/component Button +``` + +그리고 `$ARGUMENTS`는 `Button`로 대체될 것입니다. + +위치 매개 변수를 사용하여 개별 인수에 액세스 할 수 있습니다. + +- `$1` - 첫 번째 인수 +- `$2` - 두 번째 인수 +- `$3` - 세 번째 인수 +- 그래서 ... + +예를 들면: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +명령을 실행: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +이 교체: + +- `$1`TK1ZZ와 `$1` +- `$2`TK1ZZ와 `$2` +- `$3`TK1ZZ와 `$3` + +--- + +### 포탄 산출 + +사용 !`command` 는 [bash command](/docs/tui#bash-commands)를 프롬프트로 출력합니다. + +예를 들어, 테스트 범위를 분석하는 사용자 정의 명령을 만들려면: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +또는 최근 변경 사항 : + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +명령은 프로젝트의 루트 디렉토리에서 실행하고 출력은 프롬프트의 일부가됩니다. + +--- + +## 파일 참조 + +파일명에 따라 `@`를 사용하여 명령에 파일이 포함되어 있습니다. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +파일 콘텐츠는 자동으로 프롬프트에 포함되어 있습니다. + +--- + +## 옵션 + +구성 옵션을 자세히 살펴봅시다. + +--- + +### 템플릿 + +`template` 옵션은 명령이 실행될 때 LLM에 전송될 프롬프트를 정의합니다. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +** config 옵션이 필요합니다. + +--- + +### 묘사 + +`description` 옵션을 사용하여 명령의 간단한 설명을 제공합니다. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +명령에 입력할 때 TUI의 설명으로 표시됩니다. + +--- + +## 에이전트 + +`agent` config를 선택적으로 지정합니다. [agent](/docs/agents)는 이 명령을 실행해야 합니다. +이 경우 [subagent](/docs/agents/#subagents) 명령은 기본으로 시약을 트리거합니다. +이 행동을 비활성화하려면 `subtask`를 `false`로 설정하십시오. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +** 옵션** 설정 옵션입니다. 지정된 경우, 현재 에이전트에 기본값. + +--- + +# # # 서브스크랩 + +`subtask` boolean을 사용하여 명령을 강제로 [subagent](/docs/agents/#subagents) 호출합니다. +이것은 당신이 명령을 원하지 않는 경우 유용합니다 당신의 기본 컨텍스트를 pollute하고 ** 에이전트는 시약으로 행동하는, +`mode`가 [시약](/docs/시약) 구성에 `primary`로 설정되는 경우에도. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +** 옵션** 설정 옵션입니다. + +--- + +### 모형 + +`model` config를 사용하여 이 명령의 기본 모델을 무시합니다. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +** 옵션** 설정 옵션입니다. + +--- + +## 내장 + +opencode는 `/init`, `/undo`, `/redo`, `/share`, `/help`, `/help`와 같은 몇몇 붙박이 명령을 포함합니다; [learn more] (./tui#commands). + +:::note +사용자 지정 명령은 내장 명령을 무시할 수 있습니다. +::: + +같은 이름으로 사용자 정의 명령을 정의하면 내장 명령을 무시합니다. diff --git a/packages/web/src/content/docs/ko/config.mdx b/packages/web/src/content/docs/ko/config.mdx new file mode 100644 index 000000000..bede12673 --- /dev/null +++ b/packages/web/src/content/docs/ko/config.mdx @@ -0,0 +1,685 @@ +--- +title: Config +description: Using the OpenCode JSON config. +--- + +JSON config 파일을 사용하여 OpenCode를 구성할 수 있습니다. + +--- + +## 형식 + +OpenCode는 **JSON** 및 **JSONC** (JSON with Comments) 형식을 지원합니다. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## 위치 + +다른 위치의 몇 개에 구성을 배치 할 수 있으며 그들은 +precedence의 다른 순서. + +:::note +구성 파일은 ** 함께, 대체되지 않습니다. +::: + +구성 파일은 함께 결합되어 대체되지 않습니다. 다음 구성 위치에서 설정이 결합됩니다. 나중에 configs override 이전 하나만 충돌 키. 모든 구성에서 설정이 보존됩니다. + +예를 들어, 글로벌 구성 세트 `theme: "opencode"` 및 `autoupdate: true` 및 프로젝트 구성 세트 `model: "anthropic/claude-sonnet-4-5"`를 설정하면 최종 구성은 모든 세 가지 설정을 포함합니다. + +--- + +### 임신 순서 + +Config 소스는 이 순서에서 적재됩니다 (더 많은 소스는 더 이른 것 삭제합니다): + +1. ** 원격 설정** (`.well-known/opencode`에서) - 조직 기본 +2.**Global config** (`~/.config/opencode/opencode.json`) - 사용자 선호도 +3. ** 사용자 정의 설정** (`OPENCODE_CONFIG` env var) - 사용자 정의 overrides +4. ** 프로젝트 별 설정** (`opencode.json`) - 프로젝트 별 설정 +5. **`.opencode` 디렉토리 ** - 에이전트, 명령, 플러그인 +6. ** 인라인 설정** (`OPENCODE_CONFIG_CONTENT` env var) - 런타임 오버라이드 + +이것은 프로젝트 구성은 글로벌 디폴트를 override 할 수 있으며, 글로벌 구성은 원격 조직 디폴트를 override 할 수 있습니다. + +:::note +`.opencode`와 `~/.config/opencode` 감독 사용 **plural 이름** 하위 디렉토리에 대 한: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/`, 그리고 `themes/`. Singular 이름 (예를들면, `agent/`)는 또한 뒤쪽 겸용성을 위해 지원됩니다. +::: + +--- + +### 리모트 + +조직은 `.well-known/opencode` 엔드포인트를 통해 기본 구성을 제공 할 수 있습니다. 이것은 당신이 그것을 지원하는 공급자로 정통할 때 자동적으로 fetched. + +원격 설정은 기본 레이어로 제공된 첫 번째입니다. 다른 구성 소스 (글로벌, 프로젝트)는 이러한 기본값을 무시할 수 있습니다. + +예를 들어, 조직이 기본으로 비활성화 된 MCP 서버를 제공한다면: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +로컬 설정에서 특정 서버를 사용할 수 있습니다: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +## 글로벌 + +`~/.config/opencode/opencode.json`에서 글로벌 OpenCode 구성을 배치합니다. 테마, 공급자, keybinds와 같은 사용자 전체 선호도에 대한 글로벌 구성을 사용합니다. + +글로벌 구성 overrides 원격 조직 기본. + +--- + +## 프로젝트 당 + +프로젝트 루트에 `opencode.json`를 추가합니다. Project config는 표준 구성 파일 중 가장 높은 우선순위가 있습니다. 이는 글로벌 및 원격 구성 모두 overrides합니다. + +:::tip +프로젝트의 루트에 특정 설정. +::: + +OpenCode가 시작될 때, 현재 디렉토리의 설정 파일이나 가장 가까운 Git 디렉토리로 이동합니다. + +이것은 Git로 검사되고 글로벌 하나로 동일한 schema를 사용합니다. + +--- + +### 사용자 정의 경로 + +`OPENCODE_CONFIG` 환경 변수를 사용하여 사용자 정의 구성 파일 경로 지정. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +Custom config는 precedence 순서에 있는 세계적인 프로젝트 구성 사이에서 적재됩니다. + +--- + +## 사용자 정의 디렉토리 + +`OPENCODE_CONFIG_DIR`를 사용하여 사용자 정의 구성 디렉토리 지정 +환경 변수. 이 디렉토리는 에이전트, 명령을 검색합니다, +모드 및 플러그인은 표준 `.opencode` 디렉토리와 같은, 그리고 해야 +동일한 구조를 따르십시오. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +사용자 정의 디렉토리는 글로벌 구성 및 `.opencode` 디렉토리 후로드됩니다. ** 설정할 수 있습니다. + +--- + +## 여성 + +구성 파일에는 [**`opencode.ai/config.json`**](https://opencode.ai/config.json)에서 정의된 스키마가 있습니다. + +당신의 편집자는 schema에 근거를 둔 검증하고 자동 완성될 수 있어야 합니다. + +--- + +# # # # TUI # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +`tui` 옵션을 통해 TUI-specific 설정을 구성할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +유효한 선택권: + +- `scroll_acceleration.enabled` - macOS 스타일 스크롤 가속을 가능하게합니다. ** `scroll_speed`에 대한 준비. ** +- `scroll_speed` - 사용자 정의 스크롤 속도 승수 (기본: `3`, 최소: `1`). `scroll_acceleration.enabled`가 `true`인 경우에 Ignored. +- `diff_style` - 제어 디프 렌더링. `"auto"`는 맨끝 폭에, `"stacked"` 항상 단 하나 란을 보여줍니다 적응시킵니다. + +[TUI를 사용하여 더 자세히 알아보기](/docs/tui). + +--- + +## 서버 + +`opencode serve` 및 `opencode web` 명령에 대한 서버 설정을 구성할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +유효한 선택권: + +- `port` - 듣는 항구. +- `hostname` - 듣는 호스트 이름. `mdns`가 활성화되고 hostname이 설정되지 않으면 `0.0.0.0`로 기본값이 됩니다. +- `mdns` - 사용 가능한 mDNS 서비스 발견. 이 네트워크에서 다른 장치가 OpenCode 서버를 발견 할 수 있습니다. +- `mdnsDomain` - mDNS 서비스에 대한 사용자 정의 도메인 이름. 기본 `opencode.local`. 동일한 네트워크에서 여러 인스턴스를 실행하는 데 유용합니다. +- `cors` - 브라우저 기반 클라이언트에서 HTTP 서버를 사용할 때 CORS를 허용하는 추가 기원. 가치는 가득 차있는 근원이어야 합니다 (scheme + 주인 + 선택적인 항구), 예를들면 `https://app.example.com`. + +[서버에 대해 자세히 알아보기](/docs/server). + +--- + +## 도구 + +LLM은 `tools` 옵션을 통해 사용할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[이 도구에 대해 자세히 알아보기](/docs/tools). + +--- + +## 모델 + +`provider`, `model` 및 `small_model` 옵션을 통해 OpenCode config에서 사용하려는 공급자와 모델을 구성할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +`small_model` 옵션은 제목 생성과 같은 경량 작업을 위한 별도의 모델을 구성합니다. 기본적으로, OpenCode는 당신의 공급자에게서 1개가 유효하다면 더 싼 모형을 이용하는 것을 시도합니다, 그렇지 않으면 당신의 주요 모형에 돌려보냅니다. + +공급자 선택권은 `timeout`와 `setCacheKey`를 포함할 수 있습니다: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - 밀리 초 (과태: 300000)에서 타임 아웃 요청. `false`로 분리할 수 있습니다. +- `setCacheKey` - 캐시 키가 항상 지정된 공급자를 위해 설정됩니다. + +[local model](/docs/models#local)을 구성할 수 있습니다. [더 알아보기](/docs/models). + +--- + +### 공급자 특정 선택권 + +몇몇 공급자는 일반적인 `timeout` 및 `apiKey` 조정을 넘어서 추가 윤곽 선택권을 지원합니다. + +##### 아마존 베드록 + +Amazon Bedrock는 AWS 별 구성을 지원합니다: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - Bedrock를 위한 AWS 지역 (`AWS_REGION` env var 또는 `us-east-1`에 과태) +- `profile` - AWS는 `~/.aws/credentials` (`AWS_PROFILE` env var에 과태)에서 단면도 지명했습니다 +- `endpoint` - VPC 엔드 포인트에 대한 사용자 정의 엔드 포인트 URL. 이것은 AWS 별 용어를 사용하여 일반적인 `baseURL` 옵션에 대한 별명입니다. 둘 다 지정되는 경우에, `endpoint`는 전진합니다. + +:::note +Bearer 토큰 (`AWS_BEARER_TOKEN_BEDROCK` 또는 `/connect`)은 프로파일 기반 인증을 통해 우선 순위를 부여합니다. 자세한 내용은 [authentication precedence](/docs/providers#authentication-precedence)를 참조하십시오. +::: + +[Amazon-bedrock에 대해 자세히 알아보기](/docs/providers#amazon-bedrock). + +--- + +## 테마 + +`theme` 옵션을 통해 OpenCode config에서 사용하려는 테마를 구성할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[더 알아보기](/docs/themes). + +--- + +## 에이전트 + +`agent` 옵션을 통해 특정 작업을 전문 에이전트를 구성할 수 있습니다. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +`~/.config/opencode/agents/` 또는 `.opencode/agents/`에서 Markdown 파일을 사용하여 에이전트를 정의 할 수 있습니다. [더 알아보기](/docs/시약). + +--- + +### 과태 대리인 + +`default_agent` 옵션을 사용하여 기본 에이전트를 설정할 수 있습니다. 아무도 명시적으로 지정되지 않을 때 에이전트가 사용되는 결정. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +기본 대리인은 1 차적인 대리인이어야 합니다 (미약 아닙니다). 이것은 `"build"` 또는 `"plan"`, 또는 정의된 [custom 대리인] (./agents) 같이 붙박이 대리인일 수 있습니다. 지정된 에이전트가 존재하지 않는 경우, OpenCode는 경고로 `"build"`로 돌아갑니다. + +이 설정은 모든 인터페이스에서 적용됩니다: TUI, CLI (`opencode run`), 데스크탑 앱 및 GitHub Action. + +--- + +## 공유 + +`share` 옵션을 통해 [share](/docs/share) 기능을 구성할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +이 소요: + +- `"manual"` - 명령을 통해 수동 공유 허용 (기본값) +- `"auto"` - 자동 공유 새로운 대화 +- `"disabled"` - 완전하게 공유할 수 있는 + +기본적으로 `/share` 명령을 사용하여 대화를 명시적으로 공유해야 할 수동 모드로 설정됩니다. + +--- + +## 명령 + +`command` 옵션을 통해 반복 작업을 위한 사용자 지정 명령을 구성할 수 있습니다. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +`~/.config/opencode/commands/` 또는 `.opencode/commands/`에서 Markdown 파일을 사용하여 명령을 정의 할 수 있습니다. [더 이상](/docs/commands). + +--- + +## 키빈드 + +`keybinds` 옵션을 통해 keybinds를 사용자 정의 할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[더 알아보기](/docs/keybinds). + +--- + +## 자동 업데이트 + +OpenCode는 자동으로 시작될 때 새로운 업데이트를 다운로드합니다. `autoupdate` 옵션으로 이것을 비활성화 할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +업데이트를 원하지 않으면 새로운 버전이 사용할 수있을 때 알림을하고 `autoupdate`를 `"notify"`로 설정하십시오. +Homebrew와 같은 패키지 관리자를 사용하여 설치되지 않은 경우에만 작동합니다. + +--- + +## 형식 + +`formatter` 옵션을 통해 코드 형식기를 구성할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[출판자에 대해 자세히 알아보기](/docs/formatters). + +--- + +## # 권한 + +기본적으로, opencode ** 명시된 승인 없이 모든 작업**을 허용한다. `permission` 옵션을 사용하여 이것을 변경할 수 있습니다. + +예를 들어, `edit` 및 `bash` 도구가 사용자 승인을 요구합니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[이 권한에 대해 더 알아보기](/docs/permissions). + +--- + +### 압축 + +`compaction` 옵션을 통해 컨텍스트 압축 동작을 제어할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - 컨텍스트가 풀 때 자동으로 세션을 압축합니다 (기본: `true`). +- `prune` - 토큰을 저장하기 위해 오래된 도구 출력을 제거 (기본: `true`). + +--- + +### 시계 + +`watcher` 옵션을 통해 파일워커가 패턴을 무시할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +패턴은 glob 구문을 따릅니다. 이 파일을 보시려면 noisy 디렉토리를 제외하십시오. + +--- + +### MCP 서버 + +`mcp` 옵션을 통해 사용하려는 MCP 서버를 구성할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[더 이상](/docs/mcp-servers). + +--- + +### 플러그인 + +[Plugins](/docs/plugins)는 사용자 정의 도구, 후크 및 통합으로 OpenCode를 확장합니다. + +`.opencode/plugins/` 또는 `~/.config/opencode/plugins/`에서 플러그인 파일을 배치하십시오. `plugin` 옵션을 통해 npm에서 플러그인을로드 할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[더 이상](/docs/plugins). + +--- + +### 지시 + +`instructions` 옵션을 통해 사용할 모델에 대한 지침을 구성할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +이 경로와 glob 패턴의 배열을 사용하여 명령 파일. [더 알아보기 +여기 규칙에 관하여] (./rules). + +--- + +## Disabled 공급자 + +`disabled_providers` 옵션을 통해 자동으로 로드된 공급자를 비활성화할 수 있습니다. 이것은 당신이 그들의 credentials가 유효하다하더라도 적재되는에서 특정 공급자를 방지할 때 유용합니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +`disabled_providers`는 `enabled_providers`에 우선권을 가지고 있습니다. +::: + +`disabled_providers` 옵션은 공급자 ID의 배열을 허용합니다. 공급자가 비활성화되면: + +- 환경 변수가 설정된 경우에도 로드되지 않습니다. +- API 키가 `/connect` 명령을 통해 구성되는 경우에도로드되지 않습니다. +- 공급자의 모델은 모델 선택 목록에 표시되지 않습니다. + +--- + +### Enabled 공급자 + +`enabled_providers` 옵션을 통해 공급자의 수당을 지정할 수 있습니다. 설정할 때 지정된 공급자만이 활성화되고 다른 모든 사람들이 무시됩니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +OpenCode를 제한 할 때 유용합니다. 특정 공급자를 사용하지 않도록하십시오. + +:::note +`disabled_providers`는 `enabled_providers`에 우선권을 가지고 있습니다. +::: + +공급자가 `enabled_providers`와 `disabled_providers` 둘 다에서 나타나면, `disabled_providers`는 뒤에 오는 겸용성을 위한 우선권을 가지고 갑니다. + +--- + +### 실험 + +`experimental` 열쇠는 활동적인 발달의 밑에 있는 선택권을 포함합니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::caution +실험 옵션은 안정되지 않습니다. 그들은 예고없이 변경하거나 제거 할 수 있습니다. +::: + +--- + +## 변수 + +config 파일에서 참조 환경 변수 및 파일 내용에 대한 변수 대변을 사용할 수 있습니다. + +--- + +# # # # # Env 바 + +`{env:VARIABLE_NAME}`를 사용하여 환경 변수를 대체합니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +환경 변수가 설정되지 않으면 빈 문자열로 대체됩니다. + +--- + +## 파일 + +`{file:path/to/file}`를 사용하여 파일의 내용을 대체합니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +파일 경로는: + +- config 파일 디렉토리에 관계 +- 또는 `/` 또는 `~`로 시작하는 절대 경로 + +이것들은 유용하다: + +- 별도의 파일에서 API 키와 같은 민감한 데이터를 유지. +- config를 cluttering하지 않고 큰 명령어 파일을 포함합니다. +- 여러 구성 파일에서 공통 구성 스니펫 공유. diff --git a/packages/web/src/content/docs/ko/custom-tools.mdx b/packages/web/src/content/docs/ko/custom-tools.mdx new file mode 100644 index 000000000..37506c8cb --- /dev/null +++ b/packages/web/src/content/docs/ko/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: Custom Tools +description: Create tools the LLM can call in opencode. +--- + +사용자 정의 도구는 LLM이 대화 중에 호출 할 수있는 기능을 만듭니다. 그들은 `read`, `write` 및 `bash`와 같은 opencode의 [붙박이 도구] (./tools)와 함께 작동합니다. + +--- + +## 도구 만들기 + +도구는 **TypeScript** 또는 **JavaScript** 파일로 정의됩니다. 그러나 도구 정의는 ** 어떤 언어로 작성된 스크립트를 호출 할 수 있습니다 ** - TypeScript 또는 JavaScript는 도구 정의 자체에서만 사용됩니다. + +--- + +## 위치 + +그들은 정의 할 수 있습니다: + +- 프로젝트의 `.opencode/tools/` 디렉토리에 배치하여 로컬. +- 또는 전 세계적으로 `~/.config/opencode/tools/`에 배치하여. + +--- + +## 구조 + +도구를 만드는 가장 쉬운 방법은 `tool()` helper를 사용하여 유형 안전 및 검증을 제공합니다. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +**파일 이름**는 **tool name**가 됩니다. 위는 `database` 공구를 만듭니다. + +--- + +### 파일 당 다수 공구 + +단일 파일에서 여러 도구를 수출할 수 있습니다. 각 수출은 ** 별도의 도구 ** 이름 ** `_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +이것은 2개의 공구를 만듭니다: `math_add`와 `math_multiply`. + +--- + +# # # # 가격 + +`tool.schema`를 사용할 수 있습니다, 그냥 [Zod](https://zod.dev), 인수 유형을 정의합니다. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +[Zod](https://zod.dev)를 직접 가져오고 일반 객체를 반환할 수 있습니다. + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### 텍스트 + +도구는 현재 세션에 대한 컨텍스트를받습니다. + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +세션 작업 디렉토리에 `context.directory`를 사용합니다. +git worktree 루트에 `context.worktree`를 사용합니다. + +--- + +## 예제 + +### Python 도구 작성 + +원하는 모든 언어로 도구를 쓸 수 있습니다. 여기에 Python을 사용하여 두 개의 숫자를 추가하는 예입니다. + +먼저 Python 스크립트로 도구를 만듭니다. + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +그런 다음 도구 정의를 만듭니다. + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +여기에 우리는 [`Bun.$`](https://bun.com/docs/runtime/shell) 유틸리티를 사용하여 파이썬 스크립트를 실행합니다. diff --git a/packages/web/src/content/docs/ko/ecosystem.mdx b/packages/web/src/content/docs/ko/ecosystem.mdx new file mode 100644 index 000000000..fdf7a2a8b --- /dev/null +++ b/packages/web/src/content/docs/ko/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: Ecosystem +description: Projects and integrations built with OpenCode. +--- + +OpenCode에 내장 된 커뮤니티 프로젝트의 컬렉션. + +:::note +이 목록에 OpenCode 관련 프로젝트를 추가하시겠습니까? PR 제출 +::: + +[awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) 및 [opencode.cafe](https://opencode.cafe), 생태계와 커뮤니티를 통합하는 커뮤니티도 확인할 수 있습니다. + +--- + +## 플러그인 + +| 이름 | 설명 | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | git sync와 live preview를 가진 고립된 Daytona 샌드박스의 OpenCode 세션을 자동으로 실행 | +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | 자주 사용되는 Helicone session headers for request grouping | +| [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Auto-inject TypeScript/Svelte 타입의 파일 검색 도구| +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | API 크레딧 대신 ChatGPT Plus/Pro 구독 사용 | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | API 결제 대신 기존 Gemini 플랜 사용 | +| [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | API 결제 대신 Antigravity의 무료 모델 사용 | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | 얕은 clones와 자동 할당된 포트가 있는 Multi-branch devcontainer 고립 | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Antigravity OAuth Plugin, 구글 검색 지원, 더 강력한 API 처리 | +| [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | 펀딩이 없는 툴 출력으로 토큰 사용 최적화 | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git)|한국어 지원 제공 업체에 대한 기본 웹 연구 지원 추가 Google 접지 스타일 | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | PTY에서 배경 프로세스를 실행하기 위한 AI Agent를 사용해서 대화형 입력을 보냅니다. · +| [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | 비동기 포탄 명령에 대한 지침 - TTY 의존 작업에서 걸림 방지 | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Wakatime의 OpenCode 사용 추적 | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | LLMs에서 생산한 Markdown 테이블 정리 | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | 10x 빠른 코드 편집 및 Morph Fast Apply API 및 게으른 편집 마커 | +| [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | 배경 에이전트, 사전 제작된 LSP/AST/MCP 도구, 큐레이터 에이전트, 클로드 코드 호환 | +| [opencode-notificator](https://github.com/panta82/opencode-notificator) | OpenCode 세션을 위한 데스크탑 알림 및 사운드 알림 | +| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | 허가, 완료 및 오류 이벤트용 데스크탑 알림 및 사운드 알림 | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | 오픈코드 컨텍스트를 기반으로 하는 AI-powered automatic Zellij session naming | +| [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | 기술검출 및 주사를 요구하는 OpenCode Agent를 게으른 로드 프롬프트 허용 | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Supermemory를 사용하여 세션 전반에 걸쳐 지속되는 메모리 | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | (영어) 상호 작용하는 계획은 시각적인 주석 및 개인/오프라인 공유를 검토합니다 | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | granular flow control과 강력한 오케스트라 시스템 확장 +| [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | cron 구문을 가진 발사된 (Mac) 또는 체계화된 (Linux)를 사용하여 작업 재발견 | +| [micode](https://github.com/vtemian/micode) | Structured Brainstorm → Plan → 세션 연속성으로 워크플로우 구현 | +| [octto](https://github.com/vtemian/octto) | 멀티 퀘스트 양식으로 AI Brainstorming을 위한 인터랙티브 브라우저 UI | +| [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agent) | 동기화 위임 및 컨텍스트의 코드 스타일 배경 에이전트 | +| [opencode-notify](https://github.com/kdcokenny/opencode-notify) | OpenCode의 Native OS 알림 – 작업이 완료되면 알 수 있습니다 | +| [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | 멀티 시약 오케스트라 묶음 하네스 – 16개 부품, 하나 설치 | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | 오픈코드를 위한 Zero-friction git worktree | + +--- + +## 프로젝트 + +| 이름 | 설명 | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | SDK 내장 OpenCode 세션을 제어하는 Discord bot | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | API에 내장된 편집기웨어 프롬프롬프 플러그인 | +| [portal](https://github.com/hosenur/portal) | Tailscale/VPN에 OpenCode를 위한 모바일 최초의 웹 UI | +| [opencode 플러그인 템플릿](https://github.com/zenobi-us/opencode-plugin-template/) | OpenCode 플러그인 구축 템플릿 | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | 오픈코드를 위한 Neovim frontend - 터미널 기반 AI 코딩 에이전트 | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | @opencode-ai/sdk를 통해 OpenCode를 사용하는 Vercel AI SDK 제공 | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | 웹 / 데스크탑 앱 및 VS Code Extension for OpenCode | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Obsidian 플러그인 Obsidian의 UI에서 OpenCode를 포함 +| 【영업】(https://github.com/different-ai/openwork) | OpenCode에 의해 구동 Claude Cowork에 대한 오픈 소스 대안 | +| [ocx](https://github.com/kdcokenny/ocx) | 휴대용, 절연 프로파일을 갖춘 OpenCode 확장 관리자. | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | OpenCode를 위한 데스크탑, 웹, 모바일 및 원격 클라이언트 앱 | + +--- + +# # 에이전트 + +| 이름 | 설명 | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [Agentic](https://github.com/Cluster444/agentic) | 구조 개발용 모듈형 AI 에이전트 및 명령 | +| [opencode-agents](https://github.com/darrenhinde/opencode-agents) | 향상된 워크플로우를 위한 컨피그, 프롬프트, 에이전트 및 플러그인 | diff --git a/packages/web/src/content/docs/ko/enterprise.mdx b/packages/web/src/content/docs/ko/enterprise.mdx new file mode 100644 index 000000000..66f646bc2 --- /dev/null +++ b/packages/web/src/content/docs/ko/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: Enterprise +description: Using OpenCode securely in your organization. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise는 코드와 데이터가 인프라를 결코 나타낸다는 것을 보증하는 단체입니다. SSO 및 내부 AI 게이트웨이와 통합하는 중앙화 된 구성을 사용하여 이것을 할 수 있습니다. + +:::note +OpenCode는 코드 또는 컨텍스트 데이터를 저장하지 않습니다. +::: + +OpenCode Enterprise로 시작하려면: + +1. 시험은 당신의 팀과 내부적으로 합니다. +2. ** 연락처** 가격 및 구현 옵션을 논의합니다. + +--- + +## 시험 + +OpenCode는 오픈 소스이며 코드를 저장하지 않거나 컨텍스트 데이터, 그래서 개발자는 단순히 [get start](/docs/) 그리고 재판을 수행 할 수 있습니다. + +--- + +## 데이터 처리 + +**OpenCode는 코드 또는 컨텍스트 데이터를 저장하지 않습니다. ** 모든 처리는 로컬 또는 직접 API 호출을 통해 AI 공급자. + +이것은 당신이 신뢰하는 공급자, 또는 내부를 사용하고 있는 경우에 +AI 게이트웨이, OpenCode를 안전하게 사용할 수 있습니다. + +여기에서 유일한 caveat는 선택적인 `/share` 특징입니다. + +--- + +### 공유 대화 + +사용자가 `/share` 기능을 활성화하면 대화와 관련된 데이터가 opencode.ai에서 이러한 공유 페이지를 호스팅하는 데 사용됩니다. + +데이터는 현재 CDN의 가장자리 네트워크를 통해 제공되며 사용자가 가까운 가장자리에 캐시됩니다. + +우리는 당신이 당신의 재판을 위해 이것을 비활성화하는 것을 추천합니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[공유에 대해 더 알아보기](/docs/share). + +--- + +### 코드 소유권 + +**OpenCode에 의해 생성 된 모든 코드를 소유합니다. ** 제한 또는 소유권 주장이 없습니다. + +--- + +## 가격 + +OpenCode Enterprise의 per-seat 모델을 사용합니다. LLM 게이트웨이를 가지고 있다면 토큰을 사용할 수 없습니다. 가격 및 구현 옵션에 대한 자세한 내용은 **contact us**. + +--- + +## 배포 + +시험이 완료되면 OpenCode를 사용해야합니다. +조직, 당신은 할 수 있습니다 **contact us** 토론하기 +가격 및 구현 옵션. + +--- + +### 중앙 Config + +OpenCode를 설정하여 전체 조직의 단일 중앙 구성을 사용할 수 있습니다. + +이 중앙 집중식 구성은 SSO 공급자와 통합할 수 있으며 내부 AI 게이트웨이 만 모든 사용자 액세스를 보장합니다. + +--- + +### SSO 통합 + +중앙 구성을 통해 OpenCode는 인증 기관의 SSO 공급자와 통합 할 수 있습니다. + +OpenCode는 기존 ID 관리 시스템을 통해 내부 AI 게이트웨이에 대한 자격 증명을 얻을 수 있습니다. + +--- + +## 내부 AI 게이트웨이 + +중앙 설정으로, OpenCode는 내부 AI 게이트웨이만 사용할 수 있습니다. + +또한 다른 모든 AI 제공 업체를 비활성화 할 수 있습니다, 모든 요청은 조직의 승인 된 인프라를 통해 이동합니다. + +--- + +## 셀프 호스팅 + +공유 페이지를 비활성화하는 것이 좋습니다. +당신의 조직, 우리는 또한 당신의 인프라에 자기 호스팅을 도울 수 있습니다. + +이것은 현재 우리의 로드맵에 있습니다. 관심이 있다면, ****를 알려줍니다. + +--- + +## 자주 묻는 질문 + +

+What is OpenCode Enterprise? + +OpenCode Enterprise는 코드와 데이터가 인프라를 결코 나타낸다는 것을 보증하는 단체입니다. SSO 및 내부 AI 게이트웨이와 통합하는 중앙화 된 구성을 사용하여 이것을 할 수 있습니다. + +
+ +
+How do I get started with OpenCode Enterprise? + +단순히 팀과 내부 평가판을 시작합니다. 기본값으로 OpenCode는 코드를 저장하지 않거나 context data, 시작하기 쉬운 만들기. + +그런 다음 **contact us**는 가격과 구현 옵션을 논의합니다. + +
+ +
+How does enterprise pricing work? + +우리는 per-seat 기업 가격을 제안합니다. LLM 게이트웨이를 가지고 있다면 토큰을 사용할 수 없습니다. 더 자세한 내용은 **contact us** 를 통해 조직의 요구에 따라 맞춤형 견적을 제공합니다. + +
+ +
+Is my data secure with OpenCode Enterprise? + +예. OpenCode는 코드 또는 컨텍스트 데이터를 저장하지 않습니다. 모든 처리는 로컬 또는 직접 API 호출을 통해 AI 공급자. 중앙 설정 및 SSO 통합으로 데이터는 조직의 인프라 내에서 안전하게 유지됩니다. + +
+ +
+Can we use our own private NPM registry? + +OpenCode는 Bun's native `.npmrc` 파일 지원을 통해 개인 npm 등록을 지원합니다. 조직이 JFrog Artifactory, Nexus 또는 이와 같은 개인 레지스트리를 사용한다면, 개발자가 OpenCode를 실행하기 전에 인증됩니다. + +개인 레지스트리로 인증을 설정하려면: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +`~/.npmrc`를 인증 세부 사항으로 만듭니다. OpenCode는 자동으로 +지금 구매하세요. + +:::caution +OpenCode를 실행하기 전에 개인 레지스트리에 로그인해야합니다. +::: + +또는 `.npmrc` 파일을 수동으로 구성할 수 있습니다. + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +개발자는 OpenCode를 실행하기 전에 개인 레지스트리에 로그인해야하며 패키지를 설치할 수 있습니다. + +
diff --git a/packages/web/src/content/docs/ko/formatters.mdx b/packages/web/src/content/docs/ko/formatters.mdx new file mode 100644 index 000000000..4f2106d95 --- /dev/null +++ b/packages/web/src/content/docs/ko/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: Formatters +description: OpenCode uses language specific formatters. +--- + +OpenCode는 언어 별 형식을 사용하여 작성 또는 편집 한 후 자동으로 파일을 포맷합니다. 이 생성 된 코드는 프로젝트의 코드 스타일을 따릅니다. + +--- + +## 내장 + +OpenCode는 인기있는 언어 및 프레임 워크에 대한 몇 가지 내장 형식자와 함께 제공됩니다. 아래는 formatters, 지원된 파일 확장 및 명령 또는 구성 옵션의 목록입니다. + +| 형식 | 연장 | 요구 사항 | +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| gofmt | .go | `gofmt` 명령 가능 | +| 믹스 | .ex, .ex, .eex, .heex, .leex, .neex, .sface | `mix` 명령 가능 | +인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 +| 바이오메 | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, [기타](https://biomejs.dev/) | `biome.json(c)` 구성 파일 | +| 지그 | .zig, .zon | `zig` 명령 가능 | +| clang-format | .c, .cpp, .h, .hpp, .ino, [기타](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` 구성 파일 | +| ktlint | .kt, .kts | `ktlint` 명령 가능 | +| ruff | .py, .pyi | 구성 가능한 `ruff` 명령 | +| rustfmt | .rs | `rustfmt` 명령 가능 | +| 화물fmt | .rs | `cargo fmt` 명령 가능 | +| uv | .py, .pyi | `uv` 명령 가능 | +| rubocop | .rb, .rake, .gemspec, .ru | `rubocop` 명령 사용 가능 | +| 표준 | .rb, .rake, .gemspec, .ru | `standardrb` 명령 사용 가능 | +| htmlbeautifier | .erb, .html.erb | `htmlbeautifier` 명령 가능 | +| 공기 | .R | `air` 명령 가능 | +| 다트 | 다트 | `dart` 명령 | +| ocamlformat | .ml, .mli | `ocamlformat` 명령 가능·`.ocamlformat` 설정 파일 | +| 지형 | .tf, .tfvars | `terraform` 명령 가능 | +| gleam | .gleam | `gleam` 명령 가능 | +| nixfmt | .nix | `nixfmt` 명령 가능 | +| shfmt | .sh, .bash | `shfmt` 명령 가능 | +| 핀 | .php | `laravel/pint` 의존도 `composer.json` | +| oxfmt (Experimental) | .js, .jsx, .ts, .tsx | `oxfmt` Dependency in `package.json`, [experimental env 변수 플래그](/docs/cli/#experimental) | +| ormolu | .hs | `ormolu` 명령 가능 | + +그래서 프로젝트가 `prettier`를 `package.json`에 가지고 있다면, OpenCode는 자동으로 그것을 사용합니다. + +--- + +## 어떻게 작동합니까? + +OpenCode가 파일을 작성하거나 편집할 때: + +1. 모든 활성화된 formatters에 대한 파일 확장을 확인합니다. +2. 파일에 적절한 형식의 명령을 실행합니다. +3. 형식 변경을 자동으로 적용합니다. + +이 과정은 배경에서 발생합니다. 코드 스타일은 수동 단계없이 유지됩니다. + +--- + +## 구성 + +OpenCode config의 `formatter` 섹션을 통해 형식기를 사용자 정의 할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +각 formatter 윤곽은 다음을 지원합니다: + +| 재산 | 유형 | 묘사 | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` | 불린 | 이 세트를 `true`로 포맷터 비활성화 | +| `command` | 문자열[] | 형식을 실행하는 명령 | +| `environment` | 객체 | 형식의 실행시 설정하는 환경 변수 | +| `extensions` | string[] | 이 형식의 파일 확장자 취급 | + +몇 가지 예제를 살펴 보자. + +--- + +## Disabling 형식자 + +`false`에 `formatter`를 세계로 바꾸기 위하여 **all** formatters: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +** 특정** 형식, `disabled`를 `true`로 설정: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### 사용자 정의 형식 + +내장 형식자를 무시하거나 명령, 환경 변수 및 파일 확장을 지정하여 새로운 것을 추가 할 수 있습니다. + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +명령의 **`$FILE` placeholder**는 형식의 파일 경로로 대체됩니다. diff --git a/packages/web/src/content/docs/ko/github.mdx b/packages/web/src/content/docs/ko/github.mdx new file mode 100644 index 000000000..d95d03ee5 --- /dev/null +++ b/packages/web/src/content/docs/ko/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: Use OpenCode in GitHub issues and pull-requests. +--- + +OpenCode는 GitHub 워크플로우와 통합됩니다. Mention `/opencode` 또는 `/oc` 당신의 의견에, 그리고 OpenCode는 당신의 GitHub 활동 주자 안에 작업을 실행할 것입니다. + +--- + +## 특징 + +- **문제**: OpenCode가 문제점을 보고 당신을 설명합니다. +- **Fix 및 구현 **: 이슈를 수정하거나 기능을 구현하려면 OpenCode에 문의하십시오. 그리고 새로운 지점에서 일하고 모든 변경으로 PR을 제출합니다. +-**Secure**: OpenCode는 GitHub의 런너 내부에서 실행됩니다. + +--- + +## 설치 + +GitHub 저장소에서 다음과 같은 명령을 실행: + +```bash +opencode github install +``` + +GitHub 앱을 설치하고 워크플로를 만들고 비밀을 설정할 수 있습니다. + +--- + +## 수동 설정 + +또는 수동으로 설정할 수 있습니다. + +1. ** GitHub 앱 설치 ** + +[**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent)에 머리가 붙습니다. 대상 저장소에 설치되어 있는지 확인하십시오. + +2. ** 워크플로우 추가 ** + +저장소에 `.github/workflows/opencode.yml`에 다음 작업 흐름 파일을 추가합니다. 적절한 `model`를 설정하고 `env`의 API 키가 필요합니다. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. ** 비밀의 API 키 저장 ** + +조직 또는 프로젝트 ** 설정**, 확장 ** 축소 및 변수 ** 왼쪽 및 선택 **Actions**. 그리고 필요한 API 키를 추가합니다. + +--- + +## 구성 + +- `model`: OpenCode를 사용하는 모형. `provider/model`의 형식을 가져 가라. **필수**입니다. +- `agent`: 사용을 위한 대리인. 1 차적인 대리인이어야 합니다. `default_agent`로 돌아와서 config 또는 `"build"`에서 찾을 수 없습니다. +- `share`: OpenCode 세션을 공유하는 것. Defaults to **true** for public 저장소. +- `prompt` : 기본 동작을 무시하기 위해 옵션 사용자 정의 프롬프트. OpenCode 프로세스 요청을 사용자 정의하기 위해 이것을 사용합니다. +- `token`: 코멘트를 생성, 커밋 변경 및 오프닝 풀 요청과 같은 작업을 수행하기위한 옵션 GitHub 액세스 토큰. 기본적으로 OpenCode는 OpenCode GitHub App에서 설치 액세스 토큰을 사용하므로 커밋, 코멘트 및 풀 요청은 앱에서 오는 것과 같이 나타납니다. + +대안으로, GitHub Action runner의 [붙박이 `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github token)을 사용하여 OpenCode GitHub 앱을 설치하지 않고 사용할 수 있습니다. 워크플로우에서 필요한 권한을 부여하는 것을 확인하십시오. + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + +또한 [개인 액세스 토큰](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT)를 사용할 수 있습니다. + +--- + +## 지원된 사건 + +OpenCode는 다음 GitHub 이벤트에 의해 트리거 될 수 있습니다: + +| 이벤트 타입 | Triggered by | 상세 | +| ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | 발행 또는 PR에 대한 의견 | 멘션 `/opencode` 또는 `/oc` 당신의 의견. OpenCode는 컨텍스트를 읽고, 지점을 만들 수 있습니다, 열린 PR, 또는 대답. · +| `pull_request_review_comment` | PR의 특정 코드 라인에 대한 의견 | Mention `/opencode` 또는 `/oc` 코드 검토 중. OpenCode는 파일 경로, 줄 번호 및 diff 컨텍스트를 수신합니다. · +| `issues` | 이슈가 열리고 편집되었습니다 | 이슈가 생성되거나 수정될 때 자동으로 OpenCode를 트리거합니다. `prompt` 입력이 필요합니다. | +| `pull_request` | PR 오픈 또는 업데이트 | PR이 열릴 때 자동 트리거 OpenCode 자동 리뷰에 대한 유용한 정보 | +| `schedule` | 크론 기반 일정 | 일정에 오픈코드를 실행합니다. `prompt` 입력을 요구합니다. 출력 로그 및 PR에 간다 (댓글이 없습니다). | +| `workflow_dispatch` | GitHub UI에서 수동 트리거 | 액션 탭을 통해 까다로운 Trigger OpenCode. `prompt` 입력을 요구합니다. 출력 로그 및 PR에 간다. | + +### 일정 예 + +자동화된 작업을 수행하는 일정에 OpenCode를 실행: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +예정된 이벤트의 경우, `prompt` 입력은 **필요 ** 이후의 지시를 추출할 수 없습니다. 사용자 컨텍스트 없이 실행되는 워크플로우는 권한 확인을 위해, 워크플로우는 `contents: write`와 `pull-requests: write`를 부여해야 하며, OpenCode가 지점이나 PR을 만들게 됩니다. + +--- + +## Pull 요청 예제 + +자동 검토 PR 때 그들은 열려있거나 업데이트 : + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +`pull_request` 이벤트의 경우 `prompt`가 제공되지 않은 경우, 풀 요청을 검토하는 OpenCode 기본값. + +--- + +### 문제 부족 예제 + +자동으로 새로운 문제를 삼는다. 이 예제는 스팸을 줄이기 위해 30 일 이상 계정 필터 : + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +`issues` 사건을 위해, `prompt` 입력은 ** 필요 ** 거기에서 지시를 추출하는 코멘트가 없습니다. + +--- + +## 사용자 정의 프롬프트 + +OpenCode의 작업 흐름을 사용자 정의하는 기본 프롬프트를 부여합니다. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +이것은 특정한 검토 기준, 기호화 기준, 또는 당신의 프로젝트에 관련된 초점 지역을 enforcing를 위해 유용합니다. + +--- + +## 예제 + +GitHub에서 OpenCode를 사용할 수있는 몇 가지 예입니다. + +- **문제 설명** + +GitHub 문제에서 이 의견 추가. + + ``` + /opencode explain this issue + ``` + +OpenCode는 모든 코멘트를 포함하여 전체 스레드를 읽고, 명확한 설명과 대답. + +- **문제** + +GitHub 문제에서: + + ``` + /opencode fix this + ``` + +OpenCode는 새로운 지점을 만들 것이며 변경 사항을 실행하고 PR을 변경합니다. + +-**Review PR 및 변경 사항** + +GitHub PR에 다음 댓글을 남겨주세요. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + +OpenCode는 요청한 변경을 구현하고 동일한 PR에 커밋합니다. + +- ** 특정 코드 라인** + +PR의 "Files" 탭의 코드 라인에 직접 댓글을 남겨주세요. OpenCode는 파일, 줄 번호 및 diff 컨텍스트를 자동으로 감지하여 정확한 응답을 제공합니다. + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + +특정 라인에 대한 의견이 있을 때, OpenCode는 다음과 같습니다. +- 검토되는 정확한 파일 +- 코드의 특정 라인 +- 주변 diff 컨텍스트 +- 라인 번호 정보 + +파일 경로 또는 라인 번호를 수동으로 지정하지 않고 더 많은 대상 요청을 허용합니다. diff --git a/packages/web/src/content/docs/ko/gitlab.mdx b/packages/web/src/content/docs/ko/gitlab.mdx new file mode 100644 index 000000000..b536586a8 --- /dev/null +++ b/packages/web/src/content/docs/ko/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: Use OpenCode in GitLab issues and merge requests. +--- + +OpenCode는 GitLab CI/CD 파이프라인 또는 GitLab Duo를 통해 GitLab 워크플로우와 통합됩니다. + +두 경우, OpenCode는 GitLab runners에서 실행됩니다. + +--- + +#GitLab CI 소개 + +OpenCode는 일반 GitLab 파이프라인에서 작동합니다. [CI 구성품](https://docs.gitlab.com/ee/ci/components/)로 파이프라인에 구축할 수 있습니다. + +여기에서 우리는 OpenCode에 대한 커뮤니티 생성 CI / CD 구성품을 사용하고 있습니다. [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### 특징 + +- **일당 사용자 지정 구성 사용**: 사용자 정의 구성 디렉토리와 OpenCode 구성, 예를 들어 `./config/#custom-directory`는 OpenCode invocation 당 활성화하거나 비활성화 할 수 있습니다. +- ** 최소 설정**: CI 구성 요소는 OpenCode를 배경으로 설정하면 OpenCode 구성과 초기 프롬프트를 만들 필요가 있습니다. +- **Flexible**: CI 구성 요소는 여러 입력을 지원합니다. + +--- + +## 설정 + +1. OpenCode 인증 JSON을 **Settings** > **CI/CD** > **Variables**에서 파일 유형 CI 환경 변수로 저장하십시오. "Masked and hidden"로 표시하십시오. +2. `.gitlab-ci.yml` 파일에 뒤에 추가하십시오. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +더 많은 입력 및 사용 사례 [docs를 체크 아웃] (https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) 이 구성 요소에 대한. + +--- + +## GitLab 듀오 + +OpenCode는 GitLab 워크플로우와 통합됩니다. +코멘트에 Mention `@opencode`, OpenCode는 GitLab CI 파이프라인 내에서 작업을 실행합니다. + +--- + +### 특징 + +- **문제**: OpenCode가 문제점을 보고 당신을 설명합니다. +- **Fix 및 구현 **: 이슈를 수정하거나 기능을 구현하려면 OpenCode에 문의하십시오. +새로운 지점을 만들고 변화를 병합 요청을 제기합니다. +- **Secure**: OpenCode는 GitLab runners에서 실행됩니다. + +--- + +## 설정 + +OpenCode는 GitLab CI/CD 파이프라인에서 실행되며, 여기서 설정해야 할 일은 다음과 같습니다. + +:::tip +[**GitLab docs**](https://docs.gitlab.com/user/duo agent platform/agent assistant/) 를 체크 아웃하십시오. +::: + +1. GitLab 환경 설정 +2. CI/CD 설치 +3. AI 모형 공급자 API 열쇠를 얻으십시오 +4. 서비스 계정 만들기 +5. CI/CD 변수 구성 +6. Flow config 파일을 만들려면 다음과 같습니다. + +
+ + Flow configuration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +자세한 지침에 대한 [GitLab CLI Agent docs](https://docs.gitlab.com/user/duo agent platform/agent assistant/)를 참조할 수 있습니다. + +--- + +### 예제 + +다음은 GitLab에서 OpenCode를 사용할 수있는 몇 가지 예입니다. + +:::tip +`@opencode`보다 다른 트리거 구문을 사용할 수 있습니다. +::: + +- **문제 설명** + +GitLab 문제에서이 코멘트를 추가하십시오. + + ``` + @opencode explain this issue + ``` + +OpenCode는 문제와 대답을 명확하게 설명합니다. + +- **문제** + +GitLab 문제에서, 말한다: + + ``` + @opencode fix this + ``` + +OpenCode는 새로운 지점을 만들 것이며 변경 사항을 구현하고 변경 사항을 병합 요청을 엽니다. + +- **Review 병합 요청** + +GitLab 병합 요청에 대한 다음 의견을 남겨주세요. + + ``` + @opencode review this merge request + ``` + +OpenCode는 병합 요청을 검토하고 피드백을 제공합니다. diff --git a/packages/web/src/content/docs/ko/ide.mdx b/packages/web/src/content/docs/ko/ide.mdx new file mode 100644 index 000000000..5e9c807e3 --- /dev/null +++ b/packages/web/src/content/docs/ko/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: The OpenCode extension for VS Code, Cursor, and other IDEs +--- + +OpenCode는 VS Code, Cursor, 또는 터미널을 지원하는 IDE와 통합합니다. 시작하려면 터미널에서 `opencode`를 실행하십시오. + +--- + +## 사용법 + +-**Quick Launch**: `Cmd+Esc` (Mac) 또는 `Ctrl+Esc` (Windows/Linux)를 사용하여 균열 단자 전망에 OpenCode를 열거나 기존 터미널 세션을 이미 실행하면 됩니다. +-**New Session**: `Cmd+Shift+Esc` (Mac) 또는 `Ctrl+Shift+Esc` (Windows/Linux)를 사용하여 새로운 OpenCode 터미널 세션을 시작하려면 이미 열리면 됩니다. UI에서 OpenCode 버튼을 클릭합니다. +-**Context Awareness**: OpenCode로 현재 선택 또는 탭을 자동으로 공유합니다. +- ** 파일 참조 단축키 ** : 파일 참조를 삽입하려면 `Cmd+Option+K` (Mac) 또는 `Alt+Ctrl+K` (Linux / Windows)를 사용하십시오. 예를 들어, `@File#L37-42`. + +--- + +## 설치 + +VS Code에 OpenCode를 설치하고 Cursor, Windsurf, VSCodium과 같은 인기있는 포크 : + +1. VS 코드 열기 +2. 통합 맨끝을 여십시오 +3. 실행 `opencode` - 확장 자동으로 설치 + +당신이 TUI에서 `/editor` 또는 `/export`를 실행할 때 다른 한편에, 당신은 `export EDITOR="code --wait"`를 설정할 필요가 있을 것입니다. [Learn more](/docs/tui/#editor-setup). + +--- + +## 수동 설치 + +확장 마켓 플레이스에서 **OpenCode**를 검색하고 **Install**를 클릭합니다. + +--- + +### 문제 해결 + +확장이 자동으로 설치되지 않는 경우: + +- 통합 터미널에서 `opencode`를 실행하는 것을 보장합니다. +- IDE용 CLI가 설치됩니다. +- VS 코드 : `code` 명령 +- 커서: `cursor` 명령 +- 윈드 서핑을 위해: `windsurf` 명령 +- VSCodium의 경우: `codium` 명령 +- 만약 `Cmd+Shift+P` (Mac) 또는 `Ctrl+Shift+P` (Windows/Linux)를 실행하고 "Shell Command: PATH"에서 'code' 명령을 설치하십시오 (또는 IDE에 해당) +- Ensure VS Code는 확장을 설치하는 권한이 있습니다. diff --git a/packages/web/src/content/docs/ko/index.mdx b/packages/web/src/content/docs/ko/index.mdx new file mode 100644 index 000000000..10e68f6b9 --- /dev/null +++ b/packages/web/src/content/docs/ko/index.mdx @@ -0,0 +1,359 @@ +--- +title: Intro +description: Get started with OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/)는 오픈 소스 AI 코딩 에이전트입니다. 터미널 기반 인터페이스, 데스크탑 앱 또는 IDE 확장으로 사용할 수 있습니다. + +![OpenCode TUI with the opencode theme](../../../assets/lander/screenshot.png) + +시작합시다. + +--- + +### # 필수품 + +당신의 맨끝에 있는 OpenCode를 사용하려면, 당신은 필요로 할 것입니다: + +1. 현대 맨끝 에뮬레이터는 좋아합니다: + +- [WezTerm](https://wezterm.org), 크로스 플랫폼 +- [Alacritty](https://alacritty.org), 크로스 플랫폼 +- [Ghostty] (https://ghostty.org), 리눅스 및 macOS +- [Kitty](https://sw.kovidgoyal.net/kitty/), 리눅스 및 macOS + +2. 사용하려는 LLM 공급자를 위한 API 열쇠. + +--- + +## 설치 + +OpenCode를 설치하는 가장 쉬운 방법은 설치 스크립트를 통해 입니다. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +다음 명령으로 설치할 수도 있습니다: + +- ** Node.js** 사용 + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- ** macOS 및 Linux에서 홈 Brew 사용 ** + + ```bash + brew install anomalyco/tap/opencode + ``` + +> 최신 릴리스를 위해 OpenCode 탭을 사용하는 것이 좋습니다. 공식 `brew install opencode` 공식은 Homebrew 팀에 의해 유지되고 더 자주 업데이트됩니다. + +- **Ar Linux에서 Paru를 사용 ** + + ```bash + paru -S opencode-bin + ``` + +#### 윈도우 + +:::tip[추천: WSL 사용] +Windows에서 최고의 경험을 위해 [Windows Subsystem for Linux (WSL)](/docs/windows-wsl)를 사용하는 것이 좋습니다. OpenCode의 기능으로 더 나은 성능과 전체 호환성을 제공합니다. +::: + +- ** 초콜릿 ** + + ```bash + choco install opencode + ``` + +- ** Scoop를 사용 ** + + ```bash + scoop install opencode + ``` + +- ** NPM ** + + ```bash + npm install -g opencode-ai + ``` + +- **매거진** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- ** Docker 사용** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +Bun을 사용하여 Windows에서 OpenCode 설치 지원은 현재 진행 중입니다. + +[Releases](https://github.com/anomalyco/opencode/releases)에서 이진을 할 수도 있습니다. + +--- + +## 구성 + +OpenCode를 사용하면 API 키를 구성하여 LLM 공급자를 사용할 수 있습니다. + +LLM 공급자를 사용하는 새로운 경우, [OpenCode Zen](/docs/zen)를 사용하는 것이 좋습니다. +OpenCode에 의해 테스트 및 확인 된 모델의 큐레이터 목록입니다. +팀. + +1. TUI에서 `/connect` 명령을 실행하고, opencode를 선택하고, [opencode.ai/auth](https://opencode.ai/auth)에 머리를 선택합니다. + + ```txt + /connect + ``` + +2. 로그인, 청구 세부 정보를 추가하고 API 키를 복사하십시오. + +3. API 키를 붙여. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +또는 다른 공급자 중 하나를 선택할 수 있습니다. [더 알아보기](/docs/providers#directory). + +--- + +## 초기화 + +이제 공급자를 구성했습니다. 프로젝트로 이동할 수 있습니다. +일하고 싶습니다. + +```bash +cd /path/to/project +``` + +OpenCode를 실행합니다. + +```bash +opencode +``` + +다음, 다음 명령을 실행하여 프로젝트의 OpenCode를 초기화합니다. + +```bash frame="none" +/init +``` + +OpenCode를 사용하여 프로젝트를 분석하고 `AGENTS.md` 파일을 만들 수 있습니다. +프로젝트 루트. + +:::tip +프로젝트의 `AGENTS.md` 파일을 Git에 투입해야 합니다. +::: + +이 도움말 OpenCode는 프로젝트 구조와 코딩 패턴을 이해 +사용. + +--- + +## 사용법 + +OpenCode를 사용하여 프로젝트에 작업할 준비가 되어 있습니다. 자주 묻는 질문 +모두! + +AI 코딩 에이전트를 사용하는 새로운 경우, 여기에 할 수있는 몇 가지 예입니다 +도움. + +--- + +## 질문 + +Codebase를 설명하기 위해 OpenCode를 요청할 수 있습니다. + +:::tip +`@` 키를 사용하여 프로젝트에서 파일을 검색합니다. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +이것은 당신이 작동하지 않은 코드베이스의 일부가 있다면 도움이된다. + +--- + +### 추가 기능 + +프로젝트에 새로운 기능을 추가하려면 OpenCode를 요청할 수 있습니다. 우리는 먼저 계획을 만들 것을 묻는 것이 좋습니다. + +1. **플랜을 선택 ** + +OpenCode는 Plan mode 로 변경할 수 있는 능력을 비활성화하고 +대신 제안 how 그것은 기능을 구현할 것입니다. + +**Tab** 키를 사용하여 전환합니다. 오른쪽 하단에 있는 이 지표를 볼 수 있습니다. + +```bash frame="none" title="Switch to Plan mode" + +``` + +이제 우리가해야 할 일을 설명합니다. + +```txt frame="none" +When a user deletes a note, we'd like to flag it as deleted in the database. +Then create a screen that shows all the recently deleted notes. +From this screen, the user can undelete a note or permanently delete it. +``` + +당신이 원하는 것을 이해하기 위해 OpenCode를 충분히 세부 정보를 제공하려는. 그것은 도움 +팀의 주니어 개발자에게 이야기하고 싶습니다. + +:::tip +OpenCode를 많은 컨텍스트와 예제를 제공하여 당신이 무엇을 이해하는 데 도움이 +이름 \* +::: + +2. **플랜에 대해서 ** + +플랜을 제공하면 피드백을 제공하거나 자세한 내용을 추가 할 수 있습니다. + +```txt frame="none" +We'd like to design this new screen using a design I've used before. +[Image #1] Take a look at this image and use it as a reference. +``` + +:::tip +단말에 이미지를 드래그하고 드롭하여 프롬프트에 추가합니다. +::: + +OpenCode는 어떤 이미지를 스캔할 수 있습니다. 당신은 할 수 +이 작업을 수행하고 끝으로 이미지를 삭제합니다. + +3. ** 기능 구축 ** + +플랜으로 편안하게 느끼면 Build mode by +**Tab** 키를 다시 입력합니다. + +```bash frame="none" + +``` + +그리고 변경을 요청합니다. + +```bash frame="none" +Sounds good! Go ahead and make the changes. +``` + +--- + +### 변경 + +더 똑바른 변화를 위해, 당신은 OpenCode를 직접 그것을 건설할 수 있습니다 +첫 플랜을 검토하지 않고. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +좋은 양의 세부 사항을 제공 하려면 OpenCode가 올바른 +이름 \* + +--- + +### Undo 변경 + +OpenCode를 호출하면 변경 사항을 만들 수 있습니다. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +그러나 당신이 원하는 것은 아닙니다. ** 변경할 수 없습니다 ** +`/undo` 명령을 사용하여. + +```bash frame="none" +/undo +``` + +OpenCode는 이제 당신이 만든 변경을 반전하고 원래 메시지를 표시 +다시. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +여기에서 당신은 신속하고 다시 시도 OpenCode를 요청할 수 있습니다. + +:::tip +`/undo`를 여러 번 실행할 수 있습니다. +::: + +또는 \*\* `/redo` 명령을 사용하여 변경할 수 있습니다. + +```bash frame="none" +/redo +``` + +--- + +## 공유 + +OpenCode와 나눈 대화는 [팀과 공유](/docs/share)할 수 있습니다. + +```bash frame="none" +/share +``` + +현재 대화에 대한 링크를 만들고 클립보드에 복사합니다. + +:::note +대화는 기본적으로 공유되지 않습니다. +::: + +여기 [example 대화](https://opencode.ai/s/4XP1fce5) 는 OpenCode 입니다. + +--- + +## 사용자 정의 + +그리고 그게 다야! 이제 OpenCode를 사용하여 프로입니다. + +자신의 것을 만들기 위해, 우리는 [themes](/docs/themes), [keybinds](/docs/keybinds), [configuring code formatters](/docs/formatters), [creating custom commands](/docs/commands), 또는 [OpenCode config](/docs/config)와 함께 연주하는 것을 추천합니다. diff --git a/packages/web/src/content/docs/ko/keybinds.mdx b/packages/web/src/content/docs/ko/keybinds.mdx new file mode 100644 index 000000000..ad758c3c3 --- /dev/null +++ b/packages/web/src/content/docs/ko/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: Keybinds +description: Customize your keybinds. +--- + +OpenCode는 OpenCode config를 통해 사용자 정의 할 수있는 keybinds 목록을 가지고 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## 리더 키 + +OpenCode는 대부분의 keybinds에 대한 `leader` 키를 사용합니다. 이것은 당신의 맨끝에 있는 충돌을 피합니다. + +기본적으로 `ctrl+x`는 리더 키이며 대부분의 작업은 리더 키를 먼저 누르고 단축키를 누릅니다. 예를 들어, 새 세션을 시작하려면 먼저 `ctrl+x`를 누르고 `n`를 누릅니다. + +당신은 당신의 keybinds를 위한 지도자 열쇠를 사용할 필요가 없습니다 그러나 우리는 이렇게 추천합니다. + +--- + +## 비활성화 keybind + +"none"의 값으로 구성에 키를 추가하여 keybind를 비활성화 할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## 데스크탑 프롬프트 단축키 + +OpenCode 데스크톱 앱 프롬프트 입력은 텍스트 편집을 위한 일반적인 Readline/Emacs-style 단축키를 지원합니다. 이들은 내장되어 있으며 현재 `opencode.json`를 통해 구성할 수 없습니다. + +| 단축 | 액션 | +| -------- | ---------------------------------------- | +| `ctrl+a` | 현재 행 시작으로 이동 | +| `ctrl+e` | 현재선 끝으로 이동 | +| `ctrl+b` | 커서를 다시 한 문자로 이동 | +| `ctrl+f` | 한자 앞의 커서 | +| `alt+b` | 한 단어로 커서 이동 | +| `alt+f` | 한 단어를 넘겨 주세요 | +| `ctrl+d` | 커서의 캐릭터 삭제 | +| `ctrl+k` | 노선의 종료 | +| `ctrl+u` | 노선 시작 | +| `ctrl+w` | 이전 단어 | +| `alt+d` | 다음 단어를 죽이기 | +| `ctrl+t` | 자가용 캐릭터 | +| `ctrl+g` | 팝오버를 취소 / 응답 취소 | + +--- + +## 시프트+ 이름 * + +몇몇 맨끝은 기본적으로 입력한 modifier 열쇠를 보내지 않습니다. `Shift+Enter`를 탈출 순서로 보낼 터미널을 구성해야 할 수 있습니다. + +### 윈도우 터미널 + +`settings.json`를 엽니다: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +루트 레벨 `actions` 배열에 이것을 추가하십시오: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +루트 레벨 `keybindings` 배열에 이것을 추가하십시오: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +파일을 저장하고 Windows 터미널을 다시 시작하거나 새 탭을 엽니 다. diff --git a/packages/web/src/content/docs/ko/lsp.mdx b/packages/web/src/content/docs/ko/lsp.mdx new file mode 100644 index 000000000..6bd1bc241 --- /dev/null +++ b/packages/web/src/content/docs/ko/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: LSP Servers +description: OpenCode integrates with your LSP servers. +--- + +OpenCode는 언어 서버 프로토콜 (LSP)과 통합하여 LLM은 코드베이스와 상호 작용합니다. 그것은 LLM에 피드백을 제공하기 위해 진단을 사용합니다. + +--- + +## 내장 + +OpenCode는 인기있는 언어로 여러 내장 LSP 서버와 함께 제공됩니다. + +| LSP 서버 | 연장 | 요구사항 | +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +| astro | .astro | Astro 프로젝트 자동 설치 | +| bash | .sh, .bash, .zsh, .ksh | 자동 설치 bash-language-server | +| clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | C/C++ 프로젝트용 자동 설치 | +| csharp | .cs | `.NET SDK` 설치 | +| clojure-lsp | .clj, .cljs, .cljc, .edn | `clojure-lsp` 명령 가능 | +| 다트 | 다트 | `dart` 명령 | +| deno | .ts, .tsx, .js, .jsx, .mjs | `deno` 명령 가능(자동검출 deno.json/deno.jsonc) | +| elixir-ls | .ex, .exs | `elixir` 명령 가능 | +| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | 프로젝트의 `eslint` 의존성 | +| fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` 설치 | +| gleam | .gleam | `gleam` 명령 가능 | +| gopls | .go | `go` 명령 가능 | +| hls | .hs, .lhs | `haskell-language-server-wrapper` 명령 가능 | +| jdtls | .java | `Java SDK (version 21+)` 설치 | +| kotlin-ls | .kt, .kts | Kotlin 프로젝트용 자동 설치 | +| lua-ls | .lua | 루아 사업용 자동설치 | +| nixd | .nix | `nixd` 명령 가능 | +| ocaml-lsp | .ml, .mli | `ocamllsp` 명령 가능 | +| oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .ct, .vue, .astro, .svelte | 프로젝트의 `oxlint` 신뢰성 | +| PHP intelephense | .php | PHP 프로젝트 자동 설치 | +| 프리즘 | .prisma | `prisma` 명령 가능 | +| pyright | .py, .pyi | `pyright` 의존성 설치 | +| 루비-lsp(rubocop) | .rb, .rake, .gemspec, .ru | `ruby` 및 `gem` 명령 사용 가능 | +| 녹 | .rs | `rust-analyzer` 명령 가능 | +| sourcekit-lsp | .swift, .objc, .objcpp | `swift` 설치 (MacOS의 `xcode`) | +| svelte | .svelte | Svelte 프로젝트 자동 설치 | +| 지형 | .tf, .tfvars | GitHub 릴리스의 자동 설치 | +| 작문 | .typ, .typc | GitHub 릴리스의 자동 설치 | +인가정보 | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | 프로젝트의 `typescript` 의존성 | +| vue | .vue | Vue 프로젝트 자동 설치 | +| yaml-ls | .yaml, .yml | 자동 설치 Red Hat yaml-language-server | +| zls | .zig, .zon | `zig` 명령 가능 | + +LSP 서버는 위의 파일 확장자 중 하나가 감지되고 요구 사항은 자동으로 활성화됩니다. + +:::note +`OPENCODE_DISABLE_LSP_DOWNLOAD` 환경 변수를 `true`로 설정하여 자동 LSP 서버 다운로드를 비활성화 할 수 있습니다. +::: + +--- + +## 그것이 작동하는 방법 + +opencode가 파일을 열 때, 그것은: + +1. 모든 활성화된 LSP 서버에 대한 파일 확장을 확인합니다. +2. 이미 실행되지 않은 경우 적절한 LSP 서버를 시작합니다. + +--- + +## 구성 + +오픈코드 설정에서 `lsp` 섹션을 통해 LSP 서버를 사용자 정의할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +각 LSP 서버는 다음을 지원합니다: + +| 재산 | 유형 | 묘사 | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` | 불린 | LSP 서버를 비활성화하려면 `true`로 설정 | +| `command` | 문자열[] | LSP 서버를 시작하는 명령 | +| `extensions` | string[] | 이 LSP 서버 확장 | +| `env` | 객체 | 서버 시작시 설정할 환경 변수 | +| `initialization` | 객체 | LSP 서버에 보내는 초기화 옵션 | + +몇 가지 예제를 살펴 보자. + +--- + +## 환경 변수 + +`env` 속성을 사용하여 LSP 서버를 시작할 때 환경 변수를 설정하십시오. + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### 초기화 옵션 + +`initialization` 속성을 사용하여 초기화 옵션을 LSP 서버에 전달합니다. 이들은 LSP `initialize` 요청에 보내진 서버 별 설정입니다. + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +초기화 옵션은 LSP 서버가 다릅니다. LSP 서버의 사용 가능한 옵션을 확인하세요. +::: + +--- + +### LSP 서버를 해제 + +전 세계적으로 ** 모든** LSP 서버를 비활성화하려면 `lsp`를 `false`로 설정하십시오. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +** 특정** LSP 서버를 비활성화하려면 `disabled`를 `true`로 설정하십시오. + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +## 사용자 정의 LSP 서버 + +명령 및 파일 확장명을 지정하여 사용자 정의 LSP 서버를 추가할 수 있습니다. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## 추가 정보 + +### PHP 인텔 + +PHP를 Intelephense는 라이센스 키를 통해 프리미엄 기능을 제공합니다. 텍스트 파일에서 키 (만)를 배치하여 라이센스 키를 제공 할 수 있습니다. + +- macOS/리눅스에서: `$HOME/intelephense/licence.txt` +- Windows에서: `%USERPROFILE%/intelephense/licence.txt` + +파일에는 추가 내용이 없습니다. diff --git a/packages/web/src/content/docs/ko/mcp-servers.mdx b/packages/web/src/content/docs/ko/mcp-servers.mdx new file mode 100644 index 000000000..64813b034 --- /dev/null +++ b/packages/web/src/content/docs/ko/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: MCP servers +description: Add local and remote MCP tools. +--- + +Model Context Protocol , 또는 MCP를 사용하여 OpenCode에 외부 도구를 추가할 수 있습니다. OpenCode는 로컬 및 원격 서버를 모두 지원합니다. + +추가되면 MCP 도구는 내장 도구와 함께 LLM에 자동으로 사용할 수 있습니다. + +--- + +#### 동굴 + +MCP 서버를 사용할 때 상황에 추가합니다. 도구가 많이 있으면 신속하게 추가 할 수 있습니다. 그래서 우리는 당신이 사용하는 MCP 서버와 주의를 기울여야 합니다. + +:::tip +MCP 서버는 귀하의 컨텍스트에 추가하므로, 활성화할 수 있는 것을 주의해야 합니다. +::: + +GitHub MCP 서버와 같은 특정 MCP 서버는 많은 토큰을 추가하고 컨텍스트 제한을 쉽게 초과 할 수 있습니다. + +--- + +## 사용 가능 + +`mcp`에서 MCP 서버를 정의할 수 있습니다. 각 MCP를 고유 이름으로 추가합니다. LLM을 프롬프트할 때 MCP를 참조할 수 있습니다. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +`enabled`를 `false`로 설정하여 서버를 비활성화 할 수 있습니다. config에서 제거하지 않고 서버를 일시적으로 비활성화하려는 경우 유용합니다. + +--- + +### 원격 디폴트 overriding + +조직은 `.well-known/opencode` 엔드포인트를 통해 기본 MCP 서버를 제공 할 수 있습니다. 이 서버는 기본적으로 비활성화 될 수 있으며 사용자가 필요한 것들에 대해 선택 할 수 있습니다. + +조직의 원격 설정에서 특정 서버를 활성화하려면 `enabled: true`로 로컬 구성에 추가하십시오. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +로컬 설정 값은 원격 기본값을 무시합니다. 자세한 내용은 [config precedence](/docs/config#precedence-order)를 참조하십시오. + +--- + +## 지역 + +MCP 객체 내에서 `type`를 `"local"`로 사용하는 로컬 MCP 서버를 추가하십시오. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +명령은 로컬 MCP 서버가 시작되는 방법입니다. 또한 환경 변수 목록에서 전달할 수 있습니다. + +예를 들어, 테스트 [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP 서버를 추가할 수 있는 방법입니다. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +그리고 `use the mcp_everything tool`를 내 프롬프트에 추가할 수 있습니다. + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### 옵션 + +로컬 MCP 서버를 구성하는 모든 옵션이 있습니다. + +| 옵션 | 유형 |필수 | 설명 | +| ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | 문자열 | Y | MCP 서버 연결 유형은 `"local"`. | +| `command` | Array | Y | MCP 서버를 실행하는 명령과 인수. | +| `environment` | 개체 | | 서버 실행시 설정하는 환경 변수 +| `enabled` | Boolean | | 시동에서 MCP 서버 사용 가능 | +| `timeout` | Number | | MCP 서버에서 태핑툴을 위한 타임아웃 기본 5000 (5 초). | + +--- + +## 리모트 + +`type`를 `"remote"`로 설정하여 원격 MCP 서버를 추가하십시오. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url`는 원격 MCP 서버의 URL이며 `headers` 옵션으로 헤더 목록에서 전달할 수 있습니다. + +--- + +#### 옵션 + +| 옵션 | 유형 |필수 | 설명 | +| --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | 문자열 | Y | MCP 서버 연결 유형은 `"remote"`. | +| `url` | 문자열 | Y | 원격 MCP 서버의 URL. | +| `enabled` | Boolean | | 시동에서 MCP 서버 사용 가능 | +| `headers` | 개체 | | 헤드러는 요청으로 보내드립니다. | +| `oauth` | 개체 | | OAuth 인증 구성 [OAuth](#oauth) 아래의 섹션을 참조하십시오. | +| `timeout` | Number | | MCP 서버에서 태핑툴을 위한 타임아웃 기본 5000 (5 초). | + +--- + +## 오아우트 + +OpenCode는 원격 MCP 서버에 대한 OAuth 인증을 자동으로 처리합니다. 서버가 인증이 필요할 때, OpenCode는: + +1. 401 응답을 검출하고 OAuth 흐름을 시작 +2. **Dynamic Client 등록 (RFC 7591) ** 서버에서 지원되는 경우 +3. 미래의 요청에 대해 안전하게 보관 토큰 + +--- + +## 자동 + +대부분의 OAuth-enabled MCP 서버를 위해, 특별한 윤곽은 필요하지 않습니다. 원격 서버를 구성: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +서버가 인증이 필요한 경우, OpenCode는 먼저 사용하려고 할 때 인증됩니다. 그렇지 않다면, `opencode mcp auth `를 사용하여 [manually 방아쇠](#authenticating)을 유발할 수 있습니다. + +--- + +### 사전등록 + +MCP 서버 공급자의 클라이언트 자격이있는 경우, 구성 할 수 있습니다. + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### 인증 + +인증 또는 자격 증명을 수동으로 트리거 할 수 있습니다. + +특정 MCP 서버와 인증: + +```bash +opencode mcp auth my-oauth-server +``` + +모든 MCP 서버를 나열하고 auth 상태: + +```bash +opencode mcp list +``` + +저장된 자격 제거: + +```bash +opencode mcp logout my-oauth-server +``` + +`mcp auth` 명령은 사용자의 브라우저를 엽니다. `~/.local/share/opencode/mcp-auth.json`에서 토큰을 안전하게 저장합니다. + +--- + +### # OAuth를 해제 + +서버의 자동 OAuth를 비활성화하려는 경우 (예를 들어, 대신 API 키를 사용하는 서버), `oauth`를 `false`로 설정: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### OAuth 옵션 + +| 옵션 | 유형 | 설명 | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` | 개체 \| false | OAuth config object, 또는 `false`를 비활성화하는 OAuth 자동검출. · +| `clientId` | 문자열 | OAuth 클라이언트 ID. 제공되지 않은 경우, 동적 클라이언트 등록 시도됩니다. · +| `clientSecret` | String | OAuth 클라이언트 비밀, 허가서 서버가 필요한 경우. | +| `scope` | String | OAuth 범위는 인증 중입니다. | + +# # # # # # 디버깅 + +원격 MCP 서버가 인증에 실패하면 다음과 같은 문제를 진단 할 수 있습니다. + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +`mcp debug` 명령은 현재 auth 상태를 보여 주며 HTTP 연결을 테스트하고 OAuth 발견 흐름을 시도합니다. + +--- + +## 관리 + +MCP는 OpenCode의 도구로 사용할 수 있으며 내장 도구와 함께 사용할 수 있습니다. 다른 도구와 같이 OpenCode config를 통해 관리할 수 있습니다. + +--- + +## 글로벌 + +이것은 당신이 활성화하거나 전 세계적으로 비활성화 할 수 있다는 것을 의미합니다. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +우리는 또한 모든 일치 MCPs를 비활성화하는 glob 패턴을 사용할 수 있습니다. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +여기에 우리는 모든 MCP를 비활성화하는 glob 패턴 `my-mcp*`를 사용합니다. + +--- + +## 대리인 당 ## + +MCP 서버의 많은 수를 가지고 있다면 에이전트 당만 활성화하고 전 세계적으로 비활성화 할 수 있습니다. 이 작업을 수행: + +1. 글로벌 도구로 사용 가능. +2. [agent config](/docs/agents#tools)에서 MCP 서버를 도구로 사용할 수 있습니다. + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +### 글로브 패턴 + +glob 패턴은 간단한 regex globbing 패턴을 사용합니다 : + +- `*`는 어떤 특성 (예를들면, `"my-mcp*"` 경기 `my-mcp_search`, `my-mcp_list`, 등)의 0개 이상 일치합니다. +- `?`는 정확히 하나의 문자 일치 +- 다른 모든 문자 일치 말 그대로 + +:::note +MCP 서버 도구는 서버 이름으로 prefix로 등록되므로 서버의 모든 도구를 간단하게 사용할 수 있습니다. + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## 예제 + +다음은 일반적인 MCP 서버의 예입니다. 다른 서버에 문서를 작성하려면 PR을 제출할 수 있습니다. + +--- + +# # # # 센트리 + +[Sentry MCP 서버](https://mcp.sentry.dev)를 추가하여 센트리 프로젝트와 문제와 상호 작용합니다. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +구성을 추가 한 후, Sentry로 인증: + +```bash +opencode mcp auth sentry +``` + +브라우저 창을 열어 OAuth 흐름을 완료하고 OpenCode를 Sentry 계정에 연결하십시오. + +일단 인증되면, 당신은 쿼리 문제, 프로젝트, 오류 데이터에 대한 프린트 도구를 사용할 수 있습니다. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### 콘텍스트7 + +[Context7 MCP 서버](https://github.com/upstash/context7)을 추가하여 문서를 검색합니다. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +무료 계정으로 가입한 경우 API 키를 사용하여 더 높은 속도 제한을 얻을 수 있습니다. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +여기에서 우리는 당신이 `CONTEXT7_API_KEY` 환경 변수 세트가 있다는 것을 assuming입니다. + +Context7 MCP 서버를 사용하여 `use context7`를 신속하게 추가하십시오. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +대안으로, 당신은이 같은 뭔가를 추가 할 수 있습니다 [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +## Grep by Vercel에 의해 + +[Grep by Vercel](https://grep.app) MCP 서버를 추가하여 GitHub에서 코드 스니펫을 검색합니다. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +MCP 서버 `gh_grep`라는 이름으로, `use the gh_grep tool`를 추가할 수 있습니다. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +대안으로, 당신은이 같은 뭔가를 추가 할 수 있습니다 [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/ko/models.mdx b/packages/web/src/content/docs/ko/models.mdx new file mode 100644 index 000000000..8c0ef361a --- /dev/null +++ b/packages/web/src/content/docs/ko/models.mdx @@ -0,0 +1,223 @@ +--- +title: Models +description: Configuring an LLM provider and model. +--- + +OpenCode는 [AI SDK](https://ai-sdk.dev/) 및 [Models.dev](https://models.dev)를 사용하여 **75+ LLM 제공 업체**를 지원하며 로컬 모델을 실행합니다. + +--- + +## 공급자 + +가장 인기 있는 공급자는 기본적으로 preloaded. `/connect` 명령을 통해 공급자를위한 자격 증명을 추가하면 OpenCode를 시작할 때 사용할 수 있습니다. + +자세히 알아보기 [providers](/docs/providers). + +--- + +## 모델 선택 + +공급자를 구성하면 입력하여 원하는 모델을 선택할 수 있습니다. + +```bash frame="none" +/models +``` + +--- + +## 추천 모델 + +거기에 많은 모델이 있습니다, 새로운 모델이 매주 온다. + +:::tip +우리가 추천하는 모델 중 하나를 사용하여 고려하십시오. +::: + +그러나 코드와 도구 호출 모두에서 좋은 그들 중 몇 가지가있다. + +다음은 OpenCode와 잘 작동하는 몇 가지 모델입니다. 특히 주문이 없습니다. (이것은 철저한 목록이 아니며 반드시 날짜까지입니다) : + +- GPT의 5.2 +- GPT 5.1 코덱 +- 클로드 오푸스 4.5 +- 클로드 Sonnet 4.5 +- 소형 M2.1 +- Gemini 3 프로 + +--- + +## 기본값 설정 + +기본 모델로 설정하려면 `model` 키를 설정할 수 있습니다. +OpenCode 설정. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +전체 ID는 `provider_id/model_id`입니다. 예를 들어, [OpenCode Zen](/docs/zen)을 사용한다면, GPT 5.1 Codex에 `opencode/gpt-5.1-codex`를 사용할 수 있습니다. + +[custom Provider](/docs/providers#custom)를 구성하면 `provider_id`는 구성의 `provider` 부분에서 키이며 `model_id`는 `provider.models`에서 키입니다. + +--- + +## 모델 구성 + +config를 통해 모델의 옵션을 구성할 수 있습니다. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +여기에 우리는 두 개의 내장 모델에 대한 글로벌 설정을 구성 : `gpt-5`를 통해 액세스 할 때 `openai` 공급자 및 `claude-sonnet-4-20250514`는 `anthropic` 공급자를 통해 액세스 할 때. +내장 공급자 및 모델 이름은 [Models.dev](https://models.dev)에서 찾을 수 있습니다. + +사용중인 에이전트에 이러한 옵션을 구성할 수 있습니다. 에이전트 구성은 여기에 모든 글로벌 옵션을 overrides. [더 알아보기](/docs/agents/#additional). + +내장 된 것을 확장하는 사용자 정의 변형을 정의 할 수 있습니다. Variants는 중복 항목 생성 없이 동일한 모델을 위한 다른 설정을 구성할 수 있습니다: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## 참배 + +다른 윤곽을 가진 많은 모형 지원 다수 변종. OpenCode는 인기있는 공급자를위한 기본 변형으로 배송됩니다. + +## 내장 변형 + +OpenCode는 많은 공급자를 위한 과태 변종으로 발송합니다: + +**Anthropic**: + +- `high` - 높은 생각 예산 (과태) +- `max` - 최대 생각 예산 + +** OpenAI **: + +모델에 따라 다릅니다. + +- `none` - 이유 없음 +- `minimal` - 미니멀 이유 노력 +- `low` - 낮은 이유 노력 +- `medium` - 중간 이유 노력 +- `high` - 높은 이유 노력 +- `xhigh` - 추가 높은 이유 노력 + +** 구글 **: + +- `low` - 더 낮은 노력/토큰 예산 +- `high` - 더 높은 노력 / 토큰 예산 + +:::tip +이 목록은 포괄적이지 않습니다. 다른 많은 공급자는 기본적으로 내장되어 있습니다. +::: + +### 사용자 정의 변형 + +기존의 변형을 과도하게 할 수 있거나 자신에게 추가 할 수 있습니다. + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +## 사이클 변형 + +keybind `variant_cycle`를 사용하여 변형 사이 신속하게 전환합니다. [더 알아보기](/docs/keybinds). + +--- + +## 로딩 모델 + +OpenCode가 시작될 때, 다음의 우선순위 순서에 있는 모형을 검사합니다: + +1. `--model` 또는 `-m` 명령 선 깃발. 형식은 구성 파일과 동일합니다. `provider_id/model_id`. + +2. OpenCode config의 모델 목록. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + +여기에 형식은 `provider/model`입니다. + +3. 마지막 사용된 모형. + +4. 내부 우선 순위를 사용하는 첫 번째 모델. diff --git a/packages/web/src/content/docs/ko/modes.mdx b/packages/web/src/content/docs/ko/modes.mdx new file mode 100644 index 000000000..2d84fef5b --- /dev/null +++ b/packages/web/src/content/docs/ko/modes.mdx @@ -0,0 +1,331 @@ +--- +title: Modes +description: Different modes for different use cases. +--- + +:::caution +모드는 오픈 코드 설정에서 `agent` 옵션을 통해 구성되어 있습니다. 더 보기 +`mode` 옵션이 이제 비활성화되었습니다. [더 알아보기](/docs/시약). +::: + +opencode의 모드는 다른 사용 사례에 대한 행동, 도구 및 프롬프트를 사용자 정의 할 수 있습니다. + +그것은 두 개의 내장 모드와 함께 제공됩니다 : ** 빌드 ** 및 ** 계획 **. 사용자 정의 할 수 있습니다. +opencode config를 통해 자체를 구성합니다. + +세션 중에 모드를 전환하거나 구성 파일에서 구성할 수 있습니다. + +--- + +## 내장 + +opencode는 2개의 붙박이 형태로 옵니다. + +--- + +### 빌드 + +빌드는 **default** 모드로 모든 도구가 활성화됩니다. 이것은 파일 운영 및 시스템 명령에 대한 전체 액세스가 필요한 개발 작업을위한 표준 모드입니다. + +--- + +## 계획 + +계획 및 분석을 위해 설계된 제한 모드. 계획 모드에서 다음 도구는 기본적으로 비활성화됩니다: + +- `write` - 새로운 파일을 만들 수 없습니다 +- `edit` - `.opencode/plans/*.md`에 위치한 파일을 제외하고 기존 파일을 수정할 수 없습니다. +- `patch` - 패치 적용 +- `bash` - 포탄 명령을 실행할 수 없습니다 + +이 모드는 코드를 분석하기 위해 AI를 원할 때 유용합니다. 변경 사항을 제안하거나 코드베이스에 실제 수정없이 계획을 만들 수 있습니다. + +--- + +## 전환 + +Tab 키를 사용하여 세션 중에 모드를 전환할 수 있습니다. 또는 당신의 형성된 `switch_mode` keybind. + +참조 : [Formatters](/docs/formatters) 코드 형식 설정에 대한 정보. + +--- + +## 구성 + +내장 모드를 사용자 정의하거나 구성을 통해 자신의 만들 수 있습니다. 형태는 2가지 방법으로 형성될 수 있습니다: + +### JSON 구성 + +`opencode.json` 설정 파일에서 모드 구성: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Markdown 구성 + +Markdown 파일을 사용하여 모드를 정의할 수 있습니다. 그들에 게: + +- 글로벌: `~/.config/opencode/modes/` +- 프로젝트: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Markdown 파일 이름은 모드 이름 (예 : `review.md`는 `review` 모드를 만듭니다)이됩니다. + +이 구성 옵션을 자세히 살펴봅시다. + +--- + +### 모형 + +`model` config를 사용하여 이 모드의 기본 모델을 무시합니다. 다른 작업에 최적화 된 다른 모델을 사용하는 데 유용합니다. 예를 들어, 계획을위한 빠른 모델, 구현을위한 더 많은 모델. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### 온도 + +`temperature` config와 AI의 응답의 임의성과 창의성을 제어합니다. 더 낮은 값은 더 집중하고 세심한 응답을 만듭니다. 더 높은 값은 창의력과 가변성을 증가하면서. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +온도 값은 일반적으로 0.0에서 1.0에 배열합니다: + +- **0.0-0.2**: 매우 집중하고 신중한 응답, 코드 분석 및 계획에 이상 +-**0.3-0.5**: 일부 창의력과 균형 잡힌 응답, 일반 개발 작업에 좋은 +- **0.6-1.0**: 더 창조적이고 다양한 응답, 뇌하수 및 탐험에 유용한 + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +온도가 지정되지 않은 경우, opencode는 모델별 기본 (일반적으로 0 대부분의 모델에 대한, 0.55 Qwen 모델)을 사용합니다. + +--- + +# # # # 프롬프트 + +`prompt` config를 가진 이 형태를 위한 주문 체계 신속한 파일을 지정하십시오. 신속한 파일은 모드의 목적에 특정한 지시를 포함해야 합니다. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +이 경로는 config 파일이 있는 곳에 관계됩니다. 그래서이 작품 +글로벌 opencode config 및 프로젝트 특정 구성 모두. + +--- + +## 도구 + +이 모드에서는 `tools` config를 사용할 수 있습니다. `true` 또는 `false`로 설정하여 특정 도구를 활성화하거나 비활성화 할 수 있습니다. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +도구가 지정되지 않은 경우, 모든 도구는 기본적으로 활성화됩니다. + +--- + +### 유효한 공구 + +여기에 모든 도구는 모드 구성을 통해 제어 할 수 있습니다. + +| 도구 | 설명 | +| ----------- | ----------------------- | +| `bash` | 쉘 명령 실행 | +| `edit` | 기존 파일 수정 | +| `write` | 새 파일 만들기 | +| `read` | 읽는 파일 내용 | +| `grep` | 파일 검색 | +| `glob` | 패턴으로 찾기 | +| `list` | 디렉토리 내용 보기 | +| `patch` | 파일에 패치 적용 | +| `todowrite` | 도도 목록 관리 | +| `todoread` | 읽는 도 목록 | +| `webfetch` | 사이트 맵 | + +--- + +## 사용자 정의 모드 + +구성에 추가하여 사용자 정의 모드를 만들 수 있습니다. 여기에는 두 가지 접근법이 있습니다. + +### JSON 구성 사용 + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### markdown 파일 사용 + +프로젝트 별 모드 또는 `~/.config/opencode/modes/`의 모드 파일을 만들 수 있습니다. + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### 사용 사례 + +다음은 다른 모드에 대한 일반적인 사용 사례입니다. + +- **빌딩 모드**: 모든 도구와 함께 전체 개발 작업 +- **플랜 모드**: 변화없이 분석 및 계획 +-**Review 모드**: Code review with read-only access plus 문서 도구 +- ** 디버그 모드**: bash 및 읽기 도구와 함께 조사에 집중 +- **Docs 모드**: 파일 작업과 문서 작성하지만 시스템 명령 없음 + +다른 모델을 찾을 수 있습니다 다른 사용 케이스에 대 한 좋은. diff --git a/packages/web/src/content/docs/ko/network.mdx b/packages/web/src/content/docs/ko/network.mdx new file mode 100644 index 000000000..39fac669c --- /dev/null +++ b/packages/web/src/content/docs/ko/network.mdx @@ -0,0 +1,57 @@ +--- +title: Network +description: Configure proxies and custom certificates. +--- + +OpenCode는 엔터프라이즈 네트워크 환경을 위한 표준 프록시 환경 변수 및 사용자 지정 인증서를 지원합니다. + +--- + +## 프록시 + +OpenCode는 표준 프록시 환경 변수를 존중합니다. + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::caution +TUI는 로컬 HTTP 서버와 통신합니다. routing 루프를 방지하기 위해이 연결에 대한 프록시를 우회해야합니다. +::: + +[CLI 플래그](/docs/cli#run)을 사용하여 서버 포트와 호스트명을 구성할 수 있습니다. + +--- + +### 인증 + +프록시가 기본 인증을 필요로 하는 경우 URL에서 자격 증명이 포함되어 있습니다. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::caution +암호를 해독하지 마십시오. 환경 변수를 사용하거나 자격 증명 스토리지를 확보하십시오. +::: + +NTLM 또는 Kerberos와 같은 고급 인증을 요구하는 프록시는 인증 방법을 지원하는 LLM Gateway를 사용하여 고려합니다. + +--- + +## 사용자 정의 인증서 + +엔터프라이즈가 HTTPS 연결을 위해 사용자 정의 CA를 사용한다면, OpenCode를 사용하여 신뢰합니다. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +프록시 연결과 직접 API 액세스를 위한 이 작업. diff --git a/packages/web/src/content/docs/ko/permissions.mdx b/packages/web/src/content/docs/ko/permissions.mdx new file mode 100644 index 000000000..178759d89 --- /dev/null +++ b/packages/web/src/content/docs/ko/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: Permissions +description: Control which actions require approval to run. +--- + +OpenCode는 주어진 동작이 자동으로 실행되는지 결정하기 위해 `permission` config를 사용하거나 차단합니다. + +`v1.1.1`의 것과 같이, 유산 `tools` 불린 구성은 deprecated이고 `permission`로 합병되었습니다. 오래된 `tools` config는 여전히 뒤쪽 호환성을 위해 지원됩니다. + +--- + +## 활동 + +각 권한 규칙은 다음과 같습니다: + +- `"allow"` - 승인없이 실행 +- `"ask"` - 승인을위한 신속한 +- `"deny"` - 동작 차단 + +--- + +## 구성 + +글로벌 권한(`*` 포함) 및 특정 도구를 부여할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +한 번에 모든 권한을 설정할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## 과립 규칙 (Object Syntax) + +대부분의 권한을 위해 도구 입력을 기반으로 다른 작업을 적용 할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +규칙은 패턴 일치에 의해 평가됩니다, ** 마지막 일치 규칙 우승 **. 일반적인 패턴은 catch-all `"*"` 규칙을 먼저 넣는 것입니다, 그리고 그 후에 더 구체적인 규칙. + +## 와일드카드 + +Permission 본 사용 간단한 wildcard 일치: + +- `*`는 어떤 성격든지의 0개 이상 일치합니다 +- `?`는 정확히 하나의 문자 일치 +- 다른 모든 문자 일치 말 그대로 + +## 홈 디렉토리 확장 + +`~` 또는 `$HOME`를 사용할 수 있습니다 패턴의 시작에 홈 디렉토리를 참조. 이것은 특히 유용합니다 [`external_directory`] (#external-directories) 규칙. + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +## 외부 감독 + +`external_directory`를 사용하여 도구가 OpenCode가 시작된 작업 디렉토리 밖에 터치 경로가 호출되도록합니다. 이것은 입력 (예 : `read`, `edit`, `list`, `glob`, `glob`, `grep` 및 많은 `bash` 명령)로 경로를 수행하는 모든 도구에 적용됩니다. + +홈 확장 (`~/...`와 같은) 패턴이 작성된 방법에 영향을 미칩니다. 그것은 현재의 작업 공간의 외부 경로 부분을 만들지 않습니다, 그래서 작업 디렉토리 외부 경로는 여전히 `external_directory`를 통해 허용해야합니다. + +예를 들어, 이것은 `~/projects/personal/`의 모든 것에 액세스 할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +여기에 허용되는 모든 디렉토리는 현재 작업 공간과 동일한 기본값을 상속합니다. [`read` defaults to `allow`](#defaults)는 `external_directory`에서 `external_directory`의 항목에 대해 읽을 수 있습니다. 도구가 이러한 경로에 제한 될 때 명시적 규칙을 추가하십시오. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +신뢰할 수있는 경로에 초점을 맞춘 목록을 유지하고 다른 도구 (예 : `bash`)에 필요한대로 추가 허용하거나 deny 규칙을 층을 설정합니다. + +--- + +## 사용 가능한 권한 + +OpenCode 권한은 도구 이름에 의해 키 입력되며, 두 개의 안전 가드 : + +- `read` - 파일 읽기 (파일 경로의 매칭) +- `edit` - 모든 파일 수정 (covers `edit`, `write`, `patch`, `multiedit`) +- `glob` - 파일 globbing (glob 패턴 매칭) +- `grep` - 콘텐츠 검색 ( regex 패턴 매칭) +- `list` - 디렉토리의 목록 파일 (폴더 경로 매칭) +- `bash` - 쉘 명령 실행 (`git status --porcelain`와 같은 팟 명령) +- `task` - 시약 출시 (미시 시약 유형) +- `skill` - 기술을 로딩 (기술 이름을 매칭) +- `lsp` - LSP 쿼리 실행 (현재 비 과립) +- `todoread`, `todowrite` - 토도 목록의 읽기 / 업데이트 +- `webfetch` - URL을 fetching ( URL을 매칭) +- `websearch`, `codesearch` - 웹 / 코드 검색 (문자 쿼리) +- `external_directory` - 프로젝트 작업 디렉토리 외부의 도구 접촉 경로 때 트리거 +- `doom_loop` - 동일한 도구 호출이 동일한 입력으로 3 번 반복 할 때 트리거 + +--- + +## 기본 + +아무것도 지정하지 않는 경우, OpenCode는 permissive 기본값에서 시작합니다. + +- `"allow"`에 기본 권한. +- `doom_loop` 및 `external_directory` 기본적으로 `"ask"`. +- `read`는 `"allow"`이고, 그러나 `.env` 파일은 기본적으로 denied: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## "Ask"는 무엇입니까? + +OpenCode가 승인되면 UI는 세 가지 결과를 제공합니다. + +- `once` - 이 요청을 승인 +- `always` - 제안 된 패턴과 일치하는 미래 요청 (현재 OpenCode 세션의 나머지) +- `reject` - 요청을 거부 + +`always`는 도구 (예를 들면, bash 승인 일반적으로 `git status*`와 같은 안전한 명령 접두사)에 의해 approve가 제공 될 패턴의 집합. + +--- + +# # 에이전트 + +에이전트 당 권한이 부여 될 수 있습니다. 에이전트 권한은 글로벌 구성과 합병되며, 에이전트 규칙은 우선합니다. [Learn more](/docs/agents#permissions) 약 에이전트 권한. + +:::note +[Granular Rules (Object Syntax)](#granular-rules-object-syntax))에 대한 자세한 패턴 매칭 예제를 참조하십시오. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +Markdown의 에이전트 권한을 구성할 수 있습니다. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tip +인자와 명령에 대한 패턴 매칭을 사용합니다. `"grep *"`는 `grep pattern file.txt`를 허용하고, `"grep"`는 혼자 그것을 막을 것입니다. `git status`와 같은 명령은 기본 동작을 위해 작동하지만, 인수가 전달될 때 명시된 권한 (`"git status *"`와 같은)이 필요합니다. +::: diff --git a/packages/web/src/content/docs/ko/plugins.mdx b/packages/web/src/content/docs/ko/plugins.mdx new file mode 100644 index 000000000..e070e4c21 --- /dev/null +++ b/packages/web/src/content/docs/ko/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: Plugins +description: Write your own plugins to extend OpenCode. +--- + +플러그인은 다양한 이벤트와 사용자 정의 행동으로 후킹하여 OpenCode를 확장 할 수 있습니다. 플러그인을 만들 수 있습니다 새로운 기능을 추가, 외부 서비스와 통합, 또는 OpenCode의 기본 동작을 수정. + +예를 들어, 커뮤니티에 의해 생성 된 [plugins](/docs/ecosystem#plugins)를 확인하십시오. + +--- + +## 플러그인 사용 + +플러그인을로드하는 두 가지 방법이 있습니다. + +--- + +## 현지 파일에서 + +플러그인 디렉토리에 JavaScript 또는 TypeScript 파일을 배치합니다. + +- `.opencode/plugins/` - 프로젝트 레벨 플러그인 +- `~/.config/opencode/plugins/` - 글로벌 플러그인 + +이 디렉토리의 파일은 자동으로 시작에로드됩니다. + +--- + +### 부터 npm + +config 파일에 npm 패키지를 지정합니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +일반 및 범위의 npm 패키지 모두 지원됩니다. + +[ecosystem](/docs/ecosystem#plugins)에서 사용할 수 있는 플러그인을 찾아보세요. + +--- + +## 플러그인이 설치되는 방법 + +**npm 플러그인**는 시작시 Bun을 사용하여 자동으로 설치됩니다. 패키지와 그들의 의존성은 `~/.cache/opencode/node_modules/`에서 캐시됩니다. + +**Local 플러그인 ** 플러그인 디렉토리에서 직접로드됩니다. 외부 패키지를 사용하려면 구성 디렉토리 내 `package.json`를 작성해야 합니다 ([Dependencies](#dependencies)), 또는 플러그인을 npm에 게시하고 [config에 추가](/docs/config#plugins). + +--- + +## 짐 순서 + +플러그인은 모든 소스에서로드되며 모든 후크는 순서대로 실행됩니다. 짐 순서는: + +1. 글로벌 구성 (`~/.config/opencode/opencode.json`) +2. 프로젝트 구성 (`opencode.json`) +3. 글로벌 플러그인 디렉토리 (`~/.config/opencode/plugins/`) +4. 프로젝트 플러그인 디렉토리 (`.opencode/plugins/`) + +동일한 이름과 버전을 가진 중복 npm 포장은 한 번 적재됩니다. 하지만, 로컬 플러그인과 같은 이름과 npm 플러그인은 모두 별도로로드됩니다. + +--- + +## 플러그인 만들기 + +플러그인은 **JavaScript/TypeScript 모듈**입니다. +기능. 각 함수는 context 객체를 수신하고 Hooks 객체를 반환합니다. + +--- + +### 종점 + +로컬 플러그인 및 사용자 정의 도구는 외부 npm 패키지를 사용할 수 있습니다. `package.json`를 config 디렉토리에 추가하면 필요한 의존도가 있습니다. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode는 `bun install`를 시작합니다. 플러그인 및 도구가 가져올 수 있습니다. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### 기본 구조 + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +플러그인 기능 수신: + +- `project`: 현재 프로젝트 정보. +- `directory`: 현재 작업 디렉토리. +- `worktree`: git worktree 경로. +- `client`: AI와 상호 작용을 위한 opencode SDK 클라이언트. +- `$`: Bun's [shell API](https://bun.com/docs/runtime/shell) 명령어를 실행합니다. + +--- + +### TypeScript 지원 + +TypeScript 플러그인의 경우 플러그인 패키지에서 유형을 가져올 수 있습니다. + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +## 이벤트 + +플러그인은 예제 섹션에서 아래에서 볼 때 이벤트에 가입 할 수 있습니다. 여기에 다른 이벤트의 목록입니다. + +### 명령어 이벤트 + +- `command.executed` + +### 파일 이벤트 + +- `file.edited` +- `file.watcher.updated` + +### 설치 이벤트 + +- `installation.updated` + +### LSP 이벤트 + +- `lsp.client.diagnostics` +- `lsp.updated` + +### 메시지 이벤트 + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### 권한 이벤트 + +- `permission.asked` +- `permission.replied` + +### 서버 이벤트 + +- `server.connected` + +### 세션 이벤트 + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +### Todo 이벤트 + +- `todo.updated` + +#### 포탄 사건 + +- `shell.env` + +# # # # # 도구 이벤트 + +- `tool.execute.after` +- `tool.execute.before` + +#### TUI 이벤트 + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## 예제 + +opencode를 확장하기 위해 사용할 수있는 플러그인의 몇 가지 예입니다. + +--- + +## 알림 보내기 + +특정 이벤트가 발생할 때 알림을 전송: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +macOS에서 AppleScript를 실행하려면 `osascript`를 사용하고 있습니다. 여기에 우리는 그것을 사용하여 알림을 보낼 수 있습니다. + +:::note +OpenCode 데스크톱 앱을 사용하는 경우 응답이 준비되어 있거나 세션 오류가 있을 때 시스템 알림을 자동으로 보낼 수 있습니다. +::: + +--- + +### .env 보호 + +읽기 `.env` 파일에서 opencode를 방지하십시오: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### Inject 환경 변수 + +환경 변수를 모든 쉘 실행 (AI 도구 및 사용자 터미널)로 주사하십시오. + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### 사용자 정의 도구 + +플러그인은 Opencode에 사용자 정의 도구를 추가 할 수 있습니다 : + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +`tool` helper는 opencode가 호출 할 수있는 사용자 정의 도구를 만듭니다. Zod schema 기능을 가지고 도구 정의를 반환: + +- `description`: 도구는 무엇을 +- `args`: 도구의 인수에 대한 Zod 스키마 +- `execute`: 도구가 호출될 때 실행되는 기능 + +사용자 정의 도구는 내장 도구와 함께 Opencode를 사용할 수 있습니다. + +--- + +### 로깅 + +구조화된 로깅을 위한 `console.log` 대신에 `client.app.log()`를 사용하십시오: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +레벨: `debug`, `info`, `warn`, `error`. [SDK 문서](https://opencode.ai/docs/sdk)를 참고하세요. + +--- + +## Compaction 걸이 + +세션이 압축 될 때 포함 된 컨텍스트를 사용자 지정: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +LLM의 앞에 `experimental.session.compacting` 걸이 불은 오염 요약을 생성합니다. 기본 압축 프롬프트가 놓을 수 있도록 도메인 별 컨텍스트를 주입합니다. + +당신은 또한 `output.prompt`를 조정해서 조밀함을 전적으로 대체할 수 있습니다: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +`output.prompt`가 설정되면 완전히 기본 압축 프롬프트를 대체합니다. `output.context` 배열은 이 경우에 무시됩니다. diff --git a/packages/web/src/content/docs/ko/providers.mdx b/packages/web/src/content/docs/ko/providers.mdx new file mode 100644 index 000000000..fc21a2693 --- /dev/null +++ b/packages/web/src/content/docs/ko/providers.mdx @@ -0,0 +1,1889 @@ +--- +title: Providers +description: Using any LLM provider in OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode는 [AI SDK](https://ai-sdk.dev/) 및 [Models.dev](https://models.dev)를 사용하여 **75+ LLM 제공 업체**를 지원하며 로컬 모델을 실행합니다. + +필요한 공급자를 추가하려면: + +1. `/connect` 명령을 사용하여 공급자를 위한 API 열쇠를 추가하십시오. +2. OpenCode config에 있는 공급자를 구성하십시오. + +--- + +### 등급 + +공급자의 API 키를 `/connect` 명령으로 추가하면 저장됩니다. +`~/.local/share/opencode/auth.json`에서. + +--- + +# # # # 콘피그 + +OpenCode의 `provider` 섹션을 통해 공급자를 사용자 정의 할 수 있습니다. +설정. + +--- + +### 기본 URL + +`baseURL` 옵션을 설정하여 모든 공급자를위한 기본 URL을 사용자 정의 할 수 있습니다. 프록시 서비스 또는 사용자 정의 엔드포인트를 사용할 때 유용합니다. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## 오픈코드 젠 + +OpenCode Zen은 OpenCode 팀이 제공하는 모델 목록입니다. +OpenCode와 잘 작동하도록 테스트 및 검증. [더 알아보기](/docs/zen). + +:::tip +새로운 경우, OpenCode Zen로 시작하는 것이 좋습니다. +::: + +1. TUI에서 `/connect` 명령을 실행하고, opencode를 선택하고, [opencode.ai/auth](https://opencode.ai/auth)에 머리를 선택합니다. + + ```txt + /connect + ``` + +2. 로그인, 청구 세부 정보를 추가하고 API 키를 복사하십시오. + +3. API 키를 붙여. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. TUI의 `/models`를 실행하여 우리가 추천하는 모델 목록을 볼 수 있습니다. + + ```txt + /models + ``` + +OpenCode의 다른 공급자와 같이 작동하고 사용하기에 완전히 선택적입니다. + +--- + +## 디렉토리 + +세부사항에 있는 공급자의 몇몇을 보십시오. 공급자를 추가하려는 경우 +목록, PR을 무료로 엽니 다. + +:::note +여기에서 공급자를 볼 수 없습니다? PR 제출 +::: + +--- + +# # # 302. 사이트맵 + +1. [302.AI 콘솔](https://302.ai/)에 머리, 계정을 만들고 API 키를 생성합니다. + +2. `/connect` 명령을 실행하고 **302.AI**를 검색하십시오. + + ```txt + /connect + ``` + +3. 302.AI API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 모델을 선택하려면 `/models` 명령을 실행하십시오. + + ```txt + /models + ``` + +--- + +### 아마존 베드록 + +OpenCode로 Amazon Bedrock을 사용하려면: + +1. Amazon Bedrock 콘솔 및 요청에서 ** 모델 카탈로그**에 머리 +원하는 모델에 액세스. + + :::tip +Amazon Bedrock에서 원하는 모델에 액세스해야합니다. + ::: + +2. ** 설정** 다음 방법 중 하나를 사용하여: + +### 환경 변수 (빠른 시작) + +opencode를 실행하는 동안 이러한 환경 변수 중 하나를 설정: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + +또는 bash 프로필에 추가: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + +#### 설정 파일 (추천) + +프로젝트 별 또는 지속적 구성의 경우 `opencode.json`를 사용하십시오. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + +** 유효한 옵션:** +- `region` - AWS 지역 (예: `us-east-1`, `eu-west-1`) +- `profile` - AWS는 `~/.aws/credentials`에서 단면도를 지명했습니다 +- `endpoint` - VPC 엔드 포인트에 대한 사용자 정의 엔드 포인트 URL (일반 `baseURL` 옵션 별) + + :::tip +구성 파일 옵션은 환경 변수에 대한 precedence를 가져옵니다. + ::: + +#### 고급: VPC 엔드포인트 + +Bedrock의 VPC 엔드포인트를 사용하는 경우: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::note +`endpoint` 옵션은 일반적인 `baseURL` 옵션의 별칭입니다. `endpoint`와 `baseURL` 둘 다 지정되는 경우에, `endpoint`는 전진합니다. + ::: + +#### 인증 방법 +-**`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`**: IAM 사용자 생성 및 AWS 콘솔에서 액세스 키를 생성 +- **`AWS_PROFILE`**: `~/.aws/credentials`의 프로필 이름을 사용합니다. `aws configure --profile my-profile` 또는 `aws sso login`로 첫번째 구성 +- **`AWS_BEARER_TOKEN_BEDROCK`**: Amazon Bedrock 콘솔에서 장기적인 API 키 생성 +- **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: EKS IRSA (서비스 계정을위한IAM 역할) 또는 OIDC federation과 다른 쿠버네티스 환경. 이 환경 변수는 서비스 계정 할당을 사용할 때 쿠버네티스에 의해 자동으로 주사됩니다. + +#### 인증 + +Amazon Bedrock은 다음과 같은 인증 우선 순위를 사용합니다. +1. ** 브라우저 토큰 ** - `AWS_BEARER_TOKEN_BEDROCK` 환경 변수 또는 `/connect` 명령에서 토큰 +2. **AWS Credential Chain ** - 프로필, 액세스 키, 공유 자격 증명, IAM 역할, 웹 ID 토큰 (EKS IRSA), 인스턴스 메타 데이터 + + :::note +Bearer 토큰을 설정할 때 (`/connect` 또는 `AWS_BEARER_TOKEN_BEDROCK`를 통해), 구성 된 프로파일을 포함한 모든 AWS 자격 방법을 통해 우선 순위가됩니다. + ::: + +3. 당신이 원하는 모형을 선정하기 위하여 `/models` 명령을 실행하십시오. + + ```txt + /models + ``` + +:::note +custom inference profiles를 위해, 열쇠에 있는 모형 그리고 공급자 이름을 사용하고 arn에 `id` 재산을 놓습니다. 이것은 정확한 캐싱을 지킵니다: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +# # # # 안토픽 + +1. 가입하면 `/connect` 명령을 실행하고 Anthropic을 선택합니다. + + ```txt + /connect + ``` + +2. **Claude Pro/Max** 옵션을 선택하고 브라우저를 열 수 있습니다. +자주 묻는 질문 + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. 이제 모든 Anthropic 모델은 `/models` 명령을 사용할 때 사용할 수 있어야합니다. + + ```txt + /models + ``` + +:::정보 +OpenCode의 Claude Pro/Max 구독을 사용하여 [Anthropic](https://anthropic.com)에서 공식적으로 지원되지 않습니다. +::: + +##### API 키 사용 + +Pro/Max 구독이 없는 경우 **Create an API Key**를 선택할 수 있습니다. 브라우저를 열고 Anthropic에 로그인하고 터미널에서 붙여넣을 수있는 코드를 제공합니다. + +또는 이미 API 키가 있다면, ** 수동으로 API Key**를 입력하고 터미널에서 붙여넣을 수 있습니다. + +--- + +### Azure 오픈AI + +:::note +"나는 미안 해요, 하지만 나는 그 요청을 지원할 수 없습니다" 오류, 에서 콘텐츠 필터를 변경 시도 ** defaultV2** 에 ** 과태** 당신의 Azure 자원에. +::: + +1. [Azure 포털](https://portal.azure.com/) 이상으로 머리와 **Azure OpenAI** 리소스를 만듭니다. 당신은 필요로 할 것이다: +- **소스 이름**: 이것은 API 엔드 포인트의 일부가됩니다 (`https://RESOURCE_NAME.openai.azure.com/`) +- ** API 키**: `KEY 1` 또는 당신의 자원에서 `KEY 2` + +2. [Azure AI Foundry](https://ai.azure.com/)로 이동하여 모델을 배포합니다. + + :::note +배포 이름은 제대로 작동하려면 opencode의 모델 이름을 일치해야합니다. + ::: + +3. `/connect` 명령을 실행하고 **Azure**를 검색하십시오. + + ```txt + /connect + ``` + +4. API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. 환경 변수로 리소스 이름을 설정: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + +또는 bash 프로파일에 추가: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. `/models` 명령을 실행하여 배포 된 모델을 선택하십시오. + + ```txt + /models + ``` + +--- + +### Azure Cognitive 서비스 + +1. [Azure 포털](https://portal.azure.com/) 이상으로 머리와 **Azure OpenAI** 리소스를 만듭니다. 당신은 필요로 할 것이다: +- **소스 이름**: 이것은 API 엔드 포인트의 일부가됩니다 (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) +- ** API 키**: `KEY 1` 또는 당신의 자원에서 `KEY 2` + +2. [Azure AI Foundry](https://ai.azure.com/)로 이동하여 모델을 배포합니다. + + :::note +배포 이름은 제대로 작동하려면 opencode의 모델 이름을 일치해야합니다. + ::: + +3. `/connect` 명령을 실행하고 **Azure Cognitive Services**를 검색하십시오. + + ```txt + /connect + ``` + +4. API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. 환경 변수로 리소스 이름을 설정: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + +또는 bash 프로파일에 추가: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. `/models` 명령을 실행하여 배포 된 모델을 선택하십시오. + + ```txt + /models + ``` + +--- + +# # # # 기본 + +1. [Baseten] (https://app.baseten.co/)에 머리는, 계정을 만들고, API 열쇠를 생성합니다. + +2. `/connect` 명령을 실행하고 **Baseten**를 검색하십시오. + + ```txt + /connect + ``` + +3. Baseten API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 모델을 선택하려면 `/models` 명령을 실행하십시오. + + ```txt + /models + ``` + +--- + +# # # # Cerebras의 + +1. [Cerebras 콘솔] (https://inference.cerebras.ai/)에 머리, 계정을 만들고 API 키를 생성합니다. + +2. `/connect` 명령을 실행하고 **Cerebras**를 검색하십시오. + + ```txt + /connect + ``` + +3. Cerebras API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 Qwen 3 Coder 480B . + + ```txt + /models + ``` + +--- + +## Cloudflare AI 게이트웨이 + +Cloudflare AI 게이트웨이는 OpenAI, Anthropic, Workers AI 등의 모델에 액세스할 수 있으며, 통합된 엔드포인트를 통해 더 많은 기능을 제공합니다. [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/)를 사용하면 각 공급자의 별도의 API 키가 필요하지 않습니다. + +1. [Cloudflare 대시보드](https://dash.cloudflare.com/)에 머리, **AI** > **AI Gateway**로 이동하고 새로운 게이트웨이를 만듭니다. + +2. 계정 ID 및 Gateway ID를 환경 변수로 설정하십시오. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. `/connect` 명령을 실행하고 ** Cloudflare AI Gateway**를 검색하십시오. + + ```txt + /connect + ``` + +4. Cloudflare API 토큰을 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +또는 환경 변수로 설정한다. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. 모델을 선택하려면 `/models` 명령을 실행하십시오. + + ```txt + /models + ``` + +Opencode config를 통해 모델을 추가할 수 있습니다. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +# # # # 코텍 + +1. [Cortecs 콘솔] (https://cortecs.ai/)에 머리, 계정을 만들고 API 키를 생성합니다. + +2. `/connect` 명령을 실행하고 **Cortecs**를 검색하십시오. + + ```txt + /connect + ``` + +3. Cortecs API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 Kimi K2 Instruct . + + ```txt + /models + ``` + +--- + +## 딥스카이 + +1. [DeepSeek 콘솔] (https://platform.deepseek.com/)에 머리, 계정을 만들고, ** 새로운 API 키**를 클릭합니다. + +2. `/connect` 명령을 실행하고 **DeepSeek**를 검색하십시오. + + ```txt + /connect + ``` + +3. DeepSeek API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 DeepSeek 모델을 선택하십시오. DeepSeek Reasoner . + + ```txt + /models + ``` + +--- + +## 딥 인프라 + +1. [Deep Infra 대시보드](https://deepinfra.com/dash)에 머리로, 계정을 만들고 API 키를 생성합니다. + +2. `/connect` 명령을 실행하고 **Deep Infra**를 검색하십시오. + + ```txt + /connect + ``` + +3. 딥 인프라 API 키 입력. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 모델을 선택하려면 `/models` 명령을 실행하십시오. + + ```txt + /models + ``` + +--- + +## 펌웨어 + +1. [Firmware 대시보드] (https://app.firmware.ai/signup)에 머리, 계정을 만들고 API 키를 생성합니다. + +2. `/connect` 명령을 실행하고 **Firmware**를 검색하십시오. + + ```txt + /connect + ``` + +3. Firmware API 키 입력. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 모델을 선택하려면 `/models` 명령을 실행하십시오. + + ```txt + /models + ``` + +--- + +## 불꽃 놀이 AI + +1. [Fireworks AI 콘솔](https://app.fireworks.ai/)에 머리, 계정을 만들고 ** API 키**를 클릭합니다. + +2. `/connect` 명령을 실행하고 ** 불꽃 놀이 AI **를 검색하십시오. + + ```txt + /connect + ``` + +3. 불꽃 놀이 AI API 열쇠를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 Kimi K2 Instruct . + + ```txt + /models + ``` + +--- + +### GitLab 듀오 + +프로젝트 Duo는 GitLab의 Anthropic 프록시를 통해 기본 툴 호출 기능을 갖춘 AI-powered Agentic 채팅을 제공합니다. + +1. `/connect` 명령을 실행하고 GitLab을 선택합니다. + + ```txt + /connect + ``` + +2. 인증 방법을 선택하십시오: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + +#### OAuth 사용 (추천) + +Select**OAuth**와 브라우저는 권한이 없습니다. + +### 개인 액세스 토큰 사용 +1. [GitLab User Settings > Access Tokens](https://gitlab.com/-/user settings/personal access tokens)로 이동 +2. 새 토큰 추가 ** +3. 이름: `OpenCode`의 범위: `api` +4. 토큰 복사 (`glpat-`와 함께 시작) +5. 맨끝에서 그것을 입력하십시오 + +3. 유효한 모형을 보기 위하여 `/models` 명령을 실행하십시오. + + ```txt + /models + ``` + +세 개의 클로드 기반 모델은 다음과 같습니다. +-**duo-chat-haiku-4-5** (기본값) - 빠른 작업에 대한 빠른 응답 +-**duo-chat-sonnet-4-5** - 대부분의 워크플로우의 밸런스 성능 +-**duo-chat-opus-4-5** - 복잡한 분석 가능 + +:::note +'GITLAB TOKEN' 환경 변수를 지정할 수도 있습니다. +opencode auth 저장소에 토큰을 저장합니다. +::: + +#### 셀프 호스팅 GitLab + +:::노트[컴포지션 노트] +OpenCode는 세션 제목을 생성하고 같은 일부 AI 작업을 위해 작은 모델을 사용합니다. +기본적으로 gpt-5-nano를 사용하도록 구성되며 Zen에서 호스팅됩니다. OpenCode를 잠금 +자신의 GitLab-hosted 인스턴스를 사용하여 다음을 추가하십시오. +`opencode.json` 파일. 세션 공유를 비활성화하는 것이 좋습니다. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +자체 호스팅 GitLab 인스턴스: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +인스턴스가 사용자 정의 AI Gateway를 실행하면: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +또는 bash 프로파일에 추가: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +GitLab 관리자는 다음을 활성화해야합니다. + +1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab duo/turn on off/) 사용자, 그룹 또는 인스턴스 +2. 특징 깃발 (철도 콘솔을 통해): +- `agent_platform_claude_code` +- `third_party_agents_enabled` + ::: + +####OAuth for Self-Hosted 인스턴스 + +자체 호스팅 된 인스턴스를 위해 Oauth 작업을 만들기 위해, 당신은 만들 필요가 +새로운 응용 프로그램 (설정 → 응용 프로그램) +콜백 URL `http://127.0.0.1:8080/callback` 및 다음 범위: + +- api (당신의 대신에 API에 액세스) +- read user (개인 정보 읽기) +- read repository (Repository에 읽은 전용 접근) + +그런 다음 환경 변수로 애플리케이션 ID를 노출: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +[opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth) 홈페이지에 대한 추가 문서. + +##### 윤곽 + +`opencode.json`를 통해 주문을 받아서 만드십시오: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API 도구 (선택, 그러나 높게 추천되는) + +GitLab 도구에 액세스하려면 (merge 요청, 문제, 파이프라인, CI/CD 등): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +이 플러그인은 MR 리뷰, 문제 추적, 파이프라인 모니터링 등을 포함한 종합 GitLab 저장소 관리 기능을 제공합니다. + +--- + +프로젝트 + +GitHub Copilot 구독을 사용하여 opencode: + +:::note +몇몇 모형은 [Pro+를 필요로 할지도 모릅니다 +구독] (https://github.com/features/copilot/plans) 사용. + +일부 모델은 수동으로 활성화해야합니다 [GitHub Copilot 설정](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. `/connect` 명령을 실행하고 GitHub Copilot을 검색하십시오. + + ```txt + /connect + ``` + +2. [github.com/login/device](https://github.com/login/device)로 이동하여 코드를 입력합니다. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. 이제 원하는 모델을 선택하기 위해 `/models` 명령을 실행합니다. + + ```txt + /models + ``` + +--- + +### 구글 Vertex AI + +OpenCode로 Google Vertex AI를 사용하려면: + +1. Google Cloud Console에서 ** Model Garden**을 통해 헤드를 확인하고 확인하십시오. +당신의 지역에서 유효한 모형. + + :::note +Vertex AI API를 사용하여 Google Cloud 프로젝트를 수행해야합니다. + ::: + +2. 필요한 환경 변수를 설정: +- `GOOGLE_CLOUD_PROJECT`: 당신의 구글 클라우드 프로젝트 ID +- `VERTEX_LOCATION` (선택): Vertex AI를 위한 지구 (`global`에 과태) +- 인증(초당): +- `GOOGLE_APPLICATION_CREDENTIALS`: 서비스 계정 JSON 키 파일 경로 +- gcloud CLI를 사용하여 인증 : `gcloud auth application-default login` + +opencode를 실행하면서 설정한다. + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + +또는 bash 프로파일에 추가하십시오. + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::tip +`global` 지구는 가용성을 개량하고 추가 비용 없이 과실을 감소시킵니다. 데이터 거주 요건에 대한 지역 엔드포인트(e.g., `us-central1`)를 사용하십시오. [더 알아보기](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional and global endpoints) +::: + +3. 당신이 원하는 모형을 선정하기 위하여 `/models` 명령을 실행하십시오. + + ```txt + /models + ``` + +--- + +# # # # # Groq + +1. [Groq 콘솔](https://console.groq.com/)에 머리, click **Create API Key**, 키 복사. + +2. `/connect` 명령을 실행하고 Groq에 대한 검색. + + ```txt + /connect + ``` + +3. 공급자를 위한 API 열쇠를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 원하는 것을 선택합니다. + + ```txt + /models + ``` + +--- + +###Hugging 얼굴 + +[Hugging Face Inference Provider](https://huggingface.co/docs/inference-providers)는 17+ 공급자가 지원하는 오픈 모델에 대한 액세스를 제공합니다. + +1. [Hugging Face settings](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained)를 통해 토큰을 Inference Provider에게 호출할 권한을 부여합니다. + +2. `/connect` 명령을 실행하고 **Hugging Face**를 검색하십시오. + + ```txt + /connect + ``` + +3. Hugging Face 토큰을 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 Kimi-K2-Instruct 또는 GLM-4.6 . + + ```txt + /models + ``` + +--- + +### 헬리콘 + +[Helicone](https://helicone.ai)는 AI 애플리케이션에 대한 로깅, 모니터링 및 분석 기능을 제공하는 LLM Observability 플랫폼입니다. Helicone AI Gateway는 모델을 기반으로 적절한 공급자에게 요청을 자동으로 전달합니다. + +1. [Helicone](https://helicone.ai)에 머리, 계정을 만들고, 대시보드에서 API 키를 생성합니다. + +2. `/connect` 명령을 실행하고 ** Helicone**를 검색하십시오. + + ```txt + /connect + ``` + +3. Helicone API 열쇠를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 모델을 선택하려면 `/models` 명령을 실행하십시오. + + ```txt + /models + ``` + +캐싱 및 속도 제한과 같은 더 많은 공급자와 고급 기능을 위해 [Helicone 문서] (https://docs.helicone.ai)를 확인하십시오. + +#### 선택 사항 + +이벤트에서 Opencode를 통해 자동으로 구성되지 않는 Helicone의 기능 또는 모델을 볼 수 있습니다. + +여기에 [Helicone의 모델 디렉토리](https://helicone.ai/models), 당신은 당신이 추가 할 모델의 ID를 잡아이 필요. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +# # # # # 사용자 정의 헤더 + +Helicone는 캐싱, 사용자 추적 및 세션 관리와 같은 기능을 위한 사용자 정의 헤더를 지원합니다. `options.headers`를 사용하여 공급자 구성에 추가하십시오: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### 세션 추적 + +Helicone's [Sessions](https://docs.helicone.ai/features/sessions) 기능으로 그룹 관련 LLM 요청이 가능합니다. [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) 플러그인을 사용하여 각 OpenCode 대화를 Helicone 세션으로 자동 로그인하십시오. + +```bash +npm install -g opencode-helicone-session +``` + +설정에 추가하십시오. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +플러그인은 `Helicone-Session-Id` 및 `Helicone-Session-Name` 헤더를 귀하의 요청에 주사합니다. Helicone의 세션 페이지에서는 별도의 세션으로 나열된 각 OpenCode 대화를 볼 수 있습니다. + +# # # # # # 공통 헬리콥터 + +| 헤드러 | Description +| -------------------------- | ------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | 대응 캐싱 (`true`/`false`) | +| `Helicone-User-Id` | 사용자별 추적 가능 | +| `Helicone-Property-[Name]` | 사용자 정의 속성 추가(예: `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | 신속한 대응 | + +모든 사용 가능한 헤더에 대한 [Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory)를 참조하십시오. + +--- + +# # # # llama.cpp를 + +[llama.cpp's](https://github.com/ggml-org/llama.cpp) llama-server 유틸리티를 통해 로컬 모델을 사용할 수 있습니다. + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +이 예제에서: + +- `llama.cpp`는 주문 공급자 ID입니다. 원하는 문자열이 될 수 있습니다. +- `npm`는 이 공급자를 위해 사용할 포장을 지정합니다. 여기, `@ai-sdk/openai-compatible`는 OpenAI 호환 API에 사용됩니다. +- `name`는 UI에 있는 공급자를 위한 전시 이름입니다. +- `options.baseURL`는 로컬 서버의 엔드포인트입니다. +- `models`는 모델 ID를 구성하는 맵입니다. 모델 이름은 모델 선택 목록에 표시됩니다. + +--- + +# # # # # # IO.NET + +IO.NET은 다양한 사용 사례에 최적화된 17개의 모델을 제공합니다: + +1. [IO.NET 콘솔](https://ai.io.net/)에 머리, 계정을 만들고 API 키를 생성합니다. + +2. `/connect` 명령을 실행하고 **IO.NET**를 검색하십시오. + + ```txt + /connect + ``` + +3. IO.NET API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 모델을 선택하려면 `/models` 명령을 실행하십시오. + + ```txt + /models + ``` + +--- + +### LM 스튜디오 + +LM Studio를 통해 로컬 모델을 사용할 수 있습니다. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +이 예제에서: + +- `lmstudio`는 주문 공급자 ID입니다. 원하는 문자열이 될 수 있습니다. +- `npm`는 이 공급자를 위해 사용할 포장을 지정합니다. 여기, `@ai-sdk/openai-compatible`는 OpenAI 호환 API에 사용됩니다. +- `name`는 UI에 있는 공급자를 위한 전시 이름입니다. +- `options.baseURL`는 로컬 서버의 엔드포인트입니다. +- `models`는 모델 ID를 구성하는 맵입니다. 모델 이름은 모델 선택 목록에 표시됩니다. + +--- + +## 문샷 AI + +Moonshot AI에서 Kimi K2 사용 : + +1. [Moonshot AI 콘솔] (https://platform.moonshot.ai/console)에 머리, 계정을 만들고, ** API 키**를 클릭합니다. + +2. `/connect` 명령을 실행하고 **Moonshot AI**를 검색하십시오. + + ```txt + /connect + ``` + +3. Moonshot API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 Kimi K2 . + + ```txt + /models + ``` + +--- + +## 미니 맥스 + +1. [MiniMax API 콘솔](https://platform.minimax.io/login)에 머리, 계정을 만들고 API 키를 생성합니다. + +2. `/connect` 명령을 실행하고 **MiniMax**를 검색하십시오. + + ```txt + /connect + ``` + +3. MiniMax API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 M2.1 . + + ```txt + /models + ``` + +--- + +## Nebius 토큰 공장 + +1. [Nebius Token Factory 콘솔] (https://tokenfactory.nebius.com/)에 머리, 계정을 만들고, ** 키 추가 **. + +2. `/connect` 명령을 실행하고 **Nebius Token Factory**를 검색하십시오. + + ```txt + /connect + ``` + +3. Nebius 토큰 공장 API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 Kimi K2 Instruct . + + ```txt + /models + ``` + +--- + +# # # # 오라마 + +Ollama를 통해 로컬 모델을 사용할 수 있습니다. + +:::tip +Ollama는 OpenCode를 자동으로 구성할 수 있습니다. 자세한 내용은 [Ollama 통합 문서](https://docs.ollama.com/integrations/opencode)를 참조하십시오. +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +이 예제에서: + +- `ollama`는 주문 공급자 ID입니다. 원하는 문자열이 될 수 있습니다. +- `npm`는 이 공급자를 위해 사용할 포장을 지정합니다. 여기, `@ai-sdk/openai-compatible`는 OpenAI 호환 API에 사용됩니다. +- `name`는 UI에 있는 공급자를 위한 전시 이름입니다. +- `options.baseURL`는 로컬 서버의 엔드포인트입니다. +- `models`는 모델 ID를 구성하는 맵입니다. 모델 이름은 모델 선택 목록에 표시됩니다. + +:::tip +도구 호출이 작동하지 않는 경우, Ollama에서 `num_ctx` 증가. 주위 시작 16k - 32k. +::: + +--- + +##Ollama 클라우드 + +OpenCode로 Ollama Cloud를 사용하려면: + +1. [https://ollama.com/](https://ollama.com/) 이상 머리와 로그인하거나 계정을 만들 수 있습니다. + +2. Navigate to**Settings** > **Keys** 및 click **API Key**를 추가하여 새로운 API 키 생성. + +3. OpenCode에서 사용을 위한 API 열쇠를 복사하십시오. + +4. `/connect` 명령을 실행하고 ** Ollama Cloud**를 검색하십시오. + + ```txt + /connect + ``` + +5. Ollama Cloud API 키 입력. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. ** 중요 **: OpenCode의 클라우드 모델을 사용하기 전에, 로컬 모델 정보를 끌어야 합니다: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. `/models` 명령을 실행하여 Ollama Cloud 모델을 선택하십시오. + + ```txt + /models + ``` + +--- + +### 오픈아이 + +[ChatGPT Plus 또는 Pro] (https://chatgpt.com/pricing)에 가입하는 것이 좋습니다. + +1. 가입하면 `/connect` 명령을 실행하고 OpenAI를 선택하십시오. + + ```txt + /connect + ``` + +2. **ChatGPT Plus/Pro** 옵션을 선택하고 브라우저를 열 수 있습니다. +자주 묻는 질문 + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. 이제 모든 OpenAI 모델은 `/models` 명령을 사용할 때 사용할 수 있어야합니다. + + ```txt + /models + ``` + +##### API 키 사용 + +API 키가 이미 있다면 ** 수동으로 API 키**를 입력하고 터미널에서 붙여넣을 수 있습니다. + +--- + +## 오픈코드 젠 + +OpenCode Zen은 OpenCode 팀에서 제공하는 테스트 및 검증된 모델 목록입니다. [더 알아보기](/docs/zen). + +1. 로그인 **OpenCode Zen** and click**Create API Key**. + +2. `/connect` 명령을 실행하고 **OpenCode Zen**를 검색하십시오. + + ```txt + /connect + ``` + +3. OpenCode API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 Qwen 3 Coder 480B . + + ```txt + /models + ``` + +--- + +## 오픈로자 + +1. [OpenRouter 대시보드] (https://openrouter.ai/settings/keys)에 머리, click ** API Key**를 클릭하고 키를 복사합니다. + +2. `/connect` 명령을 실행하고 OpenRouter를 검색하십시오. + + ```txt + /connect + ``` + +3. 공급자를 위한 API 열쇠를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 많은 OpenRouter 모델은 기본적으로 `/models` 명령을 실행하여 원하는 것을 선택합니다. + + ```txt + /models + ``` + +Opencode config를 통해 추가 모델을 추가할 수 있습니다. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. 당신은 또한 당신의 opencode config를 통해 그들을 주문을 받아서 만들 수 있습니다. 공급자 지정의 예입니다. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP AI 핵심 + +SAP AI Core는 OpenAI, Anthropic, Google, Amazon, Meta, Mistral 및 AI21의 40+ 모델에 대한 액세스를 제공합니다. + +1. [SAP BTP Cockpit](https://account.hana.ondemand.com/)로 이동하여 SAP AI Core 서비스 인스턴스로 이동하고 서비스 키를 만듭니다. + + :::tip +서비스 키는 `clientid`, `clientsecret`, `url` 및 `serviceurls.AI_API_URL`를 포함하는 JSON 객체입니다. **Services** > **Instances 및 Subscriptions** 아래 AI Core 인스턴스를 찾을 수 있습니다. + ::: + +2. `/connect` 명령을 실행하고 **SAP AI Core**를 검색하십시오. + + ```txt + /connect + ``` + +3. 서비스 키 JSON을 입력하십시오. + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + +또는 `AICORE_SERVICE_KEY` 환경 변수를 설정: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + +또는 bash 프로파일에 추가: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. 선택적으로 배치 ID 및 자원 그룹: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::note +이 설정은 선택 사항이며 SAP AI Core 설정에 따라 구성해야합니다. + ::: + +5. `/models` 명령을 실행하여 40+ 유효한 모형에서 선택하십시오. + + ```txt + /models + ``` + +--- + +### OVHcloud AI 엔드포인트 + +1. [OVHcloud 패널] (https://ovh.com/manager)에 머리. `Public Cloud` 섹션으로 이동, `AI & Machine Learning` > `AI Endpoints` 및 `API Keys` 탭에서, ** 새로운 API 키 활성화 **. + +2. `/connect` 명령을 실행하고 ** OVHcloud AI Endpoints**를 검색하십시오. + + ```txt + /connect + ``` + +3. OVHcloud AI Endpoints API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 gpt-oss-120b . + + ```txt + /models + ``` + +--- + +### 스케일웨이 + +Opencode를 사용하여 [Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/)를 사용하려면: + +1. [Scaleway 콘솔 IAM 설정](https://console.scaleway.com/iam/api-keys)를 통해 새로운 API 키 생성. + +2. `/connect` 명령을 실행하고 **Scaleway**를 검색하십시오. + + ```txt + /connect + ``` + +3. Scaleway API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오. devstral-2-123b-instruct-2512 또는 gpt-oss-120b . + + ```txt + /models + ``` + +--- + +## 함께 AI + +1. [Together AI 콘솔](https://api.together.ai)에 머리, 계정을 만들고 ** 키 추가 **를 클릭합니다. + +2. `/connect` 명령을 실행하고 **Together AI**를 검색하십시오. + + ```txt + /connect + ``` + +3. 함께 AI API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 Kimi K2 Instruct . + + ```txt + /models + ``` + +--- + +## 베니스 AI + +1. [Venice AI 콘솔] (https://venice.ai)에 머리, 계정을 만들고 API 키를 생성합니다. + +2. `/connect` 명령을 실행하고 **Venice AI **를 검색하십시오. + + ```txt + /connect + ``` + +3. 베니스 AI API 열쇠를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 Llama 3.3 70B . + + ```txt + /models + ``` + +--- + +## Vercel AI 게이트웨이 + +Vercel AI를 게이트웨이는 OpenAI, Anthropic, Google, xAI 등에서 모델에 액세스할 수 있습니다. 모델은 Markup없이 목록 가격에서 제공됩니다. + +1. [Vercel 대시보드](https://vercel.com/)에 머리, **AI Gateway** 탭으로 이동하고, **API 키**를 클릭하여 새로운 API 키 생성. + +2. `/connect` 명령을 실행하고 **Vercel AI Gateway**를 검색하십시오. + + ```txt + /connect + ``` + +3. Vercel AI Gateway API 키 입력. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 모델을 선택하려면 `/models` 명령을 실행하십시오. + + ```txt + /models + ``` + +Opencode config를 통해 모델을 사용자 정의 할 수 있습니다. 공급자 routing 순서를 지정하는 예입니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +몇몇 유용한 여정 선택권: + +| 옵션 | 설명 | +| ------------------- | ---------------------------------------------------- | +| `order` | 공급자의 순서 | +| `only` | 특정 공급자 제한 | +| `zeroDataRetention` | 제로 데이터 보유 정책만 이용 가능 | + +--- + +# # # # # # # # # # # + +1. [xAI 콘솔](https://console.x.ai/)에 머리, 계정을 만들고 API 키를 생성합니다. + +2. `/connect` 명령을 실행하고 **xAI**를 검색하십시오. + + ```txt + /connect + ``` + +3. xAI API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 Grok Beta . + + ```txt + /models + ``` + +--- + +# # # # Z.AI + +1. [Z.AI API 콘솔](https://z.ai/manage-apikey/apikey-list)에 머리, 계정을 만들고, **새로운 API 키**를 클릭합니다. + +2. `/connect` 명령을 실행하고 ** Z.AI**를 검색하십시오. + + ```txt + /connect + ``` + +**GLM 코딩 플랜**에 가입하면 **Z.AI 코딩 플랜**을 선택하십시오. + +3. Z.AI API 키를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. `/models` 명령을 실행하여 같은 모델을 선택하십시오 GLM-4.7 . + + ```txt + /models + ``` + +--- + +## ZenMux를 + +1. [ZenMux 대쉬보드](https://zenmux.ai/settings/keys)에 머리, click **Create API Key**, 키 복사. + +2. `/connect` 명령을 실행하고 ZenMux를 검색하십시오. + + ```txt + /connect + ``` + +3. 공급자를 위한 API 열쇠를 입력하십시오. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 많은 ZenMux 모델은 기본적으로 사전 로드되며 `/models` 명령을 실행하여 원하는 것을 선택합니다. + + ```txt + /models + ``` + +Opencode config를 통해 추가 모델을 추가할 수 있습니다. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## 사용자 정의 공급자 + +`/connect` 명령에 나열되지 않은 **OpenAI-compatible** 공급자를 추가하려면: + +:::tip +Opencode를 사용하여 OpenAI 호환 공급자를 사용할 수 있습니다. 가장 현대적인 AI 제공 업체는 OpenAI 호환 API를 제공합니다. +::: + +1. `/connect` 명령을 실행하고 ** 다른**로 스크롤하십시오. + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. 공급자를 위한 유일한 ID를 입력하십시오. + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note +기억에 남는 ID를 선택하면 구성 파일에서 이것을 사용할 수 있습니다. + ::: + +3. 공급자를 위한 당신의 API 열쇠를 입력하십시오. + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. 프로젝트 디렉토리에 `opencode.json` 파일을 만들거나 업데이트하십시오. + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + +여기에 구성 옵션: +- **npm**: AI SDK 패키지, OpenAI 호환 공급자 `@ai-sdk/openai-compatible` +-**name**: UI의 표시 이름. +- ** 모델**: 유효한 모델. +- **options.baseURL**: API 엔드포인트 URL. +- **options.apiKey**: 선택적으로 auth를 사용하지 않는 경우 API 키 설정. +- **options.headers**: 선택적으로 사용자 정의 헤더를 설정합니다. + +아래 예에서 고급 옵션에 더. + +5. `/models` 명령을 실행하고 사용자 정의 공급자와 모델은 선택 목록에서 나타납니다. + +--- + +##### 예제 + +다음은 `apiKey`, `headers` 및 모델 `limit` 옵션 설정 예입니다. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +구성 세부 사항: + +- **apiKey**: `env` 변수 구문을 사용하여 설정, [learn more](/docs/config#env-vars). +-**headers**: 각 요청으로 전송된 사용자 정의 헤더. +- **limit.context**: 최대 입력 토큰 모델은 받아들입니다. +- **limit.output**: 최대 토큰은 모델을 생성할 수 있습니다. + +`limit` 필드를 사용하면 OpenCode가 얼마나 많은 컨텍스트를 이해 할 수 있습니다. 표준 공급자는 model.dev에서 자동적으로 당깁니다. + +--- + +## 문제 해결 + +공급자 구성에 문제가 있는 경우 다음을 확인하십시오. + +1. **주의 설정 확인 **: `opencode auth list`를 실행하여 자격 증명을 볼 수 있습니다. +공급자는 config에 추가됩니다. + +이것은 Amazon Bedrock과 같은 공급자에 적용되지 않습니다. 환경 변수에 의존합니다. + +2. 주문 공급자를 위해, opencode config를 검사하고: +- `/connect` 명령에 사용되는 공급자 ID가 opencode config에서 ID를 일치시킵니다. +- 오른쪽 npm 패키지는 공급자에 사용됩니다. 예를 들어 Cerebras의 `@ai-sdk/cerebras`를 사용합니다. 그리고 다른 모든 OpenAI 호환 공급자를 위해, 사용 `@ai-sdk/openai-compatible`. +- 올바른 API 엔드포인트는 `options.baseURL` 필드에 사용됩니다. diff --git a/packages/web/src/content/docs/ko/rules.mdx b/packages/web/src/content/docs/ko/rules.mdx new file mode 100644 index 000000000..86eced224 --- /dev/null +++ b/packages/web/src/content/docs/ko/rules.mdx @@ -0,0 +1,180 @@ +--- +title: Rules +description: Set custom instructions for opencode. +--- + +`AGENTS.md` 파일을 만들 수 있도록 오픈 코드에 사용자 정의 지침을 제공 할 수 있습니다. Cursor의 규칙과 유사합니다. LLM의 컨텍스트에 포함된 지침을 통해 특정 프로젝트에 대한 행동을 사용자 정의합니다. + +--- + +## 초기화 + +새로운 `AGENTS.md` 파일을 만들려면 `/init` 명령을 opencode에서 실행할 수 있습니다. + +:::tip +프로젝트의 `AGENTS.md` 파일을 Git에 투입해야 합니다. +::: + +프로젝트가 무엇인지 이해하고 `AGENTS.md` 파일을 생성합니다. 이 도움말 opencode는 프로젝트를 더 잘 탐색합니다. + +기존 `AGENTS.md` 파일이있는 경우이 추가하려고합니다. + +--- + +## 예 + +이 파일을 수동으로 만들 수도 있습니다. 다음은 `AGENTS.md` 파일에 넣을 수있는 것들의 예입니다. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +우리는 여기에 프로젝트 별 지침을 추가하고 이것은 팀을 통해 공유됩니다. + +--- + +## 유형 + +opencode는 또한 다수 위치에서 `AGENTS.md` 파일을 읽습니다. 그리고 이것은 다른 목적을 봉사합니다. + +## 프로젝트 + +프로젝트 별 규칙에 대한 프로젝트 루트에 `AGENTS.md`를 배치합니다. 이 디렉토리 또는 하위 디렉토리에서 작업 할 때만 적용됩니다. + +## 글로벌 + +또한 `~/.config/opencode/AGENTS.md` 파일에서 글로벌 규칙을 가질 수 있습니다. 이 모든 opencode 세션에서 적용됩니다. + +이것은 Git에 전념하지 않거나 팀과 공유하지 않기 때문에 LLM이 따르는 모든 개인 규칙을 지정하는 것이 좋습니다. + +### Claude 코드 호환성 + +Claude Code에서 마이그레이션하는 경우, OpenCode는 Claude Code의 파일 컨벤션을 fallbacks로 지원합니다. + +- ** 규칙 ** : 프로젝트 디렉토리에 `CLAUDE.md` (`AGENTS.md`가 존재하지 않는 경우 사용) +- ** 글로벌 규칙**: `~/.claude/CLAUDE.md` (`~/.config/opencode/AGENTS.md`가 존재하지 않는 경우 사용) +-**Skills**: `~/.claude/skills/` — [Agent Skills](/docs/skills/)를 참조하십시오. + +Claude Code 호환성을 비활성화하려면 이러한 환경 변수 중 하나를 설정하십시오. + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## 전신 + +opencode가 시작될 때, 이 순서에 있는 규칙 파일을 찾습니다: + +1. **Local 파일 ** 현재 디렉토리에서 추적 (`AGENTS.md`, `CLAUDE.md`) +2. ** 글로벌 파일 ** `~/.config/opencode/AGENTS.md` +3. **Claude 코드 파일 ** `~/.claude/CLAUDE.md`에서 (무효한) + +첫 번째 일치 파일은 각 범주에서 승리합니다. 예를 들어, `AGENTS.md`와 `CLAUDE.md` 모두가있는 경우 `AGENTS.md` 만 사용됩니다. 유사하게, `~/.config/opencode/AGENTS.md`는 `~/.claude/CLAUDE.md`에 전진합니다. + +--- + +## 사용자 정의 지침 + +`opencode.json` 또는 글로벌 `~/.config/opencode/opencode.json`에서 사용자 지정 명령 파일을 지정할 수 있습니다. AGENTS.md에 복제하지 않고 기존 규칙을 재사용 할 수 있습니다. + +예: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +웹에서 지침을로드하는 원격 URL도 사용할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +원격 지침은 5 초 타임 아웃으로 fetched. + +모든 명령 파일은 `AGENTS.md` 파일과 결합됩니다. + +--- + +## 외부 파일을 Referencing + +opencode가 `AGENTS.md`에 있는 자동적으로 파스 파일 참조를 하지 않는 동안, 당신은 두 가지 방법으로 유사한 기능을 달성할 수 있습니다: + +## opencode.json 사용 + +`opencode.json`의 `instructions` 필드를 사용하는 것이 좋습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +## # AGENTS.md의 수동 지침 + +`AGENTS.md`에 명시된 지침을 제공함으로써 외부 파일을 읽을 수 있습니다. 여기에 실용적인 예: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +이 접근법은 다음과 같습니다: + +- 모듈, 재사용 가능한 규칙 파일 생성 +- symlinks 또는 git submodules를 통해 프로젝트 전반에 걸쳐 규칙 공유 +- 상세한 가이드를 참조하면서 AGENTS.md concise 유지 +- 특정 작업에 필요한 경우에만 opencode 로드 파일 유지 + +:::tip +공유 표준을 가진 monorepos 또는 프로젝트를 위해, glob 본을 가진 `opencode.json`를 사용하여 (`packages/*/AGENTS.md` 같이)는 수동 지시 보다는 더 유지가능합니다. +::: diff --git a/packages/web/src/content/docs/ko/sdk.mdx b/packages/web/src/content/docs/ko/sdk.mdx new file mode 100644 index 000000000..e1a1ee77c --- /dev/null +++ b/packages/web/src/content/docs/ko/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: Type-safe JS client for opencode server. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +opencode JS/TS SDK는 서버와 상호 작용을 위한 유형 안전한 클라이언트를 제공합니다. +통합 및 제어 opencode programmatically를 구축하는 데 사용됩니다. + +[Learn more](/docs/server) 서버가 어떻게 작동하나요? 예를 들어, 커뮤니티에 의해 구축 된 [projects](/docs/ecosystem#projects)를 확인하십시오. + +--- + +## 설치 + +npm에서 SDK 설치: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## 클라이언트 만들기 + +opencode의 인스턴스 만들기: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +서버와 클라이언트 모두 시작 + +#### 옵션 + +| 옵션 | 유형 | 설명 | 기본 | +| ---------- | ------------- | ----------------------- | ----------- | +| `hostname` | `string` | 서버 호스트명 | `127.0.0.1` | +| `port` | `number` | 서버포트 | `4096` | +| `signal` | `AbortSignal` | 취소 신호 | `undefined` | +| `timeout` | `number` | 서버 시작시의 시간 아웃 | `5000` | +| `config` | `Config` | 구성 객체 | `{}` | + +--- + +## 콘피그 + +구성 객체를 전달할 수 있습니다. 인스턴스는 여전히 `opencode.json`를 선택하지만 구성 인라인을 추가 할 수 있습니다. + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## 클라이언트만 + +opencode의 실행 인스턴스가 이미 있다면 클라이언트 인스턴스를 만들 수 있습니다. + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### 옵션 + +| 옵션 | 유형 | 설명 | 기본 | +| --------------- | ---------- | --------------------------------- | ----------------------- | +| `baseUrl` | `string` | 서버의 URL | `http://localhost:4096` | +| `fetch` | `function` | 사용자 정의 fetch 구현 | `globalThis.fetch` | +| `parseAs` | `string` | 응답 파싱 방법 | `auto` | +| `responseStyle` | `string` | 반품 스타일: `data` 또는 `fields` | `fields` | +| `throwOnError` | `boolean` | 반품 시 오류 | `false` | + +--- + +## 유형 + +SDK에는 모든 API 유형의 TypeScript 정의가 포함되어 있습니다. 직접 가져 오기 : + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +모든 유형은 서버의 OpenAPI 사양에서 생성되며 types 파일에서 사용할 수 있습니다. + +--- + +## 오류 + +SDK는 잡을 수 있는 오류를 던질 수 있습니다: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## API + +SDK는 type-safe 클라이언트를 통해 모든 서버 API를 노출합니다. + +--- + +## 글로벌 + +| 방법 | 설명 | 응답 | +| ----------------- | ---------------------- | ------------------------------------ | +| `global.health()` | 서버 건강 및 버전 확인 | `{ healthy: true, version: string }` | + +--- + +#### 예제 + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### 앱 + +| 방법 | 설명 | 응답 | +| -------------- | ------------------------- | ----------------------------------------------- | +| `app.log()` | 로그 항목 작성 | `boolean` | +| `app.agents()` | 이용 가능한 모든 에이전트 | 에이전트[] | + +--- + +#### 예제 + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +## 프로젝트 + +| 방법 | 설명 | 응답 | +| ------------------- | ----------------------- | --------------------------------------------- | +| `project.list()` | 모든 프로젝트 보기 | Project[] | +| `project.current()` | 현재 프로젝트 가져 오기 | Project | + +--- + +#### 예제 + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### 경로 + +| 방법 | 설명 | 응답 | +| ------------ | ------------------- | ---------------------------------------- | +| `path.get()` | 현재 경로 가져 오기 | Path | + +--- + +#### 예제 + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +# # # # 콘피그 + +| 방법 | 설명 | 응답 | +| -------------------- | -------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` | 구성 정보 | Config | +| `config.providers()` | 목록 제공업체 및 기본 모델 | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +#### 예제 + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +## 세션 + +| 방법 | 묘사 | 주 | +| ---------------------------------------------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` | 세션 일람 | Session[] | +| `session.get({ path })` | 세션 가져 오기 | Session | +| `session.children({ path })` | 목록 어린이 세션 | 반품 Session | +| `session.create({ body })` | 세션 만들기 | 리턴 Session | +| `session.delete({ path })` | 세션 삭제 | `boolean` 반품 | +| `session.update({ path, body })` | 업데이트 세션 속성 | 반품 Session | +| `session.init({ path, body })` | Analyze 앱을 만들고 `AGENTS.md` | `boolean`를 반환 | +| `session.abort({ path })` | 운영 중인 세션 | 반품 `boolean` | +| `session.share({ path })` | 공유 세션 | 반품 Session | +| `session.unshare({ path })` | 공유 세션 | 반품 Session | +| `session.summarize({ path, body })` | 세션 요약 | 반품 `boolean` | +| `session.messages({ path })` | 세션의 메시지 목록 | `{ info: `Message`, parts: `Part`}[]` | +| `session.message({ path })` | 메시지 상세정보 | 반품 `{ info: `Message`, parts: `Part[]`}` | +| `session.prompt({ path, body })` | 신속한 메시지 보내기 | `body.noReply: true` 반환 UserMessage (콘텍스트 전용). 과태 반환 AssistantMessage 에 AI 응답 | +| `session.command({ path, body })` | 세션으로 명령을 전송 | `{ info: `AssistantMessage`, parts: `Part[]`}` | +| `session.shell({ path, body })` | 쉘 명령을 실행 | AssistantMessage | +| `session.revert({ path, body })` | 메시지 다시 변환 | Session | +| `session.unrevert({ path })` | 통일된 메시지 | 반품 Session | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | 허가 요청 대응 | 반품 `boolean` | + +--- + +#### 예제 + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +## 파일 + +| 방법 | 설명 | 응답 | +| ------------------------- | ---------------------------- | -------------------------------------------------------------------------------------- | +| `find.text({ query })` | 파일에서 텍스트 검색 | `path`, `lines`, `line_number`, `absolute_offset`, `submatches`와 일치하는 개체의 배열 | +| `find.files({ query })` | 이름의 파일 및 디렉토리 찾기 | `string[]` (경로) | +| `find.symbols({ query })` | 업무 공간 기호 찾기 | Symbol | +| `file.read({ query })` | 파일 보기 | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | 트랙 된 파일 상태를 확인 | 파일[] | + +`find.files`는 몇몇 선택적인 조회 분야를 지원합니다: + +- `type`: `"file"` 또는 `"directory"` +- `directory`: 검색에 대한 프로젝트 루트를 override +- `limit`: 최대 결과 (1-200) + +--- + +#### 예제 + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +# # # # TUI + +| 방법 | 설명 | 응답 | +| ------------------------------ | ------------------------ | --------- | +| `tui.appendPrompt({ body })` | 프롬프트에 텍스트를 부여 | `boolean` | +| `tui.openHelp()` | 도움말 열기 | `boolean` | +| `tui.openSessions()` | 세션 선택 안내 | `boolean` | +| `tui.openThemes()` | 테마 선택 해제 | `boolean` | +| `tui.openModels()` | 모델 선택 안내 | `boolean` | +| `tui.submitPrompt()` | 현재 프롬프트 제출 | `boolean` | +| `tui.clearPrompt()` | 프롬프트 클리어 | `boolean` | +| `tui.executeCommand({ body })` | 명령어 실행 | `boolean` | +| `tui.showToast({ body })` | 쇼 토스트 알림 | `boolean` | + +--- + +#### 예제 + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +# # # # # 가을 + +| 방법 | 설명 | 응답 | +| ------------------- | -------------- | --------- | +| `auth.set({ ... })` | 인증 자격 증명 | `boolean` | + +--- + +#### 예제 + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +## 이벤트 + +| 방법 | 설명 | 응답 | +| ------------------- | ----------------------- | ----------------------- | +| `event.subscribe()` | 서버-sent 이벤트 스트림 | 서버-sent 이벤트 스트림 | + +--- + +#### 예제 + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/ko/server.mdx b/packages/web/src/content/docs/ko/server.mdx new file mode 100644 index 000000000..f91cc0888 --- /dev/null +++ b/packages/web/src/content/docs/ko/server.mdx @@ -0,0 +1,287 @@ +--- +title: Server +description: Interact with opencode server over HTTP. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +`opencode serve` 명령은 opencode 클라이언트가 사용할 수 있는 OpenAPI 엔드포인트를 노출하는 headless HTTP 서버를 실행합니다. + +--- + +### 사용법 + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### 옵션 + +| 플래그 | 설명 | 기본 | +| --------------- | ------------------------------------------ | ---------------- | ------ | +| `--port` | 시포트 | `4096` | +| `--hostname` | 듣고 싶은 이름 | `127.0.0.1` | +| `--mdns` | 보이지 않는 mDNS 발견 | `false` | +| `--mdns-domain` | mDNS 서비스에 대한 사용자 정의 도메인 이름 | `opencode.local` | +| `--cors` | `[]` | `[]` | 한국어 | + +`--cors`는 다수 시간을 통과될 수 있습니다: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### 인증 + +`OPENCODE_SERVER_PASSWORD`를 설정하여 서버를 HTTP Basic auth로 보호합니다. `opencode` 또는 `OPENCODE_SERVER_USERNAME`를 오버라이드로 설정하는 사용자의 기본값. 이것은 `opencode serve`와 `opencode web` 둘 다에 적용합니다. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### 어떻게 작동합니까? + +`opencode`를 실행하면 TUI와 서버를 시작합니다. TUI는 어디에 있습니까? +서버와 대화하는 클라이언트. 서버는 OpenAPI 3.1 spec을 노출 +끝점. 이 엔드포인트는 [SDK](/docs/sdk)을 생성하는 데도 사용됩니다. + +:::tip +opencode 서버를 사용하여 opencode programmatically와 상호 작용합니다. +::: + +이 아키텍처는 opencode 지원 여러 클라이언트를 허용하고 opencode programmatically와 상호 작용 할 수 있습니다. + +독립 서버를 시작하려면 `opencode serve`를 실행할 수 있습니다. 당신이 있는 경우에 +오픈 코드 TUI 실행, `opencode serve` 새로운 서버를 시작합니다. + +--- + +#### 기존 서버에 연결 + +TUI를 시작하면 무작위로 포트와 호스트 이름을 할당합니다. 대신 `--hostname`와 `--port` [flags](/docs/cli)에서 전달할 수 있습니다. 그런 다음 서버에 연결하십시오. + +[`/tui`](#tui) 엔드포인트는 서버를 통해 TUI를 구동하는 데 사용될 수 있습니다. 예를 들어 미리 작성하거나 프롬프트를 실행할 수 있습니다. 이 설정은 OpenCode [IDE](/docs/ide) 플러그인에 의해 사용됩니다. + +--- + +## 사양 + +서버는 OpenAPI 3.1 spec을 게시합니다. + +``` +http://:/doc +``` + +예를 들어, `http://localhost:4096/doc`. 클라이언트를 생성하거나 요청 및 응답 유형을 검사하는 spec를 사용하십시오. 또는 Swagger 탐험가에서 볼 수 있습니다. + +--- + +## API + +opencode 서버는 다음과 같은 API를 노출합니다. + +--- + +## 글로벌 + +| 방법 | 경로 | 설명 | 응답 | +| ----- | ---------------- | ------------------------- | ------------------------------------ | +| `GET` | `/global/health` | 서버 건강 및 버전 | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | 글로벌 이벤트(SSE 스트림) | 이벤트 스트림 | + +--- + +## 프로젝트 + +| 방법 | 경로 | 설명 | 응답 | +| ----- | ------------------ | ----------------------- | --------------------------------------------- | +| `GET` | `/project` | 모든 프로젝트 보기 | Project[] | +| `GET` | `/project/current` | 현재 프로젝트 가져 오기 | 프로젝트 | + +--- + +### 경로 & VCS + +| 방법 | 경로 | 설명 | 응답 | +| ----- | ------- | ----------------------------- | ------------------------------------------- | +| `GET` | `/path` | 현재 경로 받기 | Path | +| `GET` | `/vcs` | 현재 프로젝트의 VCS 정보 받기 | VcsInfo | + +--- + +### 인스턴스 + +| 방법 | 경로 | 설명 | 응답 | +| ------ | ------------------- | -------------------- | --------- | +| `POST` | `/instance/dispose` | 현재 인스턴스를 해제 | `boolean` | + +--- + +### 콘피그 + +| 방법 | 경로 | 설명 | 응답 | +| ------- | ------------------- | -------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` | 구성정보 | Config | +| `PATCH` | `/config` | 업데이트 구성 | Config | +| `GET` | `/config/providers` | 목록 제공업체 및 기본 모델 | `{ providers: ` 사이트 맵`, default: { [key: string]: string } }` | + +--- + +## 공급자 + +| 방법 | 경로 | 설명 | 응답 | +| ------ | -------------------------------- | --------------------------- | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` | 모든 공급자 목록 | `{ all: `Provider[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | 공급자 인증 메서드 가져오기 | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | OAuth를 사용한 공급자 허가 | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | 공급자를 위한 OAuth 콜백 | `boolean` | + +--- + +## 세션 + +| 방법 | 경로 | 설명 | 주 | +| -------- | ---------------------------------------- | ---------------------------------- | ----------------------------------------------------------------------------- | +| `GET` | `/session` | 모든 세션 일람표 | 반환 Session[] | +| `POST` | `/session` | 새 세션 만들기 | 몸: `{ parentID?, title? }`, 반환 Session | +| `GET` | `/session/status` | 모든 세션의 세션 상태를 가져옵니다 | `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | 세션 상세보기 | 반품 Session | +| `DELETE` | `/session/:id` | 세션 삭제 및 모든 데이터 | `boolean` | +| `PATCH` | `/session/:id` | 업데이트 세션 속성 | 본체: `{ title? }`, 반환 Session | +| `GET` | `/session/:id/children` | 세션의 어린이 세션 | 리턴 Session[] | +| `GET` | `/session/:id/todo` | 세션별 도우미 목록 받기 | Todo[] | +| `POST` | `/session/:id/init` | 분석 응용 프로그램 및 `AGENTS.md` | 몸: `{ messageID, providerID, modelID }`, 반환 `boolean` | +| `POST` | `/session/:id/fork` | 메시지의 기존 세션 | 몸: `{ messageID? }`, 반환 Session | +| `POST` | `/session/:id/abort` | 운영 중인 세션 | 반품 `boolean` | +| `POST` | `/session/:id/share` | 세션 공유 | Session | +| `DELETE` | `/session/:id/share` | 세션 공유 | Session | +| `GET` | `/session/:id/diff` | `/session/:id/diff` | `messageID?`, 반환 FileDiff[] | +| `POST` | `/session/:id/summarize` | 세션을 요약 | 본체: `{ providerID, modelID }`, `boolean` 반환 | +| `POST` | `/session/:id/revert` | 메시지 재생 | 몸: `{ messageID, partID? }`, 반환 `boolean` | +| `POST` | `/session/:id/unrevert` | 통일된 모든 메시지 | 반품 `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | 허가 요청 대응 | 본체: `{ response, remember? }`, `boolean` | + +--- + +## 메시지 + +| 방법 | 경로 | 설명 | 주 | +| ------ | --------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` | 세션의 목록 메시지 | 쿼리: `limit?`, `{ info: `Message`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` | 응답을 위해 메시지를 보내고 기다립니다 | 몸: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, 반환 `{ info: `Message`, parts: `Part[]`}` | +| `GET` | `/session/:id/message/:messageID` | 메시지 보내기 | `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/prompt_async` | 비동기적으로 메시지 보내기 | 몸: `/session/:id/message`와 동일, `204 No Content`를 반환 | +| `POST` | `/session/:id/command` | 슬래시 명령어 실행 | 본체: `{ messageID?, agent?, model?, command, arguments }`, 반환 `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/shell` | 쉘 명령 실행 | 체: `{ agent, model?, command }`, 반환 `{ info: `Message`, parts: `Part[]`}` | + +--- + +## 명령 + +| 방법 | 경로 | 설명 | 응답 | +| ----- | ---------- | --------- | --------------------------------------------- | +| `GET` | `/command` | 모든 명령 | Command[] | + +--- + +## 파일 + +| 방법 | 경로 | 설명 | 응답 | +| ----- | ------------------------ | ------------------------------------- | -------------------------------------------------------------------------------------- | ---------- | +| `GET` | `/find?pattern=` | 파일의 텍스트 검색 | `path`, `lines`, `line_number`, `absolute_offset`, `submatches`와 일치하는 개체의 배열 | +| `GET` | `/find/file?query=` | `string[]` | `string[]` | `string[]` | +| `GET` | `/find/symbol?query=` | 업무공간 기호 찾기 | Symbol[] | +| `GET` | `/file?path=` | 파일 목록 및 디렉토리 | FileNode[] | +| `GET` | `/file/content?path=

` | 파일 보기 | FileContent | +| `GET` | `/file/status` | 트랙 된 파일에 대한 상태를 얻으십시오 | 파일[] | + +#### `/find/file` 쿼리 매개 변수 + +- `query` (required) - 검색 문자열 (fuzzy 일치) +- `type` (선택 사항) - `"file"` 또는 `"directory"`에 제한 결과 +- `directory` (선택 사항) - 검색에 대한 프로젝트 루트를 무시 +- (선택) `limit` - 최대 결과 (1-200) +- `dirs` (옵션) - 레거시 플래그 (`"false"`는 파일만 반환) + +--- + +## 도구 (실험) + +| 방법 | 경로 | 설명 | 응답 | +| ----- | ------------------------------------------- | ----------------------- | --------------------------------------------- | +| `GET` | `/experimental/tool/ids` | 모든 도구 ID | 도구 | +| `GET` | `/experimental/tool?provider=

&model=` | 모델용 JSON 스키마 목록 | 도구 목록 | + +--- + +### LSP의 체재자 & MCP + +| 방법 | 경로 | 설명 | 응답 | +| ------ | ------------ | ---------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | LSP 서버 상태 | LSPStatus[] | +| `GET` | `/formatter` | 형식의 상태를 확인 | FormatterStatus[] | +| `GET` | `/mcp` | MCP 서버 상태를 얻는다 | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | MCP 서버가 동적 | 본체: `{ name, config }`, MCP 상태 객체를 반환 | + +--- + +## 에이전트 + +| 방법 | 경로 | 설명 | 응답 | +| ----- | -------- | ------------------------- | ----------------------------------------------- | +| `GET` | `/agent` | 이용 가능한 모든 에이전트 | 에이전트[] | + +--- + +### 로깅 + +| 방법 | 경로 | 설명 | 응답 | +| ------ | ------ | ----------------------------------------------------- | --------- | +| `POST` | `/log` | 로그 입력 바디: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| 방법 | 경로 | 설명 | 응답 | +| ------ | ----------------------- | ----------------------------------------- | -------------- | +| `POST` | `/tui/append-prompt` | 프롬프트에 텍스트를 부여 | `boolean` | +| `POST` | `/tui/open-help` | 도움말 대화 열기 | `boolean` | +| `POST` | `/tui/open-sessions` | 세션 선택 안내 | `boolean` | +| `POST` | `/tui/open-themes` | 테마 선택 안내 | `boolean` | +| `POST` | `/tui/open-models` | 모델 선택 안내 | `boolean` | +| `POST` | `/tui/submit-prompt` | 현재 프롬프트 제출 | `boolean` | +| `POST` | `/tui/clear-prompt` | 시프트 클리어 | `boolean` | +| `POST` | `/tui/execute-command` | 명령어 실행(`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | 쇼 토스트(`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | 다음 컨트롤 요청 시 기다리고 | 제어 요청 개체 | +| `POST` | `/tui/control/response` | 통제 요청(`{ body }`) 대응 | `boolean` | + +--- + +### 인증 + +| 방법 | 경로 | 설명 | 응답 | +| ----- | ----------- | --------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | 인증 자격 증명 몸은 공급자 스키마를 일치해야 합니다 | `boolean` | + +--- + +## 이벤트 + +| 방법 | 경로 | 설명 | 응답 | +| ----- | -------- | ------------------------------------------------------------------------------- | ------------------------ | +| `GET` | `/event` | 서버 침묵 이벤트 스트림. 첫 번째 이벤트는 `server.connected`, 그 후 버스 이벤트 | Server-sent event stream | + +--- + +### 문서 + +| 방법 | 경로 | 설명 | 응답 | +| ----- | ------ | ---------------- | ------------------------ | +| `GET` | `/doc` | OpenAPI 3.1 사양 | HTML 페이지 OpenAPI 사양 | diff --git a/packages/web/src/content/docs/ko/share.mdx b/packages/web/src/content/docs/ko/share.mdx new file mode 100644 index 000000000..99f4f74a8 --- /dev/null +++ b/packages/web/src/content/docs/ko/share.mdx @@ -0,0 +1,128 @@ +--- +title: Share +description: Share your OpenCode conversations. +--- + +OpenCode의 공유 기능은 OpenCode 대화에 대한 공개 링크를 만들 수 있으므로 Teammates와 협업하거나 다른 곳에서 도움을받을 수 있습니다. + +:::note +공유 대화는 링크를 통해 누구나 쉽게 접근할 수 있습니다. +::: + +--- + +## 어떻게 작동합니까? + +대화를 공유할 때, OpenCode: + +1. 세션에 대한 독특한 공개 URL 만들기 +2. 우리의 서버에 대화 기록 동기화 +3. 공유 가능한 링크를 통해 접근 할 수있는 대화 만들기 — `opncd.ai/s/` + +--- + +## 공유 + +OpenCode는 대화가 공유되는 방법을 제어하는 세 가지 공유 모드를 지원합니다. + +--- + +## 수동 (과태) + +기본적으로 OpenCode는 수동 공유 모드를 사용합니다. 세션은 자동으로 공유되지 않지만 `/share` 명령을 사용하여 수동으로 공유 할 수 있습니다. + +``` +/share +``` + +클립보드에 복사할 수 있는 독특한 URL을 생성합니다. + +[config 파일](/docs/config)에서 수동 모드를 명시적으로 설정하려면: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +## 자동차 공유 + +`share` 옵션을 설정하여 모든 새로운 대화에 대한 자동 공유를 활성화 할 수 있습니다 `"auto"` 당신의 [config 파일](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +자동 공유 활성화로 모든 새로운 대화는 자동으로 공유되고 링크가 생성됩니다. + +--- + +# # # # 비활성화 + +`share` 옵션을 설정하여 완전히 공유할 수 있습니다. `"disabled"`에 [config file](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +주어진 프로젝트를 위해 팀 전반에 걸쳐 이것을 시행하려면 프로젝트에 `opencode.json`에 추가하고 Git로 확인하십시오. + +--- + +## 비 쉐링 + +대화를 중지하고 공공 액세스에서 제거 : + +``` +/unshare +``` + +이 공유 링크를 제거하고 대화와 관련된 데이터를 삭제합니다. + +--- + +## 개인 정보 + +대화를 나누면 마음이 유지되는 몇 가지가 있습니다. + +--- + +## 데이터 보유 + +공유 대화는 명시적으로 그들을 공유 할 때까지 접근 할 수 있습니다. 이름 * +다음: + +- 전체 대화 기록 +- 모든 메시지 및 응답 +- 세션 메타데이터 + +--- + +### 추천 + +- 민감한 정보를 포함하지 않는 대화 만 공유합니다. +- 공유하기 전에 대화 내용을 검토하십시오. +- 협업이 완료되면 Unshare 대화. +- 독점 코드 또는 기밀 데이터와 대화를 공유하지 마십시오. +- 민감한 프로젝트를 위해, 완전히 공유할 수 있습니다. + +--- + +## 기업용 + +기업 배포를 위해, 공유 기능은: + +- ** 보안 준수를 위해 완전히 비활성화 ** +- **SSO를 통해 인증된 사용자에 대한 제한 ** +- ** 자체 인프라 ** + +[Learn more](/docs/enterprise) 귀하의 조직에서 opencode를 사용하여. diff --git a/packages/web/src/content/docs/ko/skills.mdx b/packages/web/src/content/docs/ko/skills.mdx new file mode 100644 index 000000000..5b84684e0 --- /dev/null +++ b/packages/web/src/content/docs/ko/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "Agent Skills" +description: "Define reusable behavior via SKILL.md definitions" +--- + +Agent Skill let OpenCode discover reusable instruction from your repo 또는 홈 디렉토리. +Skills are loaded on-demand via native `skill` tool-agents see available skills and can loaded full content when needed. + +--- + +## 파일 장소 + +기술 이름 당 하나의 폴더를 만들고 내부 `SKILL.md`를 넣어. +OpenCode 이 위치를 검색: + +- 프로젝트 구성: `.opencode/skills//SKILL.md` +- 글로벌 구성: `~/.config/opencode/skills//SKILL.md` +- 프로젝트 클로드 호환 : `.claude/skills//SKILL.md` +- 글로벌 클로드 호환 : `~/.claude/skills//SKILL.md` +- 프로젝트 에이전트 호환 : `.agents/skills//SKILL.md` +- 글로벌 에이전트 호환 : `~/.agents/skills//SKILL.md` + +--- + +## 발견의 이해 + +Project-local paths의 경우, OpenCode는 git worktree에 도달 할 때까지 현재 작업 디렉토리에서 걷습니다. +그것은 `.opencode/`에 있는 어떤 어울리는 `skills/*/SKILL.md` 및 어떤 어울리는 `.claude/skills/*/SKILL.md` 또는 `.agents/skills/*/SKILL.md`를 방법 적재합니다. + +세계적인 정의는 또한 `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` 및 `~/.agents/skills/*/SKILL.md`에서 적재됩니다. + +--- + +## 쓰기 frontmatter + +각 `SKILL.md`는 YAML frontmatter로 시작해야 합니다. +이 필드는 인식됩니다: + +- `name` (필수) +- `description` (필수) +- (선택) `license` +- (선택) `compatibility` +- `metadata` (선택 사항, 문자열에 문자열 맵) + +알려진 frontmatter 필드는 무시됩니다. + +--- + +## 유효 이름 + +`name`는 해야 합니다: + +- 1–64자 +- 단 하나 hyphen 분리기를 가진 더 낮은 케이스 alphanumeric가 있으십시오 +- `-`로 시작 또는 끝 아닙니다 +- 연속 `--` 포함하지 +- `SKILL.md`를 포함하는 디렉토리 이름을 일치 + +동등한 regex: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## 길이 규칙을 따르십시오 + +`description`는 1-1024 특성이어야 합니다. +제대로 선택하기 위해 에이전트에 대해 충분히 유지하십시오. + +--- + +## 예제 사용 + +이처럼 `.opencode/skills/git-release/SKILL.md` 만들기: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## 인식 도구 설명 + +OpenCode는 `skill` 도구 설명에서 사용할 수있는 기술을 나열합니다. +각 항목에는 기술 이름 및 설명이 포함됩니다. + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +에이전트는 도구를 호출하여 기술을로드 : + +``` +skill({ name: "git-release" }) +``` + +--- + +## 권한 구성 + +기술 에이전트가 `opencode.json`의 패턴 기반 권한을 사용하여 액세스 할 수있는 제어 : + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| 허가 | 행동 | 행동 | +| ---------- | ----------------------------------------- | +| `allow` | 기술 로드 즉시 | +| `deny` | 에이전트에서 숨겨진 기술, 액세스 거부 | +| `ask` | 사용자가 적재하기 전에 승인되었습니다 | + +패턴 지원 와일드 카드: `internal-*` 경기 `internal-docs`, `internal-tools`, 등. + +--- + +## 에이전트 당 override + +글로벌 디폴트보다 특정 에이전트 다른 권한을 부여합니다. + +**사용자 지정 에이전트 ** ( 에이전트 frontmatter): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +** 내장 에이전트 ** (`opencode.json`에서): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## 기술 도구 비활성화 + +그들을 사용하지 않는 대리인을위한 완전히 비활성화 된 기술 : + +**사용자 지정 에이전트**: + +```yaml +--- +tools: + skill: false +--- +``` + +** 내장 에이전트 **: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +비활성화 할 때, `` 섹션은 완전히 부유합니다. + +--- + +## 문제 해결 선적 + +기술이 나타나지 않는 경우: + +1. `SKILL.md`는 모든 모자에서 spelled +2. `name`와 `description`를 포함하는 검사 +3. 기술 이름은 모든 위치에서 독특합니다. +4. `deny`를 가진 허가를 검사하십시오 대리인에서 숨겨집니다 diff --git a/packages/web/src/content/docs/ko/themes.mdx b/packages/web/src/content/docs/ko/themes.mdx new file mode 100644 index 000000000..6dc5cd257 --- /dev/null +++ b/packages/web/src/content/docs/ko/themes.mdx @@ -0,0 +1,369 @@ +--- +title: Themes +description: Select a built-in theme or define your own. +--- + +OpenCode를 사용하면 여러 내장 테마 중 하나에서 선택할 수 있으며 터미널 테마에 적응하는 테마를 사용하거나 사용자 정의 테마를 정의 할 수 있습니다. + +기본적으로 OpenCode는 자체 `opencode` 테마를 사용합니다. + +--- + +## 끝 필요조건 + +자신의 풀 컬러 팔레트로 올바르게 표시하려면 터미널을 지원해야합니다 ** truecolor** (24 비트 색상). 대부분의 현대 맨끝은 기본적으로 이것을 지원합니다, 그러나 당신은 그것을 가능하게 할 필요가 있을지도 모릅니다: + +-**체크 지원**: `echo $COLORTERM` - 그것은 `truecolor` 또는 `24bit`를 출력해야 합니다 +- ** truecolor 사용 가능**: 쉘 프로파일에서 환경 변수 `COLORTERM=truecolor`를 설정 +- **Terminal 호환성 **: 터미널 에뮬레이터 지원 24 비트 색상 (iTerm2, Alacritty, Kitty, Windows Terminal 및 GNOME Terminal의 최신 버전) + +truecolor 지원 없이, 테마는 감소된 색깔 정확도로 나타날지도 모릅니다 또는 가장 가까운 256 색깔 대류로 뒤떨어질지도 모릅니다. + +--- + +## 내장 테마 + +OpenCode는 여러 내장 테마와 함께 제공됩니다. + +| 이름 | 설명 | +| ---------------------- | ---------------------------------------------------------------------------- | +| `system` | 단말기의 배경 색상에 적응 | +| `tokyonight` | 【도쿄의 밤】(https://github.com/folke/tokyonight.nvim) 테마 | +| `everforest` | [Everforest]에 근거|(https://github.com/sainnhe/everforest) 테마| +| `ayu` | 【Ayu】(https://github.com/ayu-theme) 다크 테마 | +| `catppuccin` | [Catppuccin](https://github.com/catppuccin) 테마에 따라 다름 | +| `catppuccin-macchiato` | [Catppuccin](https://github.com/catppuccin) 테마에 따라 다름 | +| `gruvbox` | [Gruvbox]에 근거|(https://github.com/morhetz/gruvbox) 테마| +| `kanagawa` | 가나가와현에 기반을 두고 있습니다(https://github.com/rebelot/kanagawa.nvim) 테마 | +| `nord` | [Nord](https://github.com/nordtheme/nord) 테마에 근거| +| `matrix` | 블랙 테마의 해커 스타일 그린 | +| `one-dark` | [Atom One]을 기반으로 합니다(https://github.com/Th3Whit3Wolf/one-nvim) 다크 테마 | + +그리고 더, 우리는 끊임없이 새로운 테마를 추가하고 있습니다. + +--- + +## 시스템 테마 + +`system` 테마는 맨끝의 색깔 계획에 자동적으로 적응시키기 위하여 디자인됩니다. 고정 색상을 사용하는 전통적인 테마와 달리, system 테마: + +- ** 회색 가늠자 **: 터미널의 배경 색상을 기반으로 사용자 정의 회색 가늠자를 만들고 최적의 대조를 보장합니다. +- ** ANSI 색상 사용 ** : 터미널의 색상 팔레트를 존중하는 구문 강조 및 UI 요소에 대한 표준 ANSI 색상 (0-15). +- ** 터미널 기본 사항**: `none` 텍스트 및 배경 색상을 사용하여 터미널의 네이티브 외관을 유지합니다. + +시스템 테마는 사용자를위한 것입니다 : + +- OpenCode가 터미널의 외관과 일치해야 합니다. +- 사용자 정의 터미널 색상 구성 +- 모든 터미널 응용 분야의 일관된 모습 + +--- + +## 테마 사용 + +테마를 `/theme` 명령어로 선택하여 테마를 선택할 수 있습니다. 또는 [config](/docs/config)에서 지정할 수 있습니다. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## 사용자 정의 테마 + +OpenCode는 사용자가 쉽게 테마를 만들 수 있도록 유연한 JSON 기반 테마 시스템을 지원합니다. + +--- + +# # # # # Hierarchy의 + +테마는 다음과 같은 순서에서 여러 디렉토리에서로드됩니다. 나중에 감독은 이전 것을 무시합니다. + +1.**Built-in themes** - 이것은 바이너리에 내장되어 있습니다. +2. **사용자 설정 디렉토리 ** - `~/.config/opencode/themes/*.json` 또는 `$XDG_CONFIG_HOME/opencode/themes/*.json`에서 정의 +3. ** 루트 디렉토리 ** - `/.opencode/themes/*.json`에서 정의 +4. **현재 작업 디렉토리 ** - `./.opencode/themes/*.json`에서 정의 + +여러 디렉토리가 같은 이름을 가진 테마를 포함한다면, 더 높은 우선 순위를 가진 디렉토리의 테마가 사용됩니다. + +--- + +### 테마 만들기 + +사용자 정의 테마를 만들려면 테마 디렉토리 중 하나에서 JSON 파일을 만듭니다. + +사용자 넓은 테마: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +프로젝트 별 테마. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON 형식 + +테마는 유연한 JSON 형식을 사용하여 지원: + +-**Hex 색상**: `"#ffffff"` +- ** ANSI 색상**: `3` (0-255) +- ** 색상 참조 ** : `"primary"` 또는 사용자 정의 정의 +- ** 어두운 / 조명 변형 ** : `{"dark": "#000", "light": "#fff"}` +- ** 색상 없음 ** : `"none"` - 터미널의 기본 색상 또는 투명 사용 + +--- + +### 색상 정의 + +`defs` 단면도는 선택적이고 당신은 주제에서 참조될 수 있는 재사용할 수 있는 색깔을 정의할 수 있습니다. + +--- + +## 터미널 기본값 + +특별한 가치 `"none"`는 맨끝의 기본 색깔을 상속하기 위하여 어떤 색깔든지를 위해 사용될 수 있습니다. 이것은 특히 당신의 맨끝의 색깔 계획과 이음새가 없는 혼합 테마 창조를 위해 유용합니다: + +- `"text": "none"` - 터미널의 기본 전경 색상 사용 +- `"background": "none"` - 터미널의 기본 배경 색상 사용 + +--- + +### 예제 + +사용자 정의 테마의 예입니다 : + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/ko/tools.mdx b/packages/web/src/content/docs/ko/tools.mdx new file mode 100644 index 000000000..339981272 --- /dev/null +++ b/packages/web/src/content/docs/ko/tools.mdx @@ -0,0 +1,379 @@ +--- +title: Tools +description: Manage the tools an LLM can use. +--- + +도구는 LLM을 사용하여 코드베이스에서 작업을 수행 할 수 있습니다. OpenCode는 내장 도구 세트로 제공되지만, [custom tools](/docs/custom-tools) 또는 [MCP 서버](/docs/mcp-servers)로 확장할 수 있습니다. + +기본적으로 모든 도구는**enabled**이며, 실행할 권한이 없습니다. [permissions](/docs/permissions)를 통해 공구 동작을 제어할 수 있습니다. + +--- + +## 구성 + +`permission` 필드를 사용하여 도구 동작을 제어합니다. 각 도구에 대한 승인이 필요할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +한 번에 여러 도구를 제어 할 와일드 카드를 사용할 수 있습니다. 예를 들어, MCP 서버의 모든 도구에 대한 승인을 요구합니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[Learn more](/docs/permissions) configuring 권한에 대해. + +--- + +## 내장 + +다음은 OpenCode에서 사용할 수있는 모든 내장 도구입니다. + +--- + +# # # # # # bash + +프로젝트 환경에서 쉘 명령을 실행합니다. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +이 도구는 `npm install`, `git status` 또는 다른 쉘 명령과 같은 터미널 명령을 실행하는 LLM을 허용합니다. + +--- + +### 편집 + +정확한 문자열 교체를 사용하여 기존 파일을 수정합니다. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +이 도구는 정확한 텍스트 일치를 대체하여 파일에 정확한 편집을 수행합니다. LLM은 코드를 modify하는 1 차적인 방법입니다. + +--- + +### 쓰기 + +새로운 파일을 만들거나 기존의 것을 덮어쓰기. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +LLM을 사용하여 새 파일을 만듭니다. 이미 존재하는 경우 기존 파일을 덮어쓰겠습니다. + +:::note +`write` 공구는 모든 파일 수정 (`edit`, `write`, `patch`, `multiedit`)를 포함하는 `edit` 허가에 의해 통제됩니다. +::: + +--- + +### 읽기 + +codebase에서 파일 내용을 읽으십시오. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +이 도구는 파일을 읽고 내용을 반환합니다. 큰 파일에 대한 특정 라인 범위를 읽을 수 있습니다. + +--- + +# # # # 그라프 + +정규 표현식을 사용하여 파일 내용을 검색합니다. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Codebase에서 빠른 콘텐츠 검색. 전체 regex 문법 및 파일 패턴 필터링 지원. + +--- + +# # # # glob + +패턴 매칭으로 파일 찾기. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +`**/*.js` 또는 `src/**/*.ts`와 같은 glob 패턴을 사용하여 파일 검색. 수정 시간에 의해 정렬 된 파일 경로 반환. + +--- + +### 리스트 + +주어진 경로의 파일 및 디렉토리 목록. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +이 도구는 디렉토리 내용을 나열합니다. 그것은 glob 패턴을 필터 결과에 받아들입니다. + +--- + +### lsp (실험) + +정의, 참고, hover info 및 호출 hierarchy와 같은 코드 인텔리전스 기능을 얻기 위해 구성 된 LSP 서버와 인터랙트. + +:::note +이 도구는 `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (또는 `OPENCODE_EXPERIMENTAL=true`) 때만 유효합니다. +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +지원된 가동은 `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` 및 `outgoingCalls`를 포함합니다. + +LSP 서버가 프로젝트에 사용할 수 있는 구성하려면 [LSP Servers](/docs/lsp)를 참조하십시오. + +--- + +## 패치 + +파일에 패치를 적용합니다. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +이 도구는 코드베이스에 패치 파일을 적용합니다. 다양한 소스에서 diffs 및 Patch를 적용하는 데 유용합니다. + +:::note +`patch` 공구는 모든 파일 수정 (`edit`, `write`, `patch`, `multiedit`)를 포함하는 `edit` 허가에 의해 통제됩니다. +::: + +--- + +### 기술 + +[skill](/docs/skills) (`SKILL.md` 파일)을로드하고 대화의 내용을 반환합니다. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +## todowrite에 + +코딩 세션 중에 todo 목록을 관리합니다. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +복잡한 작업 중에 진행 상황을 추적하기 위해 작업 목록을 만들고 업데이트합니다. LLM은 멀티 단계 작업을 구성하기 위해 이것을 사용합니다. + +:::note +이 도구는 기본으로 시약을 비활성화하지만 수동으로 활성화 할 수 있습니다. [더 알아보기](/docs/agents/#permissions) +::: + +--- + +# # # # todoread + +기존의 todo 목록 읽기. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +현재 todo 목록 상태를 읽습니다. 작업이 종료되거나 완료되는 것을 추적하기 위해 LLM에 의해 사용됩니다. + +:::note +이 도구는 기본으로 시약을 비활성화하지만 수동으로 활성화 할 수 있습니다. [더 알아보기](/docs/agents/#permissions) +::: + +--- + +# # # # 웹 사이트 + +Fetch 웹 콘텐츠. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +LLM을 fetch 및 웹 페이지를 읽을 수 있습니다. 온라인 리소스를 찾는 데 도움이 되는 문서 또는 연구 + +--- + +# # # # 웹 검색 + +웹 검색 + +:::note +이 도구는 OpenCode 제공 업체 또는 `OPENCODE_ENABLE_EXA` 환경 변수가 모든 진실 값 (예 : `true` 또는 `1`)로 설정할 때만 사용할 수 있습니다. + +OpenCode를 실행할 때 활성화: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Exa AI를 사용하여 웹 검색을 수행하여 관련 정보를 온라인으로 찾으십시오. 연구 주제에 유용한, 현재 이벤트를 찾는, 또는 훈련 데이터 차단을 넘어 정보를 수집. + +API 키가 필요하지 않습니다 - 도구는 인증없이 Exa AI의 호스팅 MCP 서비스에 직접 연결됩니다. + +:::tip +`websearch`를 사용하면 특정 URL (retrieval)에서 콘텐츠를 검색해야합니다. +::: + +--- + +### 질문 + +실행 중에 사용자의 질문 요청. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +이 도구는 작업 중에 LLM을 요청할 수 있습니다. 그것은 유용합니다: + +- 사용자 선호도 또는 요구 사항 변경 +- 주위 지침 +- 구현 선택에 대한 결정 +- 어떤 방향에 대한 선택 제공 + +각 질문에는 헤더, 질문 텍스트 및 옵션 목록이 포함되어 있습니다. 사용자는 제공된 선택권에서 선택하거나 주문 대답을 타자를 수 있습니다. 여러 질문이 있을 때, 사용자는 모든 답변을 제출하기 전에 그들 사이에서 탐색 할 수 있습니다. + +--- + +## 사용자 정의 도구 + +사용자 정의 도구는 LLM이 호출 할 수있는 자신의 기능을 정의 할 수 있습니다. config 파일에 정의되어 arbitrary 코드를 실행할 수 있습니다. + +[Learn more](/docs/custom-tools) 사용자 정의 도구 만들기. + +--- + +## MCP 서버 + +MCP(Model Context Protocol) 서버는 외부 도구와 서비스를 통합할 수 있습니다. 이 데이터베이스 액세스, API 통합 및 타사 서비스가 포함되어 있습니다. + +MCP 서버 구성에 대한 [Learn more](/docs/mcp-servers). + +--- + +## 내부 + +내부, 도구 `grep`, `glob`, 그리고 `list` 사용 [ripgrep](https://github.com/BurntSushi/ripgrep) 후드 아래에. 기본적으로 ripgrep은 `.gitignore` 패턴을 존중하며 `.gitignore`에 나열된 파일 및 디렉토리를 검색 및 목록에서 제외됩니다. + +--- + +# # # # Ignore 패턴 + +일반적으로 무시되는 파일을 포함하려면 프로젝트 루트에 `.ignore` 파일을 만듭니다. 이 파일은 명시적으로 특정 경로를 허용 할 수 있습니다. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +예를 들어,이 `.ignore` 파일은 `node_modules/`, `dist/` 및 `build/` 디렉토리 내에서 검색 할 수 있습니다. `.gitignore`. diff --git a/packages/web/src/content/docs/ko/troubleshooting.mdx b/packages/web/src/content/docs/ko/troubleshooting.mdx new file mode 100644 index 000000000..90138a31d --- /dev/null +++ b/packages/web/src/content/docs/ko/troubleshooting.mdx @@ -0,0 +1,300 @@ +--- +title: Troubleshooting +description: Common issues and how to resolve them. +--- + +OpenCode와 문제를 디버그하려면 로그와 로컬 데이터를 확인하여 디스크에 저장합니다. + +--- + +## 로그인 + +로그 파일은 다음과 같습니다: + +-**macOS/리눅스**: `~/.local/share/opencode/log/` +- **Windows**: 압박 `WIN+R`와 풀 `%USERPROFILE%\.local\share\opencode\log` + +로그 파일은 타임스탬프 (예 : `2025-01-09T123456.log`)과 가장 최근 10 로그 파일이 보관됩니다. + +자세한 디버그 정보를 얻기 위해 `--log-level` 명령줄 옵션을 사용하여 로그 레벨을 설정할 수 있습니다. 예를 들면, `opencode --log-level DEBUG`. + +--- + +## 저장 + +opencode 저장 세션 데이터 및 디스크에 다른 응용 데이터: + +-**macOS/리눅스**: `~/.local/share/opencode/` +- **Windows**: 압박 `WIN+R`와 풀 `%USERPROFILE%\.local\share\opencode` + +이 디렉토리는 다음과 같습니다: + +- `auth.json` - API 키, OAuth 토큰과 같은 인증 데이터 +- `log/` - 응용 프로그램 로그 +- `project/` - 세션 및 메시지 데이터와 같은 프로젝트별 데이터 +- 프로젝트가 Git repo 안에 있는 경우에, 그것은 `.//storage/`에서 저장됩니다 +- Git repo가 아닌 경우 `./global/storage/`에 저장됩니다. + +--- + +## 데스크탑 앱 + +OpenCode 데스크톱은 배경에서 로컬 OpenCode 서버 (`opencode-cli` sidecar)를 실행합니다. 대부분의 문제는 misbehaving 플러그인, 손상된 캐시, 또는 나쁜 서버 설정에 의해 발생합니다. + +## 빠른 체크 + +- 완전히 종료하고 앱을 다시 시작. +- 앱이 오류 화면을 보여 주면 ** Restart**를 클릭하고 오류 세부 정보를 복사합니다. +- macOS만: `OpenCode` 메뉴 -> **웹뷰 **(UI가 공백/frozen인 경우). + +--- + +## Disable 플러그인 + +데스크톱 앱이 출시, 거는, 또는 이상한 것에서 충돌하면 플러그인을 비활성화하여 시작합니다. + +### 글로벌 설정 확인 + +글로벌 설정 파일을 열고 `plugin` 키를 찾습니다. + +-**macOS/리눅스**: `~/.config/opencode/opencode.jsonc` (또는 `~/.config/opencode/opencode.json`) +-**macOS/Linux** (외부 설치): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: 압박 `WIN+R`와 풀 `%USERPROFILE%\.config\opencode\opencode.jsonc` + +구성 된 플러그인이있는 경우, 일시적으로 키를 제거하거나 빈 배열로 설정하여 비활성화하십시오. + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +### 플러그인 디렉터리 확인 + +OpenCode는 디스크에서 로컬 플러그인을로드 할 수 있습니다. Temporarily 이동 이러한 방법 (또는 폴더 이름을 변경) 및 데스크톱 응용 프로그램을 다시 시작: + +- **글로벌 플러그인** +-**macOS/리눅스**: `~/.config/opencode/plugins/` +- **Windows**: 압박 `WIN+R`와 풀 `%USERPROFILE%\.config\opencode\plugins` +- **프로젝트 플러그인** (프로젝트 설정만 사용) +- `/.opencode/plugins/` + +앱이 다시 일하는 경우, 재 활성화 플러그인은 한 번에 문제가 발생할 수 있습니다. + +--- + +# # # # 캐시 삭제 + +플러그인을 비활성화하는 경우 도움이되지 않습니다 (또는 플러그인 설치가 붙어있다), 캐시를 삭제 그래서 OpenCode는 그것을 재구성 할 수 있습니다. + +1. Quit OpenCode 데스크톱 완전히. +2. 캐시 디렉토리 삭제: + +-**macOS**: 찾기 -> `Cmd+Shift+G` -> 붙여넣기 `~/.cache/opencode` +- **Linux**: `~/.cache/opencode` 삭제 (또는 `rm -rf ~/.cache/opencode` 실행) +- **Windows**: 압박 `WIN+R`와 풀 `%USERPROFILE%\.cache\opencode` + +3. Restart OpenCode 데스크탑. + +--- + +## 수정 서버 연결 문제 + +OpenCode 데스크톱은 자체 로컬 서버(과태)를 시작하거나 구성된 서버 URL에 연결할 수 있습니다. + +**"Connection Failed"** 대화 상자 (또는 앱이 스패시 화면을 지나지 않습니다), 사용자 정의 서버 URL을 확인합니다. + +### 바탕 화면 기본 서버 URL 삭제 + +Home 화면에서 Server Picker를 열려면 서버 이름(상태 점)을 클릭하십시오. **기본 서버** 섹션에서 **Clear**를 클릭합니다. + +####는 `server.port`/`server.hostname`를 당신의 설정에서 제거합니다 + +`opencode.json(c)`가 `server` 섹션을 포함하면 일시적으로 제거하고 데스크톱 앱을 다시 시작합니다. + +### 환경 변수 확인 + +`OPENCODE_PORT`가 있는 경우, 데스크탑 앱은 로컬 서버의 포트를 사용하려고 합니다. + +- `OPENCODE_PORT` (또는 무료 포트를 선택) 및 재시작. + +--- + +## Linux: 웨이랜드 / X11 문제 + +Linux에서 일부 Wayland 설정은 공백 창이나 compositor 오류를 일으킬 수 있습니다. + +- If you're on Wayland and the app is blank/crashing, `OC_ALLOW_WAYLAND=1`로 출시하려고합니다. +- 더 나쁜 것을 만드는 경우, 제거하고 X11 세션에서 실행하려고합니다. + +--- + +## Windows: WebView2 실행 시간 + +Windows에서 OpenCode 데스크톱은 Microsoft Edge ** WebView2 실행 시간 **를 요구합니다. 앱이 공백 창에 열거나 시작하지 않을 경우, install/update WebView2를 설치하고 다시 시도하십시오. + +--- + +## Windows: 일반 성능 문제 + +느린 성능, 파일 액세스 문제 또는 Windows의 터미널 문제를 경험하는 경우 [WSL (Windows Subsystem for Linux)](/docs/windows-wsl)를 사용하여 시도하십시오. WSL은 OpenCode의 기능으로 더 원활하게 작동하는 Linux 환경을 제공합니다. + +--- + +## 알림 표시되지 않음 + +OpenCode 데스크톱은 시스템 알림을 보여줍니다 : + +- OS 설정에서 OpenCode에 대한 알림이 활성화되고, +- 앱 창이 집중되지 않습니다. + +--- + +## 재설정 데스크톱 앱 스토리지 (마지막 리조트) + +앱이 시작되지 않은 경우 UI 내부에서 설정을 취소할 수 없습니다. 데스크탑 앱의 저장된 상태를 재설정하십시오. + +1. Quit OpenCode 데스크탑. +2. 이 파일을 찾아 삭제 (OpenCode 데스크톱 앱 데이터 디렉토리에서 라이브): + +- `opencode.settings.dat` (데스크톱 기본 서버 URL) +- `opencode.global.dat` 및 `opencode.workspace.*.dat` (최근 서버/프로젝트와 같은 UI 국가) + +빠른 디렉토리를 찾을 수: + +-**macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (위의 파일명 검색) +- **리눅스 **: 위의 파일명에 대한 `~/.local/share`의 밑에 검색 +- **Windows**: `WIN+R` -> `%APPDATA%`를 눌러 (위의 파일 이름을 검색) + +--- + +## 도움 받기 + +OpenCode와 문제가 발생하면: + +1. ** GitHub의 문제 해결 ** + +버그 또는 요청 기능을보고하는 가장 좋은 방법은 GitHub 저장소를 통해 다음과 같습니다. + +[**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + +새로운 문제를 만들기 전에, 당신의 문제가 이미보고 된 경우 기존 문제를 검색. + +2. ** 우리의 Discord ** + +실시간 도움말 및 커뮤니티 토론을 위해 Discord 서버에 가입하십시오. + +[**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## 일반적인 문제 + +몇 가지 일반적인 문제와 해결 방법. + +--- + +## OpenCode가 시작되지 않습니다. + +1. 오류 메시지에 대한 로그 확인 +2. 맨끝에 있는 산출을 보기 위하여 `--print-logs`로 달리기를 시도하십시오 +3. 당신은 `opencode upgrade`를 가진 최신 버전이 있는 것을 지킵니다 + +--- + +### 인증 문제 + +1. TUI에서 `/connect` 명령으로 다시 입력 시도 +2. API 키가 유효하다는 것을 확인 +3. 네트워크가 공급자의 API에 연결을 허용 + +--- + +# # # # 모델 사용할 수 없습니다 + +1. 공급자와 정통한 확인 +2. config의 모델명을 수정한다. +3. 몇몇 모형은 특정한 접근 또는 구독을 요구할지도 모릅니다 + +만약 당신이 `ProviderModelNotFoundError`에 직면 하는 경우 가장 가능성이 잘못 +모델 어딘가를 나타냅니다. +모형은 이렇게 참고되어야 합니다: `/` + +예제: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +당신이 액세스 할 수있는 모델을 파악하려면, `opencode models`를 실행 + +--- + +## 공급자InitError + +ProviderInitError가 발생하면 잘못된 구성이나 손상된 구성이 있습니다. + +해결하기: + +1. 첫째로, 당신의 공급자는 [providers guide] (./providers)를 따르기 위하여 제대로 설치됩니다 +2. 문제가 발생하면 저장된 구성을 삭제하십시오. + + ```bash + rm -rf ~/.local/share/opencode + ``` + +Windows에서, `WIN+R`를 누르고 삭제하십시오: `%USERPROFILE%\.local\share\opencode` + +3. TUI의 `/connect` 명령을 사용하여 공급자와 재해. + +--- + +### AI APICallError와 공급자 포장 문제점 + +API 호출 오류가 발생하면, 이 공급 업체 패키지로 인해 발생할 수 있습니다. opencode 동적 설치 공급자 패키지 (OpenAI, Anthropic, Google 등) 필요 하 고 로컬로 캐시. + +공급자 패키지 문제를 해결하려면: + +1. 공급자 포장 캐시를 지우십시오: + + ```bash + rm -rf ~/.cache/opencode + ``` + +Windows에서, `WIN+R`를 누르고 삭제하십시오: `%USERPROFILE%\.cache\opencode` + +2. 최신 공급자 포장을 재설치하는 Restart opencode + +이것은 종종 모델 매개 변수와 API 변경과 호환성 문제를 해결하는 공급자 패키지의 가장 최근 버전을 다운로드하기 위해 opencode를 강제합니다. + +--- + +# # # # 복사 / Linux에서 작동하지 않음 + +Linux 사용자는 다음과 같은 클립 보드 유틸리티 중 하나가 복사 / 붙여 넣기 기능에 설치해야합니다. + +** X11 시스템:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**웨이랜드 시스템:** + +```bash +apt install -y wl-clipboard +``` + +** 헤드리스 환경에 대한:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode는 당신이 Wayland를 사용하고 `wl-clipboard`를 선호하는 경우에 검출할 것입니다, 그렇지 않으면의 순서에 있는 클립보드 공구를 찾아낼 것입니다: `xclip`와 `xsel`. diff --git a/packages/web/src/content/docs/ko/tui.mdx b/packages/web/src/content/docs/ko/tui.mdx new file mode 100644 index 000000000..6cddc50d5 --- /dev/null +++ b/packages/web/src/content/docs/ko/tui.mdx @@ -0,0 +1,390 @@ +--- +title: TUI +description: Using the OpenCode terminal user interface. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode는 LLM과 함께 프로젝트를 위해 대화형 터미널 인터페이스 또는 TUI를 제공합니다. + +OpenCode는 현재 디렉토리에 TUI를 시작합니다. + +```bash +opencode +``` + +또는 특정 작업 디렉토리에 대해 시작할 수 있습니다. + +```bash +opencode /path/to/project +``` + +TUI에 있다면 메시지가 표시됩니다. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## 파일 참조 + +`@`를 사용하여 메시지에 파일을 참조 할 수 있습니다. 이것은 현재 작업 디렉토리에서 fuzzy 파일 검색입니다. + +:::tip +`@`를 사용하여 메시지의 참조 파일을 사용할 수 있습니다. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +파일의 내용이 자동으로 대화에 추가됩니다. + +--- + +## Bash 명령 + +`!`를 사용하여 쉘 명령을 실행합니다. + +```bash frame="none" +!ls -la +``` + +명령의 출력은 도구 결과로 대화에 추가됩니다. + +--- + +## 명령 + +OpenCode TUI를 사용할 때, `/`를 입력하여 명령 이름을 따라 작업을 신속하게 실행할 수 있습니다. 예를 들면: + +```bash frame="none" +/help +``` + +대부분의 명령은 `ctrl+x`를 `ctrl+x`가 기본 리더 키입니다. [더 알아보기](/docs/keybinds). + +여기에 모든 가능한 슬래시 명령이 있습니다. + +--- + +### 연결 + +OpenCode에 대한 공급자를 추가합니다. 사용 가능한 공급자에서 선택하고 API 키를 추가 할 수 있습니다. + +```bash frame="none" +/connect +``` + +--- + +### 콤팩트 + +현재 세션을 압축합니다. 앨리스 : `/summarize` + +```bash frame="none" +/compact +``` + +** Keybind:** `ctrl+x c` + +--- + +### 세부사항 + +토글 툴 실행 세부 사항. + +```bash frame="none" +/details +``` + +** Keybind:** `ctrl+x d` + +--- + +### 편집기 + +메시지를 작성하기 위한 외부 편집기를 엽니다. `EDITOR` 환경에서 설정된 편집기를 사용합니다. [더 알아보기](#editor-setup). + +```bash frame="none" +/editor +``` + +** Keybind:** `ctrl+x e` + +--- + +### 출구 + +OpenCode를 종료합니다. Aliases : `/quit`, `/q` + +```bash frame="none" +/exit +``` + +** Keybind:** `ctrl+x q` + +--- + +### 수출 + +Markdown에 대한 현재 대화를 내보내고 기본 편집기에서 열립니다. `EDITOR` 환경에서 설정된 편집기를 사용합니다. [더 알아보기](#editor-setup). + +```bash frame="none" +/export +``` + +** Keybind:** `ctrl+x x` + +--- + +### 도움 + +도움말 대화 상자를 표시합니다. + +```bash frame="none" +/help +``` + +** Keybind:** `ctrl+x h` + +--- + +# # # # # # # 인 + +`AGENTS.md` 파일을 만들거나 업데이트하십시오. [더 알아보기](/docs/rules). + +```bash frame="none" +/init +``` + +** Keybind:** `ctrl+x i` + +--- + +## 모델 + +사용 가능한 모델 목록. + +```bash frame="none" +/models +``` + +** Keybind:** `ctrl+x m` + +--- + +## 새로운 + +새로운 세션을 시작합니다. 앨리스 : `/clear` + +```bash frame="none" +/new +``` + +** Keybind:** `ctrl+x n` + +--- + +# # # # # 재도 + +이전 undone 메시지 Redo. `/undo`를 사용하는 후에만 유효한. + +:::tip +모든 파일 변경도 복원됩니다. +::: + +내부적으로 Git을 사용하여 파일 변경을 관리합니다. 그래서 프로젝트 ** +Git 저장소**입니다. + +```bash frame="none" +/redo +``` + +** Keybind:** `ctrl+x r` + +--- + +## 세션 + +세션 간 목록 및 전환. Aliases : `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +** Keybind:** `ctrl+x l` + +--- + +## 공유 + +현재 세션 공유. [더 알아보기](/docs/share). + +```bash frame="none" +/share +``` + +** Keybind:** `ctrl+x s` + +--- + +## 테마 + +사용할 수 있는 테마 목록. + +```bash frame="none" +/theme +``` + +** Keybind:** `ctrl+x t` + +--- + +### 생각 + +대화의 사고/거주 블록의 가시성을 토합니다. 사용할 때, 확장 된 생각을 지원하는 모델의 이유 프로세스를 볼 수 있습니다. + +:::note +이 명령은 생각 블록이 ** 표시되었는지 여부 만 제어 ** - 모델의 소싱 기능을 활성화하거나 비활성화하지 않습니다. toggle 실제적인 reasoning 기능에, 모형 변종을 통해서 주기 위하여 `ctrl+t`를 이용합니다. +::: + +```bash frame="none" +/thinking +``` + +--- + +# # # # # 취소 + +대화에서 마지막 메시지. 가장 최근의 사용자 메시지, 모든 후속 응답 및 모든 파일 변경 제거. + +:::tip +어떤 파일 변경도 복제됩니다. +::: + +내부적으로 Git을 사용하여 파일 변경을 관리합니다. 그래서 프로젝트 ** +Git 저장소**입니다. + +```bash frame="none" +/undo +``` + +** Keybind:** `ctrl+x u` + +--- + +# # # # 공유 + +Unshare 현재 세션. [더 알아보기](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## 에디터 설정 + +`/editor`와 `/export` 명령 모두는 `EDITOR` 환경변수에서 지정된 편집기를 사용합니다. + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + +영원한 만들기 위하여, 당신의 포탄 단면도에 이것을 추가하십시오; +`~/.bashrc`, `~/.zshrc`, 등. + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + +영구적으로, use **System Properties** > ** 환경 +변수**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + +영구적으로 만들려면 PowerShell 프로파일에 추가하십시오. + + + + +인기있는 편집기 옵션은 다음과 같습니다 : + +- `code` - Visual Studio 코드 +- `cursor` - 커서 +- `windsurf` - 윈드 서핑 +- `nvim` - Neovim 편집기 +- `vim` - Vim 편집기 +- `nano` - 나노 편집기 +- `notepad` - 윈도우 노트패드 +- `subl` - 승화 텍스트 + +:::note +VS Code와 같은 일부 편집기는 `--wait` 플래그와 함께 시작해야합니다. +::: + +일부 편집기는 명령줄 인수가 차단 모드에서 실행되어야 합니다. `--wait` 플래그는 닫힐 때까지 편집기 프로세스 블록을 만듭니다. + +--- + +## 구성 + +OpenCode config 파일을 통해 TUI 동작을 사용자 정의할 수 있습니다. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### 옵션 + +- `scroll_acceleration` - 부드러운 자연 스크롤을위한 macOS 스타일 스크롤 가속 가능. 사용할 때, 스크롤 속도는 빠른 스크롤 제스처로 증가하고 느린 움직임을 위해 정확한 유지. **이 설정은 `scroll_speed`를 통해 우선 순위를 부여하고 활성화 할 때. ** +- `scroll_speed` - 스크롤 명령 (최소 : `1`)을 사용하여 TUI 스크롤을 빠르게 제어합니다. 기본 `3`. ** 참고: `scroll_acceleration.enabled`가 `true`로 설정되면 무시됩니다.** + +--- + +## 사용자 정의 + +명령 팔레트 (`ctrl+x h` 또는 `/help`)를 사용하여 TUI보기의 다양한 측면을 사용자 정의 할 수 있습니다. 재시작에 따른 설정 persist. + +--- + +#### 사용자 이름 전시 + +사용자 이름이 채팅 메시지에 나타나는지 여부를 수정합니다. 이것을 통해 접근: + +- 명령 팔레트 : "username" 또는 "hide 사용자" 검색 +- 자동 설정은 TUI 세션을 통해 기억됩니다. diff --git a/packages/web/src/content/docs/ko/web.mdx b/packages/web/src/content/docs/ko/web.mdx new file mode 100644 index 000000000..e79d69d21 --- /dev/null +++ b/packages/web/src/content/docs/ko/web.mdx @@ -0,0 +1,142 @@ +--- +title: Web +description: Using OpenCode in your browser. +--- + +OpenCode는 브라우저에서 웹 응용 프로그램을 실행할 수 있으며 터미널을 필요로하지 않고 동일한 강력한 AI 코딩 경험을 제공합니다. + +![OpenCode Web - 새로운 세션](../../../assets/web/web-homepage-new-session.png) + +## 시작하기 + +실행하여 웹 인터페이스를 시작: + +```bash +opencode web +``` + +`127.0.0.1`의 로컬 서버를 랜덤 사용 가능한 포트로 시작하고 기본 브라우저에서 OpenCode를 자동으로 엽니다. + +:::caution +`OPENCODE_SERVER_PASSWORD`가 설정되지 않은 경우 서버가 중단되지 않습니다. 이것은 로컬 사용을위한 괜찮지만 네트워크 액세스를 설정해야합니다. +::: + +:::tip[Windows 사용자] +최고의 경험을 위해서는 PowerShell보다 `opencode web`를 실행하십시오. 적절한 파일 시스템 액세스 및 터미널 통합을 보장합니다. +::: + +--- + +## 구성 + +명령줄 플래그 또는 [config file](/docs/config)에서 웹 서버를 구성할 수 있습니다. + +## 포트 + +기본적으로 OpenCode는 사용할 수 있는 포트를 선택합니다. 포트를 지정할 수 있습니다: + +```bash +opencode web --port 4096 +``` + +## 호스트 이름 + +기본적으로 서버는 `127.0.0.1` (localhost only)에 바인딩합니다. 네트워크에서 OpenCode를 사용할 수 있도록: + +```bash +opencode web --hostname 0.0.0.0 +``` + +`0.0.0.0`를 사용할 때, OpenCode는 로컬 및 네트워크 주소를 모두 표시합니다. + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### mDNS 발견 + +로컬 네트워크에서 서버를 발견할 수 있는 mDNS: + +```bash +opencode web --mdns +``` + +이 자동으로 `0.0.0.0`에 hostname을 설정하고 `opencode.local`로 서버를 광고합니다. + +동일한 네트워크에서 여러 인스턴스를 실행하려면 mDNS 도메인 이름을 지정할 수 있습니다. + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +# # # # # # CORS + +CORS에 대한 추가 도메인을 허용하려면 (사용자 정의 frontends에 적합) : + +```bash +opencode web --cors https://example.com +``` + +### 인증 + +액세스를 보호하려면 `OPENCODE_SERVER_PASSWORD` 환경 변수를 사용하여 암호를 설정하십시오. + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +`opencode`에 대한 사용자의 기본값은 `OPENCODE_SERVER_USERNAME`로 변경할 수 있습니다. + +--- + +## 웹 인터페이스 사용 + +시작되면 웹 인터페이스는 OpenCode 세션에 액세스 할 수 있습니다. + +## 세션 + +홈페이지에서 세션을 보고 관리합니다. 활성 세션을 볼 수 있으며 새로운 것을 시작합니다. + +![OpenCode Web - Active Session](../../../assets/web/web-homepage-active-session.png) + +## 서버 상태 + +"See Servers"를 클릭하여 연결된 서버와 상태를 볼 수 있습니다. + +![OpenCode Web - Servers 참조](../../../assets/web/web-homepage-see-servers.png) + +--- + +## 터미널 부착 + +실행 웹 서버에 터미널 TUI를 연결할 수 있습니다. + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +웹 인터페이스와 터미널을 동시에 사용할 수 있도록, 같은 세션과 상태를 공유합니다. + +--- + +## Config 파일 + +`opencode.json` config 파일에서 서버 설정을 구성할 수 있습니다: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +Command line flags는 config 파일 설정에 대한 precedence를 가져옵니다. diff --git a/packages/web/src/content/docs/ko/windows-wsl.mdx b/packages/web/src/content/docs/ko/windows-wsl.mdx new file mode 100644 index 000000000..a493cb16b --- /dev/null +++ b/packages/web/src/content/docs/ko/windows-wsl.mdx @@ -0,0 +1,119 @@ +--- +title: Windows (WSL) +description: WSL로 Windows에서 OpenCode를 더 편하게 사용하세요. +--- + +import { Steps } from "@astrojs/starlight/components" + +OpenCode는 Windows에서 직접 실행할 수 있지만, 가장 좋은 사용 경험을 위해 [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) 사용을 권장합니다. WSL은 OpenCode 기능과 자연스럽게 동작하는 Linux 환경을 제공합니다. + +:::tip[왜 WSL인가요?] +WSL은 더 나은 파일 시스템 성능, 완전한 터미널 지원, 그리고 OpenCode가 의존하는 개발 도구와의 호환성을 제공합니다. +::: + +--- + +## 설정 + + + +1. **WSL 설치하기** + + 아직 설치하지 않았다면 Microsoft 공식 가이드를 따라 [WSL을 설치](https://learn.microsoft.com/en-us/windows/wsl/install)하세요. + +2. **WSL에 OpenCode 설치하기** + + WSL 설정이 끝나면 WSL 터미널을 열고 [설치 방법](/docs/) 중 하나로 OpenCode를 설치하세요. + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **WSL에서 OpenCode 실행하기** + + 프로젝트 디렉터리로 이동한 뒤(OpenCode에서 Windows 파일은 `/mnt/c/`, `/mnt/d/` 등으로 접근) OpenCode를 실행하세요. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## 데스크톱 앱 + WSL 서버 + +OpenCode 데스크톱 앱을 쓰면서 서버는 WSL에서 실행하고 싶다면 다음처럼 진행하세요. + +1. **WSL에서 서버 시작하기** + + 외부 연결을 허용하려면 `--hostname 0.0.0.0` 옵션을 사용하세요. + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **데스크톱 앱 연결하기** + + `http://localhost:4096`로 연결하세요. + +:::note +환경에 따라 `localhost`가 동작하지 않으면 WSL의 IP 주소를 사용하세요(WSL에서 `hostname -I` 실행). 이후 `http://:4096`로 접속하면 됩니다. +::: + +:::caution +`--hostname 0.0.0.0`을 사용할 때는 `OPENCODE_SERVER_PASSWORD`를 설정해 서버를 보호하세요. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## 웹 클라이언트 + WSL + +Windows에서 웹 사용 경험을 가장 좋게 하려면: + +1. **PowerShell 대신 WSL 터미널에서 `opencode web` 실행하기** + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Windows 브라우저에서 접속하기** + + `http://localhost:`로 접속하세요(OpenCode가 URL을 출력합니다). + +WSL에서 `opencode web`를 실행하면 올바른 파일 시스템 접근과 터미널 통합을 유지하면서도 Windows 브라우저에서 바로 사용할 수 있습니다. + +--- + +## Windows 파일 접근 + +WSL에서는 `/mnt/` 디렉터리를 통해 Windows 파일 전체에 접근할 수 있습니다. + +- `C:` drive → `/mnt/c/` +- `D:` drive → `/mnt/d/` +- 다른 드라이브도 같은 방식입니다 + +예시: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +가장 매끄러운 경험을 원한다면 저장소를 WSL 파일시스템(예: `~/code/`)으로 복제하거나 복사한 뒤 그 위치에서 OpenCode를 실행해 보세요. +::: + +--- + +## 팁 + +- Windows 드라이브에 있는 프로젝트라도 OpenCode는 WSL에서 실행하면 파일 접근이 더 자연스럽습니다 +- 통합된 개발 워크플로를 위해 OpenCode와 함께 VS Code의 [WSL 확장](https://code.visualstudio.com/docs/remote/wsl)을 사용해 보세요 +- OpenCode 설정과 세션은 WSL 환경의 `~/.local/share/opencode/`에 저장됩니다 diff --git a/packages/web/src/content/docs/ko/zen.mdx b/packages/web/src/content/docs/ko/zen.mdx new file mode 100644 index 000000000..12bba4204 --- /dev/null +++ b/packages/web/src/content/docs/ko/zen.mdx @@ -0,0 +1,254 @@ +--- +title: Zen +description: Curated list of models provided by OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen은 OpenCode 팀에서 제공하는 테스트 및 검증된 모델 목록입니다. + +:::note +OpenCode Zen은 현재 베타입니다. +::: + +Zen은 OpenCode의 다른 공급자와 같이 작동합니다. OpenCode Zen에 로그인하고 +API 키. 그것은 ** 완전 옵션 ** 당신은 사용할 필요가 없습니다 +OpenCode입니다. + +--- + +## 배경 + +거기에 모델의 큰 수는 있지만 몇 가지의 +이 모형은 뿐 아니라 기호화 대리인 작동합니다. 또한, 대부분의 공급자는 +아주 다르게 형성하십시오; 그래서 당신은 아주 다른 성과 및 질을 얻습니다. + +:::tip +OpenCode와 잘 작동하는 모델 및 공급자의 선택 그룹을 테스트했습니다. +::: + +OpenRouter와 같은 무언가를 통해 모델을 사용하고 있다면 결코 할 수 없습니다. +당신이 원하는 모델의 최고의 버전을 얻는 경우. + +이것을 해결하기 위해, 우리는 몇 가지 일을했다 : + +1. 우리는 모형의 선택 그룹을 시험하고 그들의 팀에 대략 이야기했습니다 +가장 좋은 것. +2. 우리는 그(것)들이 봉사한 것을 확인하기 위하여 몇몇 공급자와 일했습니다 +견적 요청 +3. 마지막으로, 우리는 model/provider의 조합을 벤치마크하고 올랐습니다 +우리가 좋은 권고를 느끼는 목록으로. + +OpenCode Zen은 이 모델에 액세스 할 수있는 AI 게이트웨이입니다. + +--- + +## 어떻게 작동합니까? + +OpenCode Zen은 OpenCode의 다른 공급자와 같습니다. + +1. 로그인 **OpenCode Zen**, 청구 추가 +세부 사항 및 API 키 복사. +2. TUI에서 `/connect` 명령을 실행하고 OpenCode Zen을 선택하고 API 키를 붙여 넣으십시오. +3. TUI의 `/models`를 실행하여 우리가 추천하는 모델 목록을 볼 수 있습니다. + +요청에 따라 청구되며 계정에 크레딧을 추가 할 수 있습니다. + +--- + +## 엔드포인트 + +다음 API 엔드포인트를 통해 모델에 액세스할 수 있습니다. + +| 모델명 | 모델명 | 엔드포인트 | AI SDK Package | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | 일본 +| GPT 5.2 코덱 | gpt-5.2 코덱 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | 후쿠오카현 +| GPT 5.1 코덱 | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 코덱 맥스 | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 코덱 미니 | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | 일본 +| GPT 5 코덱 | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 나노 | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| 클로드손넷 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| 클로드 아들넷 4 | 클로드슨넷-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| 클로드 하이쿠 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| 클로드 하이쿠 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| 클로드 오푸스 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| 클로드 오푸스 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| 클로드 오푸스 4.1 | 클로드오푸스-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| 젬니 3 프로 | 젬니 3 프로 | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| 젬니 3 플래시 | 젬니 3 플래시 | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| 미니 맥스 M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| 미니 맥스 M2.1 무료 | 미니max-m2.1-무료 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | 일본 +| GLM 4.7 무료 | glm-4.7-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | 일본 +| 김이 K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| 김이 K2.5 무료 | kimi-k2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| 김이 K2 생각 | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| 김이 K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3 코더 480B | Qwen3- 코더 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| 빅클래스 | 빅클래스 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +OpenCode config에서 [model id](/docs/config/#models) +형식 `opencode/`를 사용합니다. 예를 들어, GPT 5.2 Codex의 경우, +설정에서 `opencode/gpt-5.2-codex`를 사용합니다. + +--- + +## 모델 + +사용할 수 있는 모델과 메타데이터의 전체 목록은 다음과 같습니다: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## 가격 + +우리는 pay-as-you-go 모델을 지원합니다. 아래는 1M 토큰 ** 당 가격입니다. + +| 모델 | 입력 | 출력 | 통번역 | 통번역 +| --------------------------------- | ------ | ------ | ----------- | ------------ | +| 빅클래스 | 무료 | | 무료 | | | | +| MiniMax M2.1 무료 | | 무료 | | | | +| 최소 M2.1 | 0.30 | $1.20 | 0.10 | - | +| GLM 4.7 무료 | | 무료 | | | | | +인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 +| GLM 4.6 | $0.60 | $2.20 | 0.10 | - | +| 김이 K2.5 무료 | | | 무료 | | | | | +| 김이 K2.5 | $0.60 | $3.00 | $0.08 | - | +| 김이 K2 생각 | $ 0.40 | $2.50 | - | - | +| 김이 K2 | 0.40 | $2.50 | - | - | +| Qwen3 코더 480B | $0.45 | $1.50 | - | - | +| 클로드손넷 4.5(≤ 200K 토큰) | $3.00 | $15.00 | $0.30 | $3.75 | +| 클로드손넷 4.5(> 200K 토큰) | $6.00 | $22.50 | $0.60 | $7.50 | +| 클로드 소네넷 4(≤ 200K 토큰) | $3.00 | $15.00 | $0.30 | $3.75 | +| 클로드 소네넷 4(> 200K 토큰) | $6.00 | $22.50 | $0.60 | $7.50 | +| 클레어 하이쿠 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | +| 클레어 하이쿠 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | +| 클로드 오푸스 4.6 (≤ 200K 토큰) | $5.00 | $25.00 | $0.50 | $6.25 | +| 클로드 오푸스 4.6 (> 200K 토큰) | $10.00 | $37.50 | $1.00 | $12.50 | +| 클로드 오푸스 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | +인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 +| 젬니 3 프로 (≤ 200K 토큰) | $2.00 | $12.00 | $0.20 | - | +| 젬니 3 프로 (> 200K 토큰) | $4.00 | $18.00 | $0.40 | - | +인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 +인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 센터 +| GPT 5.2 코덱 | $1.75 | $14.00 | $0.175 | - | +인포메이션 인포메이션 인포메이션 인포메이션 인포메이션 +| GPT 5.1 코덱 | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex Max | $10.00 | $0.125 | - | +| GPT 5.1 코덱 미니 | $0.25 | $2.00 | $0.025 | - | +| GPT 5 인| $1.07 | $8.50 | $0.107 | - | +| GPT 5 코드 | $1.07 | $8.50 | $0.107 | - | +| GPT 5 나노 | 무료 | | 무료 | | | | + +You might notice Claude Haiku 3.5 사용 역사. 이것은 세션의 제목을 생성하는 데 사용되는 [low cost model](/docs/config/#models)입니다. + +:::note +신용 카드 수수료는 비용 (4.4% + 거래 당 $0.30)에 따라 전달됩니다. 우리는 그 이상을 청구하지 않습니다. +::: + +무료 모델: + +- GLM의 4.7 제한된 시간에 OpenCode에서 무료로 사용할 수 있습니다. 팀은 피드백을 수집하고 모델을 개선하기 위해이 시간을 사용합니다. +- 김이 K2.5 제한된 시간에 OpenCode에서 무료로 사용할 수 있습니다. 팀은 피드백을 수집하고 모델을 개선하기 위해이 시간을 사용합니다. +- 미니 맥스 M2.1 제한된 시간에 OpenCode에서 무료로 사용할 수 있습니다. 팀은 피드백을 수집하고 모델을 개선하기 위해이 시간을 사용합니다. +- Big Pickle은 제한된 시간 동안 OpenCode에서 무료 훔친 모델입니다. 팀은 피드백을 수집하고 모델을 개선하기 위해이 시간을 사용합니다. + +Contact us if you have any questions. + +--- + +### 자동 로드 + +잔액이 $ 5 미만인 경우 Zen은 $ 20를 자동으로 다시로드합니다. + +자동로드 금액을 변경할 수 있습니다. 또한 완전히 자동 부하를 비활성화 할 수 있습니다. + +--- + +## 월간 제한 + +또한 전체 작업 공간에 대한 월간 사용 제한을 설정할 수 있습니다. +당신의 팀의 일원. + +예를 들어, 매달 사용 제한을 $20로 설정하면 Zen은 사용하지 않습니다. +한 달에 $ 20 이상. 그러나 자동 로드가 활성화되면 Zen이 종료 될 수 있습니다. +잔액이 $5 미만인 경우 $20 이상 충전. + +--- + +## 개인 정보 + +우리의 모든 모델은 미국에서 호스팅됩니다. 우리의 공급자는 제로 보유 정책을 따르고 모형 훈련을 위한 당신의 자료를 이용하지 않습니다, 뒤에 오는 예외로: + +- Big Pickle : 무료 기간 동안 수집 된 데이터는 모델을 개선하기 위해 사용될 수있다. +- GLM 4.7 무료 : 무료 기간 동안 수집 된 데이터는 모델을 개선하기 위해 사용될 수있다. +- Kimi K2.5 무료 : 무료 기간 동안 수집 된 데이터는 모델을 개선하기 위해 사용될 수있다. +- MiniMax M2.1 무료 : 무료 기간 동안 수집 된 데이터는 모델을 개선하기 위해 사용될 수있다. +- OpenAI APIs: 요청은 [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data)에 따라 30일 동안 유지됩니다. +- Anthropic APIs : 요청은 [Anthropic's Data Policies] (https://docs.anthropic.com/en/docs/claude-code/data-usage)에 따라 30 일 동안 유지됩니다. + +--- + +## 팀 + +Zen은 팀을 위해 잘 작동합니다. 팀메이트를 초대 할 수 있습니다, 역할 할당, curate +당신의 팀 용도 및 더 많은 모델을. + +:::note +Workspaces는 현재 베타의 일부로 팀에 무료로 제공됩니다. +::: + +작업 공간 관리는 현재 베타의 일부로 팀에 무료로 제공됩니다. 우리는 +가격을 곧 공유하십시오. + +--- + +## 역할 + +작업 공간에 팀메이트를 초대하고 역할 할당 할 수 있습니다. + +- **Admin**: 모델, 회원, API 키 및 청구 +- **회원**: 자신의 API 키만 관리 + +Admins는 또한 통제의 밑에 비용을 지키는 각 일원을 위한 매달 지출 한계를 놓을 수 있습니다. + +--- + +## 모델 접근 + +관리자는 작업 공간에 특정 모델을 활성화하거나 비활성화 할 수 있습니다. 장애인 모델에 요청은 오류를 반환합니다. + +이것은 당신이 모델의 사용을 비활성화하려는 경우 유용합니다 +데이터 수집 + +--- + +## 자신의 열쇠를 가져옵니다 + +OpenAI 또는 Anthropic API 키를 사용하여 Zen에서 다른 모델에 액세스 할 수 있습니다. + +자신의 키를 사용할 때, 토큰은 Zen에 의해 공급자에 의해 직접 청구됩니다. + +예를 들어, 조직은 이미 OpenAI 또는 Anthropic에 대한 열쇠가있을 수 있습니다. +Zen이 제공하는 것을 대신 사용하고 싶습니다. + +--- + +## 목표 + +OpenCode Zen을 생성했습니다. + +1. **Benchmark ** 코딩 에이전트에 대한 최고의 모델 / 프로바이더. +2. ** 고품질 ** 옵션에 액세스하고 더 싼 공급자에 고급 성능 또는 노선을 내리지 마십시오. +3. 비용에 판매해서 ** 가격 하락 **를 따라 통과하십시오; 그래서 단지 감적은 우리의 가공 비용을 커버하는 것입니다. +4. 잠금 해제 ** 다른 코딩 에이전트와 함께 사용할 수 있도록. 그리고 항상 OpenCode와 다른 모든 공급자를 사용할 수 있습니다. diff --git a/packages/web/src/content/docs/nb/1-0.mdx b/packages/web/src/content/docs/nb/1-0.mdx new file mode 100644 index 000000000..6d0ea43f5 --- /dev/null +++ b/packages/web/src/content/docs/nb/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: Migrerer til 1.0 +description: Hva er nytt i OpenCode 1.0. +--- + +OpenCode 1.0 er en fullstendig omskrivning av TUI. + +Vi gikk fra den go+bubbletea-baserte TUI som hadde ytelses- og kapasitetsproblemer til et internt rammeverk (OpenTUI) skrevet i zig+solidjs. + +Den nye TUI fungerer som den gamle siden den kobles til den samme opencode-serveren. + +--- + +## Oppgradering + +Du bør ikke autooppgraderes til 1.0 hvis du bruker en tidligere +versjon. Men noen eldre versjoner av OpenCode henter alltid den nyeste. + +For å oppgradere manuelt, kjør + +```bash +$ opencode upgrade 1.0.0 +``` + +For å nedgradere tilbake til 0.x, kjør + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## UX endringer + +Sesjonshistorikken er mer komprimert, og viser bare fullstendige detaljer om redigerings- og bash-verktøyet. + +Vi la til en kommandolinje som nesten alt flyter gjennom. Trykk ctrl+p for å få det opp i en hvilken som helst sammenheng og se alt du kan gjøre. + +Lagt til en øktsidelinje (kan byttes) med nyttig informasjon. + +Vi fjernet noe funksjonalitet som vi ikke var sikre på at noen faktisk brukte. Hvis noe viktig mangler, åpne et problem, så legger vi det til raskt igjen. + +--- + +## Brytende endringer + +### Keybindings omdøpt + +- meldinger_tilbake -> meldinger_angre +- switch_agent -> agent_cycle +- switch_agent_reverse -> agent_cycle_reverse +- switch_mode -> agent_cycle +- switch_mode_reverse -> agent_cycle_reverse + +### Keybindings fjernet + +- messages_layout_toggle +- meldinger_neste +- meldinger_forrige +- file_diff_toggle +- filsøk +- fil_lukk +- fil_liste +- app_hjelp +- prosjekt_init +- tool_details +- tenkeblokker diff --git a/packages/web/src/content/docs/nb/acp.mdx b/packages/web/src/content/docs/nb/acp.mdx new file mode 100644 index 000000000..c5cbc402f --- /dev/null +++ b/packages/web/src/content/docs/nb/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACP Støtte +description: Bruk OpenCode i en hvilken som helst ACP-kompatibel editor. +--- + +OpenCode støtter [Agent Client Protocol](https://agentclientprotocol.com) eller (ACP), slik at du kan bruke den direkte i kompatible redaktører og IDE-er. + +:::tupp +For en liste over redaktører og verktøy som støtter ACP, sjekk ut [ACP fremdriftsrapport](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP er en åpen protokoll som standardiserer kommunikasjon mellom koderedigerere og AI kodeagenter. + +--- + +## Konfigurer + +For å bruke OpenCode via ACP, konfigurer redigeringsprogrammet til å kjøre kommandoen `opencode acp`. + +Kommandoen starter OpenCode som en ACP-kompatibel underprosess som kommuniserer med redaktøren din over JSON-RPC via stdio. + +Nedenfor er eksempler på populære redaktører som støtter ACP. + +--- + +### Zed + +Legg til i [Zed](https://zed.dev)-konfigurasjonen (`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +For å åpne den, bruk handlingen `agent: new thread` i **Kommandopaletten**. + +Du kan også binde en hurtigtast ved å redigere `keymap.json`: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### JetBrains IDE-er + +Legg til [JetBrains IDE](https://www.jetbrains.com/) acp.json i henhold til [dokumentasjonen](https://www.jetbrains.com/help/ai-assistant/acp.html): + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +For å åpne den, bruk den nye 'OpenCode'-agenten i AI Chat-agentvelgeren. + +--- + +### Avante.nvim + +Legg til i [Avante.nvim](https://github.com/yetone/avante.nvim)-konfigurasjonen: + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +Hvis du trenger å sende miljøvariabler: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +For å bruke OpenCode som en ACP-agent i [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim), legg til følgende i Neovim-konfigurasjonen: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +Denne konfigurasjonen setter opp CodeCompanion til å bruke OpenCode som ACP-agent for chat. + +Hvis du trenger å sende miljøvariabler (som `OPENCODE_API_KEY`), se [Konfigurere adaptere: miljøvariabler](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) i CodeCompanion.nvim-dokumentasjonen for fullstendige detaljer. + +## Støtte + +OpenCode fungerer på samme måte via ACP som i terminalen. Alle funksjoner støttes: + +:::note +Noen innebygde skråstrekkommandoer som `/undo` og `/redo` støttes for øyeblikket ikke. +::: + +- Innebygde verktøy (filoperasjoner, terminalkommandoer, etc.) +- Egendefinerte verktøy og skråstrekkommandoer +- MCP servere konfigurert i OpenCode-konfigurasjonen +- Prosjektspesifikke regler fra `AGENTS.md` +- Tilpassede formatere og linters +- Agenter og tillatelsessystem diff --git a/packages/web/src/content/docs/nb/agents.mdx b/packages/web/src/content/docs/nb/agents.mdx new file mode 100644 index 000000000..1a0c3f076 --- /dev/null +++ b/packages/web/src/content/docs/nb/agents.mdx @@ -0,0 +1,747 @@ +--- +title: Agenter +description: Konfigurer og bruk spesialiserte agenter. +--- + +Agenter er spesialiserte AI-assistenter som kan konfigureres for spesifikke oppgaver og arbeidsflyter. De lar deg lage fokuserte verktøy med tilpassede meldinger, modeller og verktøytilgang. + +:::tupp +Bruk planagenten til å analysere kode og gjennomgå forslag uten å gjøre noen kodeendringer. +::: + +Du kan bytte mellom agenter under en økt eller påkalle dem med `@`-omtalen. + +--- + +## Typer + +Det er to typer agenter i OpenCode; primære agenter og subagenter. + +--- + +### Primæragenter + +Primæragenter er de viktigste assistentene du samhandler direkte med. Du kan bla gjennom dem ved å bruke **Tab**-tasten, eller din konfigurerte `switch_agent`-tastebinding. Disse agentene håndterer hovedsamtalen din. Verktøytilgang konfigureres via tillatelser - for eksempel har Build alle verktøy aktivert mens Plan er begrenset. + +:::tupp +Du kan bruke **Tab**-tasten for å bytte mellom primære agenter under en økt. +::: + +OpenCode kommer med to innebygde primære agenter, **Build** og **Plan**. Godt +se på disse nedenfor. + +--- + +### Subagenter + +Subagenter er spesialiserte assistenter som primære agenter kan påkalle for spesifikke oppgaver. Du kan også starte dem manuelt ved å **@ nevne** dem i meldingene dine. + +OpenCode kommer med to innebygde subagenter, **General** og **Explore**. Vi skal se på dette nedenfor. + +--- + +## Innebygd + +OpenCode kommer med to innebygde primære agenter og to innebygde subagenter. + +--- + +### Bruk build + +_Modus_: `primary` + +Bygg er **standard** primæragent med alle verktøy aktivert. Dette er standardagenten for utviklingsarbeid der du trenger full tilgang til filoperasjoner og systemkommandoer. + +--- + +### Bruk plan + +_Modus_: `primary` + +En begrenset agent designet for planlegging og analyse. Vi bruker et tillatelsessystem for å gi deg mer kontroll og forhindre utilsiktede endringer. +Som standard er alt av følgende satt til `ask`: + +- `file edits`: Alle skrivinger, patcher og redigeringer +- `bash`: Alle bash-kommandoer + +Denne agenten er nyttig når du vil at LLM skal analysere kode, foreslå endringer eller lage planer uten å gjøre noen faktiske endringer i kodebasen. + +--- + +### Bruk generelt + +_Modus_: `subagent` + +En generell agent for å undersøke komplekse spørsmål og utføre flertrinnsoppgaver. Har full verktøytilgang (unntatt todo), slik at den kan gjøre filendringer når det er nødvendig. Bruk denne til å kjøre flere arbeidsenheter parallelt. + +--- + +### Bruk utforske + +_Modus_: `subagent` + +En rask, skrivebeskyttet agent for å utforske kodebaser. Kan ikke endre filer. Bruk dette når du raskt trenger å finne filer etter mønstre, søke i kode etter nøkkelord eller svare på spørsmål om kodebasen. + +--- + +### Bruk komprimering + +_Modus_: `primary` + +Skjult systemagent som komprimerer lang kontekst til et mindre sammendrag. Den kjører automatisk ved behov og kan ikke velges i UI. + +--- + +### Bruk tittel + +_Modus_: `primary` + +Skjult systemagent som genererer korte økttitler. Den kjører automatisk og kan ikke velges i UI. + +--- + +### Bruk sammendrag + +_Modus_: `primary` + +Skjult systemagent som lager øktsammendrag. Den kjører automatisk og kan ikke velges i UI. + +--- + +## Bruk + +1. For primære agenter, bruk **Tab**-tasten for å bla gjennom dem under en økt. Du kan også bruke din konfigurerte `switch_agent` nøkkelbinding. + +2. Subagenter kan påkalles: + - **Automatisk** av primære agenter for spesialiserte oppgaver basert på deres beskrivelser. + - Manuelt ved å **@ nevne** en underagent i meldingen. For eksempel. + + ```txt frame="none" + @general help me search for this function + ``` + +3. **Navigering mellom økter**: Når underagenter oppretter sine egne underordnede økter, kan du navigere mellom overordnede økter og alle underordnede økter ved å bruke: + - **\+Høyre** (eller din konfigurerte `session_child_cycle`-tastebinding) for å gå videre gjennom forelder → barn1 → barn2 → ... → forelder + - **\+Venstre** (eller din konfigurerte `session_child_cycle_reverse`-tastebinding) for å gå bakover gjennom forelder ← barn1 ← barn2 ← ... ← forelder + + Dette lar deg sømløst bytte mellom hovedsamtalen og spesialisert underagentarbeid. + +--- + +## Konfigurer + +Du kan tilpasse de innebygde agentene eller lage dine egne gjennom konfigurasjon. Agenter kan konfigureres på to måter: + +--- + +### JSON + +Konfigurer agenter i konfigurasjonsfilen `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Markdown + +Du kan også definere agenter ved å bruke markdown-filer. Plasser dem i: + +- Globalt: `~/.config/opencode/agents/` +- Per prosjekt: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Markdown-filnavnet blir agentnavnet. For eksempel oppretter `review.md` en `review`-agent. + +--- + +## Alternativer + +La oss se på disse konfigurasjonsalternativene i detalj. + +--- + +### Beskrivelse + +Bruk alternativet `description` for å gi en kort beskrivelse av hva agenten gjør og når den skal brukes. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +Dette er et **obligatorisk** konfigurasjonsalternativ. + +--- + +### Temperatur + +Kontroller tilfeldigheten og kreativiteten til LLMs svar med `temperature`-konfigurasjonen. + +Lavere verdier gjør svarene mer fokuserte og deterministiske, mens høyere verdier øker kreativiteten og variasjonen. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Temperaturverdier varierer vanligvis fra 0,0 til 1,0: + +- **0.0-0.2**: Veldig fokuserte og deterministiske svar, ideell for kodeanalyse og planlegging +- **0,3-0,5**: Balanserte svar med litt kreativitet, bra for generelle utviklingsoppgaver +- **0.6-1.0**: Mer kreative og varierte svar, nyttig for idédugnad og utforskning + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Hvis ingen temperatur er spesifisert, bruker OpenCode modellspesifikke standardinnstillinger; typisk 0 for de fleste modeller, 0,55 for Qwen-modeller. + +--- + +### Maks trinn + +Kontroller det maksimale antallet agentiske iterasjoner en agent kan utføre før den blir tvunget til å svare kun med tekst. Dette lar brukere som ønsker å kontrollere kostnadene sette en grense for agenthandlinger. + +Hvis dette ikke er satt, vil agenten fortsette å iterere til modellen velger å stoppe eller brukeren avbryter økten. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +Når grensen er nådd, mottar agenten en spesiell systemmelding som instruerer den om å svare med en oppsummering av arbeidet og anbefalte gjenværende oppgaver. + +:::forsiktighet +Det gamle `maxSteps`-feltet er avviklet. Bruk `steps` i stedet. +::: + +--- + +### Deaktiver + +Sett til `true` for å deaktivere agenten. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Spør + +Spesifiser en tilpasset systemmeldingsfil for denne agenten med `prompt`-konfigurasjonen. Spørrefilen skal inneholde instruksjoner som er spesifikke for agentens formål. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Denne banen er i forhold til hvor konfigurasjonsfilen er plassert. Så dette fungerer for både den globale OpenCode-konfigurasjonen og den prosjektspesifikke konfigurasjonen. + +--- + +### Modell + +Bruk `model`-konfigurasjonen for å overstyre modellen for denne agenten. Nyttig for bruk av ulike modeller optimalisert for ulike oppgaver. For eksempel en raskere modell for planlegging, en mer kapabel modell for implementering. + +:::tupp +Hvis du ikke spesifiserer en modell, bruker primæragenter [modell globalt konfigurert](/docs/config#models) mens subagenter vil bruke modellen til primæragenten som påkalte subagenten. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +Modellen ID i OpenCode-konfigurasjonen din bruker formatet `provider/model-id`. For eksempel, hvis du bruker [OpenCode Zen](/docs/zen), vil du bruke `opencode/gpt-5.1-codex` for GPT 5.1 Codex. + +--- + +### Verktøy + +Kontroller hvilke verktøy som er tilgjengelige i denne agenten med `tools`-konfigurasjonen. Du kan aktivere eller deaktivere spesifikke verktøy ved å sette dem til `true` eller `false`. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +Den agentspesifikke konfigurasjonen overstyrer den globale konfigurasjonen. +::: + +Du kan også bruke jokertegn for å kontrollere flere verktøy samtidig. For eksempel, for å deaktivere alle verktøy fra en MCP-server: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[Finn ut mer om verktøy](/docs/tools). + +--- + +### Tillatelser + +Du kan konfigurere tillatelser for å administrere hvilke handlinger en agent kan utføre. For øyeblikket kan tillatelsene for verktøyene `edit`, `bash` og `webfetch` konfigureres til: + +- `"ask"` — Be om godkjenning før du kjører verktøyet +- `"allow"` — Tillat alle operasjoner uten godkjenning +- `"deny"` — Deaktiver verktøyet + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +Du kan overstyre disse tillatelsene per agent. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +Du kan også angi tillatelser i Markdown-agenter. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +Du kan angi tillatelser for spesifikke bash-kommandoer. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +Dette kan ta et globmønster. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +Og du kan også bruke jokertegnet `*` for å administrere tillatelser for alle kommandoer. +Siden den siste samsvarsregelen har forrang, setter du jokertegnet `*` først og spesifikke regler etter. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[Finn ut mer om tillatelser](/docs/permissions). + +--- + +### Modus + +Kontroller agentens modus med `mode`-konfigurasjonen. Alternativet `mode` brukes til å bestemme hvordan agenten kan brukes. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +Alternativet `mode` kan settes til `primary`, `subagent` eller `all`. Hvis ingen `mode` er spesifisert, er den standard til `all`. + +--- + +### Skjult + +Skjul en underagent fra `@` autofullføringsmenyen med `hidden: true`. Nyttig for interne underagenter som bare skal påkalles programmatisk av andre agenter via oppgaveverktøyet. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +Dette påvirker kun brukersynlighet i autofullfør-menyen. Skjulte agenter kan fortsatt påkalles av modellen via oppgaveverktøyet hvis tillatelser tillater det. + +:::note +Gjelder kun `mode: subagent`-agenter. +::: + +--- + +### Oppgavetillatelser + +Kontroller hvilke subagenter en agent kan påkalle via oppgaveverktøyet med `permission.task`. Bruker glob-mønstre for fleksibel matching. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +Når den er satt til `deny`, fjernes subagenten fullstendig fra oppgaveverktøybeskrivelsen, så modellen vil ikke forsøke å starte den. + +:::tupp +Reglene evalueres i rekkefølge, og den **siste samsvarsregelen vinner**. I eksemplet ovenfor samsvarer `orchestrator-planner` med både `*` (avslå) og `orchestrator-*` (tillat), men siden `orchestrator-*` kommer etter `*`, er resultatet `allow`. +::: + +:::tupp +Brukere kan alltid starte en hvilken som helst underagent direkte via `@` autofullføringsmenyen, selv om agentens oppgavetillatelser ville nekte det. +::: + +--- + +### Farge + +Tilpass agentens visuelle utseende i UI med alternativet `color`. Dette påvirker hvordan agenten vises i grensesnittet. + +Bruk en gyldig sekskantfarge (f.eks. `#FF5733`) eller temafarge: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### Topp P + +Kontroller responsmangfoldet med alternativet `top_p`. Alternativ til temperatur for å kontrollere tilfeldighet. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +Verdiene varierer fra 0,0 til 1,0. Lavere verdier er mer fokuserte, høyere verdier mer mangfoldige. + +--- + +### Tillegg + +Eventuelle andre alternativer du spesifiserer i agentkonfigurasjonen vil bli **overført direkte** til leverandøren som modellalternativer. Dette lar deg bruke leverandørspesifikke funksjoner og parametere. + +For eksempel, med OpenAIs resonneringsmodeller kan du kontrollere resonnementinnsatsen: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +Disse tilleggsalternativene er modell- og leverandørspesifikke. Sjekk leverandørens dokumentasjon for tilgjengelige parametere. + +:::tupp +Kjør `opencode models` for å se en liste over tilgjengelige modeller. +::: + +--- + +## Opprett agenter + +Du kan opprette nye agenter ved å bruke følgende kommando: + +```bash +opencode agent create +``` + +Denne interaktive kommandoen vil: + +1. Spør hvor du skal lagre agenten; global eller prosjektspesifikk. +2. Beskrivelse av hva agenten skal gjøre. +3. Generer en passende systemmelding og identifikator. +4. La deg velge hvilke verktøy agenten har tilgang til. +5. Lag til slutt en nedmerkingsfil med agentkonfigurasjonen. + +--- + +## Brukstilfeller + +Her er noen vanlige brukstilfeller for forskjellige agenter. + +- **Byggagent**: Fullstendig utviklingsarbeid med alle verktøy aktivert +- **Planagent**: Analyse og planlegging uten å gjøre endringer +- **Anmeldelsesagent**: Kodegjennomgang med skrivebeskyttet tilgang pluss dokumentasjonsverktøy +- **Feilsøkingsagent**: Fokusert på etterforskning med bash og leseverktøy aktivert +- **Docs-agent**: Dokumentasjonsskriving med filoperasjoner, men ingen systemkommandoer + +--- + +## Eksempler + +Her er noen eksempler på agenter du kan finne nyttige. + +:::tupp +Har du en agent du vil dele? [Send inn en PR](https://github.com/anomalyco/opencode). +::: + +--- + +### Dokumentasjonsagent + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### Sikkerhetsrevisor + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/nb/cli.mdx b/packages/web/src/content/docs/nb/cli.mdx new file mode 100644 index 000000000..ce51ddf8c --- /dev/null +++ b/packages/web/src/content/docs/nb/cli.mdx @@ -0,0 +1,601 @@ +--- +title: CLI +description: OpenCode CLI alternativer og kommandoer. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode CLI starter som standard [TUI](/docs/tui) når den kjøres uten noen argumenter. + +```bash +opencode +``` + +Men den godtar også kommandoer som dokumentert på denne siden. Dette lar deg samhandle med OpenCode programmatisk. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui + +Start OpenCode-terminalbrukergrensesnittet. + +```bash +opencode [project] +``` + +#### Flagg + +| Flagg | Kort | Beskrivelse | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | Fortsett siste økt | +| `--session` | `-s` | Økt ID for å fortsette | +| `--prompt` | | Spør om å bruke | +| `--model` | `-m` | Modell å bruke i form av tilbyder/modell | +| `--agent` | | Agent å bruke | +| `--port` | | Port å lytte på | +| `--hostname` | | Vertsnavn å lytte på | + +--- + +## Kommandoer + +OpenCode CLI har også følgende kommandoer. + +--- + +### agent + +Administrer agenter for OpenCode. + +```bash +opencode agent [command] +``` + +--- + +### legg ved + +Koble en terminal til en allerede kjørende OpenCode-backend-server startet via `serve` eller `web` kommandoer. + +```bash +opencode attach [url] +``` + +Dette gjør det mulig å bruke TUI med en ekstern OpenCode-backend. For eksempel: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### Flagg + +| Flagg | Kort | Beskrivelse | +| ----------- | ----- | --------------------------------- | +| `--dir` | | Arbeidskatalog for å starte TUI i | +| `--session` | `-s` | Økt ID for å fortsette | + +--- + +#### opprette + +Opprett en ny agent med tilpasset konfigurasjon. + +```bash +opencode agent create +``` + +Denne kommandoen vil veilede deg gjennom å lage en ny agent med en tilpasset systemmelding og verktøykonfigurasjon. + +--- + +#### liste + +List opp alle tilgjengelige agenter. + +```bash +opencode agent list +``` + +--- + +### auth + +Kommando for å administrere legitimasjon og pålogging for leverandører. + +```bash +opencode auth [command] +``` + +--- + +#### pålogging + +OpenCode drives av leverandørlisten på [Models.dev](https://models.dev), så du kan bruke `opencode auth login` til å konfigurere API-nøkler for enhver leverandør du vil bruke. Dette er lagret i `~/.local/share/opencode/auth.json`. + +```bash +opencode auth login +``` + +Når OpenCode starter opp, laster den leverandørene fra legitimasjonsfilen. Og hvis det er noen nøkler definert i miljøene dine eller en `.env`-fil i prosjektet ditt. + +--- + +#### liste + +Viser alle de autentiserte leverandørene som er lagret i legitimasjonsfilen. + +```bash +opencode auth list +``` + +Eller kortversjonen. + +```bash +opencode auth ls +``` + +--- + +#### logge ut + +Logger deg ut av en leverandør ved å fjerne den fra legitimasjonsfilen. + +```bash +opencode auth logout +``` + +--- + +### github + +Administrer GitHub-agenten for depotautomatisering. + +```bash +opencode github [command] +``` + +--- + +#### installer + +Installer GitHub-agenten i depotet ditt. + +```bash +opencode github install +``` + +Dette setter opp den nødvendige GitHub Actions-arbeidsflyten og veileder deg gjennom konfigurasjonsprosessen. [Finn ut mer](/docs/github). + +--- + +#### løp + +Kjør GitHub-agenten. Dette brukes vanligvis i GitHub Actions. + +```bash +opencode github run +``` + +##### Flagg + +| Flagg | Beskrivelse | +| --------- | -------------------------------------- | +| `--event` | GitHub mock event for å kjøre agenten for | +| `--token` | GitHub personlig tilgangstoken | + +--- + +### mcp + +Administrer Model Context Protocol-servere. + +```bash +opencode mcp [command] +``` + +--- + +#### legg til + +Legg til en MCP-server til konfigurasjonen. + +```bash +opencode mcp add +``` + +Denne kommandoen vil veilede deg gjennom å legge til enten en lokal eller ekstern MCP-server. + +--- + +#### liste + +Liste alle konfigurerte MCP-servere og deres tilkoblingsstatus. + +```bash +opencode mcp list +``` + +Eller bruk den korte versjonen. + +```bash +opencode mcp ls +``` + +--- + +#### auth + +Autentiser med en OAuth-aktivert MCP-server. + +```bash +opencode mcp auth [name] +``` + +Hvis du ikke oppgir et servernavn, blir du bedt om å velge blant tilgjengelige OAuth-kompatible servere. + +Du kan også liste opp OAuth-kompatible servere og deres autentiseringsstatus. + +```bash +opencode mcp auth list +``` + +Eller bruk den korte versjonen. + +```bash +opencode mcp auth ls +``` + +--- + +#### logge ut + +Fjern OAuth-legitimasjon for en MCP-server. + +```bash +opencode mcp logout [name] +``` + +--- + +#### feilsøking + +Feilsøk OAuth-tilkoblingsproblemer for en MCP-server. + +```bash +opencode mcp debug +``` + +--- + +### modeller + +List opp alle tilgjengelige modeller fra konfigurerte leverandører. + +```bash +opencode models [provider] +``` + +Denne kommandoen viser alle modeller som er tilgjengelige på tvers av dine konfigurerte leverandører i formatet `provider/model`. + +Dette er nyttig for å finne ut det eksakte modellnavnet som skal brukes i [din konfigurasjon](/docs/config/). + +Du kan eventuelt sende en leverandør ID for å filtrere modeller etter den leverandøren. + +```bash +opencode models anthropic +``` + +#### Flagg + +| Flagg | Beskrivelse | +| ----------- | ------------------------------------------------------------ | +| `--refresh` | Oppdater modellbufferen fra models.dev | +| `--verbose` | Bruk mer detaljert modellutdata (inkluderer metadata som kostnader) | + +Bruk `--refresh`-flagget for å oppdatere den bufrede modelllisten. Dette er nyttig når nye modeller er lagt til en leverandør og du vil se dem i OpenCode. + +```bash +opencode models --refresh +``` + +--- + +### løp + +Kjør opencode i ikke-interaktiv modus ved å sende en melding direkte. + +```bash +opencode run [message..] +``` + +Dette er nyttig for skripting, automatisering eller når du vil ha et raskt svar uten å starte hele TUI. For eksempel. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +Du kan også koble til en kjørende `opencode serve`-forekomst for å unngå MCP-tjenerkaldoppstartstider ved hver kjøring: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### Flagg + +| Flagg | Kort | Beskrivelse | +| ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | | Kommandoen for å kjøre, bruk melding for args | +| `--continue` | `-c` | Fortsett siste økt | +| `--session` | `-s` | Økt ID for å fortsette | +| `--share` | | Del økten | +| `--model` | `-m` | Modell å bruke i form av tilbyder/modell | +| `--agent` | | Agent å bruke | +| `--file` | `-f` | Fil(er) som skal legges ved melding | +| `--format` | | Format: standard (formatert) eller json (rå JSON hendelser) | +| `--title` | | Tittel for økten (bruker avkortet ledetekst hvis ingen verdi er oppgitt) | +| `--attach` | | Koble til en åpen kodeserver som kjører (f.eks. http://localhost:4096) | +| `--port` | | Port for den lokale serveren (standard til tilfeldig port) | + +--- + +### server + +Start en hodeløs OpenCode-server for API-tilgang. Sjekk ut [server-dokumentene](/docs/server) for hele HTTP-grensesnittet. + +```bash +opencode serve +``` + +Dette starter en HTTP-server som gir API tilgang til OpenCode-funksjonalitet uten TUI-grensesnittet. Sett `OPENCODE_SERVER_PASSWORD` for å aktivere HTTP grunnleggende autentisering (brukernavn er standard til `opencode`). + +#### Flagg + +| Flagg | Beskrivelse | +| ------------ | ------------------------------------------ | +| `--port` | Port å lytte på | +| `--hostname` | Vertsnavn å lytte på | +| `--mdns` | Aktiver mDNS-oppdagelse | +| `--cors` | Ytterligere nettleseropprinnelse for å tillate CORS | + +--- + +### økt + +Administrer OpenCode-økter. + +```bash +opencode session [command] +``` + +--- + +#### liste + +List opp alle OpenCode-økter. + +```bash +opencode session list +``` + +##### Flagg + +| Flagg | Kort | Beskrivelse | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` | Begrens til N siste økter | +| `--format` | | Utdataformat: tabell eller json (tabell) | + +--- + +### statistikk + +Vis tokenbruk og kostnadsstatistikk for OpenCode-øktene dine. + +```bash +opencode stats +``` + +#### Flagg + +| Flagg | Beskrivelse | +| ----------- | --------------------------------------------------------------------------- | +| `--days` | Vis statistikk for de siste N dagene (hele tiden) | +| `--tools` | Antall verktøy som skal vises (alle) | +| `--models` | Vis oversikt over modellbruk (skjult som standard). Gi et tall for å vise topp N | +| `--project` | Filtrer etter prosjekt (alle prosjekter, tom streng: gjeldende prosjekt) | + +--- + +### eksport + +Eksporter øktdata som JSON. + +```bash +opencode export [sessionID] +``` + +Hvis du ikke gir en økt ID, blir du bedt om å velge fra tilgjengelige økter. + +--- + +### import + +Importer øktdata fra en JSON-fil eller OpenCode-andel URL. + +```bash +opencode import +``` + +Du kan importere fra en lokal fil eller en OpenCode-andel URL. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### web + +Start en hodeløs OpenCode-server med et webgrensesnitt. + +```bash +opencode web +``` + +Dette starter en HTTP-server og åpner en nettleser for å få tilgang til OpenCode via et nettgrensesnitt. Sett `OPENCODE_SERVER_PASSWORD` for å aktivere HTTP grunnleggende autentisering (brukernavn er standard til `opencode`). + +#### Flagg + +| Flagg | Beskrivelse | +| ------------ | ------------------------------------------ | +| `--port` | Port å lytte på | +| `--hostname` | Vertsnavn å lytte på | +| `--mdns` | Aktiver mDNS-oppdagelse | +| `--cors` | Ytterligere nettleseropprinnelse for å tillate CORS | + +--- + +### acp + +Start en ACP (Agent Client Protocol) server. + +```bash +opencode acp +``` + +Denne kommandoen starter en ACP-server som kommuniserer via stdin/stdout ved å bruke nd-JSON. + +#### Flagg + +| Flagg | Beskrivelse | +| ------------ | --------------------- | +| `--cwd` | Arbeidskatalog | +| `--port` | Port å lytte på | +| `--hostname` | Vertsnavn å lytte på | + +--- + +### avinstaller + +Avinstaller OpenCode og fjern alle relaterte filer. + +```bash +opencode uninstall +``` + +#### Flagg + +| Flagg | Kort | Beskrivelse | +| --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` | Behold konfigurasjonsfiler | +| `--keep-data` | `-d` | Behold øktdata og øyeblikksbilder | +| `--dry-run` | | Vis hva som ville blitt fjernet uten å fjerne | +| `--force` | `-f` | Hopp over bekreftelsesforespørsler | + +--- + +### oppgradering + +Oppdaterer opencode til siste versjon eller en spesifikk versjon. + +```bash +opencode upgrade [target] +``` + +For å oppgradere til siste versjon. + +```bash +opencode upgrade +``` + +For å oppgradere til en bestemt versjon. + +```bash +opencode upgrade v0.1.48 +``` + +#### Flagg + +| Flagg | Kort | Beskrivelse | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` | Installasjonsmetoden som ble brukt; krølle, npm, pnpm, bolle, brygg | + +--- + +## Globale flagg + +Åpenkoden CLI tar følgende globale flagg. + +| Flagg | Kort | Beskrivelse | +| -------------- | ----- | ------------------------------------ | +| `--help` | `-h` | Vis hjelp | +| `--version` | `-v` | Utskriftsnummer | +| `--print-logs` | | Skriv ut logger til stderr | +| `--log-level` | | Loggnivå (DEBUG, INFO, WARN, ERROR) | + +--- + +## Miljøvariabler + +OpenCode kan konfigureres ved hjelp av miljøvariabler. + +| Variabel | Skriv | Beskrivelse | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | boolsk | Del økter automatisk | +| `OPENCODE_GIT_BASH_PATH` | streng | Path to Git Bash kjørbar på Windows | +| `OPENCODE_CONFIG` | streng | Bane til konfigurasjonsfil | +| `OPENCODE_CONFIG_DIR` | streng | Bane til konfigurasjonskatalog | +| `OPENCODE_CONFIG_CONTENT` | streng | Innebygd json-konfigurasjonsinnhold | +| `OPENCODE_DISABLE_AUTOUPDATE` | boolsk | Deaktiver automatiske oppdateringskontroller | +| `OPENCODE_DISABLE_PRUNE` | boolsk | Deaktiver beskjæring av gamle data | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | boolsk | Deaktiver automatiske terminaltitteloppdateringer | +| `OPENCODE_PERMISSION` | streng | Innebygd json-tillatelseskonfigurasjon | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | boolsk | Deaktiver standard plugins | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | boolsk | Deaktiver automatiske LSP servernedlastinger | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | boolsk | Aktiver eksperimentelle modeller | +| `OPENCODE_DISABLE_AUTOCOMPACT` | boolsk | Deaktiver automatisk kontekstkomprimering | +| `OPENCODE_DISABLE_CLAUDE_CODE` | boolsk | Deaktiver lesing fra `.claude` (spørsmål + ferdigheter) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | boolsk | Deaktiver lesing `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | boolsk | Deaktiver innlasting av `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | boolsk | Deaktiver henting av modeller fra eksterne kilder | +| `OPENCODE_FAKE_VCS` | streng | Falsk VCS-leverandør for testformål | +| `OPENCODE_DISABLE_FILETIME_CHECK` | boolsk | Deaktiver filtidskontroll for optimalisering | +| `OPENCODE_CLIENT` | streng | Klientidentifikator (standard til `cli`) | +| `OPENCODE_ENABLE_EXA` | boolsk | Aktiver Exa-nettsøkeverktøy | +| `OPENCODE_SERVER_PASSWORD` | streng | Aktiver grunnleggende autentisering for `serve`/`web` | +| `OPENCODE_SERVER_USERNAME` | streng | Overstyr grunnleggende autentiseringsbrukernavn (standard `opencode`) | +| `OPENCODE_MODELS_URL` | streng | Egendefinert URL for henting av modellkonfigurasjon | + +--- + +### Eksperimentell + +Disse miljøvariablene muliggjør eksperimentelle funksjoner som kan endres eller fjernes. + +| Variabel | Skriv | Beskrivelse | +| ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | boolsk | Aktiver alle eksperimentelle funksjoner | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | boolsk | Aktiver ikonoppdagelse | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | boolsk | Deaktiver kopi ved valg i TUI | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | nummer | Standard tidsavbrudd for bash-kommandoer i ms | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | nummer | Maks utgangstokener for LLM-svar | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | boolsk | Aktiver filovervåker for hele dir | +| `OPENCODE_EXPERIMENTAL_OXFMT` | boolsk | Aktiver oxfmt formatter | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | boolsk | Aktiver eksperimentelt LSP-verktøy | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | boolsk | Deaktiver filovervåking | +| `OPENCODE_EXPERIMENTAL_EXA` | boolsk | Aktiver eksperimentelle Exa-funksjoner | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | boolsk | Aktiver eksperimentell LSP-typekontroll | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | boolsk | Aktiver eksperimentelle markdown-funksjoner | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | boolsk | Aktiver planmodus | diff --git a/packages/web/src/content/docs/nb/commands.mdx b/packages/web/src/content/docs/nb/commands.mdx new file mode 100644 index 000000000..7761c4f4a --- /dev/null +++ b/packages/web/src/content/docs/nb/commands.mdx @@ -0,0 +1,323 @@ +--- +title: Kommandoer +description: Lag egendefinerte kommandoer for repeterende oppgaver. +--- + +Egendefinerte kommandoer lar deg spesifisere en ledetekst du vil kjøre når kommandoen utføres i TUI. + +```bash frame="none" +/my-command +``` + +Egendefinerte kommandoer kommer i tillegg til de innebygde kommandoene som `/init`, `/undo`, `/redo`, `/share`, `/help`. [Finn ut mer](/docs/tui#commands). + +--- + +## Lag kommandofiler + +Lag nedmerkingsfiler i `commands/`-katalogen for å definere egendefinerte kommandoer. + +Opprett `.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Frontmatter definerer kommandoegenskaper. Innholdet blir malen. + +Bruk kommandoen ved å skrive `/` etterfulgt av kommandonavnet. + +```bash frame="none" +"/test" +``` + +--- + +## Konfigurer + +Du kan legge til egendefinerte kommandoer gjennom OpenCode-konfigurasjonen eller ved å lage markdown-filer i katalogen `commands/`. + +--- + +### JSON + +Bruk alternativet `command` i OpenCode [config](/docs/config): + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Nå kan du kjøre denne kommandoen i TUI: + +```bash frame="none" +/test +``` + +--- + +### Markdown + +Du kan også definere kommandoer ved å bruke markdown-filer. Plasser dem i: + +- Globalt: `~/.config/opencode/commands/` +- Per prosjekt: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Markdown-filnavnet blir kommandonavnet. For eksempel lar `test.md` +du løper: + +```bash frame="none" +/test +``` + +--- + +## Spør config + +Spørringene for de egendefinerte kommandoene støtter flere spesielle plassholdere og syntaks. + +--- + +### Argumenter + +Send argumenter til kommandoer ved å bruke plassholderen `$ARGUMENTS`. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +Kjør kommandoen med argumenter: + +```bash frame="none" +/component Button +``` + +Og `$ARGUMENTS` vil bli erstattet med `Button`. + +Du kan også få tilgang til individuelle argumenter ved å bruke posisjonelle parametere: + +- `$1` - Første argument +- `$2` - Andre argument +- `$3` - Tredje argument +- Og så videre... + +For eksempel: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +Kjør kommandoen: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +Dette erstatter: + +- `$1` med `config.json` +- `$2` med `src` +- `$3` med `{ "key": "value" }` + +--- + +### Shell-utgang + +Bruk _!`command`_ for å injisere [bash-kommando](/docs/tui#bash-commands)-utdata i ledeteksten. + +For eksempel, for å lage en egendefinert kommando som analyserer testdekning: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +Eller for å se gjennom nylige endringer: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +Kommandoer kjøres i prosjektets rotkatalog og utdataene deres blir en del av ledeteksten. + +--- + +### Filreferanser + +Inkluder filer i kommandoen din ved å bruke `@` etterfulgt av filnavnet. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +Filinnholdet blir automatisk inkludert i ledeteksten. + +--- + +## Alternativer + +La oss se på konfigurasjonsalternativene i detalj. + +--- + +### Mal + +Alternativet `template` definerer ledeteksten som vil bli sendt til LLM når kommandoen utføres. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +Dette er et **obligatorisk** konfigurasjonsalternativ. + +--- + +### Beskrivelse + +Bruk alternativet `description` for å gi en kort beskrivelse av hva kommandoen gjør. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +Dette vises som beskrivelsen i TUI når du skriver inn kommandoen. + +--- + +### Agent + +Bruk `agent`-konfigurasjonen for å spesifisere hvilken [agent](/docs/agents) som skal utføre denne kommandoen. +Hvis dette er en [subagent](/docs/agents/#subagents), vil kommandoen utløse en subagent påkalling som standard. +For å deaktivere denne virkemåten, sett `subtask` til `false`. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +Dette er et **valgfritt** konfigurasjonsalternativ. Hvis det ikke er spesifisert, brukes din nåværende agent som standard. + +--- + +### Deloppgave + +Bruk `subtask` boolsk for å tvinge kommandoen til å utløse en [subagent](/docs/agents/#subagents) påkalling. +Dette er nyttig hvis du vil at kommandoen ikke skal forurense din primære kontekst og vil **tvinge** agenten til å fungere som en underagent, +selv om `mode` er satt til `primary` på [agent](/docs/agents) konfigurasjonen. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +Dette er et **valgfritt** konfigurasjonsalternativ. + +--- + +### Modell + +Bruk `model`-konfigurasjonen for å overstyre standardmodellen for denne kommandoen. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Dette er et **valgfritt** konfigurasjonsalternativ. + +--- + +## Innebygd + +opencode inkluderer flere innebygde kommandoer som `/init`, `/undo`, `/redo`, `/share`, `/help`; [finn ut mer](/docs/tui#commands). + +:::note +Egendefinerte kommandoer kan overstyre innebygde kommandoer. +::: + +Hvis du definerer en egendefinert kommando med samme navn, vil den overstyre den innebygde kommandoen. diff --git a/packages/web/src/content/docs/nb/config.mdx b/packages/web/src/content/docs/nb/config.mdx new file mode 100644 index 000000000..043263e12 --- /dev/null +++ b/packages/web/src/content/docs/nb/config.mdx @@ -0,0 +1,685 @@ +--- +title: Konfig +description: Ved å bruke OpenCode JSON-konfigurasjonen. +--- + +Du kan konfigurere OpenCode ved å bruke en JSON konfigurasjonsfil. + +--- + +## Format + +OpenCode støtter både **JSON** og **JSONC** (JSON med kommentarer) formater. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## Steder + +Du kan plassere konfigurasjonen på et par forskjellige steder, og de har en +annen rekkefølge. + +:::note +Konfigurasjonsfiler er **slått sammen**, ikke erstattet. +::: + +Konfigurasjonsfiler slås sammen, ikke erstattes. Innstillinger fra følgende konfigurasjonsplasseringer kombineres. Senere konfigurasjoner overstyrer tidligere kun for motstridende nøkler. Ikke-motstridende innstillinger fra alle konfigurasjoner er bevart. + +For eksempel, hvis dine globale konfigurasjonssett `theme: "opencode"` og `autoupdate: true`, og prosjektkonfigurasjonen setter `model: "anthropic/claude-sonnet-4-5"`, vil den endelige konfigurasjonen inkludere alle tre innstillingene. + +--- + +### Forrangsrekkefølge + +Konfigurasjonskilder lastes inn i denne rekkefølgen (senere kilder overstyrer tidligere): + +1. **Ekstern konfig** (fra `.well-known/opencode`) - organisasjonsstandarder +2. **Global konfig** (`~/.config/opencode/opencode.json`) - brukerinnstillinger +3. **Egendefinert konfigurasjon** (`OPENCODE_CONFIG` env var) - egendefinerte overstyringer +4. **Prosjektkonfigurasjon** (`opencode.json` i prosjekt) - prosjektspesifikke innstillinger +5. **`.opencode` kataloger** - agenter, kommandoer, plugins +6. **Inline config** (`OPENCODE_CONFIG_CONTENT` env var) - kjøretidsoverstyringer + +Dette betyr at prosjektkonfigurasjoner kan overstyre globale standardinnstillinger, og globale konfigurasjoner kan overstyre eksterne organisasjonsstandarder. + +:::note +`.opencode` og `~/.config/opencode` katalogene bruker **flertallsnavn** for underkataloger: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/` og `themes/`. Enkeltnavn (f.eks. `agent/`) støttes også for bakoverkompatibilitet. +::: + +--- + +### Fjernkontroll + +Organisasjoner kan gi standardkonfigurasjon via `.well-known/opencode`-endepunktet. Dette hentes automatisk når du autentiserer med en leverandør som støtter det. + +Ekstern konfigurasjon lastes først, og fungerer som basislaget. Alle andre konfigurasjonskilder (global, prosjekt) kan overstyre disse standardinnstillingene. + +For eksempel, hvis organisasjonen din tilbyr MCP servere som er deaktivert som standard: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +Du kan aktivere spesifikke servere i din lokale konfigurasjon: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### Globalt + +Plasser din globale OpenCode-konfigurasjon i `~/.config/opencode/opencode.json`. Bruk global konfigurasjon for brukeromfattende preferanser som temaer, leverandører eller nøkkelbindinger. + +Global konfigurasjon overstyrer eksterne organisasjonsstandarder. + +--- + +### Per prosjekt + +Legg til `opencode.json` i prosjektroten din. Project config har den høyeste prioritet blant standard config-filer - den overstyrer både globale og eksterne konfigurasjoner. + +:::tupp +Plasser prosjektspesifikk konfigurasjon i roten til prosjektet ditt. +::: + +Når OpenCode starter opp, ser den etter en konfigurasjonsfil i gjeldende katalog eller går opp til nærmeste Git-katalog. + +Dette er også trygt å bli sjekket inn i Git og bruker samme skjema som det globale. + +--- + +### Egendefinert bane + +Spesifiser en tilpasset konfigurasjonsfilbane ved å bruke miljøvariabelen `OPENCODE_CONFIG`. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +Egendefinert konfigurasjon lastes inn mellom globale og prosjektkonfigurasjoner i prioritetsrekkefølge. + +--- + +### Egendefinert katalog + +Spesifiser en tilpasset konfigurasjonskatalog ved å bruke `OPENCODE_CONFIG_DIR` +miljøvariabel. Denne katalogen vil bli søkt etter agenter, kommandoer, +moduser og plugins akkurat som standard `.opencode` katalog, og bør +følge samme struktur. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +Den egendefinerte katalogen lastes inn etter den globale konfigurasjonen og `.opencode`-katalogene, slik at den **kan overstyre** innstillingene deres. + +--- + +## Skjema + +Konfigurasjonsfilen har et skjema som er definert i [**`opencode.ai/config.json`**](https://opencode.ai/config.json). + +Redaktøren din skal kunne validere og autofullføre basert på skjemaet. + +--- + +### TUI + +Du kan konfigurere TUI-spesifikke innstillinger gjennom alternativet `tui`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +Tilgjengelige alternativer: + +- `scroll_acceleration.enabled` - Aktiver rulleakselerasjon i macOS-stil. **Tar forrang over `scroll_speed`.** +- `scroll_speed` - Egendefinert rullehastighetsmultiplikator (standard: `3`, minimum: `1`). Ignorert hvis `scroll_acceleration.enabled` er `true`. +- `diff_style` - Kontroller diff-gjengivelse. `"auto"` tilpasser seg terminalbredden, `"stacked"` viser alltid en kolonne. + +[Les mer om bruk av TUI her](/docs/tui). + +--- + +### Server + +Du kan konfigurere serverinnstillinger for kommandoene `opencode serve` og `opencode web` gjennom alternativet `server`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +Tilgjengelige alternativer: + +- `port` - Port for å lytte på. +- `hostname` - Vertsnavn å lytte på. Når `mdns` er aktivert og ingen vertsnavn er angitt, er standard `0.0.0.0`. +- `mdns` - Aktiver mDNS-tjenesteoppdagelse. Dette lar andre enheter på nettverket oppdage OpenCode-serveren din. +- `mdnsDomain` - Egendefinert domenenavn for mDNS-tjeneste. Standard er `opencode.local`. Nyttig for å kjøre flere forekomster på samme nettverk. +- `cors` - Ytterligere opprinnelser for å tillate CORS når du bruker HTTP-serveren fra en nettleserbasert klient. Verdiene må være fullstendige opprinnelser (skjema + vert + valgfri port), f.eks. `https://app.example.com`. + +[Les mer om serveren her](/docs/server). + +--- + +### Verktøy + +Du kan administrere verktøyene en LLM kan bruke gjennom alternativet `tools`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[Les mer om verktøy her](/docs/tools). + +--- + +### Modeller + +Du kan konfigurere leverandørene og modellene du vil bruke i OpenCode-konfigurasjonen gjennom alternativene `provider`, `model` og `small_model`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +Alternativet `small_model` konfigurerer en egen modell for lette oppgaver som tittelgenerering. Som standard prøver OpenCode å bruke en billigere modell hvis en er tilgjengelig fra leverandøren din, ellers faller den tilbake til hovedmodellen din. + +Leverandøralternativer kan inkludere `timeout` og `setCacheKey`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - Be om tidsavbrudd i millisekunder (standard: 300 000). Sett til `false` for å deaktivere. +- `setCacheKey` - Sørg for at en hurtigbuffernøkkel alltid er angitt for utpekt leverandør. + +Du kan også konfigurere [lokale modeller](/docs/models#local). [Finn ut mer](/docs/models). + +--- + +#### Leverandørspesifikke alternativer + +Noen leverandører støtter flere konfigurasjonsalternativer utover de generiske innstillingene `timeout` og `apiKey`. + +##### Amazonas grunnfjell + +Amazon Bedrock støtter AWS-spesifikk konfigurasjon: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - AWS region for grunnfjell (standard til `AWS_REGION` env var eller `us-east-1`) +- `profile` - AWS navngitt profil fra `~/.aws/credentials` (standard til `AWS_PROFILE` env var) +- `endpoint` - Egendefinert endepunkt URL for VPC endepunkter. Dette er et alias for det generiske `baseURL`-alternativet som bruker AWS-spesifikk terminologi. Hvis begge er spesifisert, har `endpoint` forrang. + +:::note +Bærer-tokens (`AWS_BEARER_TOKEN_BEDROCK` eller `/connect`) har forrang over profilbasert autentisering. Se [godkjenningsprioritet](/docs/providers#authentication-precedence) for detaljer. +::: + +[Les mer om konfigurasjon av Amazons grunnfjell](/docs/providers#amazon-bedrock). + +--- + +### Temaer + +Du kan konfigurere temaet du vil bruke i OpenCode-konfigurasjonen gjennom alternativet `theme`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[Les mer her](/docs/themes). + +--- + +### Agenter + +Du kan konfigurere spesialiserte agenter for spesifikke oppgaver gjennom alternativet `agent`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +Du kan også definere agenter ved å bruke markdown-filer i `~/.config/opencode/agents/` eller `.opencode/agents/`. [Les mer her](/docs/agents). + +--- + +### Standard agent + +Du kan angi standard agent ved å bruke alternativet `default_agent`. Dette bestemmer hvilken agent som brukes når ingen er eksplisitt spesifisert. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +Standardagenten må være en primæragent (ikke en underagent). Dette kan være en innebygd agent som `"build"` eller `"plan"`, eller en [egendefinert agent](/docs/agents) du har definert. Hvis den angitte agenten ikke eksisterer eller er en subagent, vil OpenCode falle tilbake til `"build"` med en advarsel. + +Denne innstillingen gjelder for alle grensesnitt: TUI, CLI (`opencode run`), skrivebordsapp og GitHub Action. + +--- + +### Deling + +Du kan konfigurere [share](/docs/share)-funksjonen gjennom alternativet `share`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +Dette krever: + +- `"manual"` - Tillat manuell deling via kommandoer (standard) +- `"auto"` - Del nye samtaler automatisk +- `"disabled"` - Deaktiver deling helt + +Som standard er deling satt til manuell modus der du eksplisitt må dele samtaler ved å bruke kommandoen `/share`. + +--- + +### Kommandoer + +Du kan konfigurere egendefinerte kommandoer for repeterende oppgaver gjennom alternativet `command`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +Du kan også definere kommandoer ved å bruke markdown-filer i `~/.config/opencode/commands/` eller `.opencode/commands/`. [Les mer her](/docs/commands). + +--- + +### Nøkkelbindinger + +Du kan tilpasse nøkkelbindingene dine gjennom alternativet `keybinds`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[Les mer her](/docs/keybinds). + +--- + +### Autooppdatering + +OpenCode vil automatisk laste ned eventuelle nye oppdateringer når den starter opp. Du kan deaktivere dette med alternativet `autoupdate`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +Hvis du ikke vil ha oppdateringer, men ønsker å bli varslet når en ny versjon er tilgjengelig, sett `autoupdate` til `"notify"`. +Legg merke til at dette bare fungerer hvis det ikke ble installert med en pakkebehandling som Homebrew. + +--- + +### Formatere + +Du kan konfigurere kodeformatere gjennom alternativet `formatter`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[Les mer om formattere her](/docs/formatters). + +--- + +### Tillatelser + +Som standard **tillater opencode alle operasjoner** uten å kreve eksplisitt godkjenning. Du kan endre dette ved å bruke alternativet `permission`. + +For å sikre at verktøyene `edit` og `bash` krever brukergodkjenning: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[Les mer om tillatelser her](/docs/permissions). + +--- + +### Komprimering + +Du kan kontrollere atferden for kontekstkomprimering gjennom alternativet `compaction`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - Komprimer økten automatisk når konteksten er full (standard: `true`). +- `prune` - Fjern gamle verktøyutganger for å lagre tokens (standard: `true`). + +--- + +### Overvåker + +Du kan konfigurere ignoreringsmønstre for filovervåking gjennom alternativet `watcher`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +Mønstre følger glob-syntaks. Bruk dette for å ekskludere støyende kataloger fra filvisning. + +--- + +### MCP servere + +Du kan konfigurere MCP-servere du vil bruke gjennom alternativet `mcp`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[Les mer her](/docs/mcp-servers). + +--- + +### Plugins + +[Plugins](/docs/plugins) utvider OpenCode med tilpassede verktøy, kroker og integrasjoner. + +Plasser plugin-filer i `.opencode/plugins/` eller `~/.config/opencode/plugins/`. Du kan også laste inn plugins fra npm gjennom alternativet `plugin`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[Les mer her](/docs/plugins). + +--- + +### Instruksjoner + +Du kan konfigurere instruksjonene for modellen du bruker gjennom alternativet `instructions`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Dette krever en rekke baner og globmønstre til instruksjonsfiler. [Les mer +om regler her](/docs/rules). + +--- + +### Deaktiverte leverandører + +Du kan deaktivere leverandører som lastes automatisk gjennom alternativet `disabled_providers`. Dette er nyttig når du vil forhindre at enkelte leverandører lastes inn selv om deres legitimasjon er tilgjengelig. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +`disabled_providers` har prioritet over `enabled_providers`. +::: + +Alternativet `disabled_providers` godtar en rekke leverandør-ID-er. Når en leverandør er deaktivert: + +- Den blir ikke lastet selv om miljøvariabler er angitt. +- Den vil ikke bli lastet inn selv om API-nøkler er konfigurert gjennom `/connect`-kommandoen. +- Leverandørens modeller vises ikke i modellvalglisten. + +--- + +### Aktiverte leverandører + +Du kan spesifisere en godkjenningsliste over leverandører gjennom alternativet `enabled_providers`. Når angitt, vil bare de angitte leverandørene være aktivert og alle andre vil bli ignorert. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +Dette er nyttig når du vil begrense OpenCode til kun å bruke spesifikke leverandører i stedet for å deaktivere dem én etter én. + +:::note +`disabled_providers` har prioritet over `enabled_providers`. +::: + +Hvis en leverandør vises i både `enabled_providers` og `disabled_providers`, har `disabled_providers` prioritet for bakoverkompatibilitet. + +--- + +### Eksperimentell + +`experimental`-nøkkelen inneholder alternativer som er under aktiv utvikling. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::forsiktighet +Eksperimentelle alternativer er ikke stabile. De kan endres eller fjernes uten varsel. +::: + +--- + +## Variabler + +Du kan bruke variabelerstatning i konfigurasjonsfilene dine for å referere til miljøvariabler og filinnhold. + +--- + +### Env vars + +Bruk `{env:VARIABLE_NAME}` for å erstatte miljøvariabler: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +Hvis miljøvariabelen ikke er angitt, vil den bli erstattet med en tom streng. + +--- + +### Filer + +Bruk `{file:path/to/file}` for å erstatte innholdet i en fil: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +Filbaner kan være: + +- I forhold til konfigurasjonsfilkatalogen +- Eller absolutte baner som begynner med `/` eller `~` + +Disse er nyttige for: + +- Oppbevaring av sensitive data som API-nøkler i separate filer. +- Inkludert store instruksjonsfiler uten å rote konfigurasjonen din. +- Deling av vanlige konfigurasjonsbiter på tvers av flere konfigurasjonsfiler. diff --git a/packages/web/src/content/docs/nb/custom-tools.mdx b/packages/web/src/content/docs/nb/custom-tools.mdx new file mode 100644 index 000000000..556935da0 --- /dev/null +++ b/packages/web/src/content/docs/nb/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: Egendefinerte verktøy +description: Lag verktøy som LLM kan kalle inn opencode. +--- + +Egendefinerte verktøy er funksjoner du oppretter som LLM kan ringe under samtaler. De fungerer sammen med opencodes [innebygde verktøy](/docs/tools) som `read`, `write` og `bash`. + +--- + +## Opprette et verktøy + +Verktøy er definert som **TypeScript**- eller **JavaScript**-filer. Verktøydefinisjonen kan imidlertid påkalle skript skrevet på **alle språk** - TypeScript eller JavaScript brukes bare for selve verktøydefinisjonen. + +--- + +### Plassering + +De kan defineres: + +- Lokalt ved å plassere dem i `.opencode/tools/`-katalogen til prosjektet ditt. +- Eller globalt, ved å plassere dem i `~/.config/opencode/tools/`. + +--- + +### Struktur + +Den enkleste måten å lage verktøy på er å bruke `tool()`-hjelperen som gir typesikkerhet og validering. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +**filnavnet** blir **verktøynavnet**. Ovennevnte oppretter et `database`-verktøy. + +--- + +#### Flere verktøy per fil + +Du kan også eksportere flere verktøy fra en enkelt fil. Hver eksport blir **et eget verktøy** med navnet **`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +Dette lager to verktøy: `math_add` og `math_multiply`. + +--- + +### Argumenter + +Du kan bruke `tool.schema`, som bare er [Zod](https://zod.dev), for å definere argumenttyper. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +Du kan også importere [Zod](https://zod.dev) direkte og returnere et vanlig objekt: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### Kontekst + +Verktøy mottar kontekst om gjeldende økt: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +Bruk `context.directory` for øktens arbeidskatalog. +Bruk `context.worktree` for git-arbeidstreroten. + +--- + +## Eksempler + +### Skriv et verktøy i Python + +Du kan skrive verktøyene dine på hvilket som helst språk du vil. Her er et eksempel som legger til to tall ved hjelp av Python. + +Først lager du verktøyet som et Python-skript: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +Lag deretter verktøydefinisjonen som påkaller den: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +Her bruker vi [`Bun.$`](https://bun.com/docs/runtime/shell)-verktøyet for å kjøre Python-skriptet. diff --git a/packages/web/src/content/docs/nb/ecosystem.mdx b/packages/web/src/content/docs/nb/ecosystem.mdx new file mode 100644 index 000000000..50eb07903 --- /dev/null +++ b/packages/web/src/content/docs/nb/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: Økosystem +description: Prosjekter og integrasjoner bygget med OpenCode. +--- + +En samling fellesskapsprosjekter bygget på OpenCode. + +:::note +Vil du legge til ditt OpenCode-relaterte prosjekt til denne listen? Send inn en PR. +::: + +Du kan også sjekke ut [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) og [opencode.cafe](https://opencode.cafe), et fellesskap som samler økosystemet og fellesskapet. + +--- + +## Plugins + +| Navn | Beskrivelse | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | Kjør OpenCode-økter automatisk i isolerte Daytona-sandkasser med git-synkronisering og live forhåndsvisninger | +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Injiser automatisk Helicone-økthoder for forespørselsgruppering | +| [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Auto-injiser TypeScript/Svelte-typer i fillesninger med oppslagsverktøy | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Bruk ChatGPT Plus/Pro-abonnementet ditt i stedet for API kreditter | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Bruk din eksisterende Gemini-plan i stedet for API-fakturering | +| [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Bruk Antigravitys gratis modeller i stedet for API fakturering | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Multi-branch devcontainer-isolasjon med grunne kloner og automatisk tildelte porter | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Antigravity OAuth-plugin, med støtte for Google Søk og mer robust API-håndtering | +| [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Optimaliser bruken av token ved å beskjære utdaterte verktøy | +| [opencode-websearch-sitert](https://github.com/ghoulr/opencode-websearch-cited.git) | Legg til innebygd nettsøk-støtte for støttede leverandører med Googles jordet stil | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Gjør det mulig for AI-agenter å kjøre bakgrunnsprosesser i en PTY, sende interaktive input til dem. | +| [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Instruksjoner for ikke-interaktive skallkommandoer - forhindrer henger fra TTY-avhengige operasjoner | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Spor OpenCode-bruk med Wakatime | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Rydd opp avslagstabeller produsert av LLMs | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | 10 ganger raskere koderedigering med Morph Fast Apply API og late redigeringsmarkører | +| [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Bakgrunnsagenter, forhåndsbygde LSP/AST/MCP verktøy, kurerte agenter, Claude Code-kompatibel | +| [opencode-notificator](https://github.com/panta82/opencode-notificator) | Skrivebordsvarsler og lydvarsler for OpenCode-økter | +| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Skrivebordsvarsler og lydvarsler for tillatelse, fullføring og feilhendelser | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | AI-drevet automatisk Zellij-sesjonsnavn basert på OpenCode-kontekst | +| [åpenkode-dyktig](https://github.com/zenobi-us/opencode-skillful) | Tillat OpenCode-agenter til late load-meldinger på forespørsel med ferdighetsoppdagelse og injeksjon | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Vedvarende minne på tvers av økter ved hjelp av Supermemory | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Interaktiv plangjennomgang med visuell merknad og privat/offline deling | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Utvid opencode /kommandoer til et kraftig orkestreringssystem med granulær flytkontroll | +| [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Planlegg gjentakende jobber ved hjelp av launchd (Mac) eller systemd (Linux) med cron-syntaks | +| [mikokode](https://github.com/vtemian/micode) | Strukturert brainstorm → Plan → Implementer arbeidsflyt med øktkontinuitet | +| [oktto](https://github.com/vtemian/octto) | Interaktiv nettleser UI for AI idédugnad med flerspørsmålsskjemaer | +| [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Claude Bakgrunnsagenter i kodestil med asynkrondelegering og kontekstutholdenhet | +| [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Innfødte OS-varsler for OpenCode – vet når oppgaver fullføres | +| [opencode-arbeidsområde](https://github.com/kdcokenny/opencode-workspace) | Medfølgende multi-agent orkestreringssele – 16 komponenter, én installasjon | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Nullfriksjon git-arbeidstre for OpenCode | + +--- + +## Prosjekter + +| Navn | Beskrivelse | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | Discord-bot for å kontrollere OpenCode-økter, bygget på SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Neovim-plugin for redaktørbevisste meldinger, bygget på API | +| [portal](https://github.com/hosenur/portal) | Mobile-first web UI for OpenCode over Tailscale/VPN | +| [opencode plugin-mal](https://github.com/zenobi-us/opencode-plugin-template/) | Mal for å bygge OpenCode-plugins | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Neovim-grensesnitt for opencode - en terminalbasert AI-kodingsagent | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Vercel AI SDK leverandør for bruk av OpenCode via @opencode-ai/sdk | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | Web-/skrivebordsapp og VS kodeutvidelse for OpenCode | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Obsidian-plugin som bygger inn OpenCode i Obsidians UI | +| [OpenWork](https://github.com/different-ai/openwork) | Et åpen kildekode-alternativ til Claude Cowork, drevet av OpenCode | +| [ocx](https://github.com/kdcokenny/ocx) | OpenCode utvidelsesbehandler med bærbare, isolerte profiler. | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Desktop, Web, Mobile og Remote Client App for OpenCode | + +--- + +## Agenter + +| Navn | Beskrivelse | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [Agentic](https://github.com/Cluster444/agentic) | Modulære AI agenter og kommandoer for strukturert utvikling | +| [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Konfigurasjoner, meldinger, agenter og plugins for forbedrede arbeidsflyter | diff --git a/packages/web/src/content/docs/nb/enterprise.mdx b/packages/web/src/content/docs/nb/enterprise.mdx new file mode 100644 index 000000000..063640b38 --- /dev/null +++ b/packages/web/src/content/docs/nb/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: Enterprise +description: Sikker bruk av OpenCode i din organisasjon. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise er for organisasjoner som ønsker å sikre at deres kode og data aldri forlater deres infrastruktur. Den kan gjøre dette ved å bruke en sentralisert konfigurasjon som integreres med din SSO og interne AI gateway. + +:::note +OpenCode lagrer ingen av koden eller kontekstdataene dine. +::: + +For å komme i gang med OpenCode Enterprise: + +1. Gjør en prøveversjon internt med teamet ditt. +2. **Kontakt oss** for å diskutere priser og implementeringsalternativer. + +--- + +## Prøve + +OpenCode er åpen kildekode og lagrer ingen av koden eller kontekstdataene dine, så utviklerne dine kan ganske enkelt [komme i gang](/docs/) og utføre en prøveversjon. + +--- + +### Datahåndtering + +**OpenCode lagrer ikke koden eller kontekstdataene dine.** All behandling skjer lokalt eller gjennom direkte API-anrop til AI-leverandøren din. + +Dette betyr at så lenge du bruker en leverandør du stoler på, eller en intern +AI gateway, kan du bruke OpenCode sikkert. + +Det eneste forbeholdet her er den valgfrie `/share`-funksjonen. + +--- + +#### Deler samtaler + +Hvis en bruker aktiverer funksjonen `/share`, sendes samtalen og dataene knyttet til den til tjenesten vi bruker til å være vert for disse delesidene på opencode.ai. + +Dataene leveres for øyeblikket gjennom vårt CDNs edge-nettverk, og bufres på kanten nær brukerne dine. + +Vi anbefaler at du deaktiverer dette for prøveversjonen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[Finn ut mer om deling](/docs/share). + +--- + +### Kodeeierskap + +**Du eier all kode produsert av OpenCode.** Det er ingen lisensieringsbegrensninger eller eierskapskrav. + +--- + +## Priser + +Vi bruker en per-sete-modell for OpenCode Enterprise. Hvis du har din egen LLM-gateway, tar vi ikke betalt for tokens som brukes. For mer informasjon om priser og implementeringsalternativer, **kontakt oss**. + +--- + +## Implementering + +Når du har fullført prøveversjonen og du er klar til å bruke OpenCode på +organisasjonen din, kan du **kontakte oss** for å diskutere +prissetting og implementeringsalternativer. + +--- + +### Sentral konfig + +Vi kan sette opp OpenCode for å bruke en enkelt sentral konfigurasjon for hele organisasjonen din. + +Denne sentraliserte konfigurasjonen kan integreres med SSO-leverandøren din og sikrer at alle brukere kun får tilgang til din interne AI-gateway. + +--- + +### SSO integrasjon + +Gjennom den sentrale konfigurasjonen kan OpenCode integreres med organisasjonens SSO-leverandør for autentisering. + +Dette lar OpenCode få legitimasjon for din interne AI-gateway gjennom ditt eksisterende identitetsadministrasjonssystem. + +--- + +### Intern AI gateway + +Med den sentrale konfigurasjonen kan OpenCode også konfigureres til kun å bruke din interne AI-gateway. + +Du kan også deaktivere alle andre AI-leverandører, og sikre at alle forespørsler går gjennom organisasjonens godkjente infrastruktur. + +--- + +### Selvhosting + +Selv om vi anbefaler å deaktivere delingssidene for å sikre at dataene dine aldri forsvinner +organisasjonen din, kan vi også hjelpe deg med å være vert for dem på din infrastruktur. + +Dette er nå på veikartet vårt. Hvis du er interessert, **gi oss beskjed**. + +--- + +## FAQ + +

+What is OpenCode Enterprise? + +OpenCode Enterprise er for organisasjoner som ønsker å sikre at deres kode og data aldri forlater deres infrastruktur. Den kan gjøre dette ved å bruke en sentralisert konfigurasjon som integreres med din SSO og interne AI gateway. + +
+ +
+How do I get started with OpenCode Enterprise? + +Bare start med en intern prøveversjon med teamet ditt. OpenCode lagrer som standard ikke koden eller kontekstdataene dine, noe som gjør det enkelt å komme i gang. + +Så **kontakt oss** for å diskutere priser og implementeringsalternativer. + +
+ +
+How does enterprise pricing work? + +Vi tilbyr bedriftspriser per sete. Hvis du har din egen LLM-gateway, tar vi ikke betalt for tokens som brukes. For ytterligere detaljer, **kontakt oss** for et tilpasset tilbud basert på organisasjonens behov. + +
+ +
+Is my data secure with OpenCode Enterprise? + +Ja. OpenCode lagrer ikke koden eller kontekstdataene dine. All behandling skjer lokalt eller gjennom direkte API-anrop til AI-leverandøren din. Med sentral konfigurasjon og SSO-integrasjon forblir dataene dine sikre i organisasjonens infrastruktur. + +
+ +
+Can we use our own private NPM registry? + +OpenCode støtter private npm-registre gjennom Buns opprinnelige `.npmrc`-filstøtte. Hvis organisasjonen din bruker et privat register, som JFrog Artifactory, Nexus eller lignende, sørg for at utviklerne er autentisert før du kjører OpenCode. + +Slik setter du opp autentisering med ditt private register: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +Dette oppretter `~/.npmrc` med autentiseringsdetaljer. OpenCode vil automatisk +plukke opp dette. + +:::forsiktighet +Du må være logget inn i det private registeret før du kjører OpenCode. +::: + +Alternativt kan du konfigurere en `.npmrc`-fil manuelt: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Utviklere må være logget på det private registeret før de kjører OpenCode for å sikre at pakker kan installeres fra bedriftsregisteret. + +
diff --git a/packages/web/src/content/docs/nb/formatters.mdx b/packages/web/src/content/docs/nb/formatters.mdx new file mode 100644 index 000000000..9349188bc --- /dev/null +++ b/packages/web/src/content/docs/nb/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: Formatere +description: OpenCode bruker språkspesifikke formatere. +--- + +OpenCode formaterer automatisk filer etter at de er skrevet eller redigert ved hjelp av språkspesifikke formatere. Dette sikrer at koden som genereres følger kodestilene til prosjektet ditt. + +--- + +## Innebygd + +OpenCode kommer med flere innebygde formatere for populære språk og rammeverk. Nedenfor er en liste over formatere, støttede filutvidelser og kommandoer eller konfigurasjonsalternativer den trenger. + +| Formater | Utvidelser | Krav | +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| gofmt | .go | `gofmt` kommando tilgjengelig | +| blande | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` kommando tilgjengelig | +| penere | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml og [mer](https://prettier.io/docs/en/index.html) | `prettier` avhengighet i `package.json` | +| biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml og [mer](https://biomejs.dev/) | `biome.json(c)` konfigurasjonsfil | +| sikk | .zig, .zon | `zig` kommando tilgjengelig | +| klang-format | .c, .cpp, .h, .hpp, .ino og [mer](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` konfigurasjonsfil | +| ktlint | .kt, .kts | `ktlint` kommando tilgjengelig | +| ruff | .py, .pyi | `ruff` kommando tilgjengelig med config | +| rustfmt | .rs | `rustfmt` kommando tilgjengelig | +| cargofmt | .rs | `cargo fmt` kommando tilgjengelig | +| uv | .py, .pyi | `uv` kommando tilgjengelig | +| rubocop | .rb, .rake, .gemspec, .ru | `rubocop` kommando tilgjengelig | +| standardrb | .rb, .rake, .gemspec, .ru | `standardrb` kommando tilgjengelig | +| htmlbeautifier | .erb, .html.erb | `htmlbeautifier` kommando tilgjengelig | +| luft | .R | `air` kommando tilgjengelig | +| dart | .dart | `dart` kommando tilgjengelig | +| ocamlformat | .ml, .mli | `ocamlformat` kommando tilgjengelig og `.ocamlformat` konfigurasjonsfil | +| terraform | .tf, .tfvars | `terraform` kommando tilgjengelig | +| glimt | .gleam | `gleam` kommando tilgjengelig | +| nixfmt | .nix | `nixfmt` kommando tilgjengelig | +| shfmt | .sh, .bash | `shfmt` kommando tilgjengelig | +| halvliter | .php | `laravel/pint` avhengighet i `composer.json` | +| oxfmt (Eksperimentell) | .js, .jsx, .ts, .tsx | `oxfmt` avhengighet i `package.json` og et [eksperimentelt env variabel flagg](/docs/cli/#experimental) | +| ormolu | .hs | `ormolu` kommando tilgjengelig | + +Så hvis prosjektet ditt har `prettier` i `package.json`, vil OpenCode automatisk bruke det. + +--- + +## Slik fungerer det + +Når OpenCode skriver eller redigerer en fil, gjør den: + +1. Kontrollerer filtypen mot alle aktiverte formatere. +2. Kjører riktig formateringskommando på filen. +3. Bruker formateringsendringene automatisk. + +Denne prosessen skjer i bakgrunnen, og sikrer at kodestilene dine opprettholdes uten noen manuelle trinn. + +--- + +## Konfigurer + +Du kan tilpasse formatere gjennom `formatter`-delen i OpenCode-konfigurasjonen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +Hver formateringskonfigurasjon støtter følgende: + +| Eiendom | Skriv | Beskrivelse | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` | boolsk | Sett dette til `true` for å deaktivere formatereren | +| `command` | streng[] | Kommandoen som skal kjøres for formatering | +| `environment` | objekt | Miljøvariabler som skal angis når du kjører formateringsverktøyet | +| `extensions` | streng[] | Filutvidelser denne formatereren skal håndtere | + +La oss se på noen eksempler. + +--- + +### Deaktivering av formatere + +For å deaktivere **alle** formatere globalt, sett `formatter` til `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +For å deaktivere en **spesifikk** formatering, sett `disabled` til `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Egendefinerte formatere + +Du kan overstyre de innebygde formaterne eller legge til nye ved å spesifisere kommandoen, miljøvariablene og filtypene: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +**`$FILE` plassholderen** i kommandoen vil bli erstattet med banen til filen som formateres. diff --git a/packages/web/src/content/docs/nb/github.mdx b/packages/web/src/content/docs/nb/github.mdx new file mode 100644 index 000000000..08cd56168 --- /dev/null +++ b/packages/web/src/content/docs/nb/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: Bruk OpenCode i GitHub-problemer og pull-forespørsler. +--- + +OpenCode integreres med GitHub-arbeidsflyten din. Nevn `/opencode` eller `/oc` i kommentaren din, og OpenCode vil utføre oppgaver i din GitHub Actions-løper. + +--- + +## Funksjoner + +- **Triage-problemer**: Be OpenCode se på et problem og forklare det for deg. +- **Fiks og implementer**: Be OpenCode om å fikse et problem eller implementere en funksjon. Og den vil fungere i en ny gren og sender inn en PR med alle endringene. +- **Sikkert**: OpenCode kjører inne i GitHubs løpere. + +--- + +## Installasjon + +Kjør følgende kommando i et prosjekt som er i en GitHub-repo: + +```bash +opencode github install +``` + +Dette vil lede deg gjennom å installere GitHub-appen, lage arbeidsflyten og sette opp hemmeligheter. + +--- + +### Manuell oppsett + +Eller du kan sette den opp manuelt. + +1. **Installer GitHub-appen** + + Gå over til [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). Sørg for at den er installert på mållageret. + +2. **Legg til arbeidsflyten** + + Legg til følgende arbeidsflytfil til `.github/workflows/opencode.yml` i repoen. Sørg for å sette riktige `model` og nødvendige API nøkler i `env`. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **Lagre API-nøklene i hemmeligheter** + + Utvid **Hemmeligheter og variabler** til venstre i **innstillingene** for organisasjonen eller prosjektet og velg **Handlinger**. Og legg til de nødvendige API-nøklene. + +--- + +## Konfigurasjon + +- `model`: Modellen som skal brukes med OpenCode. Tar formatet `provider/model`. Dette er **obligatorisk**. +- `agent`: Agenten som skal brukes. Må være en primær agent. Faller tilbake til `default_agent` fra config eller `"build"` hvis ikke funnet. +- `share`: Om OpenCode-økten skal deles. Standard er **true** for offentlige depoter. +- `prompt`: Valgfri egendefinert melding for å overstyre standard oppførsel. Bruk dette til å tilpasse hvordan OpenCode behandler forespørsler. +- `token`: Valgfritt GitHub-tilgangstoken for å utføre operasjoner som å lage kommentarer, foreta endringer og åpne pull-forespørsler. Som standard bruker OpenCode installasjonstilgangstokenet fra OpenCode GitHub-appen, så forpliktelser, kommentarer og pull-forespørsler ser ut til å komme fra appen. + + Alternativt kan du bruke GitHub Action-løperens [innebygde `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) uten å installere OpenCode GitHub-appen. Bare sørg for å gi de nødvendige tillatelsene i arbeidsflyten din: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + Du kan også bruke en [personlig tilgangstoken](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) hvis foretrukket. + +--- + +## Støttede hendelser + +OpenCode kan utløses av følgende GitHub-hendelser: + +| Hendelsestype | Utløst av | Detaljer | +| ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | Kommenter et problem eller PR | Nevn `/opencode` eller `/oc` i kommentaren din. OpenCode leser kontekst og kan opprette grener, åpne PR-er eller svare. | +| `pull_request_review_comment` | Kommenter spesifikke kodelinjer i en PR | Nevn `/opencode` eller `/oc` mens du ser gjennom koden. OpenCode mottar filbane, linjenummer og diff-kontekst. | +| `issues` | Utgave åpnet eller redigert | Utløs OpenCode automatisk når problemer opprettes eller endres. Krever `prompt` inngang. | +| `pull_request` | PR åpnet eller oppdatert | Utløs OpenCode automatisk når PR-er åpnes, synkroniseres eller gjenåpnes. Nyttig for automatiserte anmeldelser. | +| `schedule` | Cron-basert tidsplan | Kjør OpenCode etter en tidsplan. Krever `prompt` inngang. Utdata går til logger og PR (ingen problem å kommentere). | +| `workflow_dispatch` | Manuell utløser fra GitHub UI | Utløs OpenCode på forespørsel via fanen Handlinger. Krever `prompt` inngang. Utdata går til logger og PR-er. | + +### Tidsplan Eksempel + +Kjør OpenCode på en tidsplan for å utføre automatiserte oppgaver: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +For planlagte arrangementer er `prompt`-inngangen **påkrevd** siden det ikke er noen kommentarer å trekke ut instruksjoner fra. Planlagte arbeidsflyter kjører uten brukerkontekst for tillatelsessjekking, så arbeidsflyten må gi `contents: write` og `pull-requests: write` hvis du forventer at OpenCode oppretter grener eller PR-er. + +--- + +### Pull Request Eksempel + +Gjennomgå PR-er automatisk når de åpnes eller oppdateres: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +For `pull_request`-hendelser, hvis ingen `prompt` er oppgitt, går OpenCode som standard gjennom pull-forespørselen. + +--- + +### Issues Triage Eksempel + +Triage automatisk nye problemer. Dette eksemplet filtrerer til kontoer eldre enn 30 dager for å redusere spam: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +For `issues`-hendelser er `prompt`-inngangen **påkrevd** siden det ikke er noen kommentarer å trekke ut instruksjoner fra. + +--- + +## Egendefinerte meldinger + +Overstyr standardmeldingen for å tilpasse OpenCodes oppførsel for arbeidsflyten din. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Dette er nyttig for å håndheve spesifikke vurderingskriterier, kodestandarder eller fokusområder som er relevante for prosjektet ditt. + +--- + +## Eksempler + +Her er noen eksempler på hvordan du kan bruke OpenCode i GitHub. + +- **Forklar et problem** + + Legg til denne kommentaren i en GitHub-utgave. + + ``` + /opencode explain this issue + ``` + + OpenCode vil lese hele tråden, inkludert alle kommentarer, og svare med en tydelig forklaring. + +- **Fiks et problem** + + I en GitHub-utgave, si: + + ``` + /opencode fix this + ``` + + Og OpenCode vil opprette en ny gren, implementere endringene og åpne en PR med endringene. + +- **Gjennomgå PR-er og gjør endringer** + + Legg igjen følgende kommentar på en GitHub PR. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + OpenCode vil implementere den forespurte endringen og forplikte den til samme PR. + +- **Se gjennom spesifikke kodelinjer** + + Legg igjen en kommentar direkte på kodelinjer i PRs "Filer"-fane. OpenCode oppdager automatisk filen, linjenumrene og diff-konteksten for å gi presise svar. + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + Når du kommenterer spesifikke linjer, mottar OpenCode: + - Den nøyaktige filen blir gjennomgått + - De spesifikke kodelinjene + - Den ulik konteksten rundt + - Linjenummerinformasjon + + Dette gir mulighet for mer målrettede forespørsler uten å måtte spesifisere filstier eller linjenumre manuelt. diff --git a/packages/web/src/content/docs/nb/gitlab.mdx b/packages/web/src/content/docs/nb/gitlab.mdx new file mode 100644 index 000000000..6623e157d --- /dev/null +++ b/packages/web/src/content/docs/nb/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: Bruk OpenCode i GitLab-problemer og sammenslåingsforespørsler. +--- + +OpenCode integreres med GitLab arbeidsflyten gjennom GitLab CI/CD pipeline eller med GitLab Duo. + +I begge tilfeller vil OpenCode kjøre på GitLab-løperne dine. + +--- + +## GitLab CI + +OpenCode fungerer i en vanlig GitLab-pipeline. Du kan bygge den inn i en pipeline som en [CI komponent](https://docs.gitlab.com/ee/ci/components/) + +Her bruker vi en fellesskapsskapt CI/CD-komponent for OpenCode — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### Funksjoner + +- **Bruk tilpasset konfigurasjon per jobb**: Konfigurer OpenCode med en tilpasset konfigurasjonskatalog, for eksempel `./config/#custom-directory` for å aktivere eller deaktivere funksjonalitet per OpenCode-anrop. +- **Minimalt oppsett**: CI-komponenten setter opp OpenCode i bakgrunnen, du trenger bare å lage OpenCode-konfigurasjonen og den første ledeteksten. +- **Fleksibel**: CI-komponenten støtter flere innganger for å tilpasse virkemåten + +--- + +### Oppsett + +1. Lagre OpenCode-autentiseringen JSON som en filtype CI miljøvariabler under **Innstillinger** > **CI/CD** > **Variabler**. Sørg for å merke dem som "Masket og skjult". +2. Legg til følgende i `.gitlab-ci.yml`-filen. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +For flere inndata og brukstilfeller [sjekk ut dokumentene](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) for denne komponenten. + +--- + +## GitLab Duo + +OpenCode integreres med din GitLab arbeidsflyt. +Nevn `@opencode` i en kommentar, og OpenCode vil utføre oppgaver innenfor din GitLab CI pipeline. + +--- + +### Funksjoner + +- **Triage-problemer**: Be OpenCode se på et problem og forklare det for deg. +- **Fiks og implementer**: Be OpenCode om å fikse et problem eller implementere en funksjon. + Det vil opprette en ny filial og sende en sammenslåingsforespørsel med endringene. +- **Sikkert**: OpenCode kjører på GitLab-løperne dine. + +--- + +### Oppsett + +OpenCode kjører i GitLab CI/CD pipeline, her er det du trenger for å sette den opp: + +:::tupp +Sjekk ut [**GitLab-dokumentene**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) for oppdaterte instruksjoner. +::: + +1. Konfigurer GitLab-miljøet ditt +2. Sett opp CI/CD +3. Få en AI modellleverandør API nøkkel +4. Opprett en tjenestekonto +5. Konfigurer CI/CD variabler +6. Lag en flytkonfigurasjonsfil, her er et eksempel: + +
+ + Flow configuration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +Du kan se [GitLab CLI agents docs](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) for detaljerte instruksjoner. + +--- + +### Eksempler + +Her er noen eksempler på hvordan du kan bruke OpenCode i GitLab. + +:::tupp +Du kan konfigurere til å bruke en annen triggerfrase enn `@opencode`. +::: + +- **Forklar et problem** + + Legg til denne kommentaren i en GitLab-utgave. + + ``` + @opencode explain this issue + ``` + + OpenCode vil lese problemet og svare med en klar forklaring. + +- **Fiks et problem** + + I en GitLab-utgave, si: + + ``` + @opencode fix this + ``` + + OpenCode vil opprette en ny gren, implementere endringene og åpne en sammenslåingsforespørsel med endringene. + +- **Gjennomgå sammenslåingsforespørsler** + + Legg igjen følgende kommentar på en GitLab-sammenslåingsforespørsel. + + ``` + @opencode review this merge request + ``` + + OpenCode vil gjennomgå sammenslåingsforespørselen og gi tilbakemelding. diff --git a/packages/web/src/content/docs/nb/ide.mdx b/packages/web/src/content/docs/nb/ide.mdx new file mode 100644 index 000000000..71546e876 --- /dev/null +++ b/packages/web/src/content/docs/nb/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: OpenCode-utvidelsen for VS-kode, markør og andre IDE-er +--- + +OpenCode integreres med VS-kode, markør eller en hvilken som helst IDE som støtter en terminal. Bare kjør `opencode` i terminalen for å komme i gang. + +--- + +## Bruk + +- **Hurtigstart**: Bruk `Cmd+Esc` (Mac) eller `Ctrl+Esc` (Windows/Linux) for å åpne OpenCode i en delt terminalvisning, eller fokuser en eksisterende terminaløkt hvis en allerede kjører. +- **Ny økt**: Bruk `Cmd+Shift+Esc` (Mac) eller `Ctrl+Shift+Esc` (Windows/Linux) for å starte en ny OpenCode-terminaløkt, selv om en allerede er åpen. Du kan også klikke på OpenCode-knappen i UI. +- **Kontekstbevissthet**: Del automatisk ditt nåværende valg eller fane med OpenCode. +- **Snarveier for filreferanse**: Bruk `Cmd+Option+K` (Mac) eller `Alt+Ctrl+K` (Linux/Windows) for å sette inn filreferanser. For eksempel `@File#L37-42`. + +--- + +## Installasjon + +For å installere OpenCode på VS Code og populære gafler som Cursor, Windsurf, VSCodium: + +1. Åpne VS Code +2. Åpne den integrerte terminalen +3. Kjør `opencode` - utvidelsen installeres automatisk + +Hvis du derimot vil bruke din egen IDE når du kjører `/editor` eller `/export` fra TUI, må du angi `export EDITOR="code --wait"`. [Finn ut mer](/docs/tui/#editor-setup). + +--- + +### Manuell installasjon + +Søk etter **OpenCode** i Extension Marketplace og klikk på **Install**. + +--- + +### Feilsøking + +Hvis utvidelsen ikke kan installeres automatisk: + +- Sørg for at du kjører `opencode` i den integrerte terminalen. +- Bekreft at CLI for IDE er installert: + - For VS Code: `code` kommando + - For markør: `cursor` kommando + - For Windsurf: `windsurf` kommando + - For VSCodium: `codium` kommando + - Hvis ikke, kjør `Cmd+Shift+P` (Mac) eller `Ctrl+Shift+P` (Windows/Linux) og søk etter "Shell Command: Install 'code' command in PATH" (eller tilsvarende for din IDE) +- Sørg for at VS Code har tillatelse til å installere utvidelser diff --git a/packages/web/src/content/docs/nb/index.mdx b/packages/web/src/content/docs/nb/index.mdx new file mode 100644 index 000000000..efafd603e --- /dev/null +++ b/packages/web/src/content/docs/nb/index.mdx @@ -0,0 +1,359 @@ +--- +title: Intro +description: Kom i gang med OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) er en åpen kildekode AI kodeagent. Den er tilgjengelig som et terminalbasert grensesnitt, skrivebordsapp eller IDE-utvidelse. + +![OpenCode TUI med opencode-temaet](../../../assets/lander/screenshot.png) + +La oss komme i gang. + +--- + +#### Forutsetninger + +For å bruke OpenCode i terminalen din trenger du: + +1. En moderne terminalemulator som: + - [WezTerm](https://wezterm.org), på tvers av plattformer + - [Alacritty](https://alacritty.org), på tvers av plattformer + - [Ghostty](https://ghostty.org), Linux og macOS + - [Kitty](https://sw.kovidgoyal.net/kitty/), Linux og macOS + +2. API-nøkler for LLM-leverandørene du vil bruke. + +--- + +## Installer + +Den enkleste måten å installere OpenCode på er gjennom installasjonsskriptet. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +Du kan også installere den med følgende kommandoer: + +- **Bruke Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **Bruke Homebrew på macOS og Linux** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > Vi anbefaler å bruke OpenCode-tappen for de mest oppdaterte utgivelsene. Den offisielle `brew install opencode`-formelen vedlikeholdes av Homebrew-teamet og oppdateres sjeldnere. + +- **Bruke Paru på Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### Windows + +:::tips[Anbefalt: Bruk WSL] +For den beste opplevelsen på Windows anbefaler vi å bruke [Windows Subsystem for Linux (WSL)](/docs/windows-wsl). Det gir bedre ytelse og full kompatibilitet med OpenCodes funksjoner. +::: + +- **Bruker sjokolade** + + ```bash + choco install opencode + ``` + +- **Bruke Scoop** + + ```bash + scoop install opencode + ``` + +- **Bruker NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **Bruker Mise** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **Bruke Docker** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +Støtte for å installere OpenCode på Windows med Bun pågår for øyeblikket. + +Du kan også hente binæren fra [Releases](https://github.com/anomalyco/opencode/releases). + +--- + +## Konfigurer + +Med OpenCode kan du bruke hvilken som helst LLM-leverandør ved å konfigurere deres API-nøkler. + +Hvis du er ny til å bruke LLM-leverandører, anbefaler vi å bruke [OpenCode Zen](/docs/zen). +Det er en kuratert liste over modeller som har blitt testet og verifisert av OpenCode +team. + +1. Kjør kommandoen `/connect` i TUI, velg opencode og gå til [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Logg på, legg til faktureringsdetaljene dine og kopier API-nøkkelen. + +3. Lim inn API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +Alternativt kan du velge en av de andre leverandørene. [Finn ut mer](/docs/providers#directory). + +--- + +## Initialiser + +Nå som du har konfigurert en leverandør, kan du navigere til et prosjekt som +du vil jobbe med. + +```bash +cd /path/to/project +``` + +Og kjør OpenCode. + +```bash +opencode +``` + +Deretter initialiserer du OpenCode for prosjektet ved å kjøre følgende kommando. + +```bash frame="none" +/init +``` + +Dette vil få OpenCode til å analysere prosjektet ditt og opprette en `AGENTS.md`-fil i +prosjektroten. + +:::tupp +Du bør overgi prosjektets `AGENTS.md`-fil til Git. +::: + +Dette hjelper OpenCode med å forstå prosjektstrukturen og kodingsmønstrene +brukt. + +--- + +## Bruk + +Du er nå klar til å bruke OpenCode for å jobbe med prosjektet ditt. Spør det gjerne +noe! + +Hvis du er ny til å bruke en AI kodeagent, her er noen eksempler som kan +hjelp. + +--- + +### Still spørsmål + +Du kan be OpenCode forklare kodebasen for deg. + +:::tupp +Bruk `@`-tasten for uklart søk etter filer i prosjektet. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +Dette er nyttig hvis det er en del av kodebasen du ikke har jobbet med. + +--- + +### Legg til funksjoner + +Du kan be OpenCode legge til nye funksjoner i prosjektet ditt. Selv om vi først anbefaler å be den om å lage en plan. + +1. **Lag en plan** + + OpenCode har en _Plan-modus_ som deaktiverer evnen til å gjøre endringer og + foreslå i stedet _hvordan_ det vil implementere funksjonen. + + Bytt til den ved å bruke **Tab**-tasten. Du vil se en indikator for dette i nedre høyre hjørne. + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + La oss nå beskrive hva vi vil at den skal gjøre. + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + Du vil gi OpenCode nok detaljer til å forstå hva du ønsker. Det hjelper + å snakke med det som om du snakker med en juniorutvikler på laget ditt. + + :::tupp + Gi OpenCode mye kontekst og eksempler for å hjelpe den å forstå hva du gjør + ønsker. + ::: + +2. **Gjenta på planen** + + Når den gir deg en plan, kan du gi den tilbakemelding eller legge til flere detaljer. + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::tupp + Dra og slipp bilder i terminalen for å legge dem til ledeteksten. + ::: + + OpenCode kan skanne alle bilder du gir den og legge dem til i ledeteksten. Du kan + gjør dette ved å dra og slippe et bilde inn i terminalen. + +3. **Bygg funksjonen** + + Når du føler deg komfortabel med planen, bytt tilbake til _Byggemodus_ av + trykke på **Tab**-tasten igjen. + + ```bash frame="none" + + ``` + + Og ber den om å gjøre endringene. + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### Gjør endringer + +For mer enkle endringer kan du be OpenCode om å bygge den direkte +uten å måtte gjennomgå planen først. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +Du vil sørge for at du gir en god mengde detaljer, slik at OpenCode gjør det rette +endringer. + +--- + +### Angre endringer + +La oss si at du ber OpenCode om å gjøre noen endringer. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Men du skjønner at det ikke er det du ønsket. Du **kan angre** endringene +ved å bruke kommandoen `/undo`. + +```bash frame="none" +/undo +``` + +OpenCode vil nå tilbakestille endringene du har gjort og vise den opprinnelige meldingen +igjen. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Herfra kan du justere ledeteksten og be OpenCode om å prøve igjen. + +:::tupp +Du kan kjøre `/undo` flere ganger for å angre flere endringer. +::: + +Eller du **kan gjøre om** endringene ved å bruke `/redo`-kommandoen. + +```bash frame="none" +/redo +``` + +--- + +## Del + +Samtalene du har med OpenCode kan [deles med din +team](/docs/share). + +```bash frame="none" +/share +``` + +Dette vil opprette en kobling til den gjeldende samtalen og kopiere den til utklippstavlen. + +:::note +Samtaler deles ikke som standard. +::: + +Her er en [eksempelsamtale](https://opencode.ai/s/4XP1fce5) med OpenCode. + +--- + +## Tilpass + +Og det er det! Du er nå en proff på å bruke OpenCode. + +For å gjøre det til ditt eget anbefaler vi å [velge et tema](/docs/themes), [tilpasse nøkkelbindingene](/docs/keybinds), [konfigurere kodeformatere](/docs/formatters), [opprette egendefinerte kommandoer](/docs/commands) eller leke med [OpenCode-konfigurasjonen](/docs/config). diff --git a/packages/web/src/content/docs/nb/keybinds.mdx b/packages/web/src/content/docs/nb/keybinds.mdx new file mode 100644 index 000000000..7f10f4da7 --- /dev/null +++ b/packages/web/src/content/docs/nb/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: Keybinds +description: Tilpass tastebindingene dine. +--- + +OpenCode har en liste over nøkkelbindinger som du kan tilpasse gjennom OpenCode-konfigurasjonen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## Ledernøkkel + +OpenCode bruker en `leader`-nøkkel for de fleste nøkkelbindinger. Dette unngår konflikter i terminalen din. + +Som standard er `ctrl+x` ledertasten, og de fleste handlinger krever at du først trykker på ledertasten og deretter snarveien. For å starte en ny økt, trykker du for eksempel først `ctrl+x` og deretter `n`. + +Du trenger ikke å bruke en ledernøkkel for tastebindingene dine, men vi anbefaler at du gjør det. + +--- + +## Deaktiver tastebinding + +Du kan deaktivere en nøkkelbinding ved å legge til nøkkelen til konfigurasjonen med verdien "ingen". + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## Snarveier på skrivebordet + +Spørringsinngangen for OpenCode-skrivebordsappen støtter vanlige snarveier i Readline/Emacs-stil for redigering av tekst. Disse er innebygd og foreløpig ikke konfigurerbare via `opencode.json`. + +| Snarvei | Handling | +| -------- | ---------------------------------------- | +| `ctrl+a` | Flytt til starten av gjeldende linje | +| `ctrl+e` | Flytt til slutten av gjeldende linje | +| `ctrl+b` | Flytt markøren ett tegn tilbake | +| `ctrl+f` | Flytt markøren ett tegn fremover | +| `alt+b` | Flytt markøren ett ord tilbake | +| `alt+f` | Flytt markøren ett ord fremover | +| `ctrl+d` | Slett tegn under markøren | +| `ctrl+k` | Drep til slutten av linjen | +| `ctrl+u` | Drep til starten av linjen | +| `ctrl+w` | Drep forrige ord | +| `alt+d` | Drep neste ord | +| `ctrl+t` | Transponere tegn | +| `ctrl+g` | Avbryt popovers / avbryt kjøring av svar | + +--- + +## Shift+Enter + +Noen terminaler sender ikke modifikasjonsnøkler med Enter som standard. Du må kanskje konfigurere terminalen til å sende `Shift+Enter` som en escape-sekvens. + +### Windows Terminal + +Åpne `settings.json` på: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +Legg dette til `actions`-matrisen på rotnivå: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Legg dette til `keybindings`-matrisen på rotnivå: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Lagre filen og start Windows Terminal på nytt eller åpne en ny fane. diff --git a/packages/web/src/content/docs/nb/lsp.mdx b/packages/web/src/content/docs/nb/lsp.mdx new file mode 100644 index 000000000..a4851fb2d --- /dev/null +++ b/packages/web/src/content/docs/nb/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: LSP Servere +description: OpenCode integreres med LSP-serverne dine. +--- + +OpenCode integreres med din Language Server Protocol (LSP) for å hjelpe LLM med å samhandle med kodebasen din. Den bruker diagnostikk for å gi tilbakemelding til LLM. + +--- + +## Innebygd + +OpenCode kommer med flere innebygde LSP-servere for populære språk: + +| LSP Server | Utvidelser | Krav | +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +| astro | .astro | Autoinstallasjoner for Astro-prosjekter | +| bash | .sh, .bash, .zsh, .ksh | Autoinstallerer bash-language-server | +| clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Autoinstallasjoner for C/C++-prosjekter | +| csharp | .cs | `.NET SDK` installert | +| clojure-lsp | .clj, .cljs, .cljc, .edn | `clojure-lsp` kommando tilgjengelig | +| dart | .dart | `dart` kommando tilgjengelig | +| deno | .ts, .tsx, .js, .jsx, .mjs | `deno` kommando tilgjengelig (automatisk oppdager deno.json/deno.jsonc) | +| elixir-ls | .ex, .exs | `elixir` kommando tilgjengelig | +| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` avhengighet i prosjekt | +| fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` installert | +| glimt | .gleam | `gleam` kommando tilgjengelig | +| gopls | .go | `go` kommando tilgjengelig | +| hls | .hs, .lhs | `haskell-language-server-wrapper` kommando tilgjengelig | +| jdtls | .java | `Java SDK (version 21+)` installert | +| kotlin-ls | .kt, .kts | Autoinstallasjoner for Kotlin-prosjekter | +| lua-ls | .lua | Autoinstallasjoner for Lua-prosjekter | +| nixd | .nix | `nixd` kommando tilgjengelig | +| ocaml-lsp | .ml, .mli | `ocamllsp` kommando tilgjengelig | +| oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | `oxlint` avhengighet i prosjekt | +| php intelephense | .php | Autoinstallasjoner for PHP-prosjekter | +| prisma | .prisma | `prisma` kommando tilgjengelig | +| opphavsrett | .py, .pyi | `pyright` avhengighet installert | +| ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | `ruby` og `gem` kommandoer tilgjengelig | +| rust | .rs | `rust-analyzer` kommando tilgjengelig | +| sourcekit-lsp | .swift, .objc, .objcpp | `swift` installert (`xcode` på macOS) | +| svelte | .svelte | Autoinstallasjoner for Svelte-prosjekter | +| terraform | .tf, .tfvars | Automatiske installasjoner fra GitHub-utgivelser | +| tinymist | .typ, .typc | Automatiske installasjoner fra GitHub-utgivelser | +| maskinskrift | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` avhengighet i prosjekt | +| vue | .vue | Autoinstallasjoner for Vue-prosjekter | +| yaml-ls | .yaml, .yml | Autoinstallerer Red Hat yaml-language-server | +| zls | .zig, .zon | `zig` kommando tilgjengelig | + +LSP-servere aktiveres automatisk når en av filtypene ovenfor oppdages og kravene oppfylles. + +:::note +Du kan deaktivere automatiske LSP-servernedlastinger ved å sette miljøvariabelen `OPENCODE_DISABLE_LSP_DOWNLOAD` til `true`. +::: + +--- + +## Hvordan det fungerer + +Når opencode åpner en fil, gjør den: + +1. Kontrollerer filtypen mot alle aktiverte LSP-servere. +2. Starter den riktige LSP-serveren hvis den ikke allerede kjører. + +--- + +## Konfigurer + +Du kan tilpasse LSP-servere gjennom `lsp`-delen i opencode-konfigurasjonen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Hver LSP-server støtter følgende: + +| Eiendom | Skriv | Beskrivelse | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` | boolsk | Sett dette til `true` for å deaktivere LSP-serveren | +| `command` | streng[] | Kommandoen for å starte LSP-serveren | +| `extensions` | streng[] | Filutvidelser denne LSP-serveren skal håndtere | +| `env` | objekt | Miljøvariabler som skal angis når serveren startes | +| `initialization` | objekt | Initialiseringsalternativer for å sende til LSP-serveren | + +La oss se på noen eksempler. + +--- + +### Miljøvariabler + +Bruk egenskapen `env` til å angi miljøvariabler når du starter LSP-serveren: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### Initialiseringsalternativer + +Bruk egenskapen `initialization` til å sende initialiseringsalternativer til LSP-serveren. Dette er serverspesifikke innstillinger sendt under LSP `initialize`-forespørselen: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +Initialiseringsalternativer varierer etter LSP-server. Sjekk dokumentasjonen til LSP-serveren for tilgjengelige alternativer. +::: + +--- + +### Deaktiverer LSP-servere + +For å deaktivere **alle** LSP servere globalt, sett `lsp` til `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +For å deaktivere en **spesifikk** LSP-server, sett `disabled` til `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Egendefinerte LSP-servere + +Du kan legge til egendefinerte LSP-servere ved å spesifisere kommandoen og filtypene: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## Tilleggsinformasjon + +### PHP Intelephense + +PHP Intelephense tilbyr førsteklasses funksjoner gjennom en lisensnøkkel. Du kan oppgi en lisensnøkkel ved å plassere (bare) nøkkelen i en tekstfil på: + +- På macOS/Linux: `$HOME/intelephense/licence.txt` +- På Windows: `%USERPROFILE%/intelephense/licence.txt` + +Filen skal bare inneholde lisensnøkkelen uten ekstra innhold. diff --git a/packages/web/src/content/docs/nb/mcp-servers.mdx b/packages/web/src/content/docs/nb/mcp-servers.mdx new file mode 100644 index 000000000..863953bc7 --- /dev/null +++ b/packages/web/src/content/docs/nb/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: MCP servere +description: Legg til lokale og eksterne MCP-verktøy. +--- + +Du kan legge til eksterne verktøy i OpenCode ved å bruke _Model Context Protocol_ eller MCP. OpenCode støtter både lokale og eksterne servere. + +Når de er lagt til, er MCP-verktøy automatisk tilgjengelige for LLM sammen med innebygde verktøy. + +--- + +#### Advarsler + +Når du bruker en MCP-server, legger den til konteksten. Dette kan fort gå opp hvis du har mange verktøy. Så vi anbefaler å være forsiktig med hvilke MCP-servere du bruker. + +:::tupp +MCP servere legger til konteksten din, så du vil være forsiktig med hvilke du aktiverer. +::: + +Enkelte MCP-servere, som GitHub MCP-serveren, har en tendens til å legge til mange tokens og kan lett overskride kontekstgrensen. + +--- + +## Aktiver + +Du kan definere MCP-servere i [OpenCode Config](https://opencode.ai/docs/config/) under `mcp`. Legg til hver MCP med et unikt navn. Du kan referere til den MCP ved navn når du ber om LLM. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +Du kan også deaktivere en server ved å sette `enabled` til `false`. Dette er nyttig hvis du vil deaktivere en server midlertidig uten å fjerne den fra konfigurasjonen. + +--- + +### Overstyrer fjernstandarder + +Organisasjoner kan tilby standard MCP-servere via deres `.well-known/opencode`-endepunkt. Disse serverne kan være deaktivert som standard, slik at brukere kan melde seg på de de trenger. + +For å aktivere en spesifikk server fra organisasjonens eksterne konfigurasjon, legg den til i din lokale konfigurasjon med `enabled: true`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +Dine lokale konfigurasjonsverdier overstyrer de eksterne standardinnstillingene. Se [config precedence](/docs/config#precedence-order) for flere detaljer. + +--- + +## Lokal + +Legg til lokale MCP-servere ved å bruke `type` til `"local"` i MCP-objektet. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +Kommandoen er hvordan den lokale MCP-serveren startes. Du kan også sende inn en liste over miljøvariabler. + +For eksempel, her er hvordan du kan legge til test [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP serveren. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +Og for å bruke den kan jeg legge til `use the mcp_everything tool` i ledetekstene mine. + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### Alternativer + +Her er alle alternativene for å konfigurere en lokal MCP-server. + +| Alternativ | Skriv | Påkrevd | Beskrivelse | +| ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | String | Y | Type MCP servertilkobling, må være `"local"`. | +| `command` | Array | Y | Kommando og argumenter for å kjøre MCP-serveren. | +| `environment` | Objekt | | Miljøvariabler som skal angis når serveren kjøres. | +| `enabled` | Boolsk | | Aktiver eller deaktiver MCP-serveren ved oppstart. | +| `timeout` | Nummer | | Tidsavbrudd i ms for henting av verktøy fra MCP-serveren. Standard er 5000 (5 sekunder). | + +--- + +## Fjernkontroll + +Legg til eksterne MCP-servere ved å sette `type` til `"remote"`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` er URL til den eksterne MCP serveren og med alternativet `headers` kan du sende inn en liste over overskrifter. + +--- + +#### Alternativer + +| Alternativ | Skriv | Påkrevd | Beskrivelse | +| --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | String | Y | Type MCP servertilkobling, må være `"remote"`. | +| `url` | String | Y | URL av den eksterne MCP-serveren. | +| `enabled` | Boolsk | | Aktiver eller deaktiver MCP-serveren ved oppstart. | +| `headers` | Objekt | | Overskrifter å sende med forespørselen. | +| `oauth` | Objekt | | OAuth-autentiseringskonfigurasjon. Se delen [OAuth](#oauth) nedenfor. | +| `timeout` | Nummer | | Tidsavbrudd i ms for henting av verktøy fra MCP-serveren. Standard er 5000 (5 sekunder). | + +--- + +## OAuth + +OpenCode håndterer automatisk OAuth-autentisering for eksterne MCP-servere. Når en server krever autentisering, vil OpenCode: + +1. Oppdag 401-svaret og start OAuth-flyten +2. Bruk **Dynamisk klientregistrering (RFC 7591)** hvis det støttes av serveren +3. Lagre tokens sikkert for fremtidige forespørsler + +--- + +### Automatisk + +For de fleste OAuth-aktiverte MCP-servere er ingen spesiell konfigurasjon nødvendig. Bare konfigurer den eksterne serveren: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +Hvis serveren krever autentisering, vil OpenCode be deg om å autentisere når du prøver å bruke den for første gang. Hvis ikke, kan du [utløse flyten manuelt](#authenticating) med `opencode mcp auth `. + +--- + +### Forhåndsregistrert + +Hvis du har klientlegitimasjon fra MCP-serverleverandøren, kan du konfigurere dem: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### Autentiserer + +Du kan utløse autentisering manuelt eller administrere legitimasjon. + +Autentiser med en spesifikk MCP-server: + +```bash +opencode mcp auth my-oauth-server +``` + +Liste alle MCP-servere og deres autentiseringsstatus: + +```bash +opencode mcp list +``` + +Fjern lagret legitimasjon: + +```bash +opencode mcp logout my-oauth-server +``` + +Kommandoen `mcp auth` åpner nettleseren din for autorisasjon. Etter at du har godkjent, vil OpenCode lagre tokens sikkert i `~/.local/share/opencode/mcp-auth.json`. + +--- + +#### Deaktiverer OAuth + +Hvis du vil deaktivere automatisk OAuth for en server (f.eks. for servere som bruker API-nøkler i stedet), setter du `oauth` til `false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### OAuth-alternativer + +| Alternativ | Skriv inn | Beskrivelse | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` | Objekt \| usant | OAuth-konfigurasjonsobjekt, eller `false` for å deaktivere automatisk OAuth-deteksjon. | +| `clientId` | String | OAuth-klient ID. Hvis ikke oppgitt, vil dynamisk klientregistrering bli forsøkt. | +| `clientSecret` | String | OAuth-klienthemmelighet, hvis det kreves av autorisasjonsserveren. | +| `scope` | String | OAuth-omfang å be om under autorisasjon. | + +#### Feilsøking + +Hvis en ekstern MCP-server ikke klarer å autentisere, kan du diagnostisere problemer med: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +Kommandoen `mcp debug` viser gjeldende autentiseringsstatus, tester HTTP-tilkoblingen og forsøker OAuth-oppdagelsesflyten. + +--- + +## Administrer + +MCP-ene dine er tilgjengelige som verktøy i OpenCode, sammen med innebygde verktøy. Så du kan administrere dem gjennom OpenCode-konfigurasjonen som alle andre verktøy. + +--- + +### Globalt + +Dette betyr at du kan aktivere eller deaktivere dem globalt. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +Vi kan også bruke et globmønster for å deaktivere alle matchende MCP-er. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +Her bruker vi globmønsteret `my-mcp*` for å deaktivere alle MCP-er. + +--- + +### Per agent + +Hvis du har et stort antall MCP-servere, vil du kanskje bare aktivere dem per agent og deaktivere dem globalt. Slik gjør du dette: + +1. Deaktiver det som et verktøy globalt. +2. Aktiver MCP-serveren som et verktøy i [agent config](/docs/agents#tools). + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### Glob-mønstre + +Glob-mønsteret bruker enkle regex-globing-mønstre: + +- `*` samsvarer med null eller flere av alle tegn (f.eks. `"my-mcp*"` samsvarer med `my-mcp_search`, `my-mcp_list`, osv.) +- `?` samsvarer med nøyaktig ett tegn +- Alle andre karakterer samsvarer bokstavelig talt + +:::note +MCP serververktøy er registrert med servernavn som prefiks, så for å deaktivere alle verktøy for en server bruker du bare: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## Eksempler + +Nedenfor er eksempler på noen vanlige MCP-servere. Du kan sende inn en PR hvis du vil dokumentere andre servere. + +--- + +### Vaktvakt + +Legg til [Sentry MCP-serveren](https://mcp.sentry.dev) for å samhandle med Sentry-prosjektene og problemene dine. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +Etter å ha lagt til konfigurasjonen, autentiser med Sentry: + +```bash +opencode mcp auth sentry +``` + +Dette åpner et nettleservindu for å fullføre OAuth-flyten og koble OpenCode til Sentry-kontoen din. + +Når du er autentisert, kan du bruke Sentry-verktøy i ledetekstene dine for å spørre etter problemer, prosjekter og feildata. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Kontekst7 + +Legg til [Context7 MCP-serveren](https://github.com/upstash/context7) for å søke gjennom dokumenter. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +Hvis du har registrert deg for en gratis konto, kan du bruke API-nøkkelen din og få høyere satsgrenser. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +Her antar vi at du har `CONTEXT7_API_KEY` miljøvariabelen satt. + +Legg til `use context7` i instruksjonene for å bruke Context7 MCP-serveren. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +Alternativt kan du legge til noe slikt til din [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep av Vercel + +Legg til [Grep by Vercel](https://grep.app) MCP-serveren for å søke gjennom kodebiter på GitHub. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +Siden vi kalte MCP-serveren vår `gh_grep`, kan du legge til `use the gh_grep tool` i spørsmålene dine for å få agenten til å bruke den. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +Alternativt kan du legge til noe slikt til din [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/nb/models.mdx b/packages/web/src/content/docs/nb/models.mdx new file mode 100644 index 000000000..9d6749b30 --- /dev/null +++ b/packages/web/src/content/docs/nb/models.mdx @@ -0,0 +1,223 @@ +--- +title: Modeller +description: Konfigurere en LLM leverandør og modell. +--- + +OpenCode bruker [AI SDK](https://ai-sdk.dev/) og [Models.dev](https://models.dev) for å støtte **75+ LLM leverandører** og den støtter kjøring av lokale modeller. + +--- + +## Leverandører + +De fleste populære leverandørene er forhåndslastet som standard. Hvis du har lagt til legitimasjonen for en leverandør gjennom kommandoen `/connect`, vil den være tilgjengelig når du starter OpenCode. + +Finn ut mer om [leverandører](/docs/providers). + +--- + +## Velg en modell + +Når du har konfigurert leverandøren din, kan du velge modellen du ønsker ved å skrive inn: + +```bash frame="none" +/models +``` + +--- + +## Anbefalte modeller + +Det er mange modeller der ute, med nye modeller som kommer ut hver uke. + +:::tupp +Vurder å bruke en av modellene vi anbefaler. +::: + +Imidlertid er det bare noen få av dem som er gode til både å generere kode og verktøykalling. + +Her er flere modeller som fungerer godt med OpenCode, uten spesiell rekkefølge. (Dette er ikke en uttømmende liste og er heller ikke nødvendigvis oppdatert): + +- GPT 5.2 +- GPT 5.1 Codex +- Claude Opus 4.5 +- Claude Sonnet 4.5 +- Minimax M2.1 +- Gemini 3 Pro + +--- + +## Angi en standard + +For å angi en av disse som standardmodell, kan du angi `model`-tasten i din +OpenCode-konfigurasjon. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Her er hele ID `provider_id/model_id`. For eksempel, hvis du bruker [OpenCode Zen](/docs/zen), vil du bruke `opencode/gpt-5.1-codex` for GPT 5.1 Codex. + +Hvis du har konfigurert en [egendefinert leverandør](/docs/providers#custom), er `provider_id` nøkkelen fra `provider`-delen av konfigurasjonen din, og `model_id` er nøkkelen fra `provider.models`. + +--- + +## Konfigurer modeller + +Du kan konfigurere en modells alternativer globalt gjennom konfigurasjonen. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Her konfigurerer vi globale innstillinger for to innebygde modeller: `gpt-5` når de åpnes via `openai`-leverandøren, og `claude-sonnet-4-20250514` når de åpnes via `anthropic`-leverandøren. +De innebygde leverandør- og modellnavnene finnes på [Models.dev](https://models.dev). + +Du kan også konfigurere disse alternativene for alle agenter du bruker. Agentkonfigurasjonen overstyrer alle globale alternativer her. [Finn ut mer](/docs/agents/#additional). + +Du kan også definere tilpassede varianter som utvider de innebygde. Varianter lar deg konfigurere forskjellige innstillinger for samme modell uten å opprette dupliserte oppføringer: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## Varianter + +Mange modeller støtter flere varianter med forskjellige konfigurasjoner. OpenCode leveres med innebygde standardvarianter for populære leverandører. + +### Innebygde varianter + +OpenCode leveres med standardvarianter for mange leverandører: + +**Antropisk**: + +- `high` - Høyt budsjett (standard) +- `max` - Maksimalt tenkebudsjett + +**OpenAI**: + +Varierer etter modell, men omtrent: + +- `none` - Ingen resonnement +- `minimal` - Minimal resonnementinnsats +- `low` - Lav resonnementinnsats +- `medium` - Middels resonnementinnsats +- `high` - Høy resonnementinnsats +- `xhigh` - Ekstra høy resonnementinnsats + +**Google**: + +- `low` - Lavere innsats/tokenbudsjett +- `high` - Høyere innsats/tokenbudsjett + +:::tupp +Denne listen er ikke uttømmende. Mange andre leverandører har også innebygde standardinnstillinger. +::: + +### Egendefinerte varianter + +Du kan overstyre eksisterende varianter eller legge til dine egne: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### Syklusvarianter + +Bruk tastebindingen `variant_cycle` for raskt å bytte mellom varianter. [Finn ut mer](/docs/keybinds). + +--- + +## Laster modeller + +Når OpenCode starter opp, ser den etter modeller i følgende prioriterte rekkefølge: + +1. Kommandolinjeflagget `--model` eller `-m`. Formatet er det samme som i konfigurasjonsfilen: `provider_id/model_id`. + +2. Modelllisten i OpenCode-konfigurasjonen. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + Formatet her er `provider/model`. + +3. Den sist brukte modellen. + +4. Den første modellen bruker en intern prioritet. diff --git a/packages/web/src/content/docs/nb/modes.mdx b/packages/web/src/content/docs/nb/modes.mdx new file mode 100644 index 000000000..28ff27915 --- /dev/null +++ b/packages/web/src/content/docs/nb/modes.mdx @@ -0,0 +1,331 @@ +--- +title: Modi +description: Ulike moduser for forskjellige brukstilfeller. +--- + +:::forsiktighet +Modi er nå konfigurert gjennom alternativet `agent` i opencode-konfigurasjonen. De +Alternativet `mode` er nå utdatert. [Finn ut mer](/docs/agents). +::: + +Moduser i opencode lar deg tilpasse oppførselen, verktøyene og ledetekstene for ulike brukstilfeller. + +Den kommer med to innebygde moduser: **bygg** og **plan**. Du kan tilpasse +disse eller konfigurer din egen gjennom opencode-konfigurasjonen. + +Du kan bytte mellom moduser under en økt eller konfigurere dem i konfigurasjonsfilen. + +--- + +## Innebygd + +opencode kommer med to innebygde moduser. + +--- + +### Bygg + +Bygg er **standard**-modus med alle verktøy aktivert. Dette er standardmodusen for utviklingsarbeid der du trenger full tilgang til filoperasjoner og systemkommandoer. + +--- + +### Plan + +En begrenset modus designet for planlegging og analyse. I planmodus er følgende verktøy deaktivert som standard: + +- `write` - Kan ikke opprette nye filer +- `edit` - Kan ikke endre eksisterende filer, bortsett fra filer som ligger på `.opencode/plans/*.md` for å detaljere selve planen +- `patch` - Kan ikke bruke patcher +- `bash` - Kan ikke utføre skallkommandoer + +Denne modusen er nyttig når du vil at AI skal analysere kode, foreslå endringer eller lage planer uten å gjøre noen faktiske endringer i kodebasen. + +--- + +## Bytte + +Du kan bytte mellom moduser under en økt ved å bruke _Tab_-tasten. Eller din konfigurerte `switch_mode` nøkkelbinding. + +Se også: [Formatters](/docs/formatters) for informasjon om konfigurasjon av kodeformatering. + +--- + +## Konfigurer + +Du kan tilpasse de innebygde modusene eller lage dine egne gjennom konfigurasjon. Modi kan konfigureres på to måter: + +### JSON Konfigurasjon + +Konfigurer moduser i konfigurasjonsfilen `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Markdown-konfigurasjon + +Du kan også definere moduser ved å bruke markdown-filer. Plasser dem i: + +- Globalt: `~/.config/opencode/modes/` +- Prosjekt: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Markdown-filnavnet blir modusnavnet (f.eks. `review.md` oppretter en `review`-modus). + +La oss se på disse konfigurasjonsalternativene i detalj. + +--- + +### Modell + +Bruk `model`-konfigurasjonen for å overstyre standardmodellen for denne modusen. Nyttig for bruk av ulike modeller optimalisert for ulike oppgaver. For eksempel en raskere modell for planlegging, en mer kapabel modell for implementering. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Temperatur + +Kontroller tilfeldigheten og kreativiteten til AIs svar med `temperature`-konfigurasjonen. Lavere verdier gjør svarene mer fokuserte og deterministiske, mens høyere verdier øker kreativiteten og variasjonen. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Temperaturverdier varierer vanligvis fra 0,0 til 1,0: + +- **0.0-0.2**: Veldig fokuserte og deterministiske svar, ideell for kodeanalyse og planlegging +- **0,3-0,5**: Balanserte svar med litt kreativitet, bra for generelle utviklingsoppgaver +- **0.6-1.0**: Mer kreative og varierte svar, nyttig for idédugnad og utforskning + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Hvis ingen temperatur er spesifisert, bruker opencode modellspesifikke standarder (vanligvis 0 for de fleste modeller, 0,55 for Qwen-modeller). + +--- + +### Spør + +Spesifiser en tilpasset systemmeldingsfil for denne modusen med `prompt`-konfigurasjonen. Spørrefilen skal inneholde instruksjoner som er spesifikke for modusens formål. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Denne banen er i forhold til hvor konfigurasjonsfilen er plassert. Så dette fungerer for +både den globale opencode-konfigurasjonen og den prosjektspesifikke konfigurasjonen. + +--- + +### Verktøy + +Kontroller hvilke verktøy som er tilgjengelige i denne modusen med `tools`-konfigurasjonen. Du kan aktivere eller deaktivere spesifikke verktøy ved å sette dem til `true` eller `false`. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +Hvis ingen verktøy er spesifisert, er alle verktøy aktivert som standard. + +--- + +#### Tilgjengelige verktøy + +Her er alle verktøyene som kan kontrolleres gjennom moduskonfigurasjonen. + +| Verktøy | Beskrivelse | +| ----------- | ----------------------- | +| `bash` | Utfør skallkommandoer | +| `edit` | Endre eksisterende filer | +| `write` | Opprett nye filer | +| `read` | Les filinnhold | +| `grep` | Søk filinnhold | +| `glob` | Finn filer etter mønster | +| `list` | Liste kataloginnhold | +| `patch` | Bruk patcher på filer | +| `todowrite` | Administrer gjøremålslister | +| `todoread` | Les gjøremålslister | +| `webfetch` | Hent nettinnhold | + +--- + +## Egendefinerte moduser + +Du kan lage dine egne tilpassede moduser ved å legge dem til konfigurasjonen. Her er eksempler som bruker begge tilnærmingene: + +### Bruker JSON konfigurasjon + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Bruker markdown-filer + +Lag modusfiler i `.opencode/modes/` for prosjektspesifikke moduser eller `~/.config/opencode/modes/` for globale moduser: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### Brukstilfeller + +Her er noen vanlige brukstilfeller for forskjellige moduser. + +- **Byggemodus**: Fullt utviklingsarbeid med alle verktøy aktivert +- **Planmodus**: Analyse og planlegging uten å gjøre endringer +- **Gjennomgangsmodus**: Kodegjennomgang med skrivebeskyttet tilgang pluss dokumentasjonsverktøy +- **Feilsøkingsmodus**: Fokusert på etterforskning med bash- og leseverktøy aktivert +- **Dokumentmodus**: Dokumentasjonsskriving med filoperasjoner, men ingen systemkommandoer + +Du kan også finne at forskjellige modeller er gode for forskjellige brukstilfeller. diff --git a/packages/web/src/content/docs/nb/network.mdx b/packages/web/src/content/docs/nb/network.mdx new file mode 100644 index 000000000..3ec47554d --- /dev/null +++ b/packages/web/src/content/docs/nb/network.mdx @@ -0,0 +1,57 @@ +--- +title: Nettverk +description: Konfigurer proxyer og tilpassede sertifikater. +--- + +OpenCode støtter standard proxy-miljøvariabler og tilpassede sertifikater for bedriftsnettverksmiljøer. + +--- + +## Proxy + +OpenCode respekterer standard proxy-miljøvariabler. + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::forsiktighet +TUI kommuniserer med en lokal HTTP server. Du må omgå proxyen for denne tilkoblingen for å forhindre rutingsløyfer. +::: + +Du kan konfigurere serverens port og vertsnavn ved å bruke [CLI flagg](/docs/cli#run). + +--- + +### Autentiser + +Hvis proxyen din krever grunnleggende autentisering, inkluderer legitimasjon i URL. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::forsiktighet +Unngå hardkoding av passord. Bruk miljøvariabler eller sikker lagring av legitimasjon. +::: + +For proxyer som krever avansert autentisering som NTLM eller Kerberos, bør du vurdere å bruke en LLM Gateway som støtter autentiseringsmetoden din. + +--- + +## Egendefinerte sertifikater + +Hvis bedriften din bruker egendefinerte CA-er for HTTPS-tilkoblinger, konfigurer OpenCode til å stole på dem. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +Dette fungerer for både proxy-tilkoblinger og direkte API-tilgang. diff --git a/packages/web/src/content/docs/nb/permissions.mdx b/packages/web/src/content/docs/nb/permissions.mdx new file mode 100644 index 000000000..bd1017266 --- /dev/null +++ b/packages/web/src/content/docs/nb/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: Tillatelser +description: Kontroller hvilke handlinger som krever godkjenning for å kjøre. +--- + +OpenCode bruker `permission`-konfigurasjonen for å bestemme om en gitt handling skal kjøres automatisk, spørre deg eller blokkeres. + +Fra og med `v1.1.1` er den eldre `tools` boolske konfigurasjonen avviklet og har blitt slått sammen til `permission`. Den gamle `tools`-konfigurasjonen støttes fortsatt for bakoverkompatibilitet. + +--- + +## Handlinger + +Hver tillatelsesregel løses til en av: + +- `"allow"` — kjør uten godkjenning +- `"ask"` — be om godkjenning +- `"deny"` — blokker handlingen + +--- + +## Konfigurasjon + +Du kan angi tillatelser globalt (med `*`), og overstyre spesifikke verktøy. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +Du kan også angi alle tillatelser samtidig: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## Granulære regler (objektsyntaks) + +For de fleste tillatelser kan du bruke et objekt til å bruke forskjellige handlinger basert på verktøyinndata. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +Regler evalueres etter mønstermatch, med **siste samsvarende regel som vinner**. Et vanlig mønster er å sette oppsamlingsregelen `"*"` først, og mer spesifikke regler etter den. + +### Jokertegn + +Tillatelsesmønstre bruker enkel jokertegnsamsvar: + +- `*` samsvarer med null eller flere av alle tegn +- `?` samsvarer med nøyaktig ett tegn +- Alle andre karakterer samsvarer bokstavelig talt + +### Utvidelse av hjemmekatalog + +Du kan bruke `~` eller `$HOME` i starten av et mønster for å referere til hjemmekatalogen din. Dette er spesielt nyttig for [`external_directory`](#external-directories) regler. + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### Eksterne kataloger + +Bruk `external_directory` for å tillate verktøyanrop som berører stier utenfor arbeidskatalogen der OpenCode ble startet. Dette gjelder alle verktøy som tar en bane som input (for eksempel `read`, `edit`, `list`, `glob`, `grep` og mange `bash`-kommandoer). + +Hjemmeutvidelse (som `~/...`) påvirker bare hvordan et mønster skrives. Den gjør ikke en ekstern bane til en del av det gjeldende arbeidsområdet, så stier utenfor arbeidskatalogen må fortsatt tillates via `external_directory`. + +For eksempel gir dette tilgang til alt under `~/projects/personal/`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +Enhver katalog som er tillatt her, arver de samme standardinnstillingene som gjeldende arbeidsområde. Siden [`read` er standard til `allow`](#defaults), er lesing også tillatt for oppføringer under `external_directory` med mindre overstyrt. Legg til eksplisitte regler når et verktøy skal begrenses i disse banene, for eksempel blokkering av redigeringer mens du beholder lesninger: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +Hold listen fokusert på klarerte baner, og lag ekstra tillat eller avslå regler etter behov for andre verktøy (for eksempel `bash`). + +--- + +## Tilgjengelige tillatelser + +OpenCode-tillatelser tastes inn etter verktøynavn, pluss et par sikkerhetsvakter: + +- `read` — lesing av en fil (tilsvarer filbanen) +- `edit` — alle filendringer (dekker `edit`, `write`, `patch`, `multiedit`) +- `glob` — fil-globing (tilsvarer glob-mønsteret) +- `grep` — innholdssøk (samsvarer med regex-mønsteret) +- `list` — viser filer i en katalog (tilsvarer katalogbanen) +- `bash` — kjører skallkommandoer (matcher analyserte kommandoer som `git status --porcelain`) +- `task` — lansering av subagenter (tilsvarer subagenttypen) +- `skill` — laster en ferdighet (tilsvarer ferdighetsnavnet) +- `lsp` — kjører LSP-spørringer (for øyeblikket ikke-granulære) +- `todoread`, `todowrite` — lesing/oppdatering av gjøremålslisten +- `webfetch` — henter en URL (tilsvarer URL) +- `websearch`, `codesearch` - nett-/kodesøk (samsvarer med søket) +- `external_directory` - utløses når et verktøy berører stier utenfor prosjektets arbeidskatalog +- `doom_loop` — utløses når det samme verktøykallet gjentas 3 ganger med identisk inngang + +--- + +## Standard + +Hvis du ikke spesifiserer noe, starter OpenCode fra tillatte standardinnstillinger: + +- De fleste tillatelser er `"allow"` som standard. +- `doom_loop` og `external_directory` er standard til `"ask"`. +- `read` er `"allow"`, men `.env` filer nektes som standard: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## Hva "Spør" gjør + +Når OpenCode ber om godkjenning, gir UI tre utfall: + +- `once` — godkjenne nettopp denne forespørselen +- `always` — godkjenn fremtidige forespørsler som samsvarer med de foreslåtte mønstrene (for resten av den nåværende OpenCode-økten) +- `reject` — avslå forespørselen + +Settet med mønstre som `always` vil godkjenne, leveres av verktøyet (for eksempel, bash-godkjenninger hvitlister vanligvis et trygt kommandoprefiks som `git status*`). + +--- + +## Agenter + +Du kan overstyre tillatelser per agent. Agenttillatelser slås sammen med den globale konfigurasjonen, og agentregler har forrang. [Finn ut mer](/docs/agents#permissions) om agenttillatelser. + +:::note +Se avsnittet [Granular Rules (Object Syntax)](#granular-rules-object-syntax) ovenfor for mer detaljerte eksempler på mønstertilpasning. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +Du kan også konfigurere agenttillatelser i Markdown: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tupp +Bruk mønstertilpasning for kommandoer med argumenter. `"grep *"` tillater `grep pattern file.txt`, mens `"grep"` alene ville blokkert den. Kommandoer som `git status` fungerer for standard oppførsel, men krever eksplisitt tillatelse (som `"git status *"`) når argumenter sendes. +::: diff --git a/packages/web/src/content/docs/nb/plugins.mdx b/packages/web/src/content/docs/nb/plugins.mdx new file mode 100644 index 000000000..5c012b8c1 --- /dev/null +++ b/packages/web/src/content/docs/nb/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: Plugins +description: Skriv dine egne plugins for å utvide OpenCode. +--- + +Plugins lar deg utvide OpenCode ved å koble til ulike arrangementer og tilpasse atferd. Du kan lage plugins for å legge til nye funksjoner, integrere med eksterne tjenester eller endre OpenCodes standardoppførsel. + +For eksempler, sjekk ut [plugins](/docs/ecosystem#plugins) opprettet av fellesskapet. + +--- + +## Bruk en plugin + +Det er to måter å laste inn plugins. + +--- + +### Fra lokale filer + +Plasser JavaScript- eller TypeScript-filer i plugin-katalogen. + +- `.opencode/plugins/` - Programtillegg på prosjektnivå +- `~/.config/opencode/plugins/` - Globale plugins + +Filer i disse katalogene lastes automatisk ved oppstart. + +--- + +### Fra npm + +Spesifiser npm-pakker i konfigurasjonsfilen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +Både vanlige og scoped npm-pakker støttes. + +Bla gjennom tilgjengelige plugins i [økosystemet](/docs/ecosystem#plugins). + +--- + +### Hvordan plugins installeres + +**npm-plugins** installeres automatisk ved hjelp av Bun ved oppstart. Pakker og deres avhengigheter er bufret i `~/.cache/opencode/node_modules/`. + +**Lokale plugins** lastes direkte fra plugin-katalogen. For å bruke eksterne pakker, må du opprette en `package.json` i konfigurasjonskatalogen din (se [Dependencies](#dependencies)), eller publisere plugin-en til npm og [legg den til i konfigurasjonen din](/docs/config#plugins). + +--- + +### Last inn ordre + +Plugins lastes inn fra alle kilder og alle kroker kjøres i rekkefølge. Lastrekkefølgen er: + +1. Global konfigurasjon (`~/.config/opencode/opencode.json`) +2. Prosjektkonfigurasjon (`opencode.json`) +3. Global plugin-katalog (`~/.config/opencode/plugins/`) +4. Prosjektpluginkatalog (`.opencode/plugins/`) + +Dupliserte npm-pakker med samme navn og versjon lastes inn én gang. Imidlertid lastes en lokal plugin og en npm plugin med lignende navn begge separat. + +--- + +## Opprett en plugin + +En plugin er en **JavaScript/TypeScript-modul** som eksporterer en eller flere plugin-moduler +funksjoner. Hver funksjon mottar et kontekstobjekt og returnerer et krokobjekt. + +--- + +### Avhengigheter + +Lokale plugins og tilpassede verktøy kan bruke eksterne npm-pakker. Legg til en `package.json` til konfigurasjonskatalogen med avhengighetene du trenger. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode kjører `bun install` ved oppstart for å installere disse. Programtilleggene og verktøyene dine kan deretter importere dem. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### Grunnleggende struktur + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +Plugin-funksjonen mottar: + +- `project`: Gjeldende prosjektinformasjon. +- `directory`: Gjeldende arbeidskatalog. +- `worktree`: Git-arbeidstrebanen. +- `client`: En OpenCode SDK klient for samhandling med AI. +- `$`: Buns [skall API](https://bun.com/docs/runtime/shell) for å utføre kommandoer. + +--- + +### TypeScript-støtte + +For TypeScript-plugins kan du importere typer fra plugin-pakken: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### Hendelser + +Plugins kan abonnere på arrangementer som vist nedenfor i Eksempler-delen. Her er en liste over de forskjellige arrangementene som er tilgjengelige. + +#### Kommandohendelser + +- `command.executed` + +#### Filhendelser + +- `file.edited` +- `file.watcher.updated` + +#### Installasjonshendelser + +- `installation.updated` + +#### LSP Hendelser + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### Meldingshendelser + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### Tillatelseshendelser + +- `permission.asked` +- `permission.replied` + +#### Serverhendelser + +- `server.connected` + +#### Sesjonshendelser + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### Todo-hendelser + +- `todo.updated` + +#### Shell-hendelser + +- `shell.env` + +#### Verktøyhendelser + +- `tool.execute.after` +- `tool.execute.before` + +#### TUI Hendelser + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## Eksempler + +Her er noen eksempler på plugins du kan bruke for å utvide opencode. + +--- + +### Send varsler + +Send varsler når visse hendelser inntreffer: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +Vi bruker `osascript` for å kjøre AppleScript på macOS. Her bruker vi den til å sende varsler. + +:::note +Hvis du bruker OpenCode-skrivebordsappen, kan den sende systemvarsler automatisk når et svar er klart eller når en økt feiler. +::: + +--- + +### .env-beskyttelse + +Hindre opencode fra å lese `.env` filer: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### Injiser miljøvariabler + +Injiser miljøvariabler i all skallutførelse (AI verktøy og brukerterminaler): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### Egendefinerte verktøy + +Plugins kan også legge til egendefinerte verktøy til opencode: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +`tool`-hjelperen lager et tilpasset verktøy som opencode kan kalle. Den tar en Zod-skjemafunksjon og returnerer en verktøydefinisjon med: + +- `description`: Hva verktøyet gjør +- `args`: Zod-skjema for verktøyets argumenter +- `execute`: Funksjon som kjører når verktøyet kalles + +Dine egendefinerte verktøy vil være tilgjengelige for å OpenCode sammen med innebygde verktøy. + +--- + +### Logging + +Bruk `client.app.log()` i stedet for `console.log` for strukturert logging: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +Nivåer: `debug`, `info`, `warn`, `error`. Se [SDK dokumentasjon](https://opencode.ai/docs/sdk) for detaljer. + +--- + +### Komprimeringskroker + +Tilpass konteksten inkludert når en økt komprimeres: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +`experimental.session.compacting`-kroken avfyres før LLM genererer et fortsettelsessammendrag. Bruk den til å injisere domenespesifikk kontekst som standard komprimeringsforespørsel ville gå glipp av. + +Du kan også erstatte komprimeringsmeldingen helt ved å stille inn `output.prompt`: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +Når `output.prompt` er angitt, erstatter den standard komprimeringsprompt fullstendig. `output.context`-matrisen ignoreres i dette tilfellet. diff --git a/packages/web/src/content/docs/nb/providers.mdx b/packages/web/src/content/docs/nb/providers.mdx new file mode 100644 index 000000000..98e214b78 --- /dev/null +++ b/packages/web/src/content/docs/nb/providers.mdx @@ -0,0 +1,1889 @@ +--- +title: Leverandører +description: Bruke en hvilken som helst LLM-leverandør i OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode bruker [AI SDK](https://ai-sdk.dev/) og [Models.dev](https://models.dev) for å støtte **75+ LLM leverandører** og den støtter kjøring av lokale modeller. + +For å legge til en leverandør må du: + +1. Legg til API-nøklene for leverandøren ved å bruke kommandoen `/connect`. +2. Konfigurer leverandøren i OpenCode-konfigurasjonen. + +--- + +### Legitimasjon + +Når du legger til en leverandørs API-nøkler med `/connect`-kommandoen, lagres de +i `~/.local/share/opencode/auth.json`. + +--- + +### Konfig + +Du kan tilpasse leverandørene gjennom `provider`-delen i OpenCode +konfig. + +--- + +#### Base URL + +Du kan tilpasse basen URL for enhver leverandør ved å angi alternativet `baseURL`. Dette er nyttig når du bruker proxy-tjenester eller tilpassede endepunkter. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen er en liste over modeller levert av OpenCode-teamet som har vært +testet og verifisert for å fungere godt med OpenCode. [Finn ut mer](/docs/zen). + +:::tupp +Hvis du er ny, anbefaler vi å starte med OpenCode Zen. +::: + +1. Kjør kommandoen `/connect` i TUI, velg opencode og gå til [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Logg på, legg til faktureringsdetaljene dine og kopier API-nøkkelen. + +3. Lim inn API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør `/models` i TUI for å se listen over modeller vi anbefaler. + + ```txt + /models + ``` + +Det fungerer som alle andre leverandører i OpenCode og er helt valgfritt å bruke. + +--- + +## Katalog + +La oss se på noen av leverandørene i detalj. Hvis du vil legge til en leverandør til +liste, åpne gjerne en PR. + +:::note +Ser du ikke en leverandør her? Send inn en PR. +::: + +--- + +### 302.AI + +1. Gå over til [302.AI-konsollen](https://302.ai/), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **302.AI**. + + ```txt + /connect + ``` + +3. Skriv inn 302.AI API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +--- + +### Amazonas grunnfjell + +Slik bruker du Amazon Bedrock med OpenCode: + +1. Gå over til **modellkatalogen** i Amazon Bedrock-konsollen og be om + tilgang til modellene du ønsker. + + :::tupp + Du må ha tilgang til modellen du ønsker i Amazon Bedrock. + ::: + +2. **Konfigurer autentisering** ved å bruke en av følgende metoder: + + #### Miljøvariabler (hurtigstart) + + Angi en av disse miljøvariablene mens du kjører opencode: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + Eller legg dem til bash-profilen din: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### Konfigurasjonsfil (anbefalt) + + For prosjektspesifikk eller vedvarende konfigurasjon, bruk `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **Tilgjengelige alternativer:** + - `region` - AWS region (f.eks. `us-east-1`, `eu-west-1`) + - `profile` - AWS navngitt profil fra `~/.aws/credentials` + - `endpoint` - Egendefinert endepunkt URL for VPC endepunkter (alias for generisk `baseURL`-alternativ) + + :::tupp + Alternativer for konfigurasjonsfil har forrang over miljøvariabler. + ::: + + #### Avansert: VPC Sluttpunkter + + Hvis du bruker VPC endepunkter for Berggrunn: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::note + Alternativet `endpoint` er et alias for det generiske alternativet `baseURL`, ved å bruke AWS-spesifikk terminologi. Hvis både `endpoint` og `baseURL` er spesifisert, har `endpoint` forrang. + ::: + + #### Autentiseringsmetoder + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: Opprett en IAM-bruker og generer tilgangsnøkler i AWS-konsollen + - **`AWS_PROFILE`**: Bruk navngitte profiler fra `~/.aws/credentials`. Konfigurer først med `aws configure --profile my-profile` eller `aws sso login` + - **`AWS_BEARER_TOKEN_BEDROCK`**: Generer langsiktige API-nøkler fra Amazon Bedrock-konsollen + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: For EKS IRSA (IAM roller for tjenestekontoer) eller andre Kubernetes-miljøer med OIDC føderasjon. Disse miljøvariablene injiseres automatisk av Kubernetes når du bruker tjenestekontokommentarer. + + #### Autentiseringsprioritet + + Amazon Bedrock bruker følgende autentiseringsprioritet: + 1. **Bearer Token** - `AWS_BEARER_TOKEN_BEDROCK` miljøvariabel eller token fra kommandoen `/connect` + 2. **AWS legitimasjonskjede** - profil, tilgangsnøkler, delt legitimasjon, IAM roller, nettidentitetstokener (EKS IRSA), forekomstmetadata + + :::note + Når et bærertoken er angitt (via `/connect` eller `AWS_BEARER_TOKEN_BEDROCK`), har det forrang over alle AWS legitimasjonsmetoder inkludert konfigurerte profiler. + ::: + +3. Kjør kommandoen `/models` for å velge modellen du ønsker. + + ```txt + /models + ``` + +:::note +For egendefinerte slutningsprofiler, bruk modellen og leverandørnavnet i nøkkelen og sett egenskapen `id` til arn. Dette sikrer korrekt caching: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### Antropisk + +1. Når du har registrert deg, kjør kommandoen `/connect` og velg Antropisk. + + ```txt + /connect + ``` + +2. Her kan du velge alternativet **Claude Pro/Max** og det vil åpne nettleseren din + og ber deg om å autentisere. + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. Nå skal alle de antropiske modellene være tilgjengelige når du bruker kommandoen `/models`. + + ```txt + /models + ``` + +::: info +Å bruke Claude Pro/Max-abonnementet ditt i OpenCode støttes ikke offisielt av [Anthropic](https://anthropic.com). +::: + +##### Bruke API-tastene + +Du kan også velge **Opprett en API nøkkel** hvis du ikke har et Pro/Max-abonnement. Den åpner også nettleseren din og ber deg logge på Anthropic og gi deg en kode du kan lime inn i terminalen din. + +Eller hvis du allerede har en API-nøkkel, kan du velge **Angi API-nøkkel manuelt** og lime den inn i terminalen. + +--- + +### Azure OpenAI + +:::note +Hvis du støter på «Beklager, men jeg kan ikke hjelpe med den forespørselen»-feil, kan du prøve å endre innholdsfilteret fra **DefaultV2** til **Default** i Azure-ressursen. +::: + +1. Gå over til [Azure-portalen](https://portal.azure.com/) og lag en **Azure OpenAI**-ressurs. Du trenger: + - **Ressursnavn**: Dette blir en del av API-endepunktet (`https://RESOURCE_NAME.openai.azure.com/`) + - **API nøkkel**: Enten `KEY 1` eller `KEY 2` fra ressursen din + +2. Gå til [Azure AI Foundry](https://ai.azure.com/) og distribuer en modell. + + :::note + Distribusjonsnavnet må samsvare med modellnavnet for at opencode skal fungere skikkelig. + ::: + +3. Kjør kommandoen `/connect` og søk etter **Azure**. + + ```txt + /connect + ``` + +4. Skriv inn API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Angi ressursnavnet ditt som en miljøvariabel: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + Eller legg den til bash-profilen din: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. Kjør kommandoen `/models` for å velge den distribuerte modellen. + + ```txt + /models + ``` + +--- + +### Azure Cognitive Services + +1. Gå over til [Azure-portalen](https://portal.azure.com/) og lag en **Azure OpenAI**-ressurs. Du trenger: + - **Ressursnavn**: Dette blir en del av API-endepunktet (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) + - **API nøkkel**: Enten `KEY 1` eller `KEY 2` fra ressursen din + +2. Gå til [Azure AI Foundry](https://ai.azure.com/) og distribuer en modell. + + :::note + Distribusjonsnavnet må samsvare med modellnavnet for at opencode skal fungere skikkelig. + ::: + +3. Kjør kommandoen `/connect` og søk etter **Azure Cognitive Services**. + + ```txt + /connect + ``` + +4. Skriv inn API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Angi ressursnavnet ditt som en miljøvariabel: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + Eller legg den til bash-profilen din: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. Kjør kommandoen `/models` for å velge den distribuerte modellen. + + ```txt + /models + ``` + +--- + +### Baseten + +1. Gå over til [Baseten](https://app.baseten.co/), opprett en konto og generer en API nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Baseten**. + + ```txt + /connect + ``` + +3. Skriv inn din Baseten API nøkkel. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +--- + +### Cerebras + +1. Gå over til [Cerebras-konsollen](https://inference.cerebras.ai/), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Cerebras**. + + ```txt + /connect + ``` + +3. Skriv inn Cerebras API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### Cloudflare AI Gateway + +Cloudflare AI Gateway lar deg få tilgang til modeller fra OpenAI, Anthropic, Workers AI og mer gjennom et enhetlig endepunkt. Med [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) trenger du ikke separate API-nøkler for hver leverandør. + +1. Gå over til [Cloudflare-dashbordet](https://dash.cloudflare.com/), naviger til **AI** > **AI Gateway**, og lag en ny gateway. + +2. Angi konto ID og gateway ID som miljøvariabler. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. Kjør kommandoen `/connect` og søk etter **Cloudflare AI Gateway**. + + ```txt + /connect + ``` + +4. Skriv inn Cloudflare API-tokenet ditt. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + Eller angi den som en miljøvariabel. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + + Du kan også legge til modeller gjennom opencode-konfigurasjonen. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### Cortecs + +1. Gå over til [Cortecs-konsollen](https://cortecs.ai/), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Cortecs**. + + ```txt + /connect + ``` + +3. Skriv inn Cortecs API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### DeepSeek + +1. Gå over til [DeepSeek-konsollen](https://platform.deepseek.com/), opprett en konto og klikk på **Opprett ny API-nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **DeepSeek**. + + ```txt + /connect + ``` + +3. Skriv inn DeepSeek API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en DeepSeek-modell som _DeepSeek Reasoner_. + + ```txt + /models + ``` + +--- + +### Deep Infra + +1. Gå over til [Deep Infra-dashbordet](https://deepinfra.com/dash), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Deep Infra**. + + ```txt + /connect + ``` + +3. Skriv inn Deep Infra API nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +--- + +### Fastvare + +1. Gå over til [Firmware dashboard](https://app.firmware.ai/signup), opprett en konto og generer en API nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Firmware**. + + ```txt + /connect + ``` + +3. Skriv inn firmware API nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +--- + +### Fyrverkeri AI + +1. Gå over til [Fireworks AI-konsollen](https://app.fireworks.ai/), opprett en konto og klikk på **Create API Key**. + +2. Kjør kommandoen `/connect` og søk etter **Fireworks AI**. + + ```txt + /connect + ``` + +3. Skriv inn Fireworks AI API nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### GitLab Duo + +GitLab Duo gir AI-drevet agentchat med native verktøyoppringingsfunksjoner gjennom GitLabs antropiske proxy. + +1. Kjør kommandoen `/connect` og velg GitLab. + + ```txt + /connect + ``` + +2. Velg autentiseringsmetoden din: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### Bruke OAuth (anbefalt) + + Velg **OAuth** og nettleseren din åpnes for autorisasjon. + + #### Bruker personlig tilgangstoken + 1. Gå til [GitLab User Settings > Access Tokens](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. Klikk på **Legg til nytt token** + 3. Navn: `OpenCode`, omfang: `api` + 4. Kopier tokenet (starter med `glpat-`) + 5. Skriv den inn i terminalen + +3. Kjør kommandoen `/models` for å se tilgjengelige modeller. + + ```txt + /models + ``` + + Tre Claude-baserte modeller er tilgjengelige: + - **duo-chat-haiku-4-5** (standard) - Raske svar for raske oppgaver + - **duo-chat-sonnet-4-5** - Balansert ytelse for de fleste arbeidsflyter + - **duo-chat-opus-4-5** - Mest egnet for kompleks analyse + +:::note +Du kan også spesifisere 'GITLAB_TOKEN' miljøvariabel hvis du ikke vil +for å lagre token i opencode auth-lagring. +::: + +##### Selvhostet GitLab + +:::note[compliance note] +OpenCode bruker en liten modell for noen AI oppgaver som å generere økttittelen. +Den er konfigurert til å bruke gpt-5-nano som standard, hostet av Zen. For å låse OpenCode +for kun å bruke din egen GitLab-hostede forekomst, legg til følgende i din +`opencode.json` fil. Det anbefales også å deaktivere øktdeling. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +For selvhostede GitLab-forekomster: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +Hvis forekomsten din kjører en tilpasset AI-gateway: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +Eller legg til bash-profilen din: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +GitLab-administratoren din må aktivere følgende: + +1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) for brukeren, gruppen eller forekomsten +2. Funksjonsflagg (via Rails-konsollen): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### OAuth for selvvertsbaserte forekomster + +For å få Oauth til å fungere for din selvhostede forekomst, må du opprette +en ny applikasjon (Innstillinger → Programmer) med +tilbakeringing URL `http://127.0.0.1:8080/callback` og følgende omfang: + +- api (Få tilgang til API på dine vegne) +- read_user (Les din personlige informasjon) +- read_repository (tillater skrivebeskyttet tilgang til depotet) + +Utsett deretter applikasjonen ID som miljøvariabel: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +Mer dokumentasjon på [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth) hjemmeside. + +##### Konfigurasjon + +Tilpass gjennom `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API Verktøy (valgfritt, men sterkt anbefalt) + +For å få tilgang til GitLab-verktøy (sammenslåingsforespørsler, problemer, pipelines, CI/CD, etc.): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +Denne plugin-en gir omfattende GitLab-repository-administrasjonsfunksjoner, inkludert MR-anmeldelser, problemsporing, pipeline-overvåking og mer. + +--- + +### GitHub Copilot + +Slik bruker du GitHub Copilot-abonnementet med OpenCode: + +:::note +Noen modeller kan trenge en [Pro+ +abonnement](https://github.com/features/copilot/plans) å bruke. + +Noen modeller må aktiveres manuelt i [GitHub Copilot-innstillingene](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. Kjør kommandoen `/connect` og søk etter GitHub Copilot. + + ```txt + /connect + ``` + +2. Naviger til [github.com/login/device](https://github.com/login/device) og skriv inn koden. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. Kjør nå kommandoen `/models` for å velge modellen du ønsker. + + ```txt + /models + ``` + +--- + +### Google Vertex AI + +Slik bruker du Google Vertex AI med OpenCode: + +1. Gå over til **Model Garden** i Google Cloud Console og sjekk + modeller tilgjengelig i din region. + + :::note + Du må ha et Google Cloud-prosjekt med Vertex AI API aktivert. + ::: + +2. Angi de nødvendige miljøvariablene: + - `GOOGLE_CLOUD_PROJECT`: Google Cloud-prosjektet ditt ID + - `VERTEX_LOCATION` (valgfritt): Regionen for verteks AI (standard til `global`) + - Autentisering (velg en): + - `GOOGLE_APPLICATION_CREDENTIALS`: Bane til tjenestekontoen JSON nøkkelfil + - Autentiser med gcloud CLI: `gcloud auth application-default login` + + Sett dem mens du kjører opencode. + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + Eller legg dem til på bash-profilen din. + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::tupp +`global`-regionen forbedrer tilgjengeligheten og reduserer feil uten ekstra kostnad. Bruk regionale endepunkter (f.eks. `us-central1`) for krav til dataopphold. [Finn ut mer](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. Kjør kommandoen `/models` for å velge modellen du ønsker. + + ```txt + /models + ``` + +--- + +### Groq + +1. Gå over til [Groq-konsollen](https://console.groq.com/), klikk på **Create API Key**, og kopier nøkkelen. + +2. Kjør kommandoen `/connect` og søk etter Groq. + + ```txt + /connect + ``` + +3. Skriv inn API-nøkkelen for leverandøren. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge den du ønsker. + + ```txt + /models + ``` + +--- + +### Klemmer ansikt + +[Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers) gir tilgang til åpne modeller som støttes av 17+ leverandører. + +1. Gå over til [Hugging Face-innstillinger](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) for å opprette et token med tillatelse til å ringe til inferensleverandører. + +2. Kjør kommandoen `/connect` og søk etter **Hugging Face**. + + ```txt + /connect + ``` + +3. Skriv inn ditt Hugging Face-token. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Kimi-K2-Instruct_ eller _GLM-4.6_. + + ```txt + /models + ``` + +--- + +### Helikon + +[Helicone](https://helicone.ai) er en LLM observerbarhetsplattform som gir logging, overvåking og analyser for AI-applikasjonene dine. Helicone AI Gateway ruter forespørslene dine til riktig leverandør automatisk basert på modellen. + +1. Gå over til [Helicone](https://helicone.ai), opprett en konto og generer en API nøkkel fra dashbordet. + +2. Kjør kommandoen `/connect` og søk etter **Helicone**. + + ```txt + /connect + ``` + +3. Skriv inn Helicone API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +For flere leverandører og avanserte funksjoner som bufring og hastighetsbegrensning, sjekk [Helicone-dokumentasjonen](https://docs.helicone.ai). + +#### Valgfrie konfigurasjoner + +I tilfelle du ser en funksjon eller modell fra Helicone som ikke konfigureres automatisk gjennom opencode, kan du alltid konfigurere den selv. + +Her er [Helicone's Model Directory](https://helicone.ai/models), du trenger denne for å hente ID-ene til modellene du vil legge til. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### Egendefinerte topptekster + +Helicone støtter tilpassede overskrifter for funksjoner som bufring, brukersporing og øktadministrasjon. Legg dem til leverandørkonfigurasjonen din ved å bruke `options.headers`: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### Sesjonssporing + +Helicones [Sessions](https://docs.helicone.ai/features/sessions) funksjon lar deg gruppere relaterte LLM forespørsler sammen. Bruk [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) plugin for automatisk å logge hver OpenCode-samtale som en økt i Helicone. + +```bash +npm install -g opencode-helicone-session +``` + +Legg den til i konfigurasjonen din. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +Programtillegget injiserer `Helicone-Session-Id` og `Helicone-Session-Name` overskrifter i forespørslene dine. På Helicones Sessions-side vil du se hver OpenCode-samtale oppført som en separat økt. + +##### Vanlige helikonhoder + +| Overskrift | Beskrivelse | +| -------------------------- | -------------------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | Aktiver responsbufring (`true`/`false`) | +| `Helicone-User-Id` | Spor beregninger etter bruker | +| `Helicone-Property-[Name]` | Legg til egendefinerte egenskaper (f.eks. `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | Knytt forespørsler til spørsmålsversjoner | + +Se [Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory) for alle tilgjengelige overskrifter. + +--- + +### lama.cpp + +Du kan konfigurere opencode for å bruke lokale modeller gjennom [llama.cpps](https://github.com/ggml-org/llama.cpp) lama-server-verktøy + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +I dette eksemplet: + +- `llama.cpp` er den tilpassede leverandøren ID. Dette kan være hvilken som helst streng du vil. +- `npm` spesifiserer pakken som skal brukes for denne leverandøren. Her brukes `@ai-sdk/openai-compatible` for enhver OpenAI-kompatibel API. +- `name` er visningsnavnet for leverandøren i UI. +- `options.baseURL` er endepunktet for den lokale serveren. +- `models` er et kart over modell-ID-er til deres konfigurasjoner. Modellnavnet vil vises i modellvalglisten. + +--- + +### IO.NET + +IO.NET tilbyr 17 modeller optimert for ulike brukstilfeller: + +1. Gå over til [IO.NET-konsollen](https://ai.io.net/), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **IO.NET**. + + ```txt + /connect + ``` + +3. Skriv inn nøkkelen IO.NET API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +--- + +### LM Studio + +Du kan konfigurere opencode for å bruke lokale modeller gjennom LM Studio. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +I dette eksemplet: + +- `lmstudio` er den tilpassede leverandøren ID. Dette kan være hvilken som helst streng du vil. +- `npm` spesifiserer pakken som skal brukes for denne leverandøren. Her brukes `@ai-sdk/openai-compatible` for enhver OpenAI-kompatibel API. +- `name` er visningsnavnet for leverandøren i UI. +- `options.baseURL` er endepunktet for den lokale serveren. +- `models` er et kart over modell-ID-er til deres konfigurasjoner. Modellnavnet vil vises i modellvalglisten. + +--- + +### Måneskudd AI + +Slik bruker du Kimi K2 fra Moonshot AI: + +1. Gå over til [Moonshot AI-konsollen](https://platform.moonshot.ai/console), opprett en konto og klikk på **Opprett API-nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **Moonshot AI**. + + ```txt + /connect + ``` + +3. Skriv inn Moonshot API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge _Kimi K2_. + + ```txt + /models + ``` + +--- + +### MiniMax + +1. Gå over til [MiniMax API-konsollen](https://platform.minimax.io/login), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **MiniMax**. + + ```txt + /connect + ``` + +3. Skriv inn MiniMax API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _M2.1_. + + ```txt + /models + ``` + +--- + +### Nebius Token Factory + +1. Gå over til [Nebius Token Factory-konsollen](https://tokenfactory.nebius.com/), opprett en konto og klikk på **Legg til nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **Nebius Token Factory**. + + ```txt + /connect + ``` + +3. Skriv inn Nebius Token Factory API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Ollama + +Du kan konfigurere opencode for å bruke lokale modeller gjennom Ollama. + +:::tupp +Ollama kan automatisk konfigurere seg selv for OpenCode. Se [Ollama-integrasjonsdokumentene](https://docs.ollama.com/integrations/opencode) for detaljer. +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +I dette eksemplet: + +- `ollama` er den tilpassede leverandøren ID. Dette kan være hvilken som helst streng du vil. +- `npm` spesifiserer pakken som skal brukes for denne leverandøren. Her brukes `@ai-sdk/openai-compatible` for enhver OpenAI-kompatibel API. +- `name` er visningsnavnet for leverandøren i UI. +- `options.baseURL` er endepunktet for den lokale serveren. +- `models` er et kart over modell-ID-er til deres konfigurasjoner. Modellnavnet vil vises i modellvalglisten. + +:::tupp +Hvis verktøykall ikke fungerer, prøv å øke `num_ctx` i Ollama. Start rundt 16k - 32k. +::: + +--- + +### Ollama Cloud + +Slik bruker du Ollama Cloud med OpenCode: + +1. Gå over til [https://ollama.com/](https://ollama.com/) og logg på eller opprett en konto. + +2. Naviger til **Innstillinger** > **Nøkler** og klikk på **Legg til API nøkkel** for å generere en ny API nøkkel. + +3. Kopier API-nøkkelen for bruk i OpenCode. + +4. Kjør kommandoen `/connect` og søk etter **Ollama Cloud**. + + ```txt + /connect + ``` + +5. Skriv inn din Ollama Cloud API nøkkel. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **Viktig**: Før du bruker skymodeller i OpenCode, må du hente modellinformasjonen lokalt: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. Kjør kommandoen `/models` for å velge din Ollama Cloud-modell. + + ```txt + /models + ``` + +--- + +### OpenAI + +Vi anbefaler at du registrerer deg for [ChatGPT Plus eller Pro](https://chatgpt.com/pricing). + +1. Når du har registrert deg, kjør kommandoen `/connect` og velg OpenAI. + + ```txt + /connect + ``` + +2. Her kan du velge alternativet **ChatGPT Plus/Pro** og det åpner nettleseren din + og ber deg om å autentisere. + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. Nå skal alle OpenAI-modellene være tilgjengelige når du bruker kommandoen `/models`. + + ```txt + /models + ``` + +##### Bruke API-tastene + +Hvis du allerede har en API-nøkkel, kan du velge **Angi API-nøkkel manuelt** og lime den inn i terminalen. + +--- + +### OpenCode Zen + +OpenCode Zen er en liste over testede og verifiserte modeller levert av OpenCode-teamet. [Finn ut mer](/docs/zen). + +1. Logg på **OpenCode Zen** og klikk på **Create API Key**. + +2. Kjør kommandoen `/connect` og søk etter **OpenCode Zen**. + + ```txt + /connect + ``` + +3. Skriv inn OpenCode API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### OpenRouter + +1. Gå over til [OpenRouter-dashbordet](https://openrouter.ai/settings/keys), klikk på **Create API Key**, og kopier nøkkelen. + +2. Kjør kommandoen `/connect` og søk etter OpenRouter. + + ```txt + /connect + ``` + +3. Skriv inn API-nøkkelen for leverandøren. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Mange OpenRouter-modeller er forhåndslastet som standard, kjør kommandoen `/models` for å velge den du ønsker. + + ```txt + /models + ``` + + Du kan også legge til flere modeller gjennom opencode-konfigurasjonen. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. Du kan også tilpasse dem gjennom opencode-konfigurasjonen. Her er et eksempel på å spesifisere en leverandør + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP AI Kjerne + +SAP AI Core gir tilgang til 40+ modeller fra OpenAI, Anthropic, Google, Amazon, Meta, Mistral og AI21 gjennom en enhetlig plattform. + +1. Gå til din [SAP BTP Cockpit](https://account.hana.ondemand.com/), naviger til din SAP AI kjernetjenesteforekomst, og lag en tjenestenøkkel. + + :::tupp + Tjenestenøkkelen er et JSON-objekt som inneholder `clientid`, `clientsecret`, `url` og `serviceurls.AI_API_URL`. Du finner AI kjerneforekomsten din under **Tjenester** > **Forekomster og abonnementer** i BTP cockpiten. + ::: + +2. Kjør kommandoen `/connect` og søk etter **SAP AI Core**. + + ```txt + /connect + ``` + +3. Skriv inn tjenestenøkkelen JSON. + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + Eller angi miljøvariabelen `AICORE_SERVICE_KEY`: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + Eller legg den til bash-profilen din: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. Angi eventuelt distribusjon ID og ressursgruppe: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::note + Disse innstillingene er valgfrie og bør konfigureres i henhold til SAP AI kjerneoppsettet. + ::: + +5. Kjør kommandoen `/models` for å velge fra 40+ tilgjengelige modeller. + + ```txt + /models + ``` + +--- + +### OVHcloud AI endepunkter + +1. Gå over til [OVHcloud-panelet](https://ovh.com/manager). Naviger til `Public Cloud`-delen, `AI & Machine Learning` > `AI Endpoints` og i `API Keys`-fanen klikker du på **Opprett en ny API-nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **OVHcloud AI endepunkter**. + + ```txt + /connect + ``` + +3. Skriv inn OVHcloud AI Endpoints API nøkkel. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Scaleway + +Slik bruker du [Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/) med OpenCode: + +1. Gå over til [Scaleway Console IAM innstillinger](https://console.scaleway.com/iam/api-keys) for å generere en ny API nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Scaleway**. + + ```txt + /connect + ``` + +3. Skriv inn Scaleway API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _devstral-2-123b-instruct-2512_ eller _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Sammen AI + +1. Gå over til [Together AI-konsollen](https://api.together.ai), opprett en konto og klikk på **Legg til nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **Together AI**. + + ```txt + /connect + ``` + +3. Skriv inn Together AI API nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Venezia AI + +1. Gå over til [Venezia AI-konsollen](https://venice.ai), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Venezia AI**. + + ```txt + /connect + ``` + +3. Skriv inn Venezia AI API nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Llama 3.3 70B_. + + ```txt + /models + ``` + +--- + +### Vercel AI Gateway + +Vercel AI Gateway lar deg få tilgang til modeller fra OpenAI, Anthropic, Google, xAI og mer gjennom et enhetlig endepunkt. Modeller tilbys til listepris uten påslag. + +1. Gå over til [Vercel dashboard](https://vercel.com/), naviger til fanen **AI Gateway**, og klikk på **API nøkler** for å opprette en ny API nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **Vercel AI Gateway**. + + ```txt + /connect + ``` + +3. Skriv inn Vercel AI Gateway API nøkkel. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell. + + ```txt + /models + ``` + +Du kan også tilpasse modeller gjennom opencode-konfigurasjonen. Her er et eksempel på spesifisering av leverandørrutingsrekkefølge. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +Noen nyttige rutealternativer: + +| Alternativ | Beskrivelse | +| ------------------- | ------------------------------------------------------------- | +| `order` | Providersekvens for å prøve | +| `only` | Begrens til spesifikke leverandører | +| `zeroDataRetention` | Bruk kun leverandører med null retningslinjer for datalagring | + +--- + +### xAI + +1. Gå over til [xAI-konsollen](https://console.x.ai/), opprett en konto og generer en API-nøkkel. + +2. Kjør kommandoen `/connect` og søk etter **xAI**. + + ```txt + /connect + ``` + +3. Skriv inn xAI API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _Grok Beta_. + + ```txt + /models + ``` + +--- + +### Z.AI + +1. Gå over til [Z.AI API-konsollen](https://z.ai/manage-apikey/apikey-list), opprett en konto og klikk på **Opprett en ny API-nøkkel**. + +2. Kjør kommandoen `/connect` og søk etter **Z.AI**. + + ```txt + /connect + ``` + + Hvis du abonnerer på **GLM Coding Plan**, velg **Z.AI Coding Plan**. + +3. Skriv inn Z.AI API-nøkkelen. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Kjør kommandoen `/models` for å velge en modell som _GLM-4.7_. + + ```txt + /models + ``` + +--- + +### ZenMux + +1. Gå over til [ZenMux-dashbordet](https://zenmux.ai/settings/keys), klikk på **Create API Key**, og kopier nøkkelen. + +2. Kjør kommandoen `/connect` og søk etter ZenMux. + + ```txt + /connect + ``` + +3. Skriv inn API-nøkkelen for leverandøren. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Mange ZenMux-modeller er forhåndslastet som standard, kjør kommandoen `/models` for å velge den du ønsker. + + ```txt + /models + ``` + + Du kan også legge til flere modeller gjennom opencode-konfigurasjonen. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## Egendefinert leverandør + +Slik legger du til en **OpenAI-kompatibel**-leverandør som ikke er oppført i `/connect`-kommandoen: + +:::tupp +Du kan bruke hvilken som helst OpenAI-kompatibel leverandør med opencode. De fleste moderne AI-leverandører tilbyr OpenAI-kompatible APIer. +::: + +1. Kjør kommandoen `/connect` og rull ned til **Annet**. + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. Skriv inn en unik ID for leverandøren. + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note + Velg en minneverdig ID, du vil bruke denne i konfigurasjonsfilen din. + ::: + +3. Skriv inn API-nøkkelen for leverandøren. + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. Opprett eller oppdater `opencode.json`-filen i prosjektkatalogen: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + Her er konfigurasjonsalternativene: + - **npm**: AI SDK pakke å bruke, `@ai-sdk/openai-compatible` for OpenAI-kompatible leverandører + - **navn**: Visningsnavn i UI. + - **modeller**: Tilgjengelige modeller. + - **options.baseURL**: API endepunkt URL. + - **options.apiKey**: Angi API-nøkkelen hvis du ikke bruker auth. + - **options.headers**: Angi egendefinerte overskrifter. + + Mer om de avanserte alternativene i eksemplet nedenfor. + +5. Kjør kommandoen `/models` og din egendefinerte leverandør og modeller vil vises i utvalgslisten. + +--- + +##### Eksempel + +Her er et eksempel på innstilling av alternativene `apiKey`, `headers` og modell `limit`. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +Konfigurasjonsdetaljer: + +- **apiKey**: Angi med `env` variabel syntaks, [finn ut mer](/docs/config#env-vars). +- **overskrifter**: Egendefinerte overskrifter sendt med hver forespørsel. +- **limit.context**: Maksimalt inndatatoken som modellen godtar. +- **limit.output**: Maksimalt antall tokens modellen kan generere. + +`limit`-feltene lar OpenCode forstå hvor mye kontekst du har igjen. Standardleverandører henter disse automatisk fra models.dev. + +--- + +## Feilsøking + +Hvis du har problemer med å konfigurere en leverandør, sjekk følgende: + +1. **Sjekk autentiseringsoppsettet**: Kjør `opencode auth list` for å se om legitimasjonen + for leverandøren legges til konfigurasjonen din. + + Dette gjelder ikke leverandører som Amazon Bedrock, som er avhengige av miljøvariabler for godkjenning. + +2. For tilpassede leverandører, sjekk opencode-konfigurasjonen og: + - Sørg for at leverandøren ID som brukes i `/connect`-kommandoen samsvarer med ID i opencode-konfigurasjonen. + – Den riktige npm-pakken brukes for leverandøren. Bruk for eksempel `@ai-sdk/cerebras` for Cerebras. Og for alle andre OpenAI-kompatible leverandører, bruk `@ai-sdk/openai-compatible`. + - Kontroller at riktig API-endepunkt er brukt i `options.baseURL`-feltet. diff --git a/packages/web/src/content/docs/nb/rules.mdx b/packages/web/src/content/docs/nb/rules.mdx new file mode 100644 index 000000000..e34097381 --- /dev/null +++ b/packages/web/src/content/docs/nb/rules.mdx @@ -0,0 +1,180 @@ +--- +title: Regler +description: Set custom instructions for opencode. +--- + +Du kan gi tilpassede instruksjoner for å OpenCode ved å opprette en `AGENTS.md`-fil. Dette ligner på Cursors regler. Den inneholder instruksjoner som vil bli inkludert i LLMs kontekst for å tilpasse oppførselen til ditt spesifikke prosjekt. + +--- + +## Initialiser + +For å lage en ny `AGENTS.md` fil, kan du kjøre kommandoen `/init` i opencode. + +:::tupp +Du bør overgi prosjektets `AGENTS.md`-fil til Git. +::: + +Dette vil skanne prosjektet og alt dets innhold for å forstå hva prosjektet handler om og generere en `AGENTS.md`-fil med det. Dette hjelper opencode å navigere i prosjektet bedre. + +Hvis du har en eksisterende `AGENTS.md`-fil, vil denne prøve å legge til den. + +--- + +## Eksempel + +Du kan også bare lage denne filen manuelt. Her er et eksempel på noen ting du kan legge inn i en `AGENTS.md`-fil. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +Vi legger til prosjektspesifikke instruksjoner her, og dette vil bli delt på tvers av teamet ditt. + +--- + +## Typer + +opencode støtter også lesing av `AGENTS.md`-filen fra flere steder. Og dette tjener forskjellige formål. + +### Prosjekt + +Plasser en `AGENTS.md` i prosjektroten for prosjektspesifikke regler. Disse gjelder kun når du arbeider i denne katalogen eller dens underkataloger. + +### Globalt + +Du kan også ha globale regler i en `~/.config/opencode/AGENTS.md`-fil. Dette blir brukt på alle opencode-økter. + +Siden dette ikke er forpliktet til Git eller delt med teamet ditt, anbefaler vi å bruke dette til å spesifisere eventuelle personlige regler som LLM bør følge. + +### Claude-kodekompatibilitet + +For brukere som migrerer fra Claude Code, støtter OpenCode Claude Codes filkonvensjoner som fallbacks: + +- **Prosjektregler**: `CLAUDE.md` i prosjektkatalogen din (brukes hvis ingen `AGENTS.md` eksisterer) +- **Globale regler**: `~/.claude/CLAUDE.md` (brukes hvis ingen `~/.config/opencode/AGENTS.md` eksisterer) +- **Skills**: `~/.claude/skills/` — se [Agent Skills](/docs/skills/) for detaljer + +For å deaktivere Claude Code-kompatibilitet, sett en av disse miljøvariablene: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## Forrang + +Når opencode starter, ser den etter regelfiler i denne rekkefølgen: + +1. **Lokale filer** ved å gå opp fra gjeldende katalog (`AGENTS.md`, `CLAUDE.md`) +2. **Global fil** på `~/.config/opencode/AGENTS.md` +3. **Claude Code-fil** på `~/.claude/CLAUDE.md` (med mindre de er deaktivert) + +Den første matchende filen vinner i hver kategori. For eksempel, hvis du har både `AGENTS.md` og `CLAUDE.md`, brukes bare `AGENTS.md`. På samme måte har `~/.config/opencode/AGENTS.md` forrang over `~/.claude/CLAUDE.md`. + +--- + +## Egendefinerte instruksjoner + +Du kan spesifisere egendefinerte instruksjonsfiler i din `opencode.json` eller den globale `~/.config/opencode/opencode.json`. Dette lar deg og teamet ditt gjenbruke eksisterende regler i stedet for å måtte duplisere dem til AGENTS.md. + +Eksempel: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Du kan også bruke eksterne URL-er for å laste instruksjoner fra nettet. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +Fjerninstruksjoner hentes med 5 sekunders tidsavbrudd. + +Alle instruksjonsfilene er kombinert med `AGENTS.md`-filene dine. + +--- + +## Refererer til eksterne filer + +Selv om opencode ikke automatisk analyserer filreferanser i `AGENTS.md`, kan du oppnå lignende funksjonalitet på to måter: + +### Bruker opencode.json + +Den anbefalte tilnærmingen er å bruke feltet `instructions` i `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Manuelle instruksjoner i AGENTS.md + +Du kan lære opencode å lese eksterne filer ved å gi eksplisitte instruksjoner i `AGENTS.md`. Her er et praktisk eksempel: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +Denne tilnærmingen lar deg: + +- Lag modulære, gjenbrukbare regelfiler +- Del regler på tvers av prosjekter via symbolkoblinger eller git-undermoduler +- Hold AGENTS.md kortfattet mens du refererer til detaljerte retningslinjer +- Sørg for at opencode laster filer kun når det er nødvendig for den spesifikke oppgaven + +:::tupp +For monorepos eller prosjekter med delte standarder er bruk av `opencode.json` med glob-mønstre (som `packages/*/AGENTS.md`) mer vedlikeholdbart enn manuelle instruksjoner. +::: diff --git a/packages/web/src/content/docs/nb/sdk.mdx b/packages/web/src/content/docs/nb/sdk.mdx new file mode 100644 index 000000000..ee5ed97aa --- /dev/null +++ b/packages/web/src/content/docs/nb/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: Typesikker JS-klient for åpen kodeserver. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Åpenkoden JS/TS SDK gir en typesikker klient for samhandling med serveren. +Bruk den til å bygge integrasjoner og kontrollere opencode programmatisk. + +[Finn ut mer](/docs/server) om hvordan serveren fungerer. For eksempler, sjekk ut [prosjektene](/docs/ecosystem#projects) bygget av fellesskapet. + +--- + +## Installer + +Installer SDK fra npm: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## Opprett klient + +Opprett en forekomst av opencode: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +Dette starter både en server og en klient + +#### Alternativer + +| Alternativ | Skriv | Beskrivelse | Standard | +| ---------- | ------------- | -------------------------------- | ----------- | +| `hostname` | `string` | Server vertsnavn | `127.0.0.1` | +| `port` | `number` | Serverport | `4096` | +| `signal` | `AbortSignal` | Avbryt signal for kansellering | `undefined` | +| `timeout` | `number` | Tidsavbrudd i ms for serverstart | `5000` | +| `config` | `Config` | Konfigurasjonsobjekt | `{}` | + +--- + +## Konfig + +Du kan sende et konfigurasjonsobjekt for å tilpasse virkemåten. Forekomsten henter fortsatt din `opencode.json`, men du kan overstyre eller legge til konfigurasjon inline: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## Kun klient + +Hvis du allerede har en kjørende forekomst av opencode, kan du opprette en klientforekomst for å koble til den: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### Alternativer + +| Alternativ | Skriv inn | Beskrivelse | Standard | +| --------------- | ---------- | ---------------------------------- | ----------------------- | +| `baseUrl` | `string` | URL av serveren | `http://localhost:4096` | +| `fetch` | `function` | Egendefinert hentingimplementering | `globalThis.fetch` | +| `parseAs` | `string` | Svarparsingmetode | `auto` | +| `responseStyle` | `string` | Returstil: `data` eller `fields` | `fields` | +| `throwOnError` | `boolean` | Kast feil i stedet for retur | `false` | + +--- + +## Typer + +SDK inkluderer TypeScript-definisjoner for alle API-typer. Importer dem direkte: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +Alle typer er generert fra serverens OpenAPI-spesifikasjon og tilgjengelig i types-filen. + +--- + +## Feil + +SDK kan gi feil som du kan fange opp og håndtere: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## APIer + +SDK avslører alle server-APIer gjennom en typesikker klient. + +--- + +### Globalt + +| Metode | Beskrivelse | Svar | +| ----------------- | ---------------------------- | ------------------------------------ | +| `global.health()` | Sjekk serverhelse og versjon | `{ healthy: true, version: string }` | + +--- + +#### Eksempler + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### App + +| Metode | Beskrivelse | Svar | +| -------------- | -------------------------------- | ------------------------------------------- | +| `app.log()` | Skriv en loggoppføring | `boolean` | +| `app.agents()` | Liste alle tilgjengelige agenter | Agent[] | + +--- + +#### Eksempler + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### Prosjekt + +| Metode | Beskrivelse | Svar | +| ------------------- | -------------------------- | ---------------------------------------------- | +| `project.list()` | Liste over alle prosjekter | Prosjekt[] | +| `project.current()` | Få nåværende prosjekt | Prosjekt | + +--- + +#### Eksempler + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### Sti + +| Metode | Beskrivelse | Svar | +| ------------ | ----------------- | ---------------------------------------- | +| `path.get()` | Få gjeldende bane | Path | + +--- + +#### Eksempler + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### Konfig + +| Metode | Beskrivelse | Svar | +| -------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` | Få konfigurasjonsinformasjon | Config | +| `config.providers()` | Liste leverandører og standardmodeller | `{ providers: `Tilbyder[]`, default: { [key: string]: string } }` | + +--- + +#### Eksempler + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### økter + +| Metode | Beskrivelse | Merknader | +| ---------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| `session.list()` | Liste økter | Returnerer Session[] | +| `session.get({ path })` | Få økt | Returnerer Session | +| `session.children({ path })` | Liste over barneøkter | Returnerer Session[] | +| `session.create({ body })` | Opprett økt | Returnerer Session | +| `session.delete({ path })` | Slett økt | Returnerer `boolean` | +| `session.update({ path, body })` | Oppdater øktegenskaper | Returnerer Session | +| `session.init({ path, body })` | Analyser appen og lag `AGENTS.md` | Returnerer `boolean` | +| `session.abort({ path })` | Avbryt en løpeøkt | Returnerer `boolean` | +| `session.share({ path })` | Del økten | Returnerer Session | +| `session.unshare({ path })` | Slutt å dele økten | Returnerer Session | +| `session.summarize({ path, body })` | Oppsummer økten | Returnerer `boolean` | +| `session.messages({ path })` | Liste meldinger i en økt | Returnerer `{ info: `Message`, parts: `Del[]`}[]` | +| `session.message({ path })` | Få meldingsdetaljer | Returnerer `{ info: `Message`, parts: `Del[]`}` | +| `session.prompt({ path, body })` | Send melding | `body.noReply: true` returnerer UserMessage (kun kontekst). Standard returnerer AssistantMessage med AI svar | +| `session.command({ path, body })` | Send kommando til økt | Returnerer `{ info: `AssistantMessage`, parts: `Del[]`}` | +| `session.shell({ path, body })` | Kjør en shell-kommando | Returnerer AssistantMessage | +| `session.revert({ path, body })` | Tilbakestill en melding | Returnerer Session | +| `session.unrevert({ path })` | Gjenopprett tilbakestilte meldinger | Returnerer Session | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | Svar på en tillatelsesforespørsel | Returnerer `boolean` | + +--- + +#### Eksempler + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### Filer + +| Metode | Beskrivelse | Svar | +| ------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------ | +| `find.text({ query })` | Søk etter tekst i filer | En rekke matchobjekter med `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `find.files({ query })` | Finn filer og kataloger etter navn | `string[]` (baner) | +| `find.symbols({ query })` | Finn arbeidsområdesymboler | Symbol[] | +| `file.read({ query })` | Les en fil | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | Få status for sporede filer | Fil[] | + +`find.files` støtter noen få valgfrie søkefelt: + +- `type`: `"file"` eller `"directory"` +- `directory`: overstyr prosjektroten for søket +- `limit`: maksimalt antall resultater (1–200) + +--- + +#### Eksempler + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +| Metode | Beskrivelse | Svar | +| ------------------------------ | ---------------------------- | --------- | +| `tui.appendPrompt({ body })` | Legg til tekst i ledeteksten | `boolean` | +| `tui.openHelp()` | Åpne hjelpedialogen | `boolean` | +| `tui.openSessions()` | Åpne øktvelgeren | `boolean` | +| `tui.openThemes()` | Åpne temavelgeren | `boolean` | +| `tui.openModels()` | Åpne modellvelgeren | `boolean` | +| `tui.submitPrompt()` | Send inn gjeldende ledetekst | `boolean` | +| `tui.clearPrompt()` | Fjern ledeteksten | `boolean` | +| `tui.executeCommand({ body })` | Utfør en kommando | `boolean` | +| `tui.showToast({ body })` | Vis toastvarsel | `boolean` | + +--- + +#### Eksempler + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### Auth + +| Metode | Beskrivelse | Svar | +| ------------------- | ------------------------------- | --------- | +| `auth.set({ ... })` | Angi autentiseringslegitimasjon | `boolean` | + +--- + +#### Eksempler + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### Hendelser + +| Metode | Beskrivelse | Svar | +| ------------------- | ------------------------------ | ------------------------------ | +| `event.subscribe()` | Server-sendte hendelser stream | Server-sendte hendelser stream | + +--- + +#### Eksempler + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/nb/server.mdx b/packages/web/src/content/docs/nb/server.mdx new file mode 100644 index 000000000..04d2e9221 --- /dev/null +++ b/packages/web/src/content/docs/nb/server.mdx @@ -0,0 +1,287 @@ +--- +title: Server +description: Samhandle med opencode-server over HTTP. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Kommandoen `opencode serve` kjører en hodeløs HTTP-server som avslører et OpenAPI-endepunkt som en opencode-klient kan bruke. + +--- + +### Bruk + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### Alternativer + +| Flagg | Beskrivelse | Standard | +| --------------- | ---------------------------------------------- | ---------------- | +| `--port` | Port å lytte på | `4096` | +| `--hostname` | Vertsnavn å lytte på | `127.0.0.1` | +| `--mdns` | Aktiver mDNS-oppdagelse | `false` | +| `--mdns-domain` | Egendefinert domenenavn for mDNS-tjeneste | `opencode.local` | +| `--cors` | Ytterligere nettleseropprinnelse for å tillate | `[]` | + +`--cors` kan passeres flere ganger: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### Autentisering + +Sett `OPENCODE_SERVER_PASSWORD` for å beskytte serveren med HTTP grunnleggende autentisering. Brukernavnet er standard til `opencode`, eller sett `OPENCODE_SERVER_USERNAME` for å overstyre det. Dette gjelder både `opencode serve` og `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### Slik fungerer det + +Når du kjører `opencode` starter den en TUI og en server. Der TUI er +klient som snakker med serveren. Serveren viser en OpenAPI 3.1-spesifikasjon +endepunkt. Dette endepunktet brukes også til å generere en [SDK](/docs/sdk). + +:::tupp +Bruk opencode-serveren til å samhandle med opencode programmatisk. +::: + +Denne arkitekturen lar opencode støtte flere klienter og lar deg samhandle med opencode programmatisk. + +Du kan kjøre `opencode serve` for å starte en frittstående server. Hvis du har +opencode TUI kjører, vil `opencode serve` starte en ny server. + +--- + +#### Koble til en eksisterende server + +Når du starter TUI, tildeler den tilfeldig en port og vertsnavn. Du kan i stedet sende inn `--hostname` og `--port` [flagg](/docs/cli). Bruk deretter denne til å koble til serveren. + +[`/tui`](#tui) endepunktet kan brukes til å kjøre TUI gjennom serveren. Du kan for eksempel forhåndsutfylle eller kjøre en forespørsel. Dette oppsettet brukes av OpenCode [IDE](/docs/ide) plugins. + +--- + +## Spes + +Serveren publiserer en OpenAPI 3.1-spesifikasjon som kan vises på: + +``` +http://:/doc +``` + +For eksempel `http://localhost:4096/doc`. Bruk spesifikasjonen til å generere klienter eller inspisere forespørsels- og svartyper. Eller se den i en Swagger-utforsker. + +--- + +## APIer + +OpenCode-serveren viser følgende APIer. + +--- + +### Globalt + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ---------------- | -------------------------------- | ------------------------------------ | +| `GET` | `/global/health` | Få serverhelse og versjon | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | Få globale hendelser (SSE strøm) | Eventstrøm | + +--- + +### Prosjekt + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------------------ | --------------------------- | ---------------------------------------------- | +| `GET` | `/project` | Liste over alle prosjekter | Prosjekt[] | +| `GET` | `/project/current` | Få det nåværende prosjektet | Prosjekt | + +--- + +### Bane og VCS + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------- | ---------------------------------- | ------------------------------------------- | +| `GET` | `/path` | Få gjeldende bane | Path | +| `GET` | `/vcs` | Få VCS info for gjeldende prosjekt | VcsInfo | + +--- + +### Forekomst + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------------------- | ------------------------ | --------- | +| `POST` | `/instance/dispose` | Kast gjeldende forekomst | `boolean` | + +--- + +### Konfig + +| Metode | Sti | Beskrivelse | Svar | +| ------- | ------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` | Få konfigurasjonsinformasjon | Config | +| `PATCH` | `/config` | Oppdater konfigurasjon | Config | +| `GET` | `/config/providers` | Liste leverandører og standardmodeller | `{ providers: `Tilbyder[]`, default: { [key: string]: string } }` | + +--- + +### Leverandør + +| Metode | Sti | Beskrivelse | Svar | +| ------ | -------------------------------- | ----------------------------------------------- | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` | Liste alle leverandører | `{ all: `Tilbyder[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | Få leverandørautentiseringsmetoder | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | Autoriser en leverandør ved å bruke OAuth | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | Håndtere OAuth-tilbakeringing for en leverandør | `boolean` | + +--- + +### økter + +| Metode | Sti | Beskrivelse | Merknader | +| -------- | ---------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------- | +| `GET` | `/session` | Liste alle økter | Returnerer Session[] | +| `POST` | `/session` | Opprett en ny økt | body: `{ parentID?, title? }`, returnerer Session | +| `GET` | `/session/status` | Få øktstatus for alle økter | Returnerer `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | Få øktdetaljer | Returnerer Session | +| `DELETE` | `/session/:id` | Slett en økt og alle dens data | Returnerer `boolean` | +| `PATCH` | `/session/:id` | Oppdater øktegenskaper | body: `{ title? }`, returnerer Session | +| `GET` | `/session/:id/children` | Få en økts barneøkter | Returnerer Session[] | +| `GET` | `/session/:id/todo` | Få gjøremålslisten for en økt | Returnerer Todo[] | +| `POST` | `/session/:id/init` | Analyser appen og lag `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returnerer `boolean` | +| `POST` | `/session/:id/fork` | Fork en eksisterende økt ved en melding | body: `{ messageID? }`, returnerer Session | +| `POST` | `/session/:id/abort` | Avbryt en løpeøkt | Returnerer `boolean` | +| `POST` | `/session/:id/share` | Del en økt | Returnerer Session | +| `DELETE` | `/session/:id/share` | Slutt å dele en økt | Returnerer Session | +| `GET` | `/session/:id/diff` | Få diff for denne økten | spørring: `messageID?`, returnerer FileDiff[] | +| `POST` | `/session/:id/summarize` | Oppsummer økten | body: `{ providerID, modelID }`, returnerer `boolean` | +| `POST` | `/session/:id/revert` | Tilbakestill en melding | body: `{ messageID, partID? }`, returnerer `boolean` | +| `POST` | `/session/:id/unrevert` | Gjenopprett alle tilbakestilte meldinger | Returnerer `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | Svar på en tillatelsesforespørsel | body: `{ response, remember? }`, returnerer `boolean` | + +--- + +### Meldinger + +| Metode | Sti | Beskrivelse | Merknader | +| ------ | --------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `GET` | `/session/:id/message` | Liste meldinger i en økt | spørring: `limit?`, returnerer `{ info: `Message`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` | Send en melding og vent på svar | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, returnerer `{ info: `Message`, parts: `Part[]`}` | +| `GET` | `/session/:id/message/:messageID` | Få meldingsdetaljer | Returnerer `{ info: `Message`, parts: `Del[]`}` | +| `POST` | `/session/:id/prompt_async` | Send en melding asynkront (ingen vent) | body: samme som `/session/:id/message`, returnerer `204 No Content` | +| `POST` | `/session/:id/command` | Utfør en skråstrek-kommando | body: `{ messageID?, agent?, model?, command, arguments }`, returnerer `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/shell` | Kjør en shell-kommando | body: `{ agent, model?, command }`, returnerer `{ info: `Message`, parts: `Part[]`}` | + +--- + +### Kommandoer + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ---------- | --------------------- | ---------------------------------------------- | +| `GET` | `/command` | Liste alle kommandoer | Kommando[] | + +--- + +### Filer + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------ | +| `GET` | `/find?pattern=` | Søk etter tekst i filer | En rekke matchobjekter med `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | Finn filer og kataloger etter navn | `string[]` (baner) | +| `GET` | `/find/symbol?query=` | Finn arbeidsområdesymboler | Symbol[] | +| `GET` | `/file?path=` | Liste filer og kataloger | FilNode[] | +| `GET` | `/file/content?path=

` | Les en fil | Filinnhold | +| `GET` | `/file/status` | Få status for sporede filer | Fil[] | + +#### `/find/file` spørringsparametere + +- `query` (obligatorisk) - søkestreng (uklar samsvar) +- `type` (valgfritt) - begrense resultatene til `"file"` eller `"directory"` +- `directory` (valgfritt) — overstyr prosjektroten for søket +- `limit` (valgfritt) - maks. resultater (1–200) +- `dirs` (valgfritt) - eldre flagg (`"false"` returnerer kun filer) + +--- + +### Verktøy (eksperimentelt) + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------------------------------------------- | -------------------------------------------- | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` | Vis alle verktøy-ID-er | ToolIDs | +| `GET` | `/experimental/tool?provider=

&model=` | List verktøy med JSON-skjemaer for en modell | ToolList | + +--- + +### LSP, formattere og MCP + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------------ | ---------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | Få LSP serverstatus | LSPStatus[] | +| `GET` | `/formatter` | Få formateringsstatus | FormatterStatus[] | +| `GET` | `/mcp` | Få MCP serverstatus | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | Legg til MCP server dynamisk | body: `{ name, config }`, returnerer MCP statusobjekt | + +--- + +### Agenter + +| Metode | Sti | Beskrivelse | Svar | +| ------ | -------- | -------------------------------- | ------------------------------------------- | +| `GET` | `/agent` | Liste alle tilgjengelige agenter | Agent[] | + +--- + +### Logging + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------ | --------------------------------------------------------------------- | --------- | +| `POST` | `/log` | Skriv loggoppføring. Brødtekst: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ----------------------- | ------------------------------------------- | -------------------------- | +| `POST` | `/tui/append-prompt` | Legg til tekst i ledeteksten | `boolean` | +| `POST` | `/tui/open-help` | Åpne hjelpedialogen | `boolean` | +| `POST` | `/tui/open-sessions` | Åpne øktvelgeren | `boolean` | +| `POST` | `/tui/open-themes` | Åpne temavelgeren | `boolean` | +| `POST` | `/tui/open-models` | Åpne modellvelgeren | `boolean` | +| `POST` | `/tui/submit-prompt` | Send inn gjeldende ledetekst | `boolean` | +| `POST` | `/tui/clear-prompt` | Fjern ledeteksten | `boolean` | +| `POST` | `/tui/execute-command` | Utfør en kommando (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | Vis toast (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | Vent på neste kontrollforespørsel | Kontrollforespørselsobjekt | +| `POST` | `/tui/control/response` | Svar på en kontrollforespørsel (`{ body }`) | `boolean` | + +--- + +### Auth + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ----------- | --------------------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | Angi autentiseringslegitimasjon. Brødtekst må samsvare med leverandørskjema | `boolean` | + +--- + +### Hendelser + +| Metode | Sti | Beskrivelse | Svar | +| ------ | -------- | -------------------------------------------------------------------------------------------------- | ------------------------------ | +| `GET` | `/event` | Server-sendte hendelsesstrøm. Første arrangement er `server.connected`, deretter bussarrangementer | Server-sendte hendelser stream | + +--- + +### Dokumenter + +| Metode | Sti | Beskrivelse | Svar | +| ------ | ------ | ------------------------- | ----------------------------------- | +| `GET` | `/doc` | OpenAPI 3.1-spesifikasjon | HTML side med OpenAPI-spesifikasjon | diff --git a/packages/web/src/content/docs/nb/share.mdx b/packages/web/src/content/docs/nb/share.mdx new file mode 100644 index 000000000..16dff7c52 --- /dev/null +++ b/packages/web/src/content/docs/nb/share.mdx @@ -0,0 +1,128 @@ +--- +title: Dele +description: Del dine OpenCode-samtaler. +--- + +OpenCodes delingsfunksjon lar deg lage offentlige lenker til dine OpenCode-samtaler, slik at du kan samarbeide med lagkamerater eller få hjelp fra andre. + +:::note +Delte samtaler er offentlig tilgjengelige for alle med linken. +::: + +--- + +## Slik fungerer det + +Når du deler en samtale, OpenCode: + +1. Oppretter en unik offentlig URL for økten din +2. Synkroniserer samtaleloggen din til serverne våre +3. Gjør samtalen tilgjengelig via den delbare lenken — `opncd.ai/s/` + +--- + +## Deling + +OpenCode støtter tre delingsmoduser som kontrollerer hvordan samtaler deles: + +--- + +### Manuell (standard) + +Som standard bruker OpenCode manuell delingsmodus. Økter deles ikke automatisk, men du kan dele dem manuelt ved å bruke kommandoen `/share`: + +``` +/share +``` + +Dette vil generere en unik URL som vil bli kopiert til utklippstavlen din. + +For å eksplisitt angi manuell modus i [konfigurasjonsfilen](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### Automatisk deling + +Du kan aktivere automatisk deling for alle nye samtaler ved å sette alternativet `share` til `"auto"` i [konfigurasjonsfilen](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +Med automatisk deling aktivert, vil hver nye samtale automatisk bli delt og en kobling vil bli generert. + +--- + +### Deaktivert + +Du kan deaktivere deling helt ved å sette alternativet `share` til `"disabled"` i [konfigurasjonsfilen](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +For å håndheve dette på tvers av teamet ditt for et gitt prosjekt, legg det til `opencode.json` i prosjektet ditt og sjekk inn i Git. + +--- + +## Opphev deling + +Slik slutter du å dele en samtale og fjerner den fra offentlig tilgang: + +``` +/unshare +``` + +Dette vil fjerne delelinken og slette dataene knyttet til samtalen. + +--- + +## Personvern + +Det er et par ting du må huske på når du deler en samtale. + +--- + +### Datalagring + +Delte samtaler forblir tilgjengelige til du eksplisitt opphever deling av dem. Dette +inkluderer: + +- Full samtalehistorikk +- Alle meldinger og svar +- Metadata for økter + +--- + +### Anbefalinger + +- Del kun samtaler som ikke inneholder sensitiv informasjon. +- Se gjennom samtaleinnholdet før du deler. +- Opphev deling av samtaler når samarbeidet er fullført. +- Unngå å dele samtaler med proprietær kode eller konfidensielle data. +- For sensitive prosjekter, deaktiver deling helt. + +--- + +## For bedrifter + +For bedriftsimplementeringer kan delingsfunksjonen være: + +- **Deaktivert** helt for overholdelse av sikkerhet +- **Begrenset** til brukere som kun er autentisert gjennom SSO +- **Selvvert** på din egen infrastruktur + +[Finn ut mer](/docs/enterprise) om bruk av opencode i organisasjonen din. diff --git a/packages/web/src/content/docs/nb/skills.mdx b/packages/web/src/content/docs/nb/skills.mdx new file mode 100644 index 000000000..21168ef4b --- /dev/null +++ b/packages/web/src/content/docs/nb/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "Agentferdigheter" +description: "Definer gjenbrukbar atferd via SKILL.md-definisjoner" +--- + +Agentferdigheter lar OpenCode oppdage gjenbrukbare instruksjoner fra repo- eller hjemmekatalogen din. +Ferdigheter lastes inn på forespørsel via det opprinnelige `skill`-verktøyet – agenter ser tilgjengelige ferdigheter og kan laste inn hele innholdet når det er nødvendig. + +--- + +## Plasser filer + +Opprett én mappe per ferdighetsnavn og legg inn en `SKILL.md` i den. +OpenCode søker etter disse stedene: + +- Prosjektkonfigurasjon: `.opencode/skills//SKILL.md` +- Global konfigurasjon: `~/.config/opencode/skills//SKILL.md` +- Prosjekt Claude-kompatibel: `.claude/skills//SKILL.md` +- Global Claude-kompatibel: `~/.claude/skills//SKILL.md` +- Prosjektagent-kompatibel: `.agents/skills//SKILL.md` +- Global agent-kompatibel: `~/.agents/skills//SKILL.md` + +--- + +## Forstå oppdagelsen + +For prosjektlokale stier går OpenCode opp fra din nåværende arbeidskatalog til den når git-arbeidstreet. +Den laster alle matchende `skills/*/SKILL.md` i `.opencode/` og alle matchende `.claude/skills/*/SKILL.md` eller `.agents/skills/*/SKILL.md` underveis. + +Globale definisjoner lastes også inn fra `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` og `~/.agents/skills/*/SKILL.md`. + +--- + +## Skriv frontmaterie + +Hver `SKILL.md` må starte med YAML frontmatter. +Bare disse feltene gjenkjennes: + +- `name` (påkrevd) +- `description` (påkrevd) +- `license` (valgfritt) +- `compatibility` (valgfritt) +- `metadata` (valgfritt, streng-til-streng kart) + +Ukjente frontmatter-felter ignoreres. + +--- + +## Bekreft navn + +`name` må: + +- Bestå av 1–64 tegn +- Vær alfanumerisk med små bokstaver med skilletegn med enkelt bindestrek +- Ikke begynne eller slutte med `-` +- Ikke inneholde påfølgende `--` +- Match katalognavnet som inneholder `SKILL.md` + +Ekvivalent regulært uttrykk: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## Følg lengdereglene + +`description` må bestå av 1-1024 tegn. +Hold det spesifikt nok til at agenten kan velge riktig. + +--- + +## Bruk et eksempel + +Lag `.opencode/skills/git-release/SKILL.md` slik: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## Gjenkjenne verktøybeskrivelsen + +OpenCode viser tilgjengelige ferdigheter i `skill` verktøybeskrivelsen. +Hver oppføring inneholder ferdighetsnavnet og beskrivelsen: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +Agenten laster inn en ferdighet ved å kalle verktøyet: + +``` +skill({ name: "git-release" }) +``` + +--- + +## Konfigurer tillatelser + +Kontroller hvilke ferdigheter agenter har tilgang til ved å bruke mønsterbaserte tillatelser i `opencode.json`: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Tillatelse | Atferd | +| ---------- | ----------------------------------------- | +| `allow` | Ferdigheter lastes umiddelbart | +| `deny` | Ferdighet skjult for agent, tilgang avvist | +| `ask` | Bruker bedt om godkjenning før lasting | + +Mønstre støtter jokertegn: `internal-*` samsvarer med `internal-docs`, `internal-tools` osv. + +--- + +## Overstyring per agent + +Gi spesifikke agenter andre tillatelser enn de globale standardinnstillingene. + +**For egendefinerte agenter** (i agent frontmatter): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**For innebygde agenter** (i `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## Deaktiver ferdighetsverktøyet + +Deaktiver ferdigheter fullstendig for agenter som ikke bør bruke dem: + +**For egendefinerte agenter**: + +```yaml +--- +tools: + skill: false +--- +``` + +**For innebygde agenter**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +Når den er deaktivert, blir ``-delen utelatt helt. + +--- + +## Feilsøk lasting + +Hvis en ferdighet ikke vises: + +1. Kontroller at `SKILL.md` er stavet med store bokstaver +2. Sjekk at frontmatter inkluderer `name` og `description` +3. Sørg for at ferdighetsnavnene er unike på alle steder +4. Sjekk tillatelser – ferdigheter med `deny` er skjult for agenter diff --git a/packages/web/src/content/docs/nb/themes.mdx b/packages/web/src/content/docs/nb/themes.mdx new file mode 100644 index 000000000..d7f2fb377 --- /dev/null +++ b/packages/web/src/content/docs/nb/themes.mdx @@ -0,0 +1,369 @@ +--- +title: Temaer +description: Velg et innebygd tema eller definer ditt eget. +--- + +Med OpenCode kan du velge fra ett av flere innebygde temaer, bruke et tema som tilpasser seg terminaltemaet ditt, eller definere ditt eget tilpassede tema. + +Som standard bruker OpenCode vårt eget `opencode`-tema. + +--- + +## Terminalkrav + +For at temaer skal vises riktig med fullfargepalett, må terminalen din støtte **truecolor** (24-biters farger). De fleste moderne terminaler støtter dette som standard, men du må kanskje aktivere det: + +- **Sjekk støtte**: Kjør `echo $COLORTERM` - den skal gi ut `truecolor` eller `24bit` +- **Aktiver truecolor**: Sett miljøvariabelen `COLORTERM=truecolor` i skallprofilen din +- **Terminalkompatibilitet**: Sørg for at terminalemulatoren din støtter 24-bits farger (de fleste moderne terminaler som iTerm2, Alacritty, Kitty, Windows Terminal og nyere versjoner av GNOME Terminal gjør det) + +Uten truecolor-støtte kan temaer vises med redusert fargenøyaktighet eller falle tilbake til nærmeste 256-fargers tilnærming. + +--- + +## Innebygde temaer + +OpenCode kommer med flere innebygde temaer. + +| Navn | Beskrivelse | +| ---------------------- | ---------------------------------------------------------------------------- | +| `system` | Tilpasser seg terminalens bakgrunnsfarge | +| `tokyonight` | Basert på [Tokyonight](https://github.com/folke/tokyonight.nvim)-temaet | +| `everforest` | Basert på [Everforest](https://github.com/sainnhe/everforest)-temaet | +| `ayu` | Basert på [Ayu](https://github.com/ayu-theme) mørke tema | +| `catppuccin` | Basert på [Catppuccin](https://github.com/catppuccin)-temaet | +| `catppuccin-macchiato` | Basert på [Catppuccin](https://github.com/catppuccin)-temaet | +| `gruvbox` | Basert på [Gruvbox](https://github.com/morhetz/gruvbox)-temaet | +| `kanagawa` | Basert på [Kanagawa](https://github.com/rebelot/kanagawa.nvim)-temaet | +| `nord` | Basert på [Nord](https://github.com/nordtheme/nord)-temaet | +| `matrix` | Hacker-stil grønt på svart tema | +| `one-dark` | Basert på [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) Mørkt tema | + +Og mer, vi legger stadig til nye temaer. + +--- + +## Systemtema + +`system`-temaet er designet for å automatisk tilpasse seg terminalens fargevalg. I motsetning til tradisjonelle temaer som bruker faste farger, er _system_-temaet: + +- **Genererer gråskala**: Oppretter en tilpasset gråskala basert på terminalens bakgrunnsfarge, og sikrer optimal kontrast. +- **Bruker ANSI farger**: Bruker standard ANSI farger (0-15) for syntaksutheving og UI elementer, som respekterer terminalens fargepalett. +- **Bevarer terminalens standardinnstillinger**: Bruker `none` for tekst- og bakgrunnsfarger for å opprettholde terminalens opprinnelige utseende. + +Systemtemaet er for brukere som: + +- Vil at OpenCode skal matche terminalens utseende +- Bruk tilpassede terminalfargeskjemaer +- Foretrekker et konsistent utseende på tvers av alle terminalapplikasjoner + +--- + +## Bruke et tema + +Du kan velge et tema ved å hente frem temavalg med kommandoen `/theme`. Eller du kan spesifisere det i [config](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Egendefinerte temaer + +OpenCode støtter et fleksibelt JSON-basert temasystem som lar brukere enkelt lage og tilpasse temaer. + +--- + +### Hierarki + +Temaer lastes inn fra flere kataloger i følgende rekkefølge der senere kataloger overstyrer tidligere: + +1. **Innebygde temaer** - Disse er innebygd i binæren +2. **Brukerkonfigurasjonskatalog** - Definert i `~/.config/opencode/themes/*.json` eller `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Prosjektrotkatalog** - Definert i `/.opencode/themes/*.json` +4. **Gjeldende arbeidskatalog** - Definert i `./.opencode/themes/*.json` + +Hvis flere kataloger inneholder et tema med samme navn, vil temaet fra katalogen med høyere prioritet bli brukt. + +--- + +### Opprette et tema + +For å lage et tilpasset tema, lag en JSON-fil i en av temakatalogene. + +For brukeromfattende temaer: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +Og for prosjektspesifikke temaer. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON format + +Temaer bruker et fleksibelt JSON-format med støtte for: + +- **Sekskantfarger**: `"#ffffff"` +- **ANSI farger**: `3` (0-255) +- **Fargereferanser**: `"primary"` eller egendefinerte definisjoner +- **Mørke/lyse varianter**: `{"dark": "#000", "light": "#fff"}` +- **Ingen farge**: `"none"` - Bruker terminalens standardfarge eller transparent + +--- + +### Fargedefinisjoner + +`defs`-delen er valgfri, og den lar deg definere gjenbrukbare farger som kan refereres til i temaet. + +--- + +### Terminalstandarder + +Spesialverdien `"none"` kan brukes for hvilken som helst farge for å arve terminalens standardfarge. Dette er spesielt nyttig for å lage temaer som passer sømløst med terminalens fargeskjema: + +- `"text": "none"` - Bruker terminalens standard forgrunnsfarge +- `"background": "none"` - Bruker terminalens standard bakgrunnsfarge + +--- + +### Eksempel + +Her er et eksempel på et tilpasset tema: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/nb/tools.mdx b/packages/web/src/content/docs/nb/tools.mdx new file mode 100644 index 000000000..0b4da5ca3 --- /dev/null +++ b/packages/web/src/content/docs/nb/tools.mdx @@ -0,0 +1,379 @@ +--- +title: Verktøy +description: Administrer verktøyene en LLM kan bruke. +--- + +Verktøy lar LLM utføre handlinger i kodebasen din. OpenCode kommer med et sett med innebygde verktøy, men du kan utvide det med [egendefinerte verktøy](/docs/custom-tools) eller [MCP servere](/docs/mcp-servers). + +Som standard er alle verktøy **aktivert** og trenger ikke tillatelse for å kjøre. Du kan kontrollere verktøyets oppførsel gjennom [tillatelser](/docs/permissions). + +--- + +## Konfigurer + +Bruk feltet `permission` for å kontrollere verktøyets oppførsel. Du kan tillate, avslå eller kreve godkjenning for hvert verktøy. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +Du kan også bruke jokertegn for å kontrollere flere verktøy samtidig. For eksempel, for å kreve godkjenning for alle verktøy fra en MCP-server: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[Finn ut mer](/docs/permissions) om konfigurering av tillatelser. + +--- + +## Innebygd + +Her er alle de innebygde verktøyene som er tilgjengelige i OpenCode. + +--- + +### bash + +Utfør skallkommandoer i prosjektmiljøet ditt. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +Dette verktøyet lar LLM kjøre terminalkommandoer som `npm install`, `git status` eller en hvilken som helst annen shell-kommando. + +--- + +### rediger + +Endre eksisterende filer ved å bruke eksakte strengerstatninger. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Dette verktøyet utfører nøyaktige redigeringer av filer ved å erstatte eksakte teksttreff. Det er den primære måten LLM endrer kode på. + +--- + +### skriv + +Opprett nye filer eller overskriv eksisterende. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Bruk denne for å la LLM lage nye filer. Den vil overskrive eksisterende filer hvis de allerede eksisterer. + +:::note +`write`-verktøyet kontrolleres av tillatelsen `edit`, som dekker alle filendringer (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### lest + +Les filinnholdet fra kodebasen din. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +Dette verktøyet leser filer og returnerer innholdet. Den støtter lesing av spesifikke linjeområder for store filer. + +--- + +### grep + +Søk i filinnhold ved hjelp av regulære uttrykk. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Rask innholdssøk på tvers av kodebasen din. Støtter full regex-syntaks og filmønsterfiltrering. + +--- + +### glob + +Finn filer etter mønstermatching. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +Søk etter filer ved å bruke glob-mønstre som `**/*.js` eller `src/**/*.ts`. Returnerer samsvarende filbaner sortert etter endringstid. + +--- + +### liste + +List filer og kataloger i en gitt bane. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +Dette verktøyet viser kataloginnhold. Den aksepterer glob-mønstre for å filtrere resultater. + +--- + +### lsp (eksperimentell) + +Samhandle med dine konfigurerte LSP-servere for å få kodeintelligensfunksjoner som definisjoner, referanser, sveveinformasjon og anropshierarki. + +:::note +Dette verktøyet er bare tilgjengelig når `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (eller `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +Støttede operasjoner inkluderer `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` og `outgoingCalls`. + +For å konfigurere hvilke LSP-servere som er tilgjengelige for prosjektet ditt, se [LSP-servere](/docs/lsp). + +--- + +### patch + +Bruk patcher på filer. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Dette verktøyet bruker oppdateringsfiler til kodebasen din. Nyttig for å påføre diff og lapper fra forskjellige kilder. + +:::note +`patch`-verktøyet kontrolleres av tillatelsen `edit`, som dekker alle filendringer (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### ferdighet + +Last inn en [ferdighet](/docs/skills) (en `SKILL.md` fil) og returner innholdet i samtalen. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### for å skrive + +Administrer gjøremålslister under kodingsøkter. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +Oppretter og oppdaterer oppgavelister for å spore fremdrift under komplekse operasjoner. LLM bruker dette til å organisere flertrinnsoppgaver. + +:::note +Dette verktøyet er deaktivert for subagenter som standard, men du kan aktivere det manuelt. [Finn ut mer](/docs/agents/#permissions) +::: + +--- + +### todoread + +Les eksisterende gjøremålslister. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +Leser gjeldende gjøremålslistestatus. Brukes av LLM for å spore hvilke oppgaver som venter eller er fullført. + +:::note +Dette verktøyet er deaktivert for subagenter som standard, men du kan aktivere det manuelt. [Finn ut mer](/docs/agents/#permissions) +::: + +--- + +### webhenting + +Hent nettinnhold. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +Lar LLM hente og lese nettsider. Nyttig for å slå opp dokumentasjon eller forske på nettressurser. + +--- + +### nettsøk + +Søk på nettet for informasjon. + +:::note +Dette verktøyet er bare tilgjengelig når du bruker OpenCode-leverandøren eller når miljøvariabelen `OPENCODE_ENABLE_EXA` er satt til en sannverdi (f.eks. `true` eller `1`). + +Slik aktiverer du når du starter OpenCode: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Utfører nettsøk med Exa AI for å finne relevant informasjon på nettet. Nyttig for å undersøke emner, finne aktuelle hendelser eller samle informasjon utover treningsdataavbruddet. + +Ingen API-nøkkel kreves — verktøyet kobles direkte til Exa AIs vertsbaserte MCP-tjeneste uten autentisering. + +:::tupp +Bruk `websearch` når du trenger å finne informasjon (oppdagelse), og `webfetch` når du trenger å hente innhold fra en bestemt URL (henting). +::: + +--- + +### spørsmål + +Still brukeren spørsmål under utførelse. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +Dette verktøyet lar LLM stille spørsmål til brukeren under en oppgave. Det er nyttig for: + +- Samle brukerpreferanser eller krav +- Avklarende tvetydige instruksjoner +- Få beslutninger om gjennomføringsvalg +- Tilbyr valg om hvilken retning du skal ta + +Hvert spørsmål inkluderer en overskrift, spørsmålsteksten og en liste over alternativer. Brukere kan velge fra de angitte alternativene eller skrive inn et tilpasset svar. Når det er flere spørsmål, kan brukerne navigere mellom dem før de sender inn alle svarene. + +--- + +## Egendefinerte verktøy + +Egendefinerte verktøy lar deg definere dine egne funksjoner som LLM kan kalle. Disse er definert i konfigurasjonsfilen din og kan kjøre vilkårlig kode. + +[Finn ut mer](/docs/custom-tools) om å lage tilpassede verktøy. + +--- + +## MCP servere + +MCP (Model Context Protocol) servere lar deg integrere eksterne verktøy og tjenester. Dette inkluderer databasetilgang, API-integrasjoner og tredjepartstjenester. + +[Les mer](/docs/mcp-servers) om konfigurering av MCP-servere. + +--- + +## Internaler + +Internt bruker verktøy som `grep`, `glob` og `list` [ripgrep](https://github.com/BurntSushi/ripgrep) under panseret. Som standard respekterer ripgrep `.gitignore`-mønstre, noe som betyr at filer og kataloger som er oppført i `.gitignore` vil bli ekskludert fra søk og oppføringer. + +--- + +### Ignorer mønstre + +For å inkludere filer som normalt vil bli ignorert, lag en `.ignore`-fil i prosjektroten. Denne filen kan eksplisitt tillate visse stier. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +For eksempel lar denne `.ignore` filen ripgrep søke i `node_modules/`, `dist/` og `build/` kataloger selv om de er oppført i `.gitignore`. diff --git a/packages/web/src/content/docs/nb/troubleshooting.mdx b/packages/web/src/content/docs/nb/troubleshooting.mdx new file mode 100644 index 000000000..37ee70c3e --- /dev/null +++ b/packages/web/src/content/docs/nb/troubleshooting.mdx @@ -0,0 +1,300 @@ +--- +title: Feilsøking +description: Vanlige problemer og hvordan de kan løses. +--- + +For å feilsøke problemer med OpenCode, start med å sjekke loggene og lokale data den lagrer på disken. + +--- + +## Logger + +Loggfiler skrives til: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.local\share\opencode\log` + +Loggfiler navngis med tidsstempler (f.eks. `2025-01-09T123456.log`) og de siste 10 loggfilene beholdes. + +Du kan angi loggnivået med kommandolinjealternativet `--log-level` for å få mer detaljert feilsøkingsinformasjon. For eksempel `opencode --log-level DEBUG`. + +--- + +## Lagring + +opencode lagrer øktdata og andre applikasjonsdata på disken på: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.local\share\opencode` + +Denne katalogen inneholder: + +- `auth.json` - Autentiseringsdata som API-nøkler, OAuth-tokens +- `log/` - Applikasjonslogger +- `project/` - Prosjektspesifikke data som økt- og meldingsdata + - Hvis prosjektet er innenfor en Git-repo, lagres det i `.//storage/` + - Hvis det ikke er en Git-repo, lagres det i `./global/storage/` + +--- + +## Desktop-app + +OpenCode Desktop kjører en lokal OpenCode-server (`opencode-cli` sidevognen) i bakgrunnen. De fleste problemene er forårsaket av en plugin som fungerer dårlig, en ødelagt cache eller en dårlig serverinnstilling. + +### Raske sjekker + +- Avslutt og start appen på nytt. +- Hvis appen viser en feilskjerm, klikker du på **Start på nytt** og kopierer feildetaljene. +- Bare macOS: `OpenCode`-meny -> **Last nettvisning på nytt** (hjelper hvis UI er tom/frosset). + +--- + +### Deaktiver plugins + +Hvis skrivebordsappen krasjer ved oppstart, henger eller oppfører seg merkelig, start med å deaktivere plugins. + +#### Sjekk den globale konfigurasjonen + +Åpne den globale konfigurasjonsfilen og se etter en `plugin`-nøkkel. + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (eller `~/.config/opencode/opencode.json`) +- **macOS/Linux** (eldre installasjoner): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.config\opencode\opencode.jsonc` + +Hvis du har konfigurert plugins, deaktiver dem midlertidig ved å fjerne nøkkelen eller sette den til en tom matrise: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### Sjekk plugin-kataloger + +OpenCode kan også laste lokale plugins fra disken. Flytt disse midlertidig ut av veien (eller gi nytt navn til mappen) og start skrivebordsappen på nytt: + +- **Globale plugins** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.config\opencode\plugins` +- **Prosjektplugins** (bare hvis du bruker konfigurasjon per prosjekt) + - `/.opencode/plugins/` + +Hvis appen begynner å fungere igjen, aktiverer du plugins én om gangen for å finne ut hvilken som forårsaker problemet. + +--- + +### Tøm hurtigbufferen + +Hvis deaktivering av plugins ikke hjelper (eller en plugin-installasjon sitter fast), tøm hurtigbufferen slik at OpenCode kan gjenoppbygge den. + +1. Avslutt OpenCode Desktop helt. +2. Slett hurtigbufferkatalogen: + +- **macOS**: Finder -> `Cmd+Shift+G` -> lim inn `~/.cache/opencode` +- **Linux**: slett `~/.cache/opencode` (eller kjør `rm -rf ~/.cache/opencode`) +- **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.cache\opencode` + +3. Start OpenCode Desktop på nytt. + +--- + +### Løs problemer med servertilkobling + +OpenCode Desktop kan enten starte sin egen lokale server (standard) eller koble til en server URL du har konfigurert. + +Hvis du ser en **"Tilkobling mislyktes"**-dialogboks (eller appen kommer aldri forbi splash-skjermen), se etter en tilpasset server URL. + +#### Slett standardserveren for skrivebordet URL + +Fra startskjermen klikker du på servernavnet (med statusprikken) for å åpne servervelgeren. I delen **Standardserver** klikker du på **Slett**. + +#### Fjern `server.port` / `server.hostname` fra konfigurasjonen din + +Hvis `opencode.json(c)` inneholder en `server`-del, fjern den midlertidig og start skrivebordsappen på nytt. + +#### Sjekk miljøvariabler + +Hvis du har `OPENCODE_PORT` satt i miljøet ditt, vil skrivebordsappen prøve å bruke den porten for den lokale serveren. + +- Deaktiver `OPENCODE_PORT` (eller velg en ledig port) og start på nytt. + +--- + +### Linux: Wayland / X11 problemer + +På Linux kan noen Wayland-oppsett forårsake tomme vinduer eller kompositorfeil. + +- Hvis du er på Wayland og appen er tom/krasj, prøv å starte med `OC_ALLOW_WAYLAND=1`. +- Hvis det gjør ting verre, fjern det og prøv å starte under en X11-økt i stedet. + +--- + +### Windows: WebView2 kjøretid + +På Windows krever OpenCode Desktop Microsoft Edge **WebView2 Runtime**. Hvis appen åpnes i et tomt vindu eller ikke starter, installer/oppdater WebView2 og prøv igjen. + +--- + +### Windows: Generelle ytelsesproblemer + +Hvis du opplever treg ytelse, problemer med filtilgang eller terminalproblemer på Windows, kan du prøve å bruke [WSL (Windows Subsystem for Linux)](/docs/windows-wsl). WSL gir et Linux-miljø som fungerer mer sømløst med funksjonene til OpenCode. + +--- + +### Varsler vises ikke + +OpenCode Desktop viser bare systemvarsler når: + +- varsler er aktivert for OpenCode i OS-innstillingene dine, og +- appvinduet er ikke fokusert. + +--- + +### Tilbakestill skrivebordsapplagring (siste utvei) + +Hvis appen ikke starter og du ikke kan slette innstillingene fra UI, tilbakestill skrivebordsappens lagrede tilstand. + +1. Avslutt OpenCode Desktop. +2. Finn og slett disse filene (de finnes i OpenCode Desktop-appens datakatalog): + +- `opencode.settings.dat` (stasjonær standardserver URL) +- `opencode.global.dat` og `opencode.workspace.*.dat` (UI tilstand som nylige servere/prosjekter) + +Slik finner du katalogen raskt: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (søk deretter etter filnavnene ovenfor) +- **Linux**: søk under `~/.local/share` etter filnavnene ovenfor +- **Windows**: Trykk `WIN+R` -> `%APPDATA%` (søk deretter etter filnavnene ovenfor) + +--- + +## Får hjelp + +Hvis du opplever problemer med OpenCode: + +1. **Rapporter problemer på GitHub** + + Den beste måten å rapportere feil eller be om funksjoner på er gjennom vårt GitHub-lager: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + Før du oppretter et nytt problem, søk i eksisterende problemer for å se om problemet ditt allerede er rapportert. + +2. **Bli med i vår Discord** + + For sanntidshjelp og fellesskapsdiskusjon, bli med i vår Discord-server: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Vanlige problemer + +Her er noen vanlige problemer og hvordan du kan løse dem. + +--- + +### OpenCode vil ikke starte + +1. Sjekk loggene for feilmeldinger +2. Prøv å kjøre med `--print-logs` for å se utdata i terminalen +3. Sørg for at du har den nyeste versjonen med `opencode upgrade` + +--- + +### Autentiseringsproblemer + +1. Prøv å autentisere på nytt med kommandoen `/connect` i TUI +2. Sjekk at API-nøklene dine er gyldige +3. Sørg for at nettverket ditt tillater tilkoblinger til leverandørens API + +--- + +### Modellen er ikke tilgjengelig + +1. Sjekk at du har autentisert deg med leverandøren +2. Kontroller at modellnavnet i konfigurasjonen er riktig +3. Noen modeller kan kreve spesifikk tilgang eller abonnement + +Hvis du støter på `ProviderModelNotFoundError` er du mest sannsynlig feil +refererer til en modell et sted. +Modeller skal refereres slik: `/` + +Eksempler: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +For å finne ut hvilke modeller du har tilgang til, kjør `opencode models` + +--- + +### ProviderInitError + +Hvis du støter på en ProviderInitError, har du sannsynligvis en ugyldig eller ødelagt konfigurasjon. + +For å løse dette: + +1. Kontroller først at leverandøren din er riktig konfigurert ved å følge [leverandørveiledningen](/docs/providers) +2. Hvis problemet vedvarer, prøv å tømme den lagrede konfigurasjonen: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + På Windows, trykk `WIN+R` og slett: `%USERPROFILE%\.local\share\opencode` + +3. Autentiser på nytt med leverandøren din ved å bruke kommandoen `/connect` i TUI. + +--- + +### AI_APICallError og leverandørpakkeproblemer + +Hvis du støter på API anropsfeil, kan dette skyldes utdaterte leverandørpakker. opencode installerer dynamisk leverandørpakker (OpenAI, Anthropic, Google, etc.) etter behov og cacher dem lokalt. + +For å løse problemer med leverandørpakke: + +1. Tøm leverandørens pakkebuffer: + + ```bash + rm -rf ~/.cache/opencode + ``` + + På Windows, trykk `WIN+R` og slett: `%USERPROFILE%\.cache\opencode` + +2. Start opencode på nytt for å installere de nyeste leverandørpakkene på nytt + +Dette vil tvinge opencode til å laste ned de nyeste versjonene av leverandørpakkene, som ofte løser kompatibilitetsproblemer med modellparametere og API endringer. + +--- + +### Kopier/lim inn fungerer ikke på Linux + +Linux-brukere må ha ett av følgende utklippstavleverktøy installert for at kopier/lim inn-funksjonalitet skal fungere: + +**For X11-systemer:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**For Wayland-systemer:** + +```bash +apt install -y wl-clipboard +``` + +**For hodeløse miljøer:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode vil oppdage om du bruker Wayland og foretrekker `wl-clipboard`, ellers vil den prøve å finne utklippstavleverktøy i rekkefølgen: `xclip` og `xsel`. diff --git a/packages/web/src/content/docs/nb/tui.mdx b/packages/web/src/content/docs/nb/tui.mdx new file mode 100644 index 000000000..58b9b547e --- /dev/null +++ b/packages/web/src/content/docs/nb/tui.mdx @@ -0,0 +1,390 @@ +--- +title: TUI +description: Bruke OpenCode-terminalbrukergrensesnittet. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode gir et interaktivt terminalgrensesnitt eller TUI for å jobbe med prosjektene dine med en LLM. + +Å kjøre OpenCode starter TUI for gjeldende katalog. + +```bash +opencode +``` + +Eller du kan starte den for en bestemt arbeidskatalog. + +```bash +opencode /path/to/project +``` + +Når du er i TUI, kan du spørre den med en melding. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## Filreferanser + +Du kan referere til filer i meldingene dine ved å bruke `@`. Dette gjør et uklar filsøk i gjeldende arbeidskatalog. + +:::tupp +Du kan også bruke `@` til å referere til filer i meldingene dine. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +Innholdet i filen legges automatisk til samtalen. + +--- + +## Bash-kommandoer + +Start en melding med `!` for å kjøre en shell-kommando. + +```bash frame="none" +!ls -la +``` + +Utdataene fra kommandoen legges til samtalen som et verktøyresultat. + +--- + +## Kommandoer + +Når du bruker OpenCode TUI, kan du skrive `/` etterfulgt av et kommandonavn for raskt å utføre handlinger. For eksempel: + +```bash frame="none" +/help +``` + +De fleste kommandoer har også tastebinding som bruker `ctrl+x` som ledernøkkel, der `ctrl+x` er standard ledernøkkel. [Finn ut mer](/docs/keybinds). + +Her er alle tilgjengelige skråstrekkommandoer: + +--- + +### koble til + +Legg til en leverandør til OpenCode. Lar deg velge fra tilgjengelige leverandører og legge til deres API-nøkler. + +```bash frame="none" +/connect +``` + +--- + +### kompakt + +Komprimer gjeldende økt. _Alias_: `/summarize` + +```bash frame="none" +/compact +``` + +**Nøkkelbinding:** `ctrl+x c` + +--- + +### detaljer + +Veksle verktøyutførelsesdetaljer. + +```bash frame="none" +/details +``` + +**Nøkkelbinding:** `ctrl+x d` + +--- + +### redaktør + +Åpne eksternt redigeringsprogram for å skrive meldinger. Bruker redigeringssettet i miljøvariabelen `EDITOR`. [Finn ut mer](#editor-setup). + +```bash frame="none" +/editor +``` + +**Nøkkelbinding:** `ctrl+x e` + +--- + +### avslutt + +Avslutt OpenCode. _Aliaser_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Nøkkelbinding:** `ctrl+x q` + +--- + +### eksport + +Eksporter gjeldende samtale til Markdown og åpne i standardredigeringsprogrammet. Bruker redigeringssettet i miljøvariabelen `EDITOR`. [Finn ut mer](#editor-setup). + +```bash frame="none" +/export +``` + +**Nøkkelbinding:** `ctrl+x x` + +--- + +### hjelp + +Vis hjelpedialogen. + +```bash frame="none" +/help +``` + +**Nøkkelbinding:** `ctrl+x h` + +--- + +### init + +Opprett eller oppdater `AGENTS.md`-fil. [Finn ut mer](/docs/rules). + +```bash frame="none" +/init +``` + +**Nøkkelbinding:** `ctrl+x i` + +--- + +### modeller + +Liste over tilgjengelige modeller. + +```bash frame="none" +/models +``` + +**Nøkkelbinding:** `ctrl+x m` + +--- + +### ny + +Start en ny økt. _Alias_: `/clear` + +```bash frame="none" +/new +``` + +**Nøkkelbinding:** `ctrl+x n` + +--- + +### gjør om + +Gjenta en tidligere angret melding. Kun tilgjengelig etter bruk av `/undo`. + +:::tupp +Eventuelle filendringer vil også bli gjenopprettet. +::: + +Internt bruker dette Git til å administrere filendringene. Så ditt prosjekt **må +være et Git-depot**. + +```bash frame="none" +/redo +``` + +**Nøkkelbinding:** `ctrl+x r` + +--- + +### økter + +List opp og bytt mellom økter. _Aliaser_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Nøkkelbinding:** `ctrl+x l` + +--- + +### del + +Del gjeldende økt. [Finn ut mer](/docs/share). + +```bash frame="none" +/share +``` + +**Nøkkelbinding:** `ctrl+x s` + +--- + +### temaer + +Liste over tilgjengelige temaer. + +```bash frame="none" +/theme +``` + +**Nøkkelbinding:** `ctrl+x t` + +--- + +### tenker + +Veksle mellom synligheten av tenke-/resonneringsblokker i samtalen. Når den er aktivert, kan du se modellens resonneringsprosess for modeller som støtter utvidet tenkning. + +:::note +Denne kommandoen kontrollerer bare om tenkeblokker **vises** - den aktiverer eller deaktiverer ikke modellens resonneringsmuligheter. For å veksle mellom faktiske resonneringsmuligheter, bruk `ctrl+t` for å bla gjennom modellvarianter. +::: + +```bash frame="none" +/thinking +``` + +--- + +### angre + +Angre siste melding i samtalen. Fjerner den siste brukermeldingen, alle påfølgende svar og eventuelle filendringer. + +:::tupp +Eventuelle filendringer vil også bli tilbakestilt. +::: + +Internt bruker dette Git til å administrere filendringene. Så ditt prosjekt **må +være et Git-depot**. + +```bash frame="none" +/undo +``` + +**Nøkkelbinding:** `ctrl+x u` + +--- + +### avbryt deling + +Opphev deling av gjeldende økt. [Finn ut mer](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## Redaktøroppsett + +Både kommandoene `/editor` og `/export` bruker redigeringsprogrammet som er spesifisert i miljøvariabelen `EDITOR`. + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + + For å gjøre det permanent, legg dette til i skallprofilen din; + `~/.bashrc`, `~/.zshrc` osv. + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + + For å gjøre det permanent, bruk **Systemegenskaper** > **Miljø + Variabler**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + + For å gjøre det permanent, legg dette til i PowerShell-profilen din. + + + + +Populære redigeringsalternativer inkluderer: + +- `code` - Visual Studio Code +- `cursor` - Cursor +- `windsurf` - Vindsurfing +- `nvim` - Neovim-redaktør +- `vim` - Vim editor +- `nano` - Nano-editor +- `notepad` - Windows Notisblokk +- `subl` - Sublim tekst + +:::note +Noen redaktører som VS Code må startes med flagget `--wait`. +::: + +Noen redaktører trenger kommandolinjeargumenter for å kjøre i blokkeringsmodus. `--wait`-flagget gjør at redigeringsprosessen blokkeres til den lukkes. + +--- + +## Konfigurer + +Du kan tilpasse TUI-oppførselen gjennom OpenCode-konfigurasjonsfilen. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### Alternativer + +- `scroll_acceleration` - Aktiver rulleakselerasjon i macOS-stil for jevn, naturlig rulling. Når aktivert, øker rullehastigheten med raske rullebevegelser og forblir presis for langsommere bevegelser. **Denne innstillingen har forrang over `scroll_speed` og overstyrer den når den er aktivert.** +- `scroll_speed` - Styrer hvor raskt TUI ruller når du bruker rullekommandoer (minimum: `1`). Standard er `3`. **Merk: Dette ignoreres hvis `scroll_acceleration.enabled` er satt til `true`.** + +--- + +## Tilpasning + +Du kan tilpasse ulike aspekter av TUI-visningen ved å bruke kommandopaletten (`ctrl+x h` eller `/help`). Disse innstillingene vedvarer ved omstarter. + +--- + +#### Visning av brukernavn + +Veksle om brukernavnet ditt vises i chat-meldinger. Få tilgang til dette gjennom: + +- Kommandopalett: Søk etter "brukernavn" eller "skjul brukernavn" +- Innstillingen vedvarer automatisk og vil bli husket over TUI økter diff --git a/packages/web/src/content/docs/nb/web.mdx b/packages/web/src/content/docs/nb/web.mdx new file mode 100644 index 000000000..b1eaf6a2d --- /dev/null +++ b/packages/web/src/content/docs/nb/web.mdx @@ -0,0 +1,142 @@ +--- +title: Web +description: Bruke OpenCode i nettleseren din. +--- + +OpenCode kan kjøres som en nettapplikasjon i nettleseren din, og gir den samme kraftige AI-kodingsopplevelsen uten at du trenger en terminal. + +![OpenCode Web - Ny økt](../../../assets/web/web-homepage-new-session.png) + +## Komme i gang + +Start nettgrensesnittet ved å kjøre: + +```bash +opencode web +``` + +Dette starter en lokal server på `127.0.0.1` med en tilfeldig tilgjengelig port og åpner automatisk OpenCode i standard nettleser. + +:::forsiktighet +Hvis `OPENCODE_SERVER_PASSWORD` ikke er satt, vil serveren være usikret. Dette er greit for lokal bruk, men bør settes for nettverkstilgang. +::: + +:::tips[Windows-brukere] +For den beste opplevelsen, kjør `opencode web` fra [WSL](/docs/windows-wsl) i stedet for PowerShell. Dette sikrer riktig filsystemtilgang og terminalintegrasjon. +::: + +--- + +## Konfigurasjon + +Du kan konfigurere webserveren ved å bruke kommandolinjeflagg eller i [config file](/docs/config). + +### Port + +Som standard velger OpenCode en tilgjengelig port. Du kan spesifisere en port: + +```bash +opencode web --port 4096 +``` + +### Vertsnavn + +Som standard binder serveren seg til `127.0.0.1` (kun lokal vert). Slik gjør du OpenCode tilgjengelig på nettverket ditt: + +```bash +opencode web --hostname 0.0.0.0 +``` + +Når du bruker `0.0.0.0`, vil OpenCode vise både lokale adresser og nettverksadresser: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### mDNS-oppdagelse + +Aktiver mDNS for å gjøre serveren din synlig på det lokale nettverket: + +```bash +opencode web --mdns +``` + +Dette setter automatisk vertsnavnet til `0.0.0.0` og annonserer serveren som `opencode.local`. + +Du kan tilpasse mDNS-domenenavnet til å kjøre flere forekomster på samme nettverk: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +For å tillate flere domener for CORS (nyttig for egendefinerte grensesnitt): + +```bash +opencode web --cors https://example.com +``` + +### Autentisering + +For å beskytte tilgang, angi et passord ved hjelp av miljøvariabelen `OPENCODE_SERVER_PASSWORD`: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +Brukernavnet er standard til `opencode`, men kan endres med `OPENCODE_SERVER_USERNAME`. + +--- + +## Bruke webgrensesnittet + +Når det er startet, gir nettgrensesnittet tilgang til dine OpenCode-økter. + +### økter + +Se og administrer øktene dine fra hjemmesiden. Du kan se aktive økter og starte nye. + +![OpenCode Web - Active Session](../../../assets/web/web-homepage-active-session.png) + +### Serverstatus + +Klikk "Se servere" for å se tilkoblede servere og deres status. + +![OpenCode Web - Se servere](../../../assets/web/web-homepage-see-servers.png) + +--- + +## Koble til en terminal + +Du kan koble en terminal TUI til en kjørende webserver: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +Dette lar deg bruke både nettgrensesnittet og terminalen samtidig, og deler samme økter og tilstand. + +--- + +## Konfigurasjonsfil + +Du kan også konfigurere serverinnstillinger i `opencode.json` konfigurasjonsfilen: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +Kommandolinjeflagg har forrang over konfigurasjonsfilinnstillinger. diff --git a/packages/web/src/content/docs/nb/windows-wsl.mdx b/packages/web/src/content/docs/nb/windows-wsl.mdx new file mode 100644 index 000000000..6553ad6bf --- /dev/null +++ b/packages/web/src/content/docs/nb/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: Kjor OpenCode pa Windows med WSL for best opplevelse. +--- + +import { Steps } from "@astrojs/starlight/components" + +Selv om OpenCode kan kjore direkte pa Windows, anbefaler vi a bruke [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) for best mulig opplevelse. WSL gir et Linux-miljo som fungerer godt med funksjonene i OpenCode. + +:::tip[Hvorfor WSL?] +WSL gir bedre filsystemytelse, full terminalstotte og kompatibilitet med utviklingsverktoyene OpenCode er avhengig av. +::: + +--- + +## Oppsett + + + +1. **Installer WSL** + + Hvis du ikke har gjort det ennå, [installer WSL](https://learn.microsoft.com/en-us/windows/wsl/install) med den offisielle guiden fra Microsoft. + +2. **Installer OpenCode i WSL** + + Nar WSL er satt opp, apner du WSL-terminalen og installerer OpenCode med en av [installasjonsmetodene](/docs/). + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **Bruk OpenCode fra WSL** + + Gå til prosjektmappen din (Windows-filer finnes via `/mnt/c/`, `/mnt/d/` osv.) og kjør OpenCode. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## Skrivebordsapp + WSL-server + +Hvis du foretrekker OpenCode-skrivebordsappen, men vil kjore serveren i WSL: + +1. **Start serveren i WSL** med `--hostname 0.0.0.0` for a tillate eksterne tilkoblinger: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Koble skrivebordsappen** til `http://localhost:4096` + +:::note +Hvis `localhost` ikke fungerer i oppsettet ditt, bruk WSL-IP-adressen i stedet (fra WSL: `hostname -I`) og koble til `http://:4096`. +::: + +:::caution +Nar du bruker `--hostname 0.0.0.0`, sett `OPENCODE_SERVER_PASSWORD` for a sikre serveren. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Nettklient + WSL + +For best nettopplevelse pa Windows: + +1. **Kjor `opencode web` i WSL-terminalen** i stedet for PowerShell: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Aapne i Windows-nettleseren** pa `http://localhost:` (OpenCode skriver ut URL-en) + +Nar du kjører `opencode web` fra WSL, får du riktig filsystemtilgang og terminalintegrasjon, samtidig som det er tilgjengelig fra Windows-nettleseren din. + +--- + +## Tilgang til Windows-filer + +WSL kan fa tilgang til alle Windows-filer via `/mnt/`-katalogen: + +- `C:`-stasjon → `/mnt/c/` +- `D:`-stasjon → `/mnt/d/` +- Og sa videre... + +Eksempel: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +For en jevnere opplevelse kan du klone/kopiere repoet ditt inn i WSL-filsystemet (for eksempel under `~/code/`) og kjore OpenCode der. +::: + +--- + +## Tips + +- Kjor OpenCode i WSL for prosjekter lagret pa Windows-stasjoner: filtilgang fungerer smidig +- Bruk [WSL-utvidelsen i VS Code](https://code.visualstudio.com/docs/remote/wsl) sammen med OpenCode for en integrert utviklingsflyt +- OpenCode-konfigurasjon og sesjoner lagres i WSL-miljoet pa `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/nb/zen.mdx b/packages/web/src/content/docs/nb/zen.mdx new file mode 100644 index 000000000..4503f7c40 --- /dev/null +++ b/packages/web/src/content/docs/nb/zen.mdx @@ -0,0 +1,254 @@ +--- +title: Zen +description: Utvalgt liste over modeller levert av OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen er en liste over testede og verifiserte modeller levert av OpenCode-teamet. + +:::note +OpenCode Zen er for øyeblikket i beta. +::: + +Zen fungerer som alle andre leverandører i OpenCode. Du logger på OpenCode Zen og får +din API nøkkel. Den er **helt valgfri** og du trenger ikke bruke den for å bruke den +OpenCode. + +--- + +## Bakgrunn + +Det er et stort antall modeller der ute, men bare noen få av dem +disse modellene fungerer godt som kodeagenter. I tillegg er de fleste tilbydere +konfigurert veldig annerledes; slik at du får veldig forskjellig ytelse og kvalitet. + +:::tupp +Vi testet en utvalgt gruppe modeller og leverandører som fungerer godt med OpenCode. +::: + +Så hvis du bruker en modell gjennom noe som OpenRouter, kan du aldri bli det +sikker på om du får den beste versjonen av modellen du ønsker. + +For å fikse dette gjorde vi et par ting: + +1. Vi testet en utvalgt gruppe modeller og snakket med teamene deres om hvordan + best kjøre dem. +2. Vi samarbeidet deretter med noen få leverandører for å sikre at disse ble servert + riktig. +3. Til slutt benchmarket vi kombinasjonen av modell/leverandør og kom frem + med en liste som vi har lyst til å anbefale. + +OpenCode Zen er en AI gateway som gir deg tilgang til disse modellene. + +--- + +## Slik fungerer det + +OpenCode Zen fungerer som alle andre leverandører i OpenCode. + +1. Du logger på **OpenCode Zen**, legg til fakturering + detaljer, og kopier API-nøkkelen. +2. Du kjører kommandoen `/connect` i TUI, velger OpenCode Zen og limer inn API-nøkkelen. +3. Kjør `/models` i TUI for å se listen over modeller vi anbefaler. + +Du belastes per forespørsel, og du kan legge til kreditt på kontoen din. + +--- + +## Endepunkter + +Du kan også få tilgang til modellene våre gjennom følgende API-endepunkter. + +| Modell | Modell ID | Endepunkt | AI SDK Pakke | +| ------------------- | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 Codex | gpt-5.2-kodeks | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex | gpt-5.1-kodeks | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Codex | gpt-5-kodeks | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Sonnet 4.5 | claude-sonnett-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Sonnet 4 | claude-sonnett-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Gratis | minimax-m2.1-fri | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Gratis | glm-4.7-fri | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Gratis | kimi-k2.5-fri | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 Tenker | kimi-k2-tenking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3-koder 480B | qwen3-koder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Stor sylteagurk | stor sylteagurk | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +[modell-id](/docs/config/#models) i OpenCode-konfigurasjonen +bruker formatet `opencode/`. For eksempel, for GPT 5.2 Codex, ville du +bruk `opencode/gpt-5.2-codex` i konfigurasjonen din. + +--- + +### Modeller + +Du kan hente hele listen over tilgjengelige modeller og deres metadata fra: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## Priser + +Vi støtter en pay-as-you-go-modell. Nedenfor er prisene **per 1 million tokens**. + +| Modell | Inngang | Utgang | Bufret Les | Bufret skriv | +| --------------------------------- | ------- | ------ | ---------- | ------------ | +| Stor sylteagurk | Gratis | Gratis | Gratis | - | +| MiniMax M2.1 Gratis | Gratis | Gratis | Gratis | - | +| MiniMax M2.1 | $0,30 | $1,20 | $0,10 | - | +| GLM 4.7 Gratis | Gratis | Gratis | Gratis | - | +| GLM 4.7 | $0,60 | $2,20 | $0,10 | - | +| GLM 4.6 | $0,60 | $2,20 | $0,10 | - | +| Kimi K2.5 Gratis | Gratis | Gratis | Gratis | - | +| Kimi K2.5 | $0,60 | $3,00 | $0,08 | - | +| Kimi K2 Tenker | $0,40 | $2,50 | - | - | +| Kimi K2 | $0,40 | $2,50 | - | - | +| Qwen3-koder 480B | $0,45 | $1,50 | - | - | +| Claude Sonnet 4.5 (≤ 200K tokens) | $3,00 | $15,00 | $0,30 | $3,75 | +| Claude Sonnet 4.5 (> 200K tokens) | $6,00 | $22,50 | $0,60 | $7,50 | +| Claude Sonnet 4 (≤ 200K tokens) | $3,00 | $15,00 | $0,30 | $3,75 | +| Claude Sonnet 4 (> 200K tokens) | $6,00 | $22,50 | $0,60 | $7,50 | +| Claude Haiku 4.5 | $1,00 | $5,00 | $0,10 | $1,25 | +| Claude Haiku 3.5 | $0,80 | $4,00 | $0,08 | $1,00 | +| Claude Opus 4.6 (≤ 200K tokens) | $5,00 | $25,00 | $0,50 | $6,25 | +| Claude Opus 4.6 (> 200K tokens) | $10,00 | $37,50 | $1,00 | $12,50 | +| Claude Opus 4.5 | $5,00 | $25,00 | $0,50 | $6,25 | +| Claude Opus 4.1 | $15,00 | $75,00 | $1,50 | $18,75 | +| Gemini 3 Pro (≤ 200K tokens) | $2,00 | $12,00 | $0,20 | - | +| Gemini 3 Pro (> 200K tokens) | $4,00 | $18,00 | $0,40 | - | +| Gemini 3 Flash | $0,50 | $3,00 | $0,05 | - | +| GPT 5.2 | $1,75 | $14,00 | $0,175 | - | +| GPT 5.2 Codex | $1,75 | $14,00 | $0,175 | - | +| GPT 5.1 | $1,07 | $8,50 | $0,107 | - | +| GPT 5.1 Codex | $1,07 | $8,50 | $0,107 | - | +| GPT 5.1 Codex Max | $1,25 | $10,00 | $0,125 | - | +| GPT 5.1 Codex Mini | $0,25 | $2,00 | $0,025 | - | +| GPT 5 | $1,07 | $8,50 | $0,107 | - | +| GPT 5 Codex | $1,07 | $8,50 | $0,107 | - | +| GPT 5 Nano | Gratis | Gratis | Gratis | - | + +Du legger kanskje merke til _Claude Haiku 3.5_ i brukshistorikken din. Dette er en [lavprismodell](/docs/config/#models) som brukes til å generere titlene på øktene dine. + +:::note +Kredittkortgebyrer overføres til kostpris (4,4 % + $0,30 per transaksjon); vi belaster ikke noe utover det. +::: + +De gratis modellene: + +- GLM 4.7 Free er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle tilbakemeldinger og forbedre modellen. +- Kimi K2.5 Gratis er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle tilbakemeldinger og forbedre modellen. +- MiniMax M2.1 Free er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle tilbakemeldinger og forbedre modellen. +- Big Pickle er en stealth-modell som er gratis på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle tilbakemeldinger og forbedre modellen. + +Contact us if you have any questions. + +--- + +### Last inn automatisk + +Hvis saldoen din går under $5, vil Zen automatisk laste inn $20 på nytt. + +Du kan endre beløpet for automatisk påfylling. Du kan også deaktivere automatisk reload helt. + +--- + +### Månedlige grenser + +Du kan også angi en månedlig bruksgrense for hele arbeidsområdet og for hver +medlem av teamet ditt. + +La oss for eksempel si at du setter en månedlig bruksgrense til $20, Zen vil ikke bruke +mer enn $20 på en måned. Men hvis du har automatisk reload aktivert, kan Zen ende opp +belaster deg mer enn $20 hvis saldoen din går under $5. + +--- + +## Personvern + +Alle våre modeller er vert i US. Leverandørene våre følger en nulloppbevaringspolicy og bruker ikke dataene dine til modellopplæring, med følgende unntak: + +- Big Pickle: I løpet av gratisperioden kan innsamlede data brukes til å forbedre modellen. +- GLM 4.7 Gratis: I løpet av gratisperioden kan innsamlede data brukes til å forbedre modellen. +- Kimi K2.5 Gratis: I løpet av gratisperioden kan innsamlede data brukes til å forbedre modellen. +- MiniMax M2.1 Gratis: I løpet av gratisperioden kan innsamlede data brukes til å forbedre modellen. +- OpenAI APIer: Forespørsler oppbevares i 30 dager i samsvar med [OpenAIs datapolicyer](https://platform.openai.com/docs/guides/your-data). +- Anthropic APIer: Forespørsler oppbevares i 30 dager i samsvar med [Anthropics datapolicyer](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## For lag + +Zen fungerer også utmerket for team. Du kan invitere lagkamerater, tildele roller, kuratere +modellene laget ditt bruker, og mer. + +:::note +Arbeidsområder er for øyeblikket gratis for team som en del av betaversjonen. +::: + +Å administrere arbeidsområdet ditt er for øyeblikket gratis for team som en del av betaversjonen. Det blir vi +deler mer informasjon om prisene snart. + +--- + +### Roller + +Du kan invitere lagkamerater til arbeidsområdet ditt og tildele roller: + +- **Admin**: Administrer modeller, medlemmer, API-nøkler og fakturering +- **Medlem**: Administrer kun sine egne API-nøkler + +Administratorer kan også sette månedlige forbruksgrenser for hvert medlem for å holde kostnadene under kontroll. + +--- + +### Modelltilgang + +Administratorer kan aktivere eller deaktivere spesifikke modeller for arbeidsområdet. Forespørsler til en deaktivert modell vil returnere en feil. + +Dette er nyttig for tilfeller der du ønsker å deaktivere bruken av en modell som +samler inn data. + +--- + +### Ta med egen nøkkel + +Du kan bruke dine egne OpenAI- eller Anthropic API-nøkler mens du fortsatt har tilgang til andre modeller i Zen. + +Når du bruker dine egne nøkler, faktureres tokens direkte av leverandøren, ikke av Zen. + +For eksempel kan organisasjonen din allerede ha en nøkkel for OpenAI eller Anthropic +og du vil bruke det i stedet for det Zen gir. + +--- + +## Mål + +Vi opprettet OpenCode Zen for å: + +1. **Benchmark** de beste modellene/leverandørene for kodingsagenter. +2. Ha tilgang til alternativene for **høyeste kvalitet** og ikke nedgrader ytelsen eller rute til billigere leverandører. +3. Gi videre eventuelle **prisfall** ved å selge til kostpris; så den eneste markeringen er å dekke behandlingsgebyrene våre. +4. Ha **ingen låsing** ved å la deg bruke den med en hvilken som helst annen kodeagent. Og la deg alltid bruke en hvilken som helst annen leverandør med OpenCode også. diff --git a/packages/web/src/content/docs/pl/1-0.mdx b/packages/web/src/content/docs/pl/1-0.mdx new file mode 100644 index 000000000..e441525ae --- /dev/null +++ b/packages/web/src/content/docs/pl/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: Migracja do wersji 1.0 +description: Co nowego w OpenCode 1.0. +--- + +OpenCode 1.0 do całkowitej przeróbki TUI. + +Przeszliśmy z TUI na go+bubbletea, który miał problemy z wydajnością i możliwościami, do wewnętrznego frameworka (OpenTUI) obciążającego w zig+solidjs. + +Nowy TUI działa jak stary, łączy się z tym samym serwerem opencode. + +--- + +## Aktualizacja + +Nie automatyczna aktualizacja do wersji 1.0, która jest dostępna w wersji 1.0 +wersja. Starsze wersje OpenCode zawsze pobierają najnowszą wersję. + +Aby móc, móc + +```bash +$ opencode upgrade 1.0.0 +``` + +Aby uruchomić wersję 0.x, uruchom + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## Zmiany UX + +Historia sesji jest bardziej skompresowana i znaleziono pełne szczegóły narzędzia do edycji w bash. + +Dodaliśmy pasek kontrolny, przez który przepływa prawie wszystko. działanie nie ctrl+p, aby przejść do zdarzenia, które zawiera wszystko, co można regenerować. + +Dodano pasek boczny sesji (możliwość przejścia do urządzenia) z odłączonym dostępem. + +Usunęliśmy pewne funkcje, z których nie ma pewności, czy ktoś faktycznie korzystał. Jeśli brakuje czegoś ważnego, otwórz problem, a my szybko dodamy. + +--- + +## Przełomowe zmiany + +### Zmieniono skrótów klawiszowych + +- wiadomości_przywróć -> wiadomości_cofnij +- uruchomienie_agent -> cykl_agent +- switch_agent_reverse -> agent_cycle_reverse +- tryb_przełączenie -> cykl_agenta +- switch_mode_reverse -> agent_cycle_reverse + +### Usunięto klawisze + +- Przegrzewanie_układu_wiadomości +- wiadomości_następne +- wiadomości_poprzednie +- plik_diff_toggle +- wyszukiwanie_pliku +- plik_zamknij +- lista_plików +- pomoc_aplikacji +- projekt_init +- szczegóły_narzędzia +- myślenie_bloki diff --git a/packages/web/src/content/docs/pl/acp.mdx b/packages/web/src/content/docs/pl/acp.mdx new file mode 100644 index 000000000..c5d7bf43a --- /dev/null +++ b/packages/web/src/content/docs/pl/acp.mdx @@ -0,0 +1,156 @@ +--- +title: Wsparcie AKP +description: przetwarzanie OpenCode w procesorze komunikatu z ACP. +--- + +OpenCode obsługi [Protokół klienta agenta](https://agentclientprotocol.com) lub (ACP), dzięki któremu można przejść do oprogramowania bezpośrednio w zainstalowanych edytorach i środowisku IDE. + +:::tip +Lista edytorów i narzędzi obsługujących ACP w [raportu sprzętu ACP](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP do otwierania dokumentów, które standaryzują treść między edytorami kodu a agentem kodującym AI. + +--- + +## Skonfiguruj + +Aby wybrać OpenCode przez ACP, skonfiguruj edytor tak, aby wybrać opcję `opencode acp`. + +Uruchomienie OpenCode jako podproces oprogramowania z ACP, który komunikuje się z edytorem poprzez JSON-RPC poprzez stdio. + +Poniżej znajdują się przykłady procesorów obsługujących ACP. + +--- + +### Zeda + +Dodaj do konstrukcji [Zed](https://zed.dev) (`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +Aby przejść do akcji, `agent: new thread` w **Palecie redakcji**. + +Można także po skrócie skrótowym, edytując `keymap.json`: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### IDE JetBrains + +Dodaj do swojego [JetBrains IDE](https://www.jetbrains.com/) acp.json zgodnie z [dokumentacją](https://www.jetbrains.com/help/ai-assistant/acp.html): + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +Aby przejść do nowego agenta „OpenCode” w selektorze agenta AI Chat. + +--- + +### Avante.nvim + +Dodaj do konstrukcji [Avante.nvim](https://github.com/yetone/avante.nvim): + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +Jeśli chcesz zachować bezpieczeństwo: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +Aby OpenCode jako agenta ACP w [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim), dodaj dodatkowe elementy, aby otrzymać konstrukcje Neovim: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +Ta konfiguracja CodeCompanion wymaga OpenCode jako agenta ACP dla czatu. + +Jeśli jesteś zarejestrowany jako `OPENCODE_API_KEY`, zapoznaj się z sekcją [Konfigurowanie adapterów: Zmienne przebieg](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) w dokumentacji CodeCompanion.nvim, aby uzyskać szczegółowe informacje. + +## Wsparcie + +OpenCode działa tak samo przez ACP, jak w terminalu. Obsługiwane są wszystkie funkcje: + +:::note +początek źródła ukośnikowego, takie jak `/undo` i `/redo`, nie są aktualne pobierane. +::: + +- Wbudowane narzędzie (operacje na plikach, rozwiązanie terminala itp.) +- Niestandardowe narzędzie i polecenie ukośnikowe +- Serwery MCP skonfigurowane w konfiguracji OpenCode +- Zasady dotyczące projektu od `AGENTS.md` +- Niestandardowe formatory i lintery +- Agentów systemowych i uprawnień diff --git a/packages/web/src/content/docs/pl/agents.mdx b/packages/web/src/content/docs/pl/agents.mdx new file mode 100644 index 000000000..f78d941d3 --- /dev/null +++ b/packages/web/src/content/docs/pl/agents.mdx @@ -0,0 +1,747 @@ +--- +title: Agencja +description: Konfiguruj i używaj funkcjonalnych agentów. +--- + +Agencje do urządzeń asystenci AI, które można podłączyć do gniazd zasilania i przepływów pracy. Umożliwiają tworzenie ukierunkowanych narzędzi z niestandardowymi monitami, modelami i udostępnianiem narzędzi. + +:::tip +Skorzystaj z agenta planu, aby uzyskać dostęp do kodu i przeglądać informacje bez dodatkowych zmian w kodzie. +::: + +Możesz przełączać się między agentami podczas sesji lub wywoływać ich za pomocą wzmianki `@`. + +--- + +## Typowe + +W OpenCode zasada dwóch charakterystycznych agentów; Najpierw pierwotni i subagenci. + +--- + +### Agencja Pierwsi + +Główne zasady asystenci, z podstawowym kontaktem. Możesz je mieć za pomocą klawisza **Tab** lub podwójnego skrótu klawiszowego `switch_agent`. Ci agenci obsługujący urządzenie główne. Dostęp do narzędzia jest konfigurowany za pomocą uprawnień — na przykład w programie Build wszystkie narzędzia są dostępne, a plan jest ograniczony. + +:::tip +Twój klawisz klawisza **Tab**, aby wyłączyć się między agentami podczas sesji. +::: + +OpenCode zawiera dwa puste agenty główne: **Build** i **Plan**. Dobrze +spójrz na te poniżej. + +--- + +### Podagencje + +Podagenci do pomocniczych asystenci, których można przywoływać agenci główni w celu wykonania podstawowych zadań. Możesz także wytwarzać je, **@ wspominając** o nich w swoich wiadomościach. + +OpenCode ma dwóch subagentów: **Ogólne** i **Eksploruj**. Przyjrzymy się temu poniżej. + +--- + +## Wbudowany + +OpenCode ma dwa główne agenty i dwa główne agenty podrzędne. + +--- + +### korzystać z pracy + +_Tryb_: `primary` + +Kompilacja jest **domyślnym** agentem zastosowania z ukrytymi narzędziami. Jest to standardowy agent do prac programistycznych, którego dostęp jest udostępniony do operacji na plikach i podstawowych systemowych. + +--- + +### założenie z planu + +_Tryb_: `primary` + +Zastrzeżony agent do analizy. Używamy systemu, aby włączyć Ci większe ryzyko i zapobiec niezamierzonym zmianom. +Domyślnie są wybrane na `ask`: + +- `file edits`: Wszystkie zapisy, transkrypcja i edycje +- `bash`: Wszystkie polecam bash + +Ten agent jest podłączony, gdy chcesz, aby LLM był kompatybilny z kodem, który wymaga zastosowania lub wersji plastikowej bez konieczności stosowania innej wersji bazy kodu. + +--- + +### miejsce + +_Tryb_: `subagent` + +Rozwiązanie rozwiązania złożone z zadań wieloetapowych. Pełny dostęp do narzędzia (z funkcjonalnymi funkcjami do wykonania), dzięki czemu może w razie potrzeby zostać dostarczone w plikach. Przewoźnik dziesięć, aby określić wiele jednostek roboczych. + +--- + +### eksploracji + +_Tryb_: `subagent` + +Szybki agent tylko do odczytu do eksploracji baz kodu. Nie można modyfikować plików. Użycie tej opcji, jeśli chcesz szybko uzyskać dostęp do plików według wzorców, wyszukać w kodzie słowa kluczowe lub rozwiązania dotyczące zapytań dotyczących bazy kodu. + +--- + +### zagęszczanie danych + +_Tryb_: `primary` + +Ukryty agent systemowy, który jest kontekstem kontekstowym w dużym podsumowaniu. W razie działania nie można przejść do interfejsu użytkownika. + +--- + +### jako tytuł + +_Tryb_: `primary` + +Ukryty agent systemowy, krótki tytuł sesji. Działa automatycznie i nie można przejść do interfejsu użytkownika. + +--- + +### Podsumowanie podsumowania + +_Tryb_: `primary` + +Ukryty agent systemowy, który stanowi podsumowanie podsumowania sesji. Działa automatycznie i nie można przejść do interfejsu użytkownika. + +--- + +## Stosowanie + +1. W przypadku agentów głównych klawisza **Tab**, aby przełączać się między nimi podczas sesji. Można również podać z skrótu klawiszowego `switch_agent`. + +2. Subagent można wytwarzać: + - **Automatycznie** przez głównych agentów do specjalistycznych zadań na podstawie ich opisów. + - Ręcznie, **@ wspomnienie** o subagencji w Twoich wiadomościach. Na przykład. + + ```txt frame="none" + @general help me search for this function + ``` + +3. **Nawigacja pomiędzy sesjami**: Kiedy można mieć własne sesje podrzędne, można nawigować pomiędzy sesjami nadrzędnymi a określonymi podrzędnymi, dostępnymi z: + - **\+Prawo** (lub skonfigurowane przez Ciebie klawisze `session_child_cycle`), aby przełączać się między jednostkami nadrzędnymi → podrzędnymi 1 → podrzędnymi 2 → ... → nadrzędnymi + - **\+Left** (lub skrót klawiszowy `session_child_cycle_reverse`), aby przejść dalej między macierzym ← podnośnik1 ← podnośnik2 ← ... ← prowadzącym + + Dostępna możliwość płynnego przełączania pomiędzy rozmową główną a pracą specjalistyczną subagentę. + +--- + +## Skonfiguruj + +Możliwość zastosowania agentów lub urządzeń poprzez zastosowanie. Agentów można zidentyfikować na dwóch systemach: + +--- + +### JSON + +Skonfiguruj agenta w pliku konfiguracyjnym `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Obniżka cen + +Można także definiować agentów za pomocą plików przecen. Trzymaj je w: + +- Globalnie: `~/.config/opencode/agents/` +- Na projekt: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Nazwa pliku przecen staje się nazwą agenta. Na przykład `review.md` tworzy agenta `review`. + +--- + +## Opcje + +Przyjrzyjmy się szczegółowo tym opcjom konfiguracji. + +--- + +### Opis + +miejsce `description`, aby krótko tego, co robi agent i kiedy go stosować. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +Jest to **wymagana** opcja konfiguracji. + +--- + +### Temperatura + +Kontroluj losowość i kreatywność odpowiedzi LLM za pomocą konfiguracji `temperature`. + +Niższe wartości, że odpowiedzi są bardziej skupione i deterministyczne, gdy wartość jest innowacyjna i złożona. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Wartość temperatury zwykle waha się od 0,0 do 1,0: + +- **0,0-0,2**: Bardzo skoncentrowane i deterministyczne odpowiedzi, idealne do analizy i kodu źródłowego +- **0,3-0,5**: Zrównoważona odpowiedź z chwilą powstania, dobre do ogólnych zadań rozwojowych +- **0,6–1,0**: Bardziej kreatywne i odpowiedzi, rozstrzygnięte podczas burzy mózgów i eksploracji + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Jeśli nie ma wpływu na kontrolę, OpenCode używa narzędzia do analizy danych dla modelu; 0 dla określonych modeli, 0,55 dla modeli Qwen. + +--- + +### Maksymalna liczba kroków + +Kontroluj funkcjonowanie iteracji agenta, jaki agent może być, zanim będzie dostępny wyłącznie z tekstem. Dzięki temu użytkownicy kontrolujący koszty mogą mieć wpływ na działanie agentów. + +Jeśli ta opcja nie zostanie skonfigurowana, agent będzie obowiązywał iterację, jeśli model nie zostanie wydany lub użytkownik nie będzie regularnie używany. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +Po tym, jak agent limitu otrzymuje specjalny monit systemowy nakazujący podsumowanie swojej pracy i rekomendowanych do wykonywania zadań. + +:::caution +Starsze pole `maxSteps` jest przestarzałe. Zamiast tego nadzoru `steps`. +::: + +--- + +### Wymienne + +Ustaw na `true`, aby wyłączyć agenta. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Podpowiedź + +niestandardowy plik podpowiedzi systemowych dla tego agenta z konfiguracją `prompt`. Plik informacyjny powinien zawierać dla celu agenta. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Ścieżka ta zależy od miejsca, w którym znajduje się plik konfiguracyjny. Działa również w przypadku globalnej konstrukcji OpenCode, jak i funkcjonalnej dla projektu. + +--- + +### Model + +konstrukcja nośna `model`, aby mieć model dla tego agenta. Przydatne przy różnych modelach konfiguracji w różnych zadaniach. Na przykład zastosowania modelu, skuteczne wykonanie modelu. + +:::tip +Jeśli nie ma wpływu na model, główne są [modelu skonfigurowanego globalnie](/docs/config#models), agenci podrzędni podmiotem modelu agenta, który wywołał subagentę. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +Identyfikator modelu w konfiguracji OpenCode w `provider/model-id`. Na koniec, [OpenCode Zen](/docs/zen), przestrzeganie `opencode/gpt-5.1-codex` dla kodeksu GPT 5.1. + +--- + +### Narzędzia + +Kontroluj, które narzędzia są dostępne w tej agencji, za pomocą konfiguracji `tools`. Można włączyć lub dostępne narzędzie, ustawiając je na `true` lub `false`. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +Konfiguracja specjalna dla agenta globalnego. +::: + +Można także zastosować symboli wieloznacznych do kontrolowanych wielu narzędzi jednocześnie. Na przykład, aby wyłączyć wszystkie narzędzia z serwera MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[Dowiedz się więcej o narzędziach](/docs/tools). + +--- + +### Uprawnienia + +Może wystąpić możliwość działania, które może pozostać ostateczne przez agenta. Obecnie proste dla narzędzia `edit`, `bash` i `webfetch` można znaleźć w drodze: + +- `"ask"` — Monituj o zatwierdzenie przed użyciem narzędzia +- `"allow"` — Zezwalaj na wszystkie operacje bez zatwierdzenia +- `"deny"` — Wyłączenie narzędzia + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +Można mieć odpowiedni dla każdego agenta. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +Można także istnieć w agentach Markdown. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +Można podłączyć do gniazda bash. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +Może być przestrzegany globalnym. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +Możesz także uzyskać symbolu wieloznacznego `*` do zarządzania uprawnieniami dla wszystkich użytkowników. +Ostatnie dostępne źródło pierwszeństwo, symbol wieloznaczny `*` na pierwszym miejscu, wyodrębnione na końcu. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[Dowiedz się więcej o prawach](/docs/permissions). + +--- + +### Tryb + +Kontroluj tryb agenta za pomocą konfiguracji `mode`. Opcja `mode` umożliwiająca użycie środka. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +Opcję `mode` można ustawić na `primary`, `subagent` lub `all`. Jeśli nie dotyczy `mode`, jest to `all`. + +--- + +### Ukryty + +Ukryj subagenta w menu autouzupełniania `@` za pomocą `hidden: true`. Przydatne w postępowaniu sądowym podagenci, potencjalnie być wywoływani programowo przez innych agentów, którzy korzystają z pomocy jako narzędzia. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +Wpływ tylko na użytkownika w menu autouzupełniania. Model może nadal wywoływać ukrytych agentów za pomocą narzędzi do zadań, funkcji użytkowych. + +:::note +Dotyczy tylko agentów `mode: subagent`. +::: + +--- + +### Uprawnienia do zadań + +Kontroluj, których agenci podawców mogą wywołać za pomocą narzędzia zadanie za pomocą `permission.task`. Używa wzorców globalnych do elastycznego dopasowywania. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +Po ustawieniu wartości `deny` podagent zostanie usunięty z opisu narzędzia Zadania, więc model nie będzie gotowy do uruchomienia. + +:::tip +Reguły są następujące w kolejności i **ostatnia reguła wygrywająca**. W zasadzie `orchestrator-planner` jest konfiguracją `*` (odmową), jak i `orchestrator-*` (zezwolenie), ale ponieważ `orchestrator-*` użytkownika po `*`, postać jest `allow`. +::: + +:::tip +Zawsze można rozwiązać rozwiązanie, bezpośrednio poprzez menu autouzupełnieniania `@`, nawet jeśli wystąpią zadania agenta temu naprawiające. +::: + +--- + +### Kolor + +Dostosuj wygląd agenta w interfejsie użytkownika za pomocą opcji `color`. Wpływ na wygląd agenta w interfejsie. + +Narodziny kościoła szesnastkowego (np. `#FF5733`) lub koloru motywu: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### Góra P + +Kontroluj różnorodność odpowiedzi za pomocą opcji `top_p`. Alternatywa dla temperatury w celu kontrolowanej braku wartości. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +Wartość mieszkalna obejmuje zakres od 0,0 do 1,0. Niższe wartości są bardziej skoncentrowane, wyższe wartości są bardziej zaawansowane. + +--- + +### nadal + +Wszelkie inne konfiguracje w agentach **przekazane bezpośrednio** jako model sprzedawcy. Dostęp do funkcji i parametrów dostarczanych dla dostawcy. + +Na przykład dzięki modelowi rozumowania OpenAI może kontrolować rozumowanie: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +Te dodatkowe cechy można zidentyfikować od modelu i dostawcy. Sprawdź swoje dostawcę pod kątem parametrów. + +:::tip +Uruchomione `opencode models`, aby wyłączyć modele. +::: + +--- + +## Utwórz agentów + +Możesz stworzyć nowych agentów za pomocą innego polecenia: + +```bash +opencode agent create +``` + +Wykonaj decyzję: + +1. Zapytaj, gdzie zapisać agenta; globalne lub szczegółowe dla projektu. +2. Opisz tego, co agent powinien. +3. Wygeneruj właściwy monit systemowy i identyfikator. +4. Wejście do wybrania narzędzia, do którego agenta może być dostęp. +5. Na koniec pliku pliku przecen z konfiguracją agenta. + +--- + +## Przypadki użycia + +Oto kilka typowych zastosowań różnych agentów. + +- **Agent użyciai**: Pełne prace programistyczne z dostępnymi narzędziami +- **Plan agenta**: Analiza i planowanie bez zmian +- **Agent recenzujący**: Przegląd kodu z odczytu i narzędzia do dokumentacji +- **Agent debugujący**: Koncentruje się na urządzeniu z dostępnymi narzędziami bash i odczytu +- **Agent Dokumentów**: Zapisywanie dokumentacji za pomocą operacji na plikach, ale bez konieczności posiadania kopii systemowych + +--- + +## Przykład + +Oto kilka przykładowych agentów, którzy mogą się przydatni. + +:::tip +Czy masz agenta, który jest osobą towarzyszącą? [Prześlij PR](https://github.com/anomalyco/opencode). +::: + +--- + +### Dokumentacja agenta + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### Audytor bezpieczeństwa + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/pl/cli.mdx b/packages/web/src/content/docs/pl/cli.mdx new file mode 100644 index 000000000..34f0e9029 --- /dev/null +++ b/packages/web/src/content/docs/pl/cli.mdx @@ -0,0 +1,601 @@ +--- +title: interfejs wiersza polecany +description: Opcje i interfejs interfejsu CLI OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +Interfejs CLI OpenCode uruchamia się [TUI](/docs/tui), gdy jest uruchamiany bez żadnych argumentów. + +```bash +opencode +``` + +Ale także instalacja przez tę stronę. pełni przed programową interakcją z OpenCode. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui + +Uruchomienie interfejsu użytkownika terminala OpenCode. + +```bash +opencode [project] +``` + +#### Flagi + +| Flaga | Krótkie | Opis | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | Kontynuuj ostatnią datę | +| `--session` | `-s` | Identyfikator sesji, aby kontynuować | +| `--prompt` | | Monituj o zastosowanie | +| `--model` | `-m` | Model wykorzystania w postaci dostawcy/modelu | +| `--agent` | | Agent do użycia | +| `--port` | | Port do słuchania | +| `--hostname` | | Nazwa hosta, która jest częścią składową | + +--- + +## Polecenia + +Interfejs CLI OpenCode zawiera także szczegółowe polecenie. + +--- + +### agent + +Zarządzaj agentami OpenCode. + +```bash +opencode agent [command] +``` + +--- + +### przytwierdzić + +Dołącz terminal do już działającego serwera zaplecza OpenCode uruchomionego za pomocą oprogramowania `serve` lub `web`. + +```bash +opencode attach [url] +``` + +Możliwość zabezpieczenia z TUI ze zdalnym backendem OpenCode. Na przykład: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### Flagi + +| Flaga | Krótkie | Opis | +| ----------- | ----- | --------------------------------- | +| `--dir` | | Katalog roboczy do uruchomienia TUI w | +| `--session` | `-s` | Identyfikator sesji, aby kontynuować | + +--- + +#### co + +Utwórz nowego agenta z niestandardową konfiguracją. + +```bash +opencode agent create +``` + +To działanie poprowadził Cię przez proces tworzenia nowego agenta z niestandardowym monitem systemowym i konfiguracją narzędzia. + +--- + +#### lista + +Lista wszystkich agentów. + +```bash +opencode agent list +``` + +--- + +### autoryzacja + +Polecenie do zarządzania danymi uwierzytelniającymi i logowaniem dla dostawców. + +```bash +opencode auth [command] +``` + +--- + +#### login + +OpenCode jest dostępny przez listę dostawców w [Models.dev](https://models.dev), więc można użyć `opencode auth login` do skonfigurowania klucza API dla dowolnego dostawcy, który może być kontrolowany. Jest to możliwe w `~/.local/share/opencode/auth.json`. + +```bash +opencode auth login +``` + +Po uruchomieniu OpenCode ładuje dostawców z pliku poświadczeń. A jeśli twoje siedliskiem są jakieś klucze lub plik `.env` w twoim projekcie. + +--- + +#### lista + +Wyświetlanie list wszystkich uwierzytelnionych dostawców przechowywanych w pliku poświadczeń. + +```bash +opencode auth list +``` + +Lub krótka wersja. + +```bash +opencode auth ls +``` + +--- + +#### wyloguj się + +Wylogowuje Cię z dostawcy poprzez usunięcie go z pliku poświadczeń. + +```bash +opencode auth logout +``` + +--- + +### githubie + +Zarządzaj agentem GitHub w celu automatyzacji repozytorium. + +```bash +opencode github [command] +``` + +--- + +#### Dowiedz się + +Zainstaluj agenta GitHub w swoim repozytorium. + +```bash +opencode github install +``` + +Spowoduje to konieczność uruchomienia akcji GitHub i przeprowadzi cię przez proces tworzenia. [Dowiedz się więcej](/docs/github). + +--- + +#### chcesz + +Uruchom agenta na GitHubie. Jest to zwykły użytkownik w akcjach GitHub. + +```bash +opencode github run +``` + +##### Flagi + +| Flaga | Opis | +| --------- | -------------------------------------- | +| `--event` | Zdarzenie próbne GitHub, aby sprawdzić agenta dla | +| `--token` | Osobisty token dostępu GitHub | + +--- + +### mcp + +Zarządzaj serwerem kluczowego modelu kontekstowego. + +```bash +opencode mcp [command] +``` + +--- + +#### zaproponować + +Dodaj serwer MCP do swojej konfiguracji. + +```bash +opencode mcp add +``` + +To polecenie poprowadzić Cię przez proces dodawania lokalnego lub zdalnego serwera MCP. + +--- + +#### lista + +Wyświetlanie list wszystkich skonfigurowanych serwerów MCP i ich awarii. + +```bash +opencode mcp list +``` + +Lub skrót krótkiej wersji. + +```bash +opencode mcp ls +``` + +--- + +#### autoryzacja + +Uwierzytelnij się za pomocą serwera MCP z włączoną funkcją OAuth. + +```bash +opencode mcp auth [name] +``` + +Jeśli nie poddasz nazwy serwera, zostaniesz poproszony o wybranie jednego z serwerów obsługujących OAuth. + +Możesz także uruchomić serwery obsługujące OAuth i ich status uwierzytelnienia. + +```bash +opencode mcp auth list +``` + +Lub skrót krótkiej wersji. + +```bash +opencode mcp auth ls +``` + +--- + +#### wyloguj się + +Usuń doświadczenie OAuth dla serwera MCP. + +```bash +opencode mcp logout [name] +``` + +--- + +#### odpluskwić + +Debuguj problemy z połączeniem OAuth dla serwera MCP. + +```bash +opencode mcp debug +``` + +--- + +### modele + +Wyświetlanie list modeli wszystkich skonfigurowanych dostawców. + +```bash +opencode models [provider] +``` + +Do sterowania dostępnymi modelami u dostawców w `provider/model`. + +Jest to wydanie do nazwy modelu, który jest używany w [twoja] (./config/). + +Opcjonalnie możesz udostępnić identyfikator dostawcy, aby filtrować modele według tego dostawcy. + +```bash +opencode models anthropic +``` + +#### Flagi + +| Flaga | Opis | +| ----------- | ------------------------------------------------------------ | +| `--refresh` | Odśwież pamięć podręczną modele z models.dev | +| `--verbose` | Bardziej szczegółowe dane wyjściowe modelu (zawiera metadane, takie jak koszty) | + +flagi `--refresh`, aby znaleźć listę modeli w pamięci podręcznej. Jest to wymagane, gdy dostawca dodano nowe modele, które chcesz zobaczyć w OpenCode. + +```bash +opencode models --refresh +``` + +--- + +### chcesz + +Uruchomiony opencode w trybie nieinteraktywnym, przekazując bezpośrednio monit. + +```bash +opencode run [message..] +``` + +Jest to wymagane w przypadku tworzenia skryptów, automatyzacji lub gdy zostanie wysłane natychmiastowe przesłanie bez uruchomienia TUI. Na przykład. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +Można również zastosować, uruchamiając `opencode serve`, aby wyłączyć zimne uruchamianie serwera MCP przy każdym uruchomieniu: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### Flagi + +| Flaga | Krótkie | Opis | +| ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | | Polecenie do uruchomienia, komunikatu dla argumentów | +| `--continue` | `-c` | Kontynuuj ostatnią datę | +| `--session` | `-s` | Identyfikator sesji, aby kontynuować | +| `--share` | | Udostępnij sesję | +| `--model` | `-m` | Model wykorzystania w postaci dostawcy/modelu | +| `--agent` | | Agent do użycia | +| `--file` | `-f` | Pliki do załączenia do wiadomości | +| `--format` | | Format: domyślny (sformatowany) lub json (surowe rozwiązanie JSON) | +| `--title` | | Tytuł sesji (używany skróconego monitu, jeśli nie podano wartości) | +| `--attach` | | Dołącz do skutecznego serwera opencode (np. http://localhost:4096) | +| `--port` | | Port dla serwera lokalnego (domyślnie jest do portu losowego) | + +--- + +### podawać + +Uruchom bezgłowy serwer OpenCode w celu uzyskania dostępu do API. Pełny interfejs HTTP w [dokumentacji serwera](/docs/server). + +```bash +opencode serve +``` + +Spowoduje dostęp do serwera HTTP, który zapewnia dostęp do API opencode bez interfejsu TUI. Ustaw `OPENCODE_SERVER_PASSWORD`, aby włączyć podstawowe uwierzytelnianie HTTP (domyślna nazwa użytkownika do `opencode`). + +#### Flagi + +| Flaga | Opis | +| ------------ | ------------------------------------------ | +| `--port` | Port do słuchania | +| `--hostname` | Nazwa hosta, która jest częścią składową | +| `--mdns` | Włącz wykrywanie mDNS | +| `--cors` | Dodatkowe źródło użytkownika CORS | + +--- + +### Sesja + +Zarządzaj sesją OpenCode. + +```bash +opencode session [command] +``` + +--- + +#### lista + +Lista wszystkich sesji OpenCode. + +```bash +opencode session list +``` + +##### Flagi + +| Flaga | Krótkie | Opis | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` | Ograniczony do ostatniego sesji | +| `--format` | | Format wyjściowy: tabela lub json (tabela) | + +--- + +### statystyki + +Pokaż statystyki wykorzystania tokenów i sesji szkoleniowych OpenCode. + +```bash +opencode stats +``` + +#### Flagi + +| Flaga | Opis | +| ----------- | --------------------------------------------------------------------------- | +| `--days` | Pokaż statystyki z ostatnich N dni (cały czas) | +| `--tools` | Liczba narzędzi do po specyfikacji (wszystkie) | +| `--models` | Pokaż podział modelu wykorzystania (domyślnie ukryty). Podajnik usługowy, aby górne N | +| `--project` | Filtruj według projektu (wszystkie projekty, pusty ciąg: dostęp projekt) | + +--- + +### eksport + +Eksportuj dane sesji jako JSON. + +```bash +opencode export [sessionID] +``` + +Jeśli nie poddasz identyfikatora sesji, zostaniesz poproszony o wybranie jednego z sesji. + +--- + +### import + +Importuj dane sesji z pliku JSON lub adresu URL udostępniania OpenCode. + +```bash +opencode import +``` + +Możesz importować z lokalnego lub adresu URL OpenCode. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### sieć + +Uruchomiony bezgłowy serwer OpenCode z interfejsem internetowym. + +```bash +opencode web +``` + +Spowoduje dostęp do serwera HTTP i otwarcie dostępu do OpenCode przez interfejs sieciowy. Ustaw `OPENCODE_SERVER_PASSWORD`, aby włączyć podstawowe uwierzytelnianie HTTP (domyślna nazwa użytkownika do `opencode`). + +#### Flagi + +| Flaga | Opis | +| ------------ | ------------------------------------------ | +| `--port` | Port do słuchania | +| `--hostname` | Nazwa hosta, która jest częścią składową | +| `--mdns` | Włącz wykrywanie mDNS | +| `--cors` | Dodatkowe źródło użytkownika CORS | + +--- + +### akp + +Uruchomiony serwer ACP (Agent Client Protocol). + +```bash +opencode acp +``` + +Aby udostępnić serwer ACP, który komunikuje się poprzez stdin/stdout przy użyciu nd-JSON. + +#### Flagi + +| Flaga | Opis | +| ------------ | --------------------- | +| `--cwd` | Katalog roboczy | +| `--port` | Port do słuchania | +| `--hostname` | Nazwa hosta, która jest częścią składową | + +--- + +### odinstaluj + +Odinstaluj OpenCode i usuń wszystkie pliki powiązane. + +```bash +opencode uninstall +``` + +#### Flagi + +| Flaga | Krótkie | Opis | +| --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` | Zachowaj pliki konfiguracyjne | +| `--keep-data` | `-d` | Przechowuj dane sesji i szczepionek | +| `--dry-run` | | Pokaż, wykluczy bez usuwania | +| `--force` | `-f` | Pomiń monity o potwierdzenie | + +--- + +### aktualizacja + +Aktualizuje opencode do oryginalnej wersji lub oryginalnej wersji. + +```bash +opencode upgrade [target] +``` + +Aby zachować ostatnią wersję. + +```bash +opencode upgrade +``` + +Aby zobaczyć wersję pierwotną. + +```bash +opencode upgrade v0.1.48 +``` + +#### Flagi + +| Flaga | Krótkie | Opis | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` | Zastosowana metoda instalacji; curl, npm, pnpm, kok, napar | + +--- + +## Flagi globalne + +Interfejs CLI kod opencode przyjmuje flagi globalne. + +| Flaga | Krótkie | Opis | +| -------------- | ----- | ------------------------------------ | +| `--help` | `-h` | Wyświetl pomoc | +| `--version` | `-v` | Drukuj numer wersji | +| `--print-logs` | | Wydrukuj logi na stderr | +| `--log-level` | | Poziom dziennika (DEBUG, INFO, OSTRZEŻ, BŁĄD) | + +--- + +## Zmienne warunki + +OpenCode można wykryć za pomocą czyszczenia alternatywnych. + +| Zmienna | Wpisz | Opis | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | wartość logiczna | Automatycznie udostępniaj sesje | +| `OPENCODE_GIT_BASH_PATH` | ciąg | Ścieżka do pliku wykonywalnego Git Bash w systemie Windows | +| `OPENCODE_CONFIG` | ciąg | Ścieżka do pliku konfiguracyjnego | +| `OPENCODE_CONFIG_DIR` | ciąg | Ścieżka do katalogu konfiguracyjnego | +| `OPENCODE_CONFIG_CONTENT` | ciąg | Wbudowana treść konstrukcji JSON | +| `OPENCODE_DISABLE_AUTOUPDATE` | wartość logiczna | Wyłącz automatyczne sprawdzanie aktualizacji | +| `OPENCODE_DISABLE_PRUNE` | wartość logiczna | Wyłączenie regulowane | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | wartość logiczna | Wyłącz automatycznie tytuł terminala | +| `OPENCODE_PERMISSION` | ciąg | Wbudowane prawo JSON | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | wartość logiczna | Wyłączenie wtyczki | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | wartość logiczna | Wyłącz automatyczne pobieranie z serwera LSP | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | wartość logiczna | Włącz modele eksperymentalne | +| `OPENCODE_DISABLE_AUTOCOMPACT` | wartość logiczna | Wyłącz automatyczne zagęszczanie kontekstu | +| `OPENCODE_DISABLE_CLAUDE_CODE` | wartość logiczna | Wyłączenie gry z `.claude` (podpowiedź + podłączenie) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | wartość logiczna | Wyłącz czytanie `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | wartość logiczna | Wyłącz ładowanie `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | wartość logiczna | Wyłączenie modeli pobierania ze źródeł niedostępnych | +| `OPENCODE_FAKE_VCS` | ciąg | Fałszywy sprzedawca VCS do celów testowych | +| `OPENCODE_DISABLE_FILETIME_CHECK` | wartość logiczna | Wyłączone sprawdzanie pliku w celu optymalizacji | +| `OPENCODE_CLIENT` | ciąg | Identyfikator klienta (domyślnie `cli`) | +| `OPENCODE_ENABLE_EXA` | wartość logiczna | Włącz narzędzie wyszukiwania internetowego Exa | +| `OPENCODE_SERVER_PASSWORD` | ciąg | Włącz uwierzytelnianie podstawowe dla `serve`/`web` | +| `OPENCODE_SERVER_USERNAME` | ciąg | Zakończenie stosowania użytkownika z autoryzacją (domyślnie `opencode`) | +| `OPENCODE_MODELS_URL` | ciąg | Niestandardowy adres URL do pobrania konfiguracji modeli | + +--- + +### Eksperymentalny + +Te zmienne możliwości użycia funkcji eksperymentalnych, które mogą zostać lub usunięte. + +| Zmienna | Wpisz | Opis | +| ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | wartość logiczna | Włącz wszystkie funkcje eksperymentalne | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | wartość logiczna | Włącz wykrywanie ikon | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | wartość logiczna | Wyłączenie kopiowania przy wyborze w TUI | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | numer | Domyślny limit czasu dla ukrytego bash w ms | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | numer | Maksymalne tokeny wyjściowe dla odpowiedzi LLM | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | wartość logiczna | Włącz obserwatora plików dla całego katalogu | +| `OPENCODE_EXPERIMENTAL_OXFMT` | wartość logiczna | Włącz formater oxfmt | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | wartość logiczna | Włącz eksperymentalne narzędzie LSP | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | wartość logiczna | Wyłącz obserwatora plików | +| `OPENCODE_EXPERIMENTAL_EXA` | wartość logiczna | Włącz funkcje eksperymentalne Exa | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | wartość logiczna | Włącz eksperymentalne sprawdzanie typu LSP | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | wartość logiczna | Włącz funkcje eksperymentalne przecen | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | wartość logiczna | Włącz tryb planu | diff --git a/packages/web/src/content/docs/pl/commands.mdx b/packages/web/src/content/docs/pl/commands.mdx new file mode 100644 index 000000000..f5b83b7d3 --- /dev/null +++ b/packages/web/src/content/docs/pl/commands.mdx @@ -0,0 +1,323 @@ +--- +title: Polecenia +description: Tworz polecany dla powtarzalnych zadań. +--- + +Polecenia ustawienia monitu, które może zostać uruchomione po uruchomieniu tego polecenia w TUI. + +```bash frame="none" +/my-command +``` + +Polecenia stanowią dodatek do dostarczonych, takich jak `/init`, `/undo`, `/redo`, `/share`, `/help`. [Dowiedz się więcej](/docs/tui#commands). + +--- + +## Utwórz źródło plikówwe + +Utwórz pliki przecen w katalogu `commands/`, aby móc korzystać z usług polecanych. + +Utwórz `.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Frontmatter posiada właściwości. Treść staje się szablonem. + +polecany, w rejestrze `/`, a następnie polecany. + +```bash frame="none" +"/test" +``` + +--- + +## Skonfiguruj + +Dostęp do sieci przez połączenie OpenCode lub udostępnia pliki w katalogu `commands/`. + +--- + +### JSON + +opcja opcja `command` w swoim OpenCode [config](/docs/config): + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Teraz możesz wybrać opcję w TUI: + +```bash frame="none" +/test +``` + +--- + +### Obniżka cen + +Można także definiować polecenia za pomocą plików Markdown. Trzymaj je w: + +- Globalnie: `~/.config/opencode/commands/` +- Na projekt: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Nazwa pliku przecen staje się nazwą referencyjną. Na przykład `test.md` pozwala +biegniesz: + +```bash frame="none" +/test +``` + +--- + +## Szybko kliknij + +Monity dotyczące niestandardowych urządzeń obsługujących kilka specjalnych symboli zastępczych i składni. + +--- + +### Argumentacja + +Przekazuj argumentację do ręki, używając symbolu zastępczego `$ARGUMENTS`. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +Uruchomienie reakcji z argumentami: + +```bash frame="none" +/component Button +``` + +A `$ARGUMENTS` pozostanie pozostawione przez `Button`. + +Dostępność do poszczególnych argumentów można również uzyskać za pomocą parametrów funkcjonalnych: + +- `$1` - Pierwszy argument +- `$2` - Drugi argument +- `$3` - Trzeci argument +- Biorę dalej... + +Na przykład: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +Uruchomienie decyzji: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +Aby przechowywać: + +- `$1` z `config.json` +- `$2` z `src` +- `$3` z `{ "key": "value" }` + +--- + +### Wyjście z pamięci + +urządzenie __!`command`_, aby wstawić dane wyjściowe [polecenie bash](/docs/tui#bash-commands) wykonaj obciążenie. + +Na przykład, aby sprawdzić narzędzie analityczne: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +Lub aby ostatnia zmiana: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +Polecenia są uruchamiane w systemie wyjściowym, a ich dane wyjściowe są uruchamiane. + +--- + +### Referencje plików + +Dołącz pliki do swojego polecenia, używając `@`, zawierającego plik. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +Zawartość pliku jest automatycznie umieszczana w pliku. + +--- + +## Opcje + +Przyjrzyjmy się szczegółowo opcjom konfiguracji. + +--- + +### Szablon + +Opcja `template` została rozstrzygnięta, która została wysłana do LLM po wykonaniu polecenia. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +Jest to **wymagana** opcja konfiguracji. + +--- + +### Opis + +Możliwość użycia `description`, aby skrócony opis działania polecenia. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +Jest podany jako opis w TUI po wpisaniu polecenia. + +--- + +### Agent + +Zastosowanie zastosowania `agent`, aby określić, który [agent] (./agents) powinien zostać naprawiony do wyboru. +Jeśli jest to [podagent](/docs/agents/#subagents), rozwiązanie to ujawnione, podagenta. +Aby móc, ustawa `subtask` na `false`. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +Jest to **opcjonalna** opcja konfiguracji. Jeśli nie jest dostępny, dostępny jest agentem. + +--- + +### Podzadanie + +Użyj wartości logicznej `subtask`, aby wymusić wywołanie [podagenta](/docs/agents/#subagents) polecenia. +Jest to narzędzie, jeśli chcesz, aby decyzja nie zanieczyszczała kontekstu i **zmusiło** agenta do działania jako subagent, +nawet jeśli `mode` jest podłączony na `primary` w konfiguracji [agent](/docs/agents). + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +Jest to **opcjonalna** opcja konfiguracji. + +--- + +### Model + +Używając konstrukcji `model`, aby znaleźć ukryty model dla tego polecenia. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Jest to **opcjonalna** opcja konfiguracji. + +--- + +## Wbudowany + +opencode zawiera kilka istniejących urządzeń, takich jak `/init`, `/undo`, `/redo`, `/share`, `/help`; [dowiedz się więcej](/docs/tui#commands). + +:::note +Polecenia mogą zostać usunięte. +::: + +Jeśli zdefiniujesz tę samą nazwę, nastąpi decyzja. diff --git a/packages/web/src/content/docs/pl/config.mdx b/packages/web/src/content/docs/pl/config.mdx new file mode 100644 index 000000000..2ac980881 --- /dev/null +++ b/packages/web/src/content/docs/pl/config.mdx @@ -0,0 +1,685 @@ +--- +title: Konfig +description: Korzystanie z konstrukcji OpenCode JSON. +--- + +Możesz zagrać z OpenCode za pomocą pliku konfiguracyjnego JSON. + +--- + +## Format + +OpenCode obsługa formaty **JSON** i **JSONC** (JSON z komentarzami). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## Lokalizacje + +Możesz umieścić swoją instalację w kilku różnych lokalizacjach i jednym pliku +inne porządki pierwszeństwa. + +:::note +Pliki konfiguracyjne są **łączone**, a nie zastępowane. +::: + +Pliki konfiguracyjne są łączone ze sobą, a nie zastępowane. Ustawienia z lokalizacji konfiguracyjnych są konfigurowalne. Ewentualne konfiguracje zaistnieją tylko w przypadku sprzecznych kluczy. Niekonfliktowe ustawienia ze wszystkich zasobów zachowanych. + +Na zestawie, przygotowana globalna ustawi `theme: "opencode"` i `autoupdate: true`, zestaw zestawu `model: "anthropic/claude-sonnet-4-5"`, ostateczna zestaw będzie zawierał wszystkie trzy ustawienia. + +--- + +### Kolejność pierwszeństwa + +Źródła konfiguracji są ładowane w kolejności (później źródła występują wcześniej): + +1. **Zdalna konfiguracja** (od `.well-known/opencode`) – ustawienia stosowane w organizacji +2. **Konfiguracja globalna** (`~/.config/opencode/opencode.json`) – przestrzeganie użytkownika +3. **Konfiguracja niestandardowa** (`OPENCODE_CONFIG` env var) — zastosowanie zastąpienie +4. **Konfiguracja projektu** (`opencode.json` w projekcie) - ustawienia dla projektu specjalnego +5. **`.opencode` katalogi** - agent, poleca, półki +6. **Konfiguracja wbudowana** (`OPENCODE_CONFIG_CONTENT` env var) — zastąpienie środowiska wykonawczego + +to, że konfiguracje projektu mogą być dostępne na poziomie globalnym konfiguracji, a konfiguracje globalne mogą być zdalne, zdalne konfiguracja organizacji. + +:::note +W katalogach `.opencode` i `~/.config/opencode` użytkownicy są **nazwy w zwykłej mnogiej** dla podkatalogów: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/` i `themes/`. Nazwy wydane (np. `agent/`) są również objęte gwarancją kompatybilności wstecznej. +::: + +--- + +### Zdalny + +Organizacje mogą być podłączone do łączy końcowych `.well-known/opencode`. Jest pobierane automatycznie po uwierzytelnieniu u dostawcy, który obsługuje. + +Zdalna jest ładowana jako pierwsza i podstawowa. Wszystkie inne źródła konfiguracji (globalne, projektowe) mogą zostać udostępnione menu. + +Na przykład, jeśli Twoja organizacja udostępnia serwery MCP, które są siecią internetową: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +Możesz udostępnić serwery w szczegółach: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### Światowy + +Umieść swoją globalną konfigurację OpenCode w `~/.config/opencode/opencode.json`. przestrzeganie funkcji globalnej, aby uzyskać dostęp do całego użytkownika, takie jak motywy, dostawca lub skróty klawiszowe. + +Konfiguracja globalna zaawansowana, zdalne ustawienie konfiguracji. + +--- + +### muszę zrobić projekt + +Dodaj `opencode.json` w katalogu głównym projektu. Konfiguracja projektu ma priorytet wśród plików konfiguracyjnych — zaawansowane konfiguracje globalne i zdalne. + +:::tip +Instalacja wstępna dla katalogu w katalogu. +::: + +Kiedy OpenCode się uruchomi, szuka pliku konfiguracyjnego w katalogu Git. + +Można również sprawdzić w Git i tego samego schematu, co globalny. + +--- + +### Niestandardowa ścieżka + +Niestandardowe rozwiązanie konfiguracyjne, różne opcje `OPENCODE_CONFIG`. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +Konfiguracja niestandardowa jest ładowana z konfiguracją globalną i konfiguracją projektu w kolejności pierwszych. + +--- + +### Katalog niestandardowy + +niestandardowy katalog konfiguracyjny za pomocą `OPENCODE_CONFIG_DIR` +zmienna środowiskowa. Katalog ten będzie przeszukiwany pod kątem agentów, ukryty, +tryby i wtyczki, tak jak standardowy katalog `.opencode` i powinienem +podążaj tą samą strukturą. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +Katalog niestandardowy jest ładowany po katalogach global config i `.opencode`, więc **może być połączony** z ich urządzeniami. + +--- + +## Schemat + +Plik konfiguracyjny ma schemat końcowy w [**`opencode.ai/config.json`**](https://opencode.ai/config.json). + +Twój edytor powinien mieć możliwość sprawdzania poprawności i autouzupełniania na podstawie schematu. + +--- + +### TUI + +Możliwość podłączenia urządzenia dla TUI za pomocą opcji `tui`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +Dostępna opcja: + +- `scroll_acceleration.enabled` - Włącz przyspieszenie przewijania w rysiku macOS. **Ma pierwszeństwo przed `scroll_speed`.** +- `scroll_speed` - Niestandardowy mnożnik szybkości przewijania (domyślnie: `3`, minimalnie: `1`). Ignorowane, jeśli `scroll_acceleration.enabled` do `true`. +- `diff_style` – Sterowanie renderowaniem różnicowym. `"auto"` dostępny jest do szerokości terminala, `"stacked"` zawsze pojawia się pojedyncza kolumna. + +[Dowiedz się więcej o korzystaniu z TUI tutaj](/docs/tui). + +--- + +### Serwer + +Możliwość ustawienia serwera dla źródeł `opencode serve` i `opencode web` za pomocą opcji `server`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +Dostępna opcja: + +- `port` - Port do nasłuchiwania. +- `hostname` — nazwa hosta, która jest przeznaczona dla Ciebie. Gdy `mdns` jest połączony i nie jest ułożony inną nazwą hosta, jest połączony z `0.0.0.0`. +- `mdns` - Włącz wykrywanie usług mDNS. Dzięki temu zewnętrznemu urządzeniu w sieci może być przesyłany Twój serwer OpenCode. +- `mdnsDomain` - Niestandardowa nazwa domeny dla usług mDNS. Wartość domyślna do `opencode.local`. Przydatne do uruchomienia wielu zastosowań w tej samej sieci. +- `cors` - Dodatkowe źródło CORS podczas korzystania z serwera HTTP z punktu końcowego. Wartość musi być dostępna dla źródeł (schemat + host + port opcjonalny), np. `https://app.example.com`. + +[Dowiedz się więcej o tutaj](/docs/server). + +--- + +### Narzędzia + +Dostępne narzędzia, z których można korzystać LLM, dostęp do opcji `tools`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[Dowiedz się więcej o narzędziach tutaj](/docs/tools). + +--- + +### Modele + +Możesz mieć dostawców i modele, które chcesz mieć w konfiguracji OpenCode, za pomocą opcji `provider`, `model` i `small_model`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +Opcja `small_model` konfiguruje oddzielny model do lekkich zadań, takich jak generowanie tytułów. Domyślnie OpenCode wyparte przez dostępny model, jeśli jest dostępny u dostawcy, w razie potrzeby powróć do innego modelu. + +Opcje dostawcy mogą być zainstalowane `timeout` i `setCacheKey`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - Limit czasu trwania w milisekundach (domyślnie: 300000). Ustaw na `false`, aby wyłączyć. +- `setCacheKey` — wkrótce, że klucz pamięci podręcznej jest zawsze gotowy dla dostawcy. + +Możesz także mieć [model lokalny](/docs/models#local). [Dowiedz się więcej](/docs/models). + +--- + +#### Opcje dostawcy dla dostawcy + +inne udostępnienie dodatkowych możliwości wyposażenia poza urządzeniami `timeout` i `apiKey`. + +##### Podłoże Amazonki + +Amazon Bedrock umożliwia podłączenie wyłącznika dla AWS: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` — region AWS dla Bedrock (domyślnie jest do `AWS_REGION` env var lub `us-east-1`) +- `profile` - profil nazwany AWS z `~/.aws/credentials` (domyślnie `AWS_PROFILE` env var) +- `endpoint` — niestandardowy adres URL punktu końcowego dla punktów końcowych VPC. Jest to alias dla opcji ogólnej `baseURL` przy użyciu terminologii specjalnej dla AWS. Jeśli oba, pierwszeństwo ma `endpoint`. + +:::note +Token okaziciela (`AWS_BEARER_TOKEN_BEDROCK` lub `/connect`) ma pierwszeństwo przed uwierzytelnianiem opartym na profilu. Aby uzyskać szczegółowe informacje, zobacz [pierwszeństwo uwierzytelniania](/docs/providers#authentication-precedence). +::: + +[Dowiedz się więcej o budowie Amazon Bedrock](/docs/providers#amazon-bedrock). + +--- + +### Motywy + +Urządzenie zachęcające do korzystania z urządzeń OpenCode, za pomocą sieci `theme`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[Dowiedz się więcej tutaj](/docs/themes). + +--- + +### Agencja + +Możliwość dostępności agentów do gniazd za pomocą opcji `agent`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +Możesz także uniknąć agentów przy użyciu plików przecen w `~/.config/opencode/agents/` lub `.opencode/agents/`. [Dowiedz się więcej tutaj](/docs/agents). + +--- + +### Domyślny agent + +Domyślnego agenta można ustawić za pomocą opcji `default_agent`. Wykrywacz, który jest używany, jeśli nie został ujawniony. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +Agent domyślny musi być agentem (nie subagentem). Może być agentem aplikacji, taki jak `"build"` lub `"plan"`, albo ukryty przez Ciebie [agent niestandardowy](/docs/agents). Jeśli agent nie istnieje lub jest podagentem, OpenCode powróć do `"build"` z ostrzeżeniem. + +Dotyczy urządzeń wszystkich interfejsów: TUI, CLI (`opencode run`), aplikacji komputerowej i akcji GitHub. + +--- + +### Partycypujący + +Możesz udostępnić [udostępnij](/docs/share) za pomocą opcji `share`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +Działaj: + +- `"manual"` – Zezwalaj na ręczne korzystanie z pomocy narzędzi (domyślnie) +- `"auto"` - Automatycznie udostępniaj nowe rozmowy +- `"disabled"` - Całkowicie udostępnienie + +Domyślnie jest rozwiązaniem na tryb medyczny, w którym należy jawnie udostępniać rozmowy za pomocą polecenia `/share`. + +--- + +### Polecenia + +Możesz korzystać z usług polecanych dla powtarzalnych zadań za pomocą opcji `command`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +Można także definiować polecenia przy użyciu plików Markdown w `~/.config/opencode/commands/` lub `.opencode/commands/`. [Dowiedz się więcej tutaj](/docs/commands). + +--- + +### Krótki kluczowy + +Możliwość zmiany skrótu klawiszowego za pomocą opcji `keybinds`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[Dowiedz się więcej tutaj](/docs/keybinds). + +--- + +### Automatyczna aktualizacja + +OpenCode automatycznie pobierze każde nowe uruchomienie. Można skorzystać z opcji `autoupdate`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +Jeśli nie chcesz aktualizacji, ale chcesz podłączyć nową wersję, ustaw `autoupdate` na `"notify"`. +Działa tylko wtedy, gdy nie jest uruchamiana przy użyciu menedżera pakietów, jak Homebrew. + +--- + +### Formacja + +Można podać kod formacyjny za pomocą opcji `formatter`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[Dowiedz się więcej o formaterach tutaj](/docs/formatters). + +--- + +### Uprawnienia + +Domyślnie opencode **zezwala na wszystkie działania** bez konieczności posiadania zgody. Można zmienić opcję `permission`. + +Na przykład, aby można było wykryć, że narzędzie `edit` i `bash` wymaga zgody użytkownika: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[Dowiedz się więcej o prawach tutaj](/docs/permissions). + +--- + +### Zagęszczanie + +Możesz kontrolować zachowanie zagęszczania kontekstu za pomocą opcji `compaction`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - Automatycznie kompaktuj, gdy kontekst jest pełny (domyślnie: `true`). +- `prune` - Usuń stare dane narzędzia, aby zapisać tokeny (domyślnie: `true`). + +--- + +### Obserwator + +Rejestracja wzorca plików za pomocą `watcher`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +Wzorce są zgodne ze składnią glob. Dostęp tej opcji, aby móc zaszumione katalogi z plikami do przeglądania. + +--- + +### Serwer MPK + +Dostęp do serwerów MCP, których chcesz używać, za pośrednictwem sieci `mcp`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[Dowiedz się więcej tutaj](/docs/mcp-servers). + +--- + +### Wtyki + +[Wtyczki](/docs/plugins) rozszerzają OpenCode o podstawowe narzędzia, hooki i integracje. + +Pliki plików wtyczek w `.opencode/plugins/` lub `~/.config/opencode/plugins/`. Można także włączyć wtyczkę z npm poprzez opcję `plugin`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[Dowiedz się więcej tutaj](/docs/plugins). + +--- + +### Instrukcja + +Instrukcja dla modelu, w której można zastosować opcję `instructions`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Pobierana do schematów i wzorców globalnych do plików graficznych. [Dowiedz się więcej +o zasadach tutaj](/docs/rules). + +--- + +### Niepełnosprawny sprzedawca + +Zasilacz ładowany automatycznie za pomocą zasilacza `disabled_providers`. Jest to możliwe, gdy istnieje możliwość podłączenia ładowania niektórych dostawców, nawet jeśli dane uwierzytelniające są dostępne. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +`disabled_providers` pierwszeństwo przed `enabled_providers`. +::: + +Opcja `disabled_providers` analiza tablica identyfikatorów dostawców. Gdy dostawca jest wyłączony: + +- Nie istnieje możliwość wystąpienia zagrożenia, które jest możliwe do zastosowania. +- Nie nastąpi uruchomienie, nawet jeśli klucz API zostanie uruchomiony za pomocą polecenia `/connect`. +- Model dostawcy nie pojawia się na liście wyboru modeli. + +--- + +### Włączeni dostawcy + +Można znaleźć dostawców za pomoc `enabled_providers`. Po ustawieniu włączeni tylko dostawcy, a wszyscy będą obecni. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +Jest to urządzenie, gdy urządzenie OpenCode jest używane tylko z urządzeniami, zamiast odłączać ich jedno po drugim. + +:::note +`disabled_providers` pierwszeństwo przed `enabled_providers`. +::: + +Jeśli obowiązująsz w `enabled_providers`, jak i `disabled_providers`, `disabled_providers` pierwszeństwo ze względu na kompatybilność wsteczną. + +--- + +### Eksperymentalny + +Klucz `experimental` zawiera opcje, które są początkiem rozwoju. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::caution +Opcje eksperymentalne nie są awaryjne. Jedna zmiana lub zmiana bez zniszczenia. +::: + +--- + +## Zmienne + +Możliwość wykorzystania danych zmiennych w plikach konfiguracyjnych, aby odwoływać się do zmiennych zewnętrznych i zawartości plików. + +--- + +### Kop. zm + +zastosowanie `{env:VARIABLE_NAME}`, aby zakończyć zmiennego przebiegu: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +Jeżeli zmienna kontrolna nie jest skonfigurowana, należy zastosować do niej pusty ciąg znaków. + +--- + +### Akta + +źródło `{file:path/to/file}`, aby znaleźć zawartość pliku: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +Ścieżki plików mogą być: + +- Względem katalogu konfiguracyjnego +- Lub nadrzędne kierowane się od `/` lub `~` + +Sądzimy, że: + +- Przechowywanie wrażliwych danych, takich jak klucze API, w oddzielnych plikach. +- Do udostępnienia dużych plików bez zaśmiecania konstrukcji. +- Udostępnianie fragmentów konfiguracji w wielu plikach konfiguracyjnych. diff --git a/packages/web/src/content/docs/pl/custom-tools.mdx b/packages/web/src/content/docs/pl/custom-tools.mdx new file mode 100644 index 000000000..3a49c341d --- /dev/null +++ b/packages/web/src/content/docs/pl/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: Narzędzia specjalistyczne +description: Twórz narzędzi, które LLM mogą być uruchamiane w otwartym kodzie. +--- + +Narzędzia stosowane do funkcji, z których LLM może korzystać podczas rozmów. Współpracują z [wbudowanymi narzędziami] (./tools) opencode, wtyczka jak `read`, `write` i `bash`. + +--- + +## Narzędzie do tworzenia + +Narzędzia tworzą pliki **TypeScript** lub **JavaScript**. Definicja narzędzia może być odwoływana do skryptów napisanych w **dowolnym języku** — TypeScript lub JavaScript są używane tylko w tym samym narzędziu. + +--- + +### Lokalizacja + +Można je uruchomić: + +- Lokalnie, umieszczając je w katalogu `.opencode/tools/` swojego projektu. +- Lub globalnie, umieszczając je w `~/.config/opencode/tools/`. + +--- + +### Struktura + +Najłatwiejszym sposobem tworzenia narzędzia jest pomocnika `tool()`, który zapewnia bezpieczeństwo i sprawdzanie poprawności. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +**Nazwa pliku** staje się **nazwą narzędzia**. Pierwotne narzędzie `database`. + +--- + +#### Wiele narzędzi na plik + +Można także eksportować wiele narzędzi z jednego pliku. Każdy eksport staje się **oddzielnym językiem** o nazwie **`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +Tworzy do dwóch narzędzi: `math_add` i `math_multiply`. + +--- + +### Argumentacja + +Do zdefiniowania argumentów można zastosować `tool.schema`, czyli po prostu [Zod](https://zod.dev). + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +Można także bezpośrednio zaimportować [Zod](https://zod.dev) i zwyczajowo zwykły obiekt: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### Kontekst + +Narzędzia kontekstowe charakterystycznej sesji: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +`context.directory` jako katalogowy pracodawczy. +`context.worktree` dla katalogu głównego zwalczającego git. + +--- + +## Przykład + +### Napisz narzędzie w Pythonie + +Napisz swoje narzędzie w języku angielskim. Oto przykład dodania dwóch liczb przy użyciu języka Python. + +Fragment utworu jako skrypt w języku Python: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +Utwór instrumentalny, który jest ukryty: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +Tutaj istnieje narzędzie [`Bun.$`](https://bun.com/docs/runtime/shell) uruchamiające skryptu w języku Python. diff --git a/packages/web/src/content/docs/pl/ecosystem.mdx b/packages/web/src/content/docs/pl/ecosystem.mdx new file mode 100644 index 000000000..774d4d283 --- /dev/null +++ b/packages/web/src/content/docs/pl/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: Ekosystem +description: Projekty i integracje zbudowane w OpenCode. +--- + +Zgromadzenie stowarzyszenia organizacji na OpenCode. + +:::note +Chcesz zadać swój projekt badawczy z OpenCode do tej listy? Prześlij PR. +::: + +Możesz także sprawdzić [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) i [opencode.cafe](https://opencode.cafe), grupę skupiającą ekosystem i społeczność. + +--- + +## Wtyki + +| Imię | Opis | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | Automatycznie uruchamiaj sesje OpenCode w izolowanych piaskownicach Daytona z synchronizacją git i podglądami na żywo | +| [sesja-helicone-opencode](https://github.com/H2Shami/opencode-helicone-session) | Automatycznie wstawiaj nagłówki sesji Helicone w celu grupowania urządzeń | +| [wstrzykiwanie typu opencode](https://github.com/nick-vi/opencode-type-inject) | Automatyczne wstrzykiwacze TypeScript/Svelte do odczytania plików za pomocą narzędzi wyszukiwania | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | wykorzystać do wykorzystania ChatGPT Plus/Pro zamiast kredytu API | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | korzystać z planu Gemini zamiast rozliczeń API | +| [auth-antygrawitacja-opencode](https://github.com/NoeFabris/opencode-antigravity-auth) | Wykorzystanie z bezpłatnych modeli Antigravity zamiast rozliczeń API | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Izolacja wielooddziałowych kontenerów deweloperskich z płytkami klonami i automatycznie przypisywanymi portami | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Wtyczka Google Antigravity OAuth z obsługą obsługi Google i bardziej niezawodną obsługą API | +| [czyszczenie-dynamiczne-kontekstu opencode](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Zoptymalizuj wykorzystanie tokena, usuwając przestarzałe dane wyjściowe narzędzia | +| [cytowane w opencode-websearch](https://github.com/ghoulr/opencode-websearch-cited.git) | Dodaj natywną obsługę wyszukiwania w sieci dla dostawców w stylu opartym na Google | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Uruchomienie agenta AI uruchamiającego się w tle w PTY i wytwarzanie ich interaktywnych danych. | +| [strategia-powłoki-opencode](https://github.com/JRedeker/opencode-shell-strategy) | Instrukcje dla nieinteraktywnych obowiązków - zaniechanie zawieszenia operacji zależnych od TTY | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Śledź udostępnić OpenCode za pomocą Wakatime | +| [formatujący tabelę opencode-md](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Oczyść tabelę przecenioną przez LLM | +| [opencode-szybkie-zastosowanie-morficzne](https://github.com/JRedeker/opencode-morph-fast-apply) | 10x szybsza edycja kodu dzięki Morph Fast Apply API i znacznikom leniwej edycji | +| [oh-mój-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Agencje odpowiedzialne w tle, gotowe narzędzia LSP/AST/MCP, wyselekcjonowani agenci, kompatybilni z Claude Code | +| [powiadamiacz opencode](https://github.com/panta82/opencode-notificator) | Powiadomienia na pulpicie i alerty dźwiękowe dotyczące sesji OpenCode | +| [powiadamiający o opencode](https://github.com/mohak34/opencode-notifier) | Powiadomienia na pulpicie i alerty dźwiękowe dotyczące uprawnień, wyników i zdarzeń o błędach | +| [nazwa-opencode-zellij](https://github.com/24601/opencode-zellij-namer) | Automatyczne nazewnictwo sesji Zellij oparte na sztucznej inteligencji w oparciu o kontekst OpenCode | +| [umiejętność obsługi opencode](https://github.com/zenobi-us/opencode-skillful) | Zezwalaj agentom OpenCode na leniwe ładowanie podpowiedzi na podstawie odkrywania możliwości i wstrzykiwania | +| [superpamięć opencode](https://github.com/supermemoryai/opencode-supermemory) | Trwała pamięć w sesjach przy użyciu Supermemory | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Interaktywny przegląd planu z adnotacją wizualną i użytkową prywatną/offline | +| [@openspoon/podzadanie2](https://github.com/spoons-and-mirrors/subtask2) | Rozszerzony kod otwarty/polecenia do połączenia sieciowego ze szczegółową kontrolą bezpieczeństwa | +| [program planujący opencode](https://github.com/different-ai/opencode-scheduler) | Zaplanuj powtarzające się zadania, używając launchd (Mac) lub systemd (Linux) ze składaną cron | +| [mikod](https://github.com/vtemian/micode) | Ustrukturyzowana burza mózgów → Plan → Wdrożenie wyjścia z ciągłością sesji | +| [okto](https://github.com/vtemian/octto) | Interaktywny interfejs do burzy mózgów AI z formularzami kontrolnymi wielu pytań | +| [agencja-w tle opencode](https://github.com/kdcokenny/opencode-background-agents) | Agencje krytyczne w tle w stylu Claude Code z delegowaniem asynchronicznym i trwałością kontekstu | +| [powiadomienie o opencode](https://github.com/kdcokenny/opencode-notify) | Natywne uruchomienie systemu dla OpenCode – wiesz, kiedy zadania zostaną zakończone | +| [obszar roboczy opencode](https://github.com/kdcokenny/opencode-workspace) | Lista wiązek orkiestracji wieloagentowej – 16 dostępna, jedna instalacja | +| [drzewo robocze opencode](https://github.com/kdcokenny/opencode-worktree) | Drzewa robocze Git o zerowym tarciu dla OpenCode | + +--- + +## Projektowanie + +| Imię | Opis | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | Bot Discord do kontrolowania sesji OpenCode, zbudowany na SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Wtyczka Neovim do podpowiedzi, zbudowana w oparciu o API | +| [portal](https://github.com/hosenur/portal) | Interfejs sieciowy do urządzeń mobilnych dla OpenCode poprzez Tailscale/VPN | +| [szablon wtyczki opencode](https://github.com/zenobi-us/opencode-plugin-template/) | Szablon do budowy wtyczek OpenCode | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Frontend Neovim dla opencode - agent kodujący AI oparty na terminalu | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Stosowanie Vercel AI SDK do użytku z OpenCode poprzez @opencode-ai/sdk | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | Aplikacja internetowa/stacjonarna i rozszerzenie VS Code dla OpenCode | +| [OpenCode-Obsydian](https://github.com/mtymek/opencode-obsidian) | Wtyczka Obsidian osadzająca OpenCode w interfejsie użytkownika Obsidian | +| [OpenWork](https://github.com/different-ai/openwork) | Alternatywa typu open source dla Claude Cowork, obsługa przez OpenCode | +| [ocx](https://github.com/kdcokenny/ocx) | Menedżer rozszerzony OpenCode z przenośnymi, izolowanymi profilami. | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Aplikacja komputerowa, internetowa, mobilna i zdalna dla OpenCode | + +--- + +## Agencja + +| Imię | Opis | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [Agent](https://github.com/Cluster444/agentic) | Modułowi agencje i polecenia AI do rozwoju strukturalnego | +| [agencja-opencode](https://github.com/darrenhinde/opencode-agents) | Konfiguracje, podpowiedzi, agencje i wtyczki usprawniające przepływ pracy | diff --git a/packages/web/src/content/docs/pl/enterprise.mdx b/packages/web/src/content/docs/pl/enterprise.mdx new file mode 100644 index 000000000..4ed4b6b65 --- /dev/null +++ b/packages/web/src/content/docs/pl/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: Przedsiębiorstwo +description: Bezpieczne korzystanie z OpenCode w Twojej organizacji. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Przedsiębiorstwo jest przeznaczone dla organizacji, która ma dostęp do zasobów, że ich kod i dane nigdy nie opuszczą infrastruktury. Może zostać zarejestrowany za pomocą zapachuralizowanej konfiguracji, która integruje się z logowaniem jednokrotnym i uruchomieniem bramą AI. + +:::note +OpenCode nie przechowuje żadnego kodu ani danych kontekstowych. +::: + +Aby skorzystać z pracy z OpenCode Przedsiębiorstwo: + +1. Przeprowadź próbę wewnętrzną ze swoim systemem. +2. **Skontaktuj się z nami**, aby omówić ceny i opcję konfiguracji. + +--- + +## Test + +OpenCode jest oprogramowaniem typu open source i nie przechowuje żadnego kodu ani danych kontekstowych, więc programiści mogą po prostu [zacząć](/docs/) i próbować próbną. + +--- + +### Obsługa danych + +**OpenCode nie dotyczy kodu źródłowego ani danych kontekstowych.** Całe zdarzenie odbywa się lokalnie lub poprzez bezpośrednio wywołane API do twojego dostawcy AI. + +to, że korzystasz z usług dostawcy, lub dostawcy zaufania +Brama AI, możesz bezpłatnie korzystać z OpenCode. + +Zastrzeżeniem jest opcjonalna funkcja `/share`. + +--- + +#### Dzielenie się rozmowami + +Jeśli użytkownicy są połączeni z `/share`, połączenie jest połączone z danymi, które zostały przesłane do usług, które są udostępniane przez hosty tych użytkowników w opencode.ai. + +Dane są aktualnie dostępne przez sieć brzegową naszego CDN i są buforowane na brzegu w pobliżu Twoich użytkowników. + +Zalecamy tę opcję na okres próbny. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[Więcej informacji o udostępnianiu](/docs/share). + +--- + +### Własność kodu + +**Jesteś właścicielem całości kodu źródłowego przez OpenCode.** Nie ma żadnych ograniczeń licencyjnych ani należących do własności. + +--- + +## Wycena + +W przypadku OpenCode Enterprise model per-seat. Jeśli posiadasz własną bramkę LLM, nie pobieramy opłat za korzystanie z tokenów. Aby uzyskać więcej informacji na temat, jeśli jest możliwe, **skontaktuj się z nami**. + +--- + +## Zastosowanie + +Gdy zasięgsz okres próbny i nadzorujesz użytkowanie z OpenCode na +swoją organizację, możesz **skontaktować się z nami**, aby omówić te dźwięki +opcja cenowa i wdrożeniowa. + +--- + +### Konfiguracja centralna + +Możliwości wykorzystania OpenCode tak, aby skorzystać z jednego zastosowania dla całej organizacji. + +Tę zapachową konfigurację można zintegrować z dostawcą SSO i specyfikacje wszyscy użytkownicy mają dostęp wyłącznie do bram wewnętrznych AI. + +--- + +### Integracja SSO + +Dzięki zastosowaniu konfiguracji OpenCode może zostać włączone z dostawcą SSO Twojej organizacji w celu uwierzytelnienia. + +Dzięki temu OpenCode może uzyskać dane uwierzytelniające dla wewnętrznej bramy AI za pośrednictwem transmisji systemu zarządzania tożsamością. + +--- + +### Wewnętrzna bramka AI + +Dzięki zastosowaniu konfiguracji OpenCode można również skorzystać z tego, że można korzystać tylko z wewnętrznych bram AI. + +Możesz także dołączyć do wszystkich innych dostawców sztucznej inteligencji, upewniając się, że wszystkie elementy przechodzą przez zatwierdzenie wykorzystania Twojej organizacji. + +--- + +### Hosting własny + +Zalecamy, aby można było je udostępnić, aby Twoje dane nigdy nie zostały opuszczone +Twoja organizacja może być pomocna w utrzymaniu ich w Twojej infrastrukturze. + +Jest to obecnie w naszym planie działania. Jeśli jesteś zainteresowany, **daj nam znać**. + +--- + +## Często zadawane pytania + +

+What is OpenCode Enterprise? + +OpenCode Przedsiębiorstwo jest przeznaczone dla organizacji, która ma dostęp do zasobów, że ich kod i dane nigdy nie opuszczą infrastruktury. Może zostać zarejestrowany za pomocą zapachuralizowanej konfiguracji, która integruje się z logowaniem jednokrotnym i uruchomieniem bramą AI. + +
+ +
+How do I get started with OpenCode Enterprise? + +Po prostu uruchom wersję próbną ze swoim. OpenCode urządzenia niezabezpieczone kodu ani danych kontekstowych, co ułatwia uruchomienie pracy. + +**skontaktuj się z nami**, aby omówić ceny i wybrać opcję. + +
+ +
+How does enterprise pricing work? + +Oferujemy ceny korporacyjne za jedno stanowisko. Jeśli posiadasz własną bramkę LLM, nie pobieramy opłat za korzystanie z tokenów. Aby uzyskać więcej informacji, **skontaktuj się z nami**, aby uzyskać wynik określony dla potrzeb Twojej organizacji. + +
+ +
+Is my data secure with OpenCode Enterprise? + +Tak. OpenCode nie przechowuje kodu ani danych kontekstowych. Całe zdarzenie odbywa się lokalnie lub poprzez bezpośrednie wywołanie API przez dostawcę AI. Dostęp do konfiguracji i integracji z logowaniem jednokrotnym Twoje dane pozostają bezpieczne w infrastrukturze organizacji. + +
+ +
+Can we use our own private NPM registry? + +OpenCode obsługuje prywatny rejestry npm poprzez natywną usługę plików `.npmrc` Buna. Jeśli Twoja organizacja korzysta z rejestru prywatnego, takiego jak JFrog Artifactory, Nexus lub wylot, przed uruchomieniem OpenCode się, że programiści zostali uwierzytelnieni. + +Aby zapewnić uwierzytelnianie w rejestrze prywatnym: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +Spowoduje to do `~/.npmrc` ze szczegółami uwierzytelniania. OpenCode zrobi to automatycznie +podniesc do. + +:::caution +Przed uruchomieniem OpenCode musisz być zalogowany do rejestru prywatnego. +::: + +Alternatywnie możesz skorzystać z pliku `.npmrc`: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Programiści muszą się zgłosić do rejestru prywatnego przed uruchomieniem OpenCode, aby mieć dostęp, że pakiety będą dostępne z rejestru przedsiębiorstwa. + +
diff --git a/packages/web/src/content/docs/pl/formatters.mdx b/packages/web/src/content/docs/pl/formatters.mdx new file mode 100644 index 000000000..d2a0181fb --- /dev/null +++ b/packages/web/src/content/docs/pl/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: Formatery +description: OpenCode używa formaterów specyficznych dla języka. +--- + +OpenCode automatycznie formatuje pliki po ich zapisaniu lub edycję przy użyciu formaterów przesyłanych dla języka. Dzięki temu wygenerowany kod będzie używany ze stylami kodu Twojego projektu. + +--- + +## Wbudowany + +OpenCode zawiera kilka wbudowanych formaterów dla nauki języków i frameworków. Zawiera listę formaterów, rozszerzonych plików oraz rozszerzenia i konfiguratory, których potrzebujesz. + +| Formater | Rozszerzenia | Wymagania | +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| gofmt | .idź | Komenda `gofmt` dostępna | +| ryzyko | .ex, .exs, .eex, .heex, .leex, .neex, .sface | Komenda `mix` dostępna | +| ładniejsza | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml i [więcej](https://prettier.io/docs/en/index.html) | Zależność `prettier` w `package.json` | +| biom | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml i [więcej](https://biomejs.dev/) | `biome.json(c)` plik konfiguracyjny | +| zyg | .zig, .zon | Komenda `zig` dostępna | +| formatuj brzęk | .c, .cpp, .h, .hpp, .ino i [więcej](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` plik konfiguracyjny | +| ktlint | .kt, .kts | Komenda `ktlint` dostępna | +| kryza | .py, .pyi | Komenda `ruff` dostępna w konstrukcji | +| rustfmt | .rs | Komenda `rustfmt` dostępna | +| załadunek | .rs | Komenda `cargo fmt` dostępna | +| UV | .py, .pyi | Komenda `uv` dostępna | +| rubocop | .rb, .rake, .gemspec, .ru | Komenda `rubocop` dostępna | +| standardowe | .rb, .rake, .gemspec, .ru | Komenda `standardrb` dostępna | +| htmlupiększacz | .erb, .html.erb | Komenda `htmlbeautifier` dostępna | +| powietrze | .R | Komenda `air` dostępna | +| strzałka | .dart | Komenda `dart` dostępna | +| formatuj ocaml | .ml, .mli | Dostępna opcja `ocamlformat` i plik konfiguracyjny `.ocamlformat` | +| terraforma | .tf, .tfvars | Komenda `terraform` dostępna | +| blask | .blask | Komenda `gleam` dostępna | +| nixfmt | .nix | Komenda `nixfmt` dostępna | +| shfmt | .sh, .bash | Komenda `shfmt` dostępna | +| kufel | .php | Zależność `laravel/pint` w `composer.json` | +| oxfmt (eksperymentalny) | .js, .jsx, .ts, .tsx | wykonanie `oxfmt` w `package.json` i [flaga eksperymentalna zmienna env](/docs/cli/#experimental) | +| ormolu | .hs | Komenda `ormolu` dostępna | + +Jeśli więc Twój projekt zawiera `prettier` w `package.json`, OpenCode automatycznie przejdź do podmiote. + +--- + +## Jak to działa + +Kiedy OpenCode zapisuje lub edytuje plik: + +1. Badanie pliku dotyczącego wszystkich danych formaterów. +2. Uruchamia decyzje wykonawcze formatujące na plik. +3. Automatycznie stosuje zmiany formatowania. + +Dziesięć procesów zachodzi w tle, konieczne jest zachowanie stylów kodu bez konieczności wykonania czynności czynnościowych. + +--- + +## Skonfiguruj + +Można dostosować formatery za pomocą sekcji `formatter` w konstrukcji OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +obsługiwane formatyzator Zobacz elementy: + +| Nieruchomość | Wpisz | Opis | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` | wartość logiczna | Ustaw tę opcję na `true`, aby wyłączyć formater | +| `command` | ciąg[] | Polecenie uruchomienia formatowania | +| `environment` | obiekt | Zmienne ustawienia do ustawień podczas uruchamiania programu formatującego | +| `extensions` | ciąg[] | Rozszerzenia plików, które powinny opuścić ten formater | + +Spójrzmy na kilka przykładów. + +--- + +### Wyłączanie formaterów + +Aby globalnie wyłączyć **wszystkie** formatery, ustaw `formatter` na `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +Aby wyłączyć **określony** formater, ustaw `disabled` na `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Niestandardowe formatery + +Może wystąpić, gdyby nastąpiło nowe, uruchomienie, zmienne udostępnienie i udostępnienie plików: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +Symbol zastępczy **`$FILE`** w poleceniu pochodziony z formatowanego pliku. diff --git a/packages/web/src/content/docs/pl/github.mdx b/packages/web/src/content/docs/pl/github.mdx new file mode 100644 index 000000000..9511d1b32 --- /dev/null +++ b/packages/web/src/content/docs/pl/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: Użyj OpenCode w problemach z GitHubem i zastosujch ściągnięcia. +--- + +OpenCode integruje się z przepływem pracy w GitHub. Wspomnij o `/opencode` lub `/oc` w swoim komentarzu, a OpenCode wykonaj zadania w ramach modułu uruchamiającego GitHub Actions. + +--- + +## Cechy + +- **Problem związany z segregacją**: Poproś OpenCode o szczegółowe wyjaśnienie problemu i wyjaśnienie go. +- **Napraw i zaimplementuj**: Poproś OpenCode o naprawienie problemu lub zaimplementowanie funkcji. Będzie dostępny w następnym oddziale i wysyłać PR ze stosowaniem dodatku. +- **Bezpieczny**: OpenCode działa w modułach sprzętowych GitHuba. + +--- + +## Instalacja + +Uruchomione dalsze postępowanie w przypadku wystąpienia w repozytorium GitHub: + +```bash +opencode github install +``` + +Aby przeprowadzić Cię przez proces instalacji aplikacji GitHub, utwórz działanie i skonfiguruj wpisy tajnych. + +--- + +### Konfiguracja ręczna + +Można też uszkodzić to rozwiązanie. + +1. **Zainstaluj aplikację GitHub** + + Wejdź na [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). wystąpienie się, że jest natychmiastowe w repozytorium usuwam. + +2. **Dodaj przepływ pracy** + + Dodaj zdalny plik pracy do `.github/workflows/opencode.yml` w swoim repozytorium. wystąpił, że ustawiłeś sędziego `model` i wymagany klucz API w `env`. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **Przechowuj klucze API w tajemnicy** + + W **ustawieniach** swojej organizacji lub projektu rozwiń **Sekretne i zmienne** po lewej stronie i wybierz **Działania**. Dodałem wymagane klucze API. + +--- + +## Konfiguracja + +- `model`: Model używany z OpenCode. Przyjmuje format `provider/model`. To **wymagane**. +- `agent`: Agent, którego należy używać. Musi być odległym agentem. Wraca do `default_agent` z konfiguracją lub `"build"`, jeśli nie został znaleziony. +- `share`: Czyć funkcję sesji OpenCode. Domyślnie **true** dla repozytoriów publicznych. +- `prompt`: Opcjonalny niestandardowy monit o zastąpienie przestrzegania zachowania. Wykorzystanie tego, aby dostosować sposób przetwarzania przez OpenCode. +- `token`: opcjonalny token dostępu GitHub podstawowe operacje, takie jak tworzenie komentarzy, zatwierdzanie zmian i otwieranie zastosowania ściągnięcia. Domyślnie OpenCode używa tokena dostępu do instalacji z aplikacji OpenCode GitHub, więc zatwierdzenia, komentarze i zasady ściągnięcia widoczne jako źródło z aplikacji. + + Alternatywnie możesz użyć [wbudowanego `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) modułu uruchamiającego GitHub Action bez instalacji aplikacji OpenCode GitHub. Pamiętaj tylko o przyznaniu wymaganych mocy w przepływie pracy: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + Jeśli chcesz, możesz także użyć [osobistych tokenów dostępu](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT). + +--- + +## Obsługiwane wydarzenia + +OpenCode może zostać wywołany przez zdarzenie GitHub: + +| Typ zdarzenia | Wywołane przez | Szczegóły | +| ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | Skomentuj problem lub PR | Wspomnij o `/opencode` lub `/oc` w swoim komentarzu. OpenCode odczytuje kontekst i może być częścią składową, otwieraną przez PR lub odpowiedzialną. | +| `pull_request_review_comment` | Komentarz określonym kodem w PR | Wspomnij o `/opencode` lub `/oc` podczas przeglądania kodu. OpenCode źródło pochodzenia, numery linii i kontekst różnicowy. | +| `issues` | Wydanie otwarte lub edytowane | Automatycznie wyzwalaj OpenCode po utworzeniu lub zmodyfikowaniu problemów. Wymaga wejścia `prompt`. | +| `pull_request` | PR otwarty lub zaktualizowany | Automatycznie wyzwalaj OpenCode, gdy PR są otwierane, synchronizowane lub ponownie otwierane. Przydatne w przypadku automatycznych znajomych. | +| `schedule` | Harmonogram oparty na Cron | Uruchom OpenCode zgodnie z harmonogramem. Wymagane wejście `prompt`. Dane wejściowe trafiają do dzienników i trafiań PR (nie ma problemu z recenzją). | +| `workflow_dispatch` | Ręczny wyłącznik z interfejsu użytkownika GitHub | Uruchom OpenCode na karcie Akcje. Wymagane wejście `prompt`. Dane wejściowe trafiają do dzienników i odbiorców PR. | + +### Przykład harmonogramu + +Uruchamiaj OpenCode zgodnie z harmonogramem, aby wykonać zautomatyzowane zadania: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +W przypadku wystąpienia danych wyjściowych `prompt` są **wymagane**, które nie są dostarczane, z których można wyodrębnić instrukcje. Zaplanowane przepływomierze pracy bez kontekstu użytkownika, który został uruchomiony, więc przepływ pracy musi `contents: write` i `pull-requests: write`, wystąpisz, że OpenCode utworzył główne lub PR. + +--- + +### Przykład żądania ściągnięcia + +Automatycznie przeglądaj żądania ściągnięcia po ich otwarciu lub aktualizacji: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +W przypadku zdarzenia `pull_request`, jeśli nie podano `prompt`, OpenCode użytkownika przeglądającego ściągnięcie. + +--- + +### Przykład segregacji problemów + +Automatycznie segreguj nowe problemy. Dziesięć przykładów filtruje do kont starszych niż 30 dni w celu ograniczenia spamu: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +W przypadku zdarzenia `issues` wprowadzenie `prompt` jest **wymagane**, ponieważ nie ma komentarza, z którego można wyodrębnić instrukcje. + +--- + +## Niestandardowe monity + +Zastąp domyślne monit, aby zastosować zachowanie OpenCode do twojego własnego pracy. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Jest to przepis wykonawczy, który podlega przepisom kodowania lub zakresów tematycznych dla twojego projektu. + +--- + +## Przykłady + +Oto kilka możliwości wykorzystania OpenCode w GitHubie. + +- **Wyjaśnij problem** + + Dodaj dziesięć komentarzy w numerze GitHub. + + ``` + /opencode explain this issue + ``` + + OpenCode przeczytaj całość, zawierając dodatek z komentarzami i odpowiedzią z jasnym wyjaśnieniem. + +- **Napraw problem** + + W numerze GitHub powiedz: + + ``` + /opencode fix this + ``` + + A OpenCode utworzy nową podstawę, wdroży zmiany i zastąpi PR ze zmiany. + +- **Przegląd zmiany PR i wprowadzenie zmiany** + + Zostaw komentarz w PR GitHub. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + OpenCode zaimplementuje uruchomioną zmianę i zatwierdzi ją do tego samego PR. + +- **Przejrzyj konkretne linie kodu** + + Zostaw komentarz bezpośrednio w wierszu kodu w dodatku „Pliki” PR. OpenCode automatyczne wykrywanie pliku, numery linii i kontekst różnicowy, aby sprawdzić odpowiedzi. + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + Komentując określone linie, OpenCode otrzymuje: + - Dokładny plik, który jest sprawdzany + - Konkretne linie kodu + - Otaczający kontekst różnicowy + - Informacje o numerze linii + + Dostępne na bardziej szczegółowe rozwiązanie bez konieczności stosowania ręcznego określania plików lub numerów wierszy. diff --git a/packages/web/src/content/docs/pl/gitlab.mdx b/packages/web/src/content/docs/pl/gitlab.mdx new file mode 100644 index 000000000..72b78f067 --- /dev/null +++ b/packages/web/src/content/docs/pl/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: użyj OpenCode w problemach z GitLabem i zastosujch scalania. +--- + +OpenCode integruje się z przepływem pracy GitLab poprzez potok GitLab CI/CD lub z GitLab Duo. + +W obu przypadkach OpenCode będzie modułem GitLab. + +--- + +## GitLab CI + +OpenCode działa w zwykłym potoku GitLab. Możesz wbudować go w potok jako [komponent CI](https://docs.gitlab.com/ee/ci/components/) + +Tutaj obowiązkowego przez społeczność komponentu CI/CD dla OpenCode — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### Cechy + +- **Użyj konfiguracji dla każdego zadania**: Skonfiguruj OpenCode z niestandardowym katalogiem konfiguracyjnym, na przykładzie `./config/#custom-directory`, aby włączyć lub funkcjonalności na każde wywołanie OpenCode. +- **Konfiguracja minimalna**: Komponent CI konfiguruje OpenCode w tle, wystarczy skonfigurować OpenCode i początkowy monit. +- **Elastyczny**: Komponent CI obsługuje kilka danych, które są stosowane w celu dostosowania jego zachowania + +--- + +### Organizować coś + +1. Przechowuj dane uwierzytelniające OpenCode w formacie JSON jako zmienne parametry CI typu pliku w specyfikacji **Ustawienia** > **CI/CD** > **Zmienne**. Zachowaj, aby być oznaczony jako „Zamaskowane i ukryte”. +2. Dodaj elementy do swojego pliku `.gitlab-ci.yml`. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +Więcej danych dotyczących użycia [sprawdź opis](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) tego komponentu. + +--- + +## Duet GitLab + +OpenCode integruje się z przepływem pracy GitLab. +Wspomnij o `@opencode` w komentarzu, a OpenCode wykonaj zadania w ramach swojego potoku GitLab CI. + +--- + +### Cechy + +- **Problem związany z segregacją**: Poproś OpenCode o szczegółowe wyjaśnienie problemu i wyjaśnienie go. +- **Napraw i zaimplementuj**: Poproś OpenCode o naprawienie problemu lub zaimplementowanie funkcji. + Utworzył nowy oddział i zgłosi ataku ze sobą. +- **Bezpieczny**: OpenCode działa na modułach GitLab. + +--- + +### Organizować coś + +OpenCode działa w potoku CI/CD GitLab. Oto, czego potrzebujesz, aby przejść do: + +:::tip +Aktualne instrukcje dotyczące [**dokumentacji GitLab**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/). +::: + +1. Skonfiguruj swoje środowisko GitLab +2. Skonfiguruj CI/CD +3. Uzyskaj klucz API dostawca modelu AI +4. Utwórz konto usługi +5. Skonfiguruj zmienne CI/CD +6. Utwórz plik konfiguracyjny, oto przykład: + +
+ + Flow configuration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +Szczegółowe instrukcje w [dokumentacji agentów GitLab CLI](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/). + +--- + +### Przykłady + +Oto kilka możliwości wykorzystania OpenCode w GitLabie. + +:::tip +Można zastosować inną metodę ograniczającą niż `@opencode`. +::: + +- **Wyjaśnij problem** + + Dodaj dziesięć komentarzy w numerze GitLab. + + ``` + @opencode explain this issue + ``` + + OpenCode przeczytaj problem i odpowiedź z wyjaśnieniem. + +- **Napraw problem** + + W numerze GitLab powiedz: + + ``` + @opencode fix this + ``` + + OpenCode utworzy nową podstawę, zaimplementuje zmiany i spowoduje, że skalowanie będzie możliwe. + +- **Przejrzyj prośby o połączenie** + + Zostaw komentarz w sprawie rozwiązania połączenia GitLab. + + ``` + @opencode review this merge request + ``` + + OpenCode sprawdzenie rozwiązania i przepuszczenie. diff --git a/packages/web/src/content/docs/pl/ide.mdx b/packages/web/src/content/docs/pl/ide.mdx new file mode 100644 index 000000000..a09475f6a --- /dev/null +++ b/packages/web/src/content/docs/pl/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: Rozszerzenie OpenCode dla VS Code, Cursor i innych IDE +--- + +OpenCode integruje się z VS Code, Cursorem lub obsługującym terminal IDE. Aby uruchomić, po prostu uruchom `opencode` w terminalu. + +--- + +## Stosowanie + +- **Szybkie uruchomienie**: użycie `Cmd+Esc` (Mac) lub `Ctrl+Esc` (Windows/Linux), aby uruchomić OpenCode w uruchamianiu terminala lub skoncentruj się na uruchamianiu terminala, jeśli jest już uruchomiony. +- **Nowa sesja**: `Cmd+Shift+Esc` (Mac) lub `Ctrl+Shift+Esc` (Windows/Linux), aby została nowa konfiguracja terminala OpenCode, nawet jeśli jest już otwarta. Możesz także kliknąć przycisk OpenCode w interfejsie użytkownika. +- **Świadomość kontekstu**: Automatycznie udostępnia wybór lub kartę za pomocą OpenCode. +- **Skróty do odwołania do plików**: `Cmd+Option+K` (Mac) lub `Alt+Ctrl+K` (Linux/Windows), aby wstawić odnośnik do plików. Na przykład `@File#L37-42`. + +--- + +## Instalacja + +Aby poznać OpenCode na VS Code w forkach, takich jak Cursor, Windsurf, VSCodium: + +1. Otwórz kod VS +2. Otwórz innowacyjny terminal +3. Uruchom `opencode` — rozszerzenie instaluje się automatycznie + +Jeśli z drugiej strony chcesz zainstalować własne IDE po uruchomieniu `/editor` lub `/export` z TUI, należy zainstalować `export EDITOR="code --wait"`. [Dowiedz się więcej](/docs/tui/#editor-setup). + +--- + +### Instalacja ręczna + +Wyszukaj **OpenCode** na rynku rozszerzonym i kliknij **Zainstaluj**. + +--- + +### Rozwiązywanie problemów + +Jeśli rozwiązanie nie zostanie zainstalowane automatycznie: + +- zastosowanie się, że użycie `opencode` w terminalu. +- zadziałanie, że CLI dla Twojego IDE jest zainstalowane: + - Dla kodu VS: polecenie `code` + - Dla kura: polecenie `cursor` + - Dla windsurfingu: decyzja `windsurf` + - Dla VSCodium: decyzja `codium` + - Jeśli nie, uruchom `Cmd+Shift+P` (Mac) lub `Ctrl+Shift+P` (Windows/Linux) i wyszukaj „Polecenie: zastosowanie decyzji„ kod ”w PATH” (lub właściwyk dla twojego IDE) +- zadziałanie, że VS Code ma pozwolenie na instalację rozszerzoną diff --git a/packages/web/src/content/docs/pl/index.mdx b/packages/web/src/content/docs/pl/index.mdx new file mode 100644 index 000000000..df97fd93f --- /dev/null +++ b/packages/web/src/content/docs/pl/index.mdx @@ -0,0 +1,359 @@ +--- +title: Wprowadzenie +description: Rozpocznij pracę z OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) do agenta kodującego AI typu open source. Dostępny jest jako interfejs terminalowy, aplikacja komputerowa lub rozszerzenie IDE. + +![OpenCode TUI z motywem opencode](../../../assets/lander/screenshot.png) + +Zacznijmy. + +--- + +#### Warunki wstępne + +Aby uzyskać dostęp do OpenCode w swoim terminalu, będziesz potrzebować: + +1. Nowoczesny emulator terminala, taki jak: + - [WezTerm](https://wezterm.org), wieloplatformowy + - [Alacritty](https://alacritty.org), wieloplatformowy + - [Ghostty](https://ghostty.org), Linux i macOS + - [Kitty](https://sw.kovidgoyal.net/kitty/), Linux i macOS + +2. Klucze API dla dostawców LLM, z których korzystasz. + +--- + +## Zainstalować + +Najłatwiejszym sposobem instalowania OpenCode jest zastosowanie skryptu instalacyjnego. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +Można także zalogować się do urządzenia instalacyjnego: + +- **Przy użyciu Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **Korzystanie z Homebrew na macOS i Linux** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > W celu uzyskania najbardziej aktualnej wersji zalecamy korzystanie z OpenCode. Oficjalna formuła `brew install opencode` jest utrzymywana przez zespół Homebrew i jest aktualizowana. + +- **Korzystanie z Paru na Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### Okna + +:::tip[Zalecane: prowadzenie WSL] +Aby najlepiej wykorzystać działanie w systemie Windows, zalecamy udostępnienie [Podsystemu Windows dla systemu Linux (WSL)](/docs/windows-wsl). pozwolenie na użytkowanie i pełna kompatybilność z funkcjami OpenCode. +::: + +- **Używając czekolady** + + ```bash + choco install opencode + ``` + +- **Korzystanie z miarki** + + ```bash + scoop install opencode + ``` + +- **Przy użyciu NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **Używając Mise’a** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **Korzystanie z Dockera** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +Obecnie trwają prace nad instalacją OpenCode w systemie Windows za pomocą Bun. + +Możesz także otrzymać plik binarny z [Releases](https://github.com/anomalyco/opencode/releases). + +--- + +## Skonfiguruj + +Dzięki OpenCode możesz korzystać z dowolnego dostawcy LLM, konfigurując jego klucze API. + +Jeśli nadal będziesz korzystać z dostawców LLM, zalecamy skorzystanie z [OpenCode Zen](/docs/zen). +Do wyselekcjonowanej listy modeli, które zostały zatwierdzone i zweryfikowane przez OpenCode +zespół. + +1. Uruchom opcję `/connect` w TUI, wybierz opencode i przejdź do [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Zaloguj się, dodaj szczegóły rozliczeniowe i skopiuj klucz API. + +3. Wklej swój klucz API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +Alternatywnie możesz wybrać jednego z dodatkowych dostawców. [Dowiedz się więcej](/docs/providers#directory). + +--- + +## Zainicjuj + +Po skonfigurowaniu dostawcy, który może przejść do projektu, który +chcesz pracować. + +```bash +cd /path/to/project +``` + +Uruchamiam OpenCode. + +```bash +opencode +``` + +Następnie zainicjuj OpenCode dla projektu, uruchamiając odpowiednią instrukcję. + +```bash frame="none" +/init +``` + +Spowoduje to, że OpenCode przeanalizuje Twój projekt i utworzy plik `AGENTS.md` +katalog główny projektu. + +:::tip +Powinieneś zatwierdzić plik `AGENTS.md` swojego projektu w Git. +::: + +Pomaga w OpenCode zrozumieniu struktury projektu i wzorce kodowania +używany. + +--- + +## Stosowanie + +Teraz możesz pracować nad swoim projektem. Możesz o to zapytać +wszystko! + +Jeśli tylko zaczniesz korzystać z agenta kodującego AI, oto kilka, które mogą być używane +pomoc. + +--- + +### Zadawaj pytania + +Możesz uruchomić OpenCode o wyjaśnienie bazy kodu. + +:::tip +klawisza klawisza `@` do wyszukiwania rozmytego plików w projekcie. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +Jest to pomocne, jeśli istnieje część bazy kodu, nad którą nie pracowałeś. + +--- + +### Dodaj funkcje + +Możesz zastosować OpenCode o nowej funkcji do Twojego projektu. Najpierw zalecamy poproszenie o wypłacenie planu. + +1. **Plan Stworza** + + OpenCode ma _tryb płaski_, który umożliwia wyłączenie zmian i + zamiast tego zasugeruj, jak_ zaimplementuje tę funkcję. + + Przejdź do niego za pomocą klawisza **Tab**. W osobnym dolnym rogu zobacz właściwy wskaźnik. + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + Opiszmy teraz, co chcemy, żeby robił. + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + Wersja OpenCode zawiera dużo oprogramowania, aby zrozumieć, czego chcesz. To pomaga + rozmawiaj z nim tak, jakbyś rozmawiał z młodszym programistą w swoim zespole. + + :::tip + Podaj OpenCode kontekstu i kontekstu, które można zrozumieć, co Ty + chcieć. + ::: + +2. **Postęp zgodnie z planem** + + Gdy będziesz mieć plan, możesz pozostawić go lub podłączyć więcej. + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::tip + Przeciągnij i upuść obrazy do terminala, aby dodać je do monitu. + ::: + + OpenCode może zeskanować obrazy, które mu przekażesz i poprosisz o potwierdzenie. Możesz + należy to, przeciągając i upuszczając obraz do terminala. + +3. **Stwórz przełącza** + + Kiedy już jest komfortowo z planem, przełącz się z powrotem do _trybu_ + zamknięcie na klawisza **Tab**. + + ```bash frame="none" + + ``` + + Poproszę o wprowadzenie zmian. + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### Wprowadź zmiany + +Aby zastosować następczą zmianę, można zastosować OpenCode lub bezpośrednio zbudowanie go +bez konieczności wcześniejszego przeglądania planu. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +Musisz mieć dostęp, że pod warunkiem dostępności narzędzia, więc OpenCode ma właściwie +zmiany. + +--- + +### Cofnij zmiany + +Załóżmy, że prosisz OpenCode o wprowadzenie zmian. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Ale z sobie sobie sprawę, że to nie jest to, czego chciałeś. **Możesz być** zmiany +za pomoc polecenia `/undo`. + +```bash frame="none" +/undo +``` + +OpenCode cofnie teraz zmiany i wyświetli wiadomość +Ponownie. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Można zastosować monit i zastosować OpenCode o próbę próby. + +:::tip +Można `/undo` wiele razy, aby uniknąć wielu zmian. +::: + +Możesz też **możesz powtórzyć** zmianę za pomocą polecenia `/redo`. + +```bash frame="none" +/redo +``` + +--- + +## Udział + +Rozmowy z OpenCode można [udostępniać swoim +zespół](/docs/share). + +```bash frame="none" +/share +``` + +Spowoduje to, że łącza do bieżących połączeń idą do schowki. + +:::note +Rozmowy nie są ogólnodostępne. +::: + +Oto [przykładowa rozmowa](https://opencode.ai/s/4XP1fce5) z OpenCode. + +--- + +## Dostosuj + +tyle! Jesteś teraz profesjonalistą w korzystaniu z OpenCode. + +Aby dostosować go do potrzeb, zalecamy [wybranie motywu](/docs/themes), [dostosowanie skrótów klawiaturowych](/docs/keybinds), [konfigurowanie programów formatujących kod](/docs/formatters), [tworzenie niestandardowych kodów](/docs/commands) lub grę z [konfiguracją OpenCode](/docs/config). diff --git a/packages/web/src/content/docs/pl/keybinds.mdx b/packages/web/src/content/docs/pl/keybinds.mdx new file mode 100644 index 000000000..106e7c1ed --- /dev/null +++ b/packages/web/src/content/docs/pl/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: Skróty klawiszowe +description: Dostosuj swoje skróty klawiszowe. +--- + +OpenCode zawiera listę skrótów klawiszowych, które można zastosować poprzez OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## Klucz lidera + +OpenCode używa klucza `leader` dla głównych skrótów klawiszowych. Rozwiązanie problemu konfliktów w terminalu. + +Domyślnie `ctrl+x` jest klawiszem głównym i główną akcją wymaga najpierw naciśnięcia klawisza lidera, a następnie skrótu. Na przykład, aby ponownie zastosować, następnie następuje `ctrl+x`, a następnie następuje `n`. + +Nie musisz mieć klawisza wiodącego do skrótów klawiszowych, ale zalecamy to Reg. + +--- + +## Wyłącz powiązanie klawiszy + +Możesz podłączyć powiązanie klawiszy, dodając klucz do swojej konfiguracji z wartością „none”. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## Skróty monitów na pulpicie + +Pole sprawdzania aplikacji komputerowej OpenCode obsługuje popularne skróty w stylu Readline/Emacs do edycji tekstu. Są one dostępne i obecnie nie można ich skonfigurować za pomocą `opencode.json`. + +| Skrót | Akcja | +| -------- | ---------------------------------------- | +| `ctrl+a` | Przejdź do źródła regularnej linii | +| `ctrl+e` | Przejdź na koniec bieżącej linii | +| `ctrl+b` | Przesuń kursor do tyłu o jeden znak | +| `ctrl+f` | Przesuń kursor o jeden znak do przodu | +| `alt+b` | Przesuń kursor o jedno słowo wstecz | +| `alt+f` | Przesuń kursor do przodu o jedno słowo | +| `ctrl+d` | Usuń znak pod kursorem | +| `ctrl+k` | Zabij do końca linii | +| `ctrl+u` | Zabij na początek linii | +| `ctrl+w` | Zabij poprzednie słowo | +| `alt+d` | Zabij następne słowo | +| `ctrl+t` | Transponuj znaki | +| `ctrl+g` | Anuluj wyskakujące okienka / przerwij uruchamianie odpowiedzi | + +--- + +## Shift+Enter + +Istnieją terminale, które nie wysyłają klawiszy modyfikujących z Enterem. Może być konieczne skonfigurowanie terminala tak, aby wysłać `Shift+Enter` jako przerwanie zakończenia. + +### Terminal Windowsowy + +Otwórz swój `settings.json` pod adresem: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +Dodaj do tablicy `actions` na poziomie wyższym: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Dodaj do tablicy `keybindings` na poziomie wyższym: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Zapisz plik i uruchom ponownie terminal Windows lub otwórz nową kartę. diff --git a/packages/web/src/content/docs/pl/lsp.mdx b/packages/web/src/content/docs/pl/lsp.mdx new file mode 100644 index 000000000..970602e7a --- /dev/null +++ b/packages/web/src/content/docs/pl/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: Serwery LSP +description: OpenCode integruje się z serwerem LSP. +--- + +OpenCode integruje się z protokołem serwera językowego (LSP), aby pomóc LLM w korzystaniu z bazowego kodu. Wykorzystuje diagnostykę, aby otrzymać odpowiedź zwrotną do LLM. + +--- + +## Wbudowany + +OpenCode posiada kilka wbudowanych serwerów LSP dla języków: + +| Serwer LSP | Rozszerzenie | Wymagania | +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +| astro | .astro | Automatyczne instalacje dla Astro | +| bash | .sh, .bash, .zsh, .ksh | Automatycznie instaluje serwer języka bash | +| brzęk | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Automatyczne instalacje dla C/C++ | +| csharp | .cs | `.NET SDK` zainstalowany | +| clojure-lsp | .clj, .cljs, .cljc, .edn | Komenda `clojure-lsp` dostępna | +| strzałka | .dart | Komenda `dart` dostępna | +| nie | .ts, .tsx, .js, .jsx, .mjs | Dostępne rozwiązanie `deno` (automatyczne wykrywanie deno.json/deno.jsonc) | +| eliksir-ls | .ex, .exs | Komenda `elixir` dostępna | +| eslin | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` zależność w projekcie | +| fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` zainstalowany | +| blask | .blask | Komenda `gleam` dostępna | +| gopls | .idź | Komenda `go` dostępna | +| hl | .hs, .lhs | Komenda `haskell-language-server-wrapper` dostępna | +| jdtl | .java | `Java SDK (version 21+)` zainstalowany | +| kotlin-ls | .kt, .kts | Automatyczne instalacje dla Kotlin | +| lua-ls | .lua | Automatyczne instalacje dla Lua | +| nixd | .nix | Komenda `nixd` dostępna | +| ocaml-lsp | .ml, .mli | Komenda `ocamllsp` dostępna | +| oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | `oxlint` zależność w projekcie | +| php inteligentny | .php | Automatyczne instalacje dla PHP | +| pryzma | .prysma | Komenda `prisma` dostępna | +| pirat | .py, .pyi | Zainstalowana zależność `pyright` | +| ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | Dostępne polecenie `ruby` i `gem` | +| rdza | .rs | Komenda `rust-analyzer` dostępna | +| sourcekit-lsp | .swift, .objc, .objcpp | `swift` zainstalowany (`xcode` na macOS) | +| smukły | smukły | Automatyczne instalacje dla aplikacji Svelte | +| terraforma | .tf, .tfvars | Automatyczne instalacje z wydań GitHub | +| malutka | .typ, .typc | Automatyczne instalacje z wydań GitHub | +| maszynopis | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` zależność w projekcie | +| vue | .vue | Automatyczne instalacje dla Vue | +| yaml-ls | .yaml, .yml | Automatycznie instaluje serwer języka yaml Red Hat | +| zł | .zig, .zon | Komenda `zig` dostępna | + +Serwery LSP są automatycznie włączane po wykryciu jednego z rozszerzonych plików i wymagań. + +:::note +Możliwość automatycznego pobierania z serwera LSP, ustawianie zmiennej środowiska `OPENCODE_DISABLE_LSP_DOWNLOAD` na `true`. +::: + +--- + +## Jak to działa + +Gdy opencode otwiera plik, to: + +1. Sprawdzanie pliku na wszystkich dostępnych serwerach LSP. +2. Uruchamia właściwy serwer LSP, jeśli jeszcze nie działa. + +--- + +## Skonfiguruj + +Możesz dostosować serwery LSP poprzez sekcję `lsp` w konfiguracji opencode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Każdy serwer LSP obsługuje szczegółowe elementy: + +| Nieruchomość | Wpisz | Opis | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` | wartość logiczna | Ustaw tę opcję na `true`, aby włączyć serwer LSP | +| `command` | ciąg[] | Polecenie uruchomienia serwera LSP | +| `extensions` | ciąg[] | Rozszerzenia plików, które powinny mieć ten serwer LSP | +| `env` | obiekt | Zmienne ustawienia podczas uruchamiania serwera | +| `initialization` | obiekt | Opcje inicjalizacji do wysłania na serwer LSP | + +Spójrzmy na kilka przykładów. + +--- + +### Zmienne środowiskowe + +Zastosowanie `env`, aby ustawić zmienne parametry transmisji podczas uruchamiania serwera LSP: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### Opcje inicjalizacji + +właściwości `initialization`, aby mieć możliwość inicjalizacji na serwerze LSP. Są to ustawienia dla serwera wysyłającego podczas przełączania LSP `initialize`: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +Opcje inicjalizacji różnią się w zależności od serwera LSP. Sprawdź swój serwer LSP pod gniazdem. +::: + +--- + +### Wyłączanie serwerów LSP + +Aby wyłączyć **wszystkie** serwery LSP globalnie, ustaw `lsp` na `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +Aby wyłączyć **określony** serwer LSP, ustawa `disabled` na `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Niestandardowe serwery LSP + +Serwer udostępniający serwery LSP, mechanizmy sterujące i udostępniane pliki: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## Dodatkowe informacje + +### PHP Intelefense + +PHP Intelephense oferuje funkcje premium poprzez klucz licencyjny. Możesz przechowywać klucz licencyjny umieszczając (tylko) klucz w pliku tekstowym pod adresem: + +- W systemie macOS/Linux: `$HOME/intelephense/licence.txt` +- W systemie Windows: `%USERPROFILE%/intelephense/licence.txt` + +Plik powinien zawierać wyłącznie klucz licencyjny, bez udostępniania treści. diff --git a/packages/web/src/content/docs/pl/mcp-servers.mdx b/packages/web/src/content/docs/pl/mcp-servers.mdx new file mode 100644 index 000000000..f0acec9b0 --- /dev/null +++ b/packages/web/src/content/docs/pl/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: Serwery MPK +description: Dodaj lokalne i zdalne narzędzie MCP. +--- + +Możesz dodać dodatkowe informacje do OpenCode za pomocą _Model Context Protocol_, w skrócie MCP. OpenCode obsługuje zarówno serwery lokalne, jak i zdalne. + +Po dodaniu narzędzi MCP są automatycznie dostępne dla LLM wraz z narzędziami narzędziowymi. + +--- + +#### Zastrzeżenia + +Kiedy używasz serwera MCP, zmieniając kontekst. Może szybko się sumować, jeśli masz dużo narzędzia. Zalecamy ostrożność, z jakich serwerów MCP korzystasz. + +:::tip +Serwery MCP dodają do twojego kontekstu, dlatego należy zachować ostrożność przy wyłączaniu tych serwerów. +::: + +Niektóre serwery MCP, takie jak serwer MCP GitHub, mają szerokie możliwości dodawania wielu tokenów i mogą łatwo przekraczać limit kontekstu. + +--- + +## Włączać + +Dostępny serwery MCP w [OpenCode Config](https://opencode.ai/docs/config/) w `mcp`. Dodaj każdy MCP z unikalną nazwą. Możesz zgłosić się do tego MCP po nazwie, pytając LLM. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +Możesz także wyłączyć serwer, ustawiając `enabled` na `false`. Jest to urządzenie, które jest urządzeniem biologicznym, bez usuwania z urządzenia. + +--- + +### Zastępowanie zdalnych ustawień domyślnych + +Organizacje mogą udostępniać serwery MCP za pośrednictwem punktu końcowego `.well-known/opencode`. Serwer może być podłączony, dzięki czemu użytkownicy mogą wybrać te, których. + +Aby włączyć serwer ze zdalnej konfiguracji organizacji, dodaj go do wyłączenia za pomocą `enabled: true`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +Lokalne wartości konfiguracyjne za występujące zdalne wartości. Aby uzyskać więcej informacji, zobacz [pierwszeństwo konfiguracji](/docs/config#precedence-order). + +--- + +## Lokalny + +Dodaj lokalne serwery MCP za pomocą `type` do `"local"` w obiekcie MCP. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +Polecenie sposobu uruchamiania lokalnego serwera MCP. Można także zainstalować listę konfiguracyjną. + +Oto przykładowy sposób dodania testowego serwera MCP [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +Aby z niego skorzystać, można dodać `use the mcp_everything tool` do moich podpowiedzi. + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### Opcje + +Oto wszystkie opcje lokalnego serwera MCP. + +| Opcja | Wpisz | Wymagane | Opis | +| ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | Ciąg | Y | Typ połączenia z serwerem MCP musi być `"local"`. | +| `command` | Tablica | Y | Polecenie i argumenty uruchamiające serwer MCP. | +| `environment` | Obiekt | | Zmienne ustawienia podczas uruchamiania serwera. | +| `enabled` | Wartość logiczna | | Włącz lub wyłącz serwer MCP podczas uruchamiania. | +| `timeout` | Numer | | Limit czasu w ms na pobieranie narzędzia z serwera MCP. Wartość domyślna do 5000 (5 sekund). | + +--- + +## Zdalny + +Dodaj zdalne serwery MCP, ustawiając `type` na `"remote"`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` na adres URL zdalnego serwera MCP i za pomocą opcji `headers` można znaleźć listę nagłówków. + +--- + +#### Opcje + +| Opcja | Wpisz | Wymagane | Opis | +| --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | Ciąg | Y | Typ połączenia z serwerem MCP musi być `"remote"`. | +| `url` | Ciąg | Y | Adres URL zdalnego serwera MCP. | +| `enabled` | Wartość logiczna | | Włącz lub wyłącz serwer MCP podczas uruchamiania. | +| `headers` | Obiekt | | Nagłówki do wysłania z wprowadzenia. | +| `oauth` | Obiekt | | Konfiguracja uwierzytelniania OAuth. Zobacz sekcję [OAuth](#oauth) poniżej. | +| `timeout` | Numer | | Limit czasu w ms na pobieranie narzędzia z serwera MCP. Wartość domyślna do 5000 (5 sekund). | + +--- + +## OAuth + +OpenCode automatyczne uwierzytelnianie OAuth dla zdalnych serwerów MCP. Gdy serwer wymaga uwierzytelnienia, OpenCode: + +1. Wykryj odpowiedź 401 i zainijuj przepływ OAuth +2. używa **Dynamicznej rejestracji klienta (RFC 7591)**, jeśli jest obsługiwana przez serwer +3. Bezpiecznie przechowuj tokeny na wypadek ewentualnego zastosowania + +--- + +### Automatyczny + +W innym serwerze MCP z włączoną funkcją OAuth nie jest wymagana specjalna funkcja. Dostępny serwer bezprzewodowy: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +Jeśli serwer wymaga uwierzytelnienia, OpenCode poprosi Cię o uwierzytelnienie przy próbie jego użycia. Jeśli nie, możesz [ręcznie podłączyć przepływ] (#authenticating) za pomocą `opencode mcp auth `. + +--- + +### Wstępnie zarejestrowany + +Jeśli posiadasz dostęp do klienta od dostawcy serwera MCP, możesz je udostępnić: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### Uwierzytelnianie + +Możesz podać potwierdzenie lub potwierdzenie poświadczenia. + +Uwierzytelnij się za pomocą standardowego serwera MCP: + +```bash +opencode mcp auth my-oauth-server +``` + +Lista wszystkich serwerów MCP i ich status uwierzytelnienia: + +```bash +opencode mcp list +``` + +Usuń zapisane dane uwierzytelniające: + +```bash +opencode mcp logout my-oauth-server +``` + +Komenda `mcp auth` została udostępniona w celu autoryzacji. Po autoryzacji OpenCode bezpieczne przechowa tokeny w `~/.local/share/opencode/mcp-auth.json`. + +--- + +#### Wyłączanie OAuth + +Jeśli chcesz włączyć automatyczne OAuth dla serwera (np. dla serwerów, które zamiast tego używać kluczy API), ustaw `oauth` na `false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### Opcje OAuth + +| Opcja | Wpisz | Opis | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` | Obiekt \| fałszywe | Obiekt konfiguracyjny OAuth lub `false`, aby wyłączyć automatyczne wykrywanie OAuth. | +| `clientId` | Ciąg | Identyfikator klienta OAuth. Jeżeli nie zostanie podany, zostanie podjęta próba dynamicznej rejestracji klienta. | +| `clientSecret` | Ciąg | Sekret klienta OAuth, plik jest wymagany przez serwer autoryzacji. | +| `scope` | Ciąg | Zakresy protokołu OAuth, których należy żądać podczas autoryzacji. | + +#### Debugowanie + +Jeśli serwer MCP nie może zostać uwierzytelniony, możesz zdiagnozować problemy z: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +Komenda `mcp debug` wyświetlanie stanu uwierzytelniania, testuje sprawdzanie protokołu HTTP i sprawdzenie sprawdzenia procesu OAuth. + +--- + +## Zarządzać + +Twoje MCP są dostępne jako narzędzie w OpenCode, obok narzędzi dodatkowych. Można to zrobić poprzez podłączenie OpenCode, jak również w innym przypadku. + +--- + +### Światowy + +Możesz to włączyć lub wyłączyć globalnie. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +Dostępne są również wzorca globu, aby wyłączyć wszystkie dyski MCP. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +Tutaj znajdziesz wzorca globalnego `my-mcp*`, aby wyłączyć wszystkie MCP. + +--- + +### Na agenta + +Jeśli masz największe serwery MCP, możesz włączyć je tylko dla poszczególnych agentów i być globalnie. Aby to zrobić: + +1. Wyłącz go jako narzędzie globalnie. +2. W [konfiguracji agenta](/docs/agents#tools) włącz serwer MCP jako narzędzie. + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### Wzory globusów + +Wzorzec glob wykorzystuje proste wzorce globowania regularnych: + +- `*` dopasowuje zero lub więcej dowolnego znaku (np. `"my-mcp*"` dopasowuje `my-mcp_search`, `my-mcp_list` itd.) +- `?` odpowiada dokładnie jednemu znakowi +- Wszystkie pozostałe znaki pasują dosłownie + +:::note +Narzędzia serwera MCP są rejestrowane z nazwą serwera jako prefiksem, więc aby uzyskać dostęp do wszystkich narzędzi dla serwera, po prostu dostęp do: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## Przykłady + +Poniżej znajdują się przykłady niektórych serwerów MCP. Twój prywatny PR, udostępniany przez inne serwery. + +--- + +### Wartownik + +Dodaj [serwer Sentry MCP](https://mcp.sentry.dev), aby móc wejść w interakcję z projektem i udostępnić Sentry. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +Po dodaniu konfiguracji uwierzytelnij się za pomocą Sentry: + +```bash +opencode mcp auth sentry +``` + +Spowoduje otwarcie okna konfiguracji, w którym można zakończyć proces OAuth i połączyć OpenCode z kontem Sentry. + +Po uwierzytelnieniu oprogramowania Sentry w swoich monitach, aby rozprzestrzeniać zagrożenia, dane i błędy. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Kontekst7 + +Dodaj [serwer Context7 MCP](https://github.com/upstash/context7), aby przeszukać dokumenty. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +Jeśli założyłeś darmowe konto, możesz użyć klucza API i uzyskać wyższy limit stawek. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +Załóż tutaj, że masz ustawioną zmienną środowiskową `CONTEXT7_API_KEY`. + +Dodaj `use context7` do swoich podpowiedzi, aby skorzystać z serwera Context7 MCP. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +Alternatywnie możesz zadać coś takiego do pliku [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep firmy Vercel + +Dodaj serwer MCP [Grep by Vercel](https://grep.app), aby przeszukać fragmenty kodu w serwisie GitHub. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +Nazwaliśmy nasz serwer MCP `gh_grep`, możesz dodać `use the gh_grep tool` do swoich podpowiedzi, aby agent mógł z niego korzystać. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +Alternatywnie możesz zadać coś takiego do pliku [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/pl/models.mdx b/packages/web/src/content/docs/pl/models.mdx new file mode 100644 index 000000000..580295fd4 --- /dev/null +++ b/packages/web/src/content/docs/pl/models.mdx @@ -0,0 +1,223 @@ +--- +title: Modele +description: Konfigurowanie dostawcy i modelu LLM. +--- + +OpenCode używa [AI SDK](https://ai-sdk.dev/) i [Models.dev](https://models.dev) do obsługi **ponad 75 dostawców LLM** i obsługi uruchamiania modeli pierwszych. + +--- + +## Dostawcy + +Dostępna usługa dostawcy jest dostępna. Jeśli otrzymasz poświadczenie dostawcy za pomocą polecenia `/connect`, będzie on dostępny po uruchomieniu OpenCode. + +Dowiedz się więcej o [dostawcach](/docs/providers). + +--- + +## Wybierz model + +Po skonfigurowaniu dostawcy możesz wybrać dostępny model, wpisując: + +```bash frame="none" +/models +``` + +--- + +## Polecane modele + +Na rynku jest mnóstwo modeli, co tydzień pojawia się nowe. + +:::tip +Rozważ skorzystanie z jednego z rekomendowanych przez nas modeli. +::: + +Jednak tylko kilka z nich jest dobrych przy generowaniu kodu, jak i wywołaniu narzędzia. + +Oto kilka modeli, które dobrze współpracują z OpenCode, w kolejności. (Nie jest to lista wyczerpująca i nie jest konieczna aktualna): + +- GPT 5.2 +- Kodeks GPT 5.1 +- Klaudiusz Opus 4.5 +- Claude Sonnet 4.5 +- Minimax M2.1 +- Bliźnięta 3Pro + +--- + +## Ustaw wartość domyślną + +Aby zainstalować jeden z nich jako model domyślny, możesz zainstalować klucz `model` w swoim +OpenCode konfiguracja + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Tutaj pełny identyfikator do `provider_id/model_id`. Na przykład, użycie [OpenCode Zen](/docs/zen), przestrzeganie `opencode/gpt-5.1-codex` dla Kodeksu GPT 5.1. + +Jeśli skonfigurowałeś [dostawcę zwykłegogo] (./providers#custom), `provider_id` jest kluczem z części `provider` twojej konfiguracji, a `model_id` jest kluczem z `provider.models`. + +--- + +## Skonfiguruj modele + +Można globalnie skorzystać z opcji modelu poprzez plik config. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Tutaj konfigurujemy urządzenia globalne dla dwóch modeli: `gpt-5` w przypadku dostępu za pośrednictwem dostawcy `openai` i `claude-sonnet-4-20250514` w przypadku dostępu za pośrednictwem dostawcy `anthropic`. +Wbudowane nazwy dostawców i modele można znaleźć na [Models.dev](https://models.dev). + +Można także skorzystać z opcji dla dowolnych agentów, których używa się. Konfiguracja agenta jest dostępna jako opcja globalna. [Dowiedz się więcej](/docs/agents/#additional). + +Można również zastosować alternatywne warianty, które wykluczają. Warianty konfiguracji ustawień konfiguracyjnych dla tego samego modelu bez tworzenia duplikatów wpisów: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## Warianty + +Wiele modeli obsługuje wiele wariantów lub różnych wybranych. OpenCode jest dostarczany z podstawowymi wariantami wariantów dla dostawców. + +### Wbudowane warianty + +OpenCode jest dostarczany z domyślnymi wariantami dla wielu dostawców: + +**Antropiczny**: + +- `high` – Wysoki budżet na przemyślenie (domyślnie) +- `max` - Maksymalny budżet na myślenie + +**OpenAI**: + +Różni się zależnością od modelu, ale mniej więcej: + +- `none` – Brak uzasadnienia +- `minimal` - Minimalny wysiłek rozumowania +- `low` - Niewielki wysiłek w zakresie rozumowania +- `medium` – Średni wysiłek rozumowania +- `high` - Duży wysiłek w zakresie rozumowania +- `xhigh` - Bardzo duży wysiłek w zakresie rozumowania + +**Google**: + +- `low` — Mniejszy nakład pracy/budżet tokena +- `high` — Większy nakład pracy/budżet tokena + +:::tip +Lista ta nie jest kompletna. Wielu innych dostawców oferuje także opcję odchylenia ustawień. +::: + +### Warianty niestandardowe + +Można uwzględnić warianty lub dodać własne: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### Warianty cyklu + +Naciśnij klawisza `variant_cycle`, aby szybko przełączać się między wariantami. [Dowiedz się więcej](/docs/keybinds). + +--- + +## Ładowanie modeli + +Po uruchomieniu OpenCode sprawdzanie modeli w następującej kolejności: + +1. Flaga wiersza autora `--model` lub `-m`. Format jest taki sam jak w pliku konfiguracyjnym: `provider_id/model_id`. + +2. Lista modeli w konstrukcji OpenCode. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + Sformatuj tutaj na `provider/model`. + +3. Ostatni używany model. + +4. Pierwszy model sterujący priorytetem wewnętrznym. diff --git a/packages/web/src/content/docs/pl/modes.mdx b/packages/web/src/content/docs/pl/modes.mdx new file mode 100644 index 000000000..a5348251d --- /dev/null +++ b/packages/web/src/content/docs/pl/modes.mdx @@ -0,0 +1,331 @@ +--- +title: Tryby +description: Różne tryby dla różnych zastosowań. +--- + +:::caution +Tryby są teraz konfigurowane za pomocą opcji `agent` w konfiguracji opencode. +Opcja `mode` jest obecnie przestarzała. [Dowiedz się więcej](/docs/agents). +::: + +Tryb udostępniania możliwości stosowania, narzędzie i podpowiedzi do różnych zastosowań. + +Posiadanie dwa tryby: **budowanie** i **planowanie**. Można dostosować +te lub skonfiguruj własne za pomocą konfiguracji opencode. + +Można przełączać się między trybami podczas sesji lub konfigurować je w pliku konfiguracyjnym. + +--- + +## Wbudowany + +opencode ma dwa puste tryby. + +--- + +### Zbudować + +Kompilacja jest trybem **domyślnym** z dostępnymi narzędziami. Jest to standardowy tryb pracy programistycznej, który jest dostępny z pełnym dostępem do operacji na plikach i oryginalnych systemach systemowych. + +--- + +### Plan + +Tryb ograniczony do analizy. W urządzeniu planowym narzędzia są przydatne: + +- `write` - Nie można stworzyć nowych plików +- `edit` — Nie można zastosować naruszenia plików, z naruszeniem praw autorskich w `.opencode/plans/*.md` w celu uszczegółowienia samego planu +- `patch` - Nie można zastosować poprawek +- `bash` - Nie można wykonać poleceń powłoki + +Ten tryb jest alternatywny, gdy chcesz, aby sztuczna inteligencja analizowała kod, sugerowała zmianę lub tworzyła projekty bez źródła zewnętrznego, które stanowi bazę kodu. + +--- + +## Przełączanie + +Możesz przełączać się między trybami podczas sesji za pomocą klawisza _Tab_. Lub skrót klawiszowy `switch_mode`. + +Zobacz także: [Formaterzy](/docs/formatters), aby uzyskać informacje na temat konfiguracji formatowania kodu. + +--- + +## Skonfiguruj + +Możliwość dostosowania alternatywnego trybu lub konfiguracji poprzez własną konfigurację. Tryb można skonfigurować na dwa systemy: + +### Konfiguracja JSON-a + +Skonfiguruj tryb w pliku konfiguracyjnym `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Konfiguracja przecen + +Można także definiować tryby za pomocą plików przecen. Trzymaj je w: + +- Globalnie: `~/.config/opencode/modes/` +- Projekt: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Nazwa pliku przecen staje się kluczem trybunału (np. `review.md` tworzy tryb `review`). + +Przyjrzyjmy się szczegółowo tym opcjom konfiguracji. + +--- + +### Model + +Zastosowanie konstrukcji `model`, aby zastosować domyślny model dla tego trybunału. Przydatne przy wykorzystaniu różnych modeli dostępnych w różnych zadaniach. Na przykład zastosowanie modelu, skuteczniejsze wykonanie modelu. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Temperatura + +Kontroluj losowość i kreatywność reakcji AI za pomocą konstrukcji `temperature`. Niższe wartości, że odpowiedzi są bardziej skupione i deterministyczne, podczas gdy najwyższa wartość jest innowacyjna i złożona. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Wartości temperatury zazwyczaj wahają się od 0,0 do 1,0: + +- **0,0-0,2**: Bardzo skoncentrowane i deterministyczne odpowiedzi, idealne do analizy i kodu źródłowego +- **0,3-0,5**: Zrównoważona odpowiedź z chwilą powstania, dobre do ogólnych zadań rozwojowych +- **0,6–1,0**: Bardziej kreatywne i odpowiedzi, rozstrzygnięte podczas burzy mózgów i eksploracji + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Jeśli nie ma wpływu na temperaturę, opencode stosuje się narzędzia badawcze dla modelu (zwykle 0 dla największych modeli, 0,55 dla modeli Qwen). + +--- + +### Podpowiedź + +niestandardowy plik podpowiedzi systemowych dla tej procedury za pomocą konfiguracji `prompt`. Plik informacyjny powinien zawierać instrukcje dotyczące przeznaczenia trybunału. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Ścieżka ta zależy od miejsca, w którym znajduje się plik konfiguracyjny. Więc to dla działa +zarówno globalna opencode, jak i specjalna dla projektu. + +--- + +### Narzędzia + +Kontroluj, które narzędzia są dostępne w tym urządzeniu, za pomocą konfiguracji `tools`. Można włączyć lub dostępne narzędzie, ustawiając je na `true` lub `false`. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +Jeśli nie ma żadnych narzędzi, wszystkie narzędzia są wyłączone. + +--- + +#### Dostępne narzędzie + +Oto wszystkie narzędzia, które można sterować za pomocą konfiguracji trybunałów. + +| Narzędzie | Opis | +| ----------- | ------------------------------------- | +| `bash` | Wykonaj polecenia powłoki | +| `edit` | Modyfikuj istniejące pliki | +| `write` | Utwórz nowe pliki | +| `read` | Przeczytaj zawartość pliku | +| `grep` | Wyszukaj zawartość pliku | +| `glob` | Znajdź pliki według wzorca | +| `list` | Lista zawartości katalogu | +| `patch` | Zastosuj poprawki do plików | +| `todowrite` | Zarządzaj listami rzeczy do wykonania | +| `todoread` | Przeczytaj listy rzeczy do zrobienia | +| `webfetch` | Pobierz zawartość internetową | + +--- + +## Tryby niestandardowe + +Możesz stworzyć własny tryb prywatny, dodając je do konfiguracji. Oto zastosowanie obu rozwiązań: + +### Korzystanie z konfiguracji JSON + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Korzystanie z plików Markdown + +Utwórz pliki trybów w `.opencode/modes/` dla trybów zapisanych dla projektu lub `~/.config/opencode/modes/` dla trybów globalnych: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### Przypadki użycia + +Oto kilka typowych zastosowań dla różnych trybów. + +- **Tryb stosowania**: Pełne prace programistyczne z dostępnymi narzędziami +- **Tryb planowania**: Analiza i planowanie bez zmian +- **Wypróbuj**: Przegląd kodu z możliwością odczytu i narzędzi do dokumentacji +- **Spróbuj debugowania**: Koncentruje się na urządzeniu z dostępnymi narzędziami bash i odczytu +- **Tryb Dokumenty**: Zapisywanie dokumentacji przy użyciu operacji na plikach, ale bez oryginalnych systemów systemowych + +Może się również zdarzyć, że różne modele są dobre w różnych wersjach użycia. diff --git a/packages/web/src/content/docs/pl/network.mdx b/packages/web/src/content/docs/pl/network.mdx new file mode 100644 index 000000000..bbb6fc1eb --- /dev/null +++ b/packages/web/src/content/docs/pl/network.mdx @@ -0,0 +1,57 @@ +--- +title: Sieć +description: Skonfiguruj serwery proxy i certyfikaty uwierzytelniające. +--- + +OpenCode obsługa standardowego zmiennego proxy i certyfikatów dla usług sieciowych przedsiębiorstw. + +--- + +## Pełnomocnik + +OpenCode respektuje standardowe zmienne środowiskowe proxy. + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::caution +TUI komunikuje się z popularnym serwerem HTTP. Aby zapobiec łączem routingu, należy ominąć serwer proxy dla tego połączenia. +::: + +Możesz pozostawić port serwera i hosta za pomocą [flaga CLI](/docs/cli#run). + +--- + +### Uwierzytelniać + +Jeśli Twój serwer proxy wymaga podstawowego uwierzytelniania, dołącz dane uwierzytelniające w adresie URL. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::caution +Unikaj kodowania haseł na stałe. Użyj testów kontrolnych lub oprogramowania poświadczeń. +::: + +W przypadku serwera proxy zaawansowanego uwierzytelniania, jak NTLM lub Kerberos, dostęp do bram LLM, który umożliwia uwierzytelnianie. + +--- + +## Certyfikaty niestandardowe + +Jeśli Twoje przedsiębiorstwo korzysta z niestandardowych usług, urzędów dostępu do HTTPS, skonfiguruj OpenCode tak, aby im ufać. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +Działają tylko w przypadku proxy, jak i bezpośredniego dostępu do API. diff --git a/packages/web/src/content/docs/pl/permissions.mdx b/packages/web/src/content/docs/pl/permissions.mdx new file mode 100644 index 000000000..d824a2ec5 --- /dev/null +++ b/packages/web/src/content/docs/pl/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: Uprawnienia +description: Kontroluj, które Akcje wymagają zatwierdzenia do uruchomienia. +--- + +OpenCode używa `permission`, aby uniknąć, czy dana akcja została wykonana automatycznie, zachowana monit lub została zablokowana. + +Od `v1.1.1` starsza stworzona logiczna `tools` jest przestarzała i została stworzona scalona z `permission`. Stara wersja `tools` jest nadal obsługiwana w celu zapewnienia zgodności wstecznej. + +--- + +## Działania + +Każda reguła uprawnień skutkuje jedną z: + +- `"allow"` — uruchamiany bez zgody +- `"ask"` — monit o zatwierdzenie +- `"deny"` — zablokuj akcję + +--- + +## Konfiguracja + +Możesz zainstalować uprawnienia globalnie (za pomocą `*`) i znajdującego się w nim narzędzia. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +Możesz także zainstalować wszystkie uprawnienia na raz: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## Szczegółowe reguły (składnia obiektu) + +Można skorzystać z różnych działań, które zależą od danych użytkowych. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +Reguły są zalecane na podstawie odpowiedniego wzorca, przy czym **ostatnia wynikaca reguła wygrywa**. Powszechnym wzorcem jest umieszczenie na pierwszym miejscu odpowiedniego catch-all `"*"`, a po bardziej szczegółowe zasady. + +### Symbole wieloznaczne + +Wzorce uprawnień z prostych dopasowywania symboli wieloznacznych: + +- `*` dopasowuje zero lub więcej dowolnego znaku +- `?` odpowiada dokładnie jednemu znakowi +- Wszystkie pozostałe znaki pasują dosłownie + +### Rozszerzenie katalogu domowego + +Możesz używać `~` lub `$HOME` na początku wzorca, aby zastosować się do swojego katalogu domowego. Jest to szczególnie szczególne w przypadku reguły [`external_directory`](#external-directories). + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### Katalogi zewnętrzne + +Użycie `external_directory`, aby zezwolić na wywołanie narzędzia, które obsługuje obsługę poza katalogiem roboczym, z uruchomieniem OpenCode. Dotyczy każdego narzędzia, które jako dane wejściowe zostało przyjęte (na przykład `read`, `edit`, `list`, `glob`, `grep` i wiele założycieli `bash`). + +Rozszerzenie domu (jak `~/...`) wpływa tylko na sposób za zwyczajowy wzorca. Nie powoduje to, że strategie zewnętrzne stają się stosowane przez `external_directory`. + +Na przykład umożliwia dostęp do wszystkiego pod `~/projects/personal/`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +Każdy dopuszczony tutaj katalog jest dziedziczy tych samych ustawień, co dostęp do obszaru roboczego. Ponieważ [`read` ma wartość domyślną `allow`](#defaults), odczyty są również dostępne dla wpisów poniżej `external_directory`, chyba że zagłębione. Dodaj dodatkowe rozwiązanie, kiedy narzędzie powinno być rozwiązaniem w tych ścieżkach, np. blokowanie edycji przy zachowaniu odczytów: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +Skoncentruj listę na zaufanych ścieżkach i dodaj dodatkowe zezwolenie lub odmowę, jeśli jest potrzebne w innych narzędziach (na przykład `bash`). + +--- + +## Dostępne uprawnienia + +Uprawnienia OpenCode są określane na podstawie nazwy narzędzia i kilku zabezpieczeń: + +- `read` — odczyt pliku (odpowiada ścieżce pliku) +- `edit` — wszystkie modyfikacje plików (obejmuje `edit`, `write`, `patch`, `multiedit`) +- `glob` — maglowanie plików (pasuje do wzorców globowania) +- `grep` — wyszukiwanie treści (pasuje do wzorca regularnego) +- `list` — wyświetlanie listy plików w katalogu (pasuje do katalogu) +- `bash` — uruchamianie poleceń powłoki (pasuje do poleceń przeanalizowanych, takich jak `git status --porcelain`) +- `task` — uruchamianie podagentów (odpowiada typowi podagenta) +- `skill` — ładowanie umiejętności (pasuje do nazwy umiejętności) +- `lsp` — uruchamianie zapytań LSP (obecnie nieszczegółowych) +- `todoread`, `todowrite` — czytanie/aktualizacja list rzeczy do wykonania +- `webfetch` — pobieranie adresu URL (pasuje do adresu URL) +- `websearch`, `codesearch` — wyszukiwanie sieci/kodu (pasuje do zapytań) +- `external_directory` — wywoływacz, gdy narzędzie jest dostępne poza katalogiem roboczym projektu +- `doom_loop` — wyzwalane, gdy samo wywołanie narzędzia zostanie powtórzone 3 razy z tymi samymi danymi podstawowymi + +--- + +## Domyślne + +Jeżeli nic nie jest określone, OpenCode zostanie uruchomione od dopuszczalnych rozwiązań diagnostycznych: + +- Dostępne uprawnienia ma wartość domyślną `"allow"`. +- `doom_loop` i `external_directory` zamek ma wartość `"ask"`. +- `read` do `"allow"`, ale pliki `.env` są odrzucane: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## Co robi „Zapytaj”. + +Gdy OpenCode poprosi o zatwierdzenie, interfejs użytkownika oferujący trzy wyniki: + +- `once` — zatwierdź tylko tę prośbę +- `always` — zastosowanie, które następuje po zastosowaniu sugerowanych wzorców (przez następczą bieżącą sesję OpenCode) +- `reject` — odrzucić + +Zestaw wzorców, które `always` zatwierdziłby, jest udostępniony przez narzędzie (na przykładzie zatwierdzenia bash zazwyczaj umieszczają na częstotliwości bezpiecznej prefiksy polecenia, takie jak `git status*`). + +--- + +## Agenci + +Można uzyskać dostęp do poszczególnych agentów. Uprawnienia agenta są skalowane z konfiguracją globalną, a następnie agenta ma pierwszeństwo. [Dowiedz się więcej](/docs/agents#permissions) o prawach agenta. + +:::note +Bardziej szczegółowe przykłady dopasowywania wzorców można znaleźć w sekcji [Reguły szczegółowe (składnia obiektu) (#granular-rules-object-syntax) powyżej. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +Możesz także mieć pozwolenie na agenta w Markdown: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tip +zastosowanie dopasowywania wzorców dla pierwotnych z argumentami. `"grep *"` pozwala na `grep pattern file.txt`, podczas gdy sam `"grep"` blokuje to. Polecenia takie jak `git status` w przypadku postępowania dyscyplinarnego, ale ostatecznego zastosowania (np. `"git status *"`) podczas stosowania argumentów. +::: diff --git a/packages/web/src/content/docs/pl/plugins.mdx b/packages/web/src/content/docs/pl/plugins.mdx new file mode 100644 index 000000000..8747c1048 --- /dev/null +++ b/packages/web/src/content/docs/pl/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: Wtyczki +description: Napisz własną wtyczkę, aby rozszerzyć OpenCode. +--- + +Wtyczki umożliwiające wyłączenie OpenCode poprzez podjęcie różnych zdarzeń i zachowanie. Można utworzyć wtyczkę, aby sprawdzić nowe funkcje, integrować się z usługami lub sprawdzaniem zachowania OpenCode. + +Aby znaleźć się z przykładami, przejrzyj [wtyczki](/docs/ecosystem#plugins) utworzone przez społeczność. + +--- + +## użyj wtyczki + +Istnieją dwa sposoby ładowania wtyczek. + +--- + +### Z plików lokalnych + +Miejsce plików JavaScript lub TypeScript w katalogu wtyczki. + +- `.opencode/plugins/` - Wtyczki na poziomie projektu +- `~/.config/opencode/plugins/` - Wtyczki globalne + +Pliki w tych katalogach są automatycznie ładowane podczas uruchamiania. + +--- + +### Z npm + +szczegółowy pakiet npm w pliku konfiguracyjnym. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +Obsługiwane są zarówno pakiety zwykłe, jak i pakiety npm o określonym zakresie. + +Przeglądaj dostępną wtyczkę w [ekosystemie](/docs/ecosystem#plugins). + +--- + +### Sposób instalacji wtyczek + +**wtyczki npm** są instalowane automatycznie przy użyciu Bun podczas uruchamiania. Pakiety i ich zależności są buforowane w `~/.cache/opencode/node_modules/`. + +**Wtyczki lokalne** są ładowane bezpośrednio z katalogu wtyczek. Aby uzyskać dostęp do zewnętrznych pakietów, musisz zainstalować `package.json` w swoim katalogu konfiguracyjnym (zobacz [Zależności](#dependencies)) lub opublikować wtyczkę w npm i [dodaj ją do swojej konfiguracji](/docs/config#plugins). + +--- + +### Załaduj zamówienie + +Wtyczki są ładowane ze wszystkich źródeł, a wszystkie hooki napisane po kolei. Kolejność ładowania do: + +1. Konfiguracja globalna (`~/.config/opencode/opencode.json`) +2. Konfiguracja projektu (`opencode.json`) +3. Globalny katalog wtyczek (`~/.config/opencode/plugins/`) +4. Katalog wtyczek projektu (`.opencode/plugins/`) + +Zduplikowane pakiety npm o tej samej nazwie i wersji są ładowane raz. Równie ważny jest dostęp lokalny i zewnętrzny npm o dodatkowych nazwach, które są zewnętrzne. + +--- + +## Utwórz wtyczkę + +Wtyczka do **moduł JavaScript/TypeScript**, który eksportuje jeden lub więcej wtyczek +funkcje. dostępna funkcja korzystania z obiektu kontekstu i głównego obiektu hooks. + +--- + +### Zależności + +Lokalne narzędzie i narzędzie, które można wykorzystać z zewnętrznych pakietów npm. Dodaj `package.json` do swojego katalogu konfiguracyjnego z zależnościami. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode uruchomienie `bun install` przy uruchomieniu, aby je uruchomić. Twoje dodatkowe funkcje będą dostępne po zaimportowaniu. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### Podstawowa struktura + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +Funkcja dostępu do: + +- `project`: Aktualne informacje o projekcie. +- `directory`: Bieżący katalog roboczy. +- `worktree`: Ścieżka eksploatacyjna Git. +- `client`: Klient SDK z otwartym kodem do sztucznej inteligencji. +- `$`: [API obudowy](https://bun.com/docs/runtime/shell) Buna do wykonywania oprogramowania. + +--- + +### Obsługa TypeScriptu + +W przypadku wtyczek TypeScript możesz importować typy z pakietu wtyczek: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### Wydarzenia + +Wtyczki mogą subskrybować zdarzenia, jak zastosować poniżej sekcji Przykłady. Oto lista różnych działań. + +#### Wydarzenia dowodzenia + +- `command.executed` + +#### Plik Wydarzenia + +- `file.edited` +- `file.watcher.updated` + +#### Wydarzenia instalacyjne + +- `installation.updated` + +#### Wydarzenia LSP + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### Wydarzenia w wiadomościach + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### Wydarzenia związane z uprawnieniami + +- `permission.asked` +- `permission.replied` + +#### Wydarzenia serwerowe + +- `server.connected` + +#### Wydarzenia sesyjne + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### Wydarzenia do zrobienia + +- `todo.updated` + +#### Wydarzenia powłoki + +- `shell.env` + +#### Wydarzenia narzędziowe + +- `tool.execute.after` +- `tool.execute.before` + +#### Wydarzenia TUI + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## Przykłady + +Oto kilka dostępnych wtyczek, które można udostępnić do kodu opencode. + +--- + +### Wysyłaj powiadomienia + +Wysyłaj powiadomienia, gdy wystąpią określone zdarzenia: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +Używamy `osascript` do uruchamiania AppleScript na macOS. Tutaj możesz przejść do wysyłania pozostałości. + +:::note +Jeśli korzystasz z aplikacji komputerowej OpenCode, może ona automatycznie wysłać wiadomość systemową, gdy odpowiedź jest gotowa lub gdy wystąpią błędy sesji. +::: + +--- + +### ochrona .env + +Zablokuj opencode czytanie plików `.env`: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### Wstrzyknij zmienne środowiskowe + +Wstrzyknij zmienne konsekwencje dla wszystkich wykonań (narzędzia AI i terminale użytkownika): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### Niestandardowe narzędzia + +Wtyczki mogą również dodawać niestandardowe narzędzia do opencode: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +Pomocnik `tool` tworzy narzędzie użytkowe, które może wywołać kod opencode. Pobierane schematu Zoda i narzędzie wyszukiwania za pomocą: + +- `description`: Co robi do narzędzia +- `args`: Schemat Zoda dla narzędzi argumentów +- `execute`: Funkcja uruchamiania po wywołaniu narzędzia + +Twoje narzędzie będzie dostępne dla otwartego kodu wraz z narzędziami użytkowymi. + +--- + +### Wycięcie lasu + +użyj `client.app.log()` zamiast `console.log` do rejestracji strukturalnego: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +Poziomy: `debug`, `info`, `warn`, `error`. Aby uzyskać szczegółowe informacje, zobacz [dokumentację pakietu SDK](https://opencode.ai/docs/sdk). + +--- + +### Haki zagęszczające + +Dostosuj kontekst dołączony podczas kompaktowania sesji: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +Hak `experimental.session.compacting` jest uruchamiany, zanim LLM wygeneruje podsumowanie kontynuacji. go, aby wstrzyknąć kontekst kontekstu dla domeny, której nie dostrzeżono przez domyślny monit o zagęszczenie. + +Można także umieścić kompletny monit o zagęszczenie, ustawiając `output.prompt`: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +Gdy urządzenie jest `output.prompt`, jest całkowicie dostępne na domyślnym monit o zagęszczanie. Tablica `output.context` jest w tym przypadku poniesiona. diff --git a/packages/web/src/content/docs/pl/providers.mdx b/packages/web/src/content/docs/pl/providers.mdx new file mode 100644 index 000000000..55364dd29 --- /dev/null +++ b/packages/web/src/content/docs/pl/providers.mdx @@ -0,0 +1,1888 @@ +--- +title: Providers +description: Korzystanie z dowolnego dostawcy LLM w OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode używa [AI SDK](https://ai-sdk.dev/) i [Models.dev](https://models.dev) do obsługi **ponad 75 dostawców LLM** i obsługuje uruchamianie modeli lokalnych. + +Aby dodać dostawcę należy: + +1. Dodaj klucze API dla dostawcy za pomocą komendy `/connect`. +2. Skonfiguruj dostawcę w konfiguracji OpenCode. + +--- + +### Credentials + +Po dodaniu kluczy API dostawcy za pomocą polecenia `/connect` są one przechowywane +in `~/.local/share/opencode/auth.json`. + +--- + +### Config + +Możesz dostosować dostawców za pomocą sekcji `provider` w swoim OpenCode +config. + +--- + +#### Base URL + +Możesz dostosować podstawowy adres URL dla dowolnego dostawcy, ustawiając opcję `baseURL`. Jest to przydatne podczas korzystania z usług proxy lub niestandardowych punktów końcowych. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen to lista modeli dostarczonych przez zespół OpenCode, które zostały +przetestowane i zweryfikowane, aby dobrze współpracować z OpenCode. [Dowiedz się więcej](/docs/zen). + +:::tip +Jeśli jesteś nowy, zalecamy rozpoczęcie od OpenCode Zen. +::: + +1. Uruchom polecenie `/connect` w TUI, wybierz opencode i przejdź do [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Zaloguj się, dodaj szczegóły rozliczeniowe i skopiuj klucz API. + +3. Wklej swój klucz API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom `/models` w TUI, aby zobaczyć listę zalecanych przez nas modeli. + + ```txt + /models + ``` + +Działa jak każdy inny dostawca w OpenCode i jest całkowicie opcjonalny w użyciu. + +--- + +## Directory + +Przyjrzyjmy się szczegółowo niektórym dostawcom. Jeśli chcesz dodać dostawcę do +listę, możesz otworzyć PR. + +:::note +Nie widzisz tutaj dostawcy? Prześlij PR. +::: + +--- + +### 302.AI + +1. Przejdź do [konsoli 302.AI](https://302.ai/), utwórz konto i wygeneruj klucz API. + +2. Uruchom komendę `/connect` i wyszukaj **302.AI**. + + ```txt + /connect + ``` + +3. Wpisz swój klucz API 302.AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom komendę `/models`, aby wybrać model. + + ```txt + /models + ``` + +--- + +### Amazon Bedrock + +Aby używać Amazon Bedrock z OpenCode: + +1. Przejdź do **Katalogu modeli** w konsoli Amazon Bedrock i poproś + dostęp do wybranych modeli. + + :::tip + Musisz mieć dostęp do żądanego modelu w Amazon Bedrock. + ::: + +2. **Skonfiguruj uwierzytelnianie** przy użyciu jednej z następujących metod: + + #### Zmienne środowiskowe (Szybki start) + + Set one of these environment variables while running opencode: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + Lub dodaj je do swojego profilu bash: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### Configuration File (Recommended) + + W przypadku konfiguracji specyficznej dla projektu lub trwałej użyj `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **Dostępne opcje:** + - `region` - AWS region (e.g., `us-east-1`, `eu-west-1`) + - `profile` - AWS named profile from `~/.aws/credentials` + - `endpoint` — niestandardowy adres URL punktu końcowego dla punktów końcowych VPC (alias dla ogólnej opcji `baseURL`) + + :::tip + Configuration file options take precedence over environment variables. + ::: + + #### Advanced: VPC Endpoints + + Jeśli używasz punktów końcowych VPC dla Bedrock: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::note + Opcja `endpoint` jest aliasem ogólnej opcji `baseURL`, używając terminologii specyficznej dla AWS. Jeśli określono zarówno `endpoint`, jak i `baseURL`, pierwszeństwo ma `endpoint`. + ::: + + #### Authentication Methods + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: Utwórz użytkownika IAM i wygeneruj klucze dostępu w konsoli AWS + - **`AWS_PROFILE`**: Użyj nazwanych profili z `~/.aws/credentials`. Najpierw skonfiguruj za pomocą `aws configure --profile my-profile` lub `aws sso login` + - **`AWS_BEARER_TOKEN_BEDROCK`**: Wygeneruj długoterminowe klucze API z konsoli Amazon Bedrock + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: Dla EKS IRSA (Role IAM dla kont usług) lub innych środowisk Kubernetes z federacją OIDC. Te zmienne środowiskowe są automatycznie wstrzykiwane przez Kubernetes podczas korzystania z adnotacji konta usługi. + + #### Authentication Precedence + + Amazon Bedrock wykorzystuje następujący priorytet uwierzytelniania: + 1. **Token nośnika** - zmienna środowiskowa `AWS_BEARER_TOKEN_BEDROCK` lub token z komendy `/connect` + 2. **AWS Credential Chain** - Profile, access keys, shared credentials, IAM roles, Web Identity Tokens (EKS IRSA), instance metadata + + :::note + When a bearer token is set (via `/connect` or `AWS_BEARER_TOKEN_BEDROCK`), it takes precedence over all AWS credential methods including configured profiles. + ::: + +3. Uruchom komendę `/models`, aby wybrać żądany model. + + ```txt + /models + ``` + +:::note +W przypadku niestandardowych profili wnioskowania użyj nazwy modelu i dostawcy w kluczu i ustaw właściwość `id` na wartość arn. Zapewnia to prawidłowe buforowanie: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### Anthropic + +1. Po zarejestrowaniu się uruchom komendę `/connect` i wybierz opcję Anthropic. + + ```txt + /connect + ``` + +2. Tutaj możesz wybrać opcję **Claude Pro/Max**, co spowoduje otwarcie przeglądarki + i poproś o uwierzytelnienie. + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. Teraz wszystkie modele antropiczne powinny być dostępne po użyciu polecenia `/models`. + + ```txt + /models + ``` + +:::info +Korzystanie z subskrypcji Claude Pro/Max w OpenCode nie jest oficjalnie obsługiwane przez [Anthropic](https://anthropic.com). +::: + +##### Using API keys + +Możesz także wybrać opcję **Utwórz klucz API**, jeśli nie masz subskrypcji Pro/Max. Otworzy się także Twoja przeglądarka i poprosi Cię o zalogowanie się do Anthropic i poda kod, który możesz wkleić w terminalu. + +Lub jeśli masz już klucz API, możesz wybrać **Wprowadź klucz API ręcznie** i wkleić go w terminalu. + +--- + +### Azure OpenAI + +:::note +Jeśli napotkasz błędy „Przykro mi, ale nie mogę pomóc w tej prośbie”, spróbuj zmienić filtr zawartości z **DefaultV2** na **Default** w zasobie platformy Azure. +::: + +1. Przejdź do [Azure portal](https://portal.azure.com/) i utwórz zasób **Azure OpenAI**. Będziesz potrzebować: + - **Nazwa zasobu**: staje się częścią punktu końcowego interfejsu API (`https://RESOURCE_NAME.openai.azure.com/`) + - **Klucz API**: `KEY 1` lub `KEY 2` z Twojego zasobu + +2. Przejdź do [Azure AI Foundry](https://ai.azure.com/) i wdróż model. + + :::note + Aby kod opencode działał poprawnie, nazwa wdrożenia musi być zgodna z nazwą modelu. + ::: + +3. Uruchom polecenie `/connect` i wyszukaj **Azure**. + + ```txt + /connect + ``` + +4. Wpisz swój klucz API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Ustaw nazwę zasobu jako zmienną środowiskową: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + Lub dodaj go do swojego profilu bash: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. Uruchom komendę `/models`, aby wybrać wdrożony model. + + ```txt + /models + ``` + +--- + +### Azure Cognitive Services + +1. Przejdź do [Azure portal](https://portal.azure.com/) i utwórz zasób **Azure OpenAI**. Będziesz potrzebować: + - **Nazwa zasobu**: staje się częścią punktu końcowego interfejsu API (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) + - **Klucz API**: `KEY 1` lub `KEY 2` z Twojego zasobu + +2. Przejdź do [Azure AI Foundry](https://ai.azure.com/) i wdróż model. + + :::note + Aby kod opencode działał poprawnie, nazwa wdrożenia musi być zgodna z nazwą modelu. + ::: + +3. Uruchom polecenie `/connect` i wyszukaj **Azure Cognitive Services**. + + ```txt + /connect + ``` + +4. Wpisz swój klucz API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Ustaw nazwę zasobu jako zmienną środowiskową: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + Lub dodaj go do swojego profilu bash: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. Uruchom komendę `/models`, aby wybrać wdrożony model. + + ```txt + /models + ``` + +--- + +### Baseten + +1. Udaj się do [Baseten](https://app.baseten.co/), utwórz konto i wygeneruj klucz API. + +2. Uruchom komendę `/connect` i wyszukaj **Baseten**. + + ```txt + /connect + ``` + +3. Wprowadź swój klucz API Baseten. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom komendę `/models`, aby wybrać model. + + ```txt + /models + ``` + +--- + +### Cerebras + +1. Przejdź do [konsoli Cerebras](https://inference.cerebras.ai/), utwórz konto i wygeneruj klucz API. + +2. Uruchom komendę `/connect` i wyszukaj **Cerebras**. + + ```txt + /connect + ``` + +3. Wprowadź swój klucz API Cerebras. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać model taki jak _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### Cloudflare AI Gateway + +Cloudflare AI Gateway umożliwia dostęp do modeli z OpenAI, Anthropic, Workers AI i innych za pośrednictwem ujednoliconego punktu końcowego. Dzięki [Ujednoliconemu rozliczeniu](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) nie potrzebujesz oddzielnych kluczy API dla każdego dostawcy. + +1. Przejdź do [panelu Cloudflare](https://dash.cloudflare.com/), przejdź do **AI** > **AI Gateway** i utwórz nową bramę. + +2. Ustaw identyfikator konta i identyfikator bramy jako zmienne środowiskowe. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. Uruchom polecenie `/connect` i wyszukaj **Cloudflare AI Gateway**. + + ```txt + /connect + ``` + +4. Wprowadź swój token API Cloudflare. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + Or set it as an environment variable. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. Uruchom komendę `/models`, aby wybrać model. + + ```txt + /models + ``` + + Możesz także dodawać modele za pomocą konfiguracji opencode. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### Cortecs + +1. Przejdź do [konsoli Cortecs](https://cortecs.ai/), utwórz konto i wygeneruj klucz API. + +2. Uruchom komendę `/connect` i wyszukaj **Cortecs**. + + ```txt + /connect + ``` + +3. Wprowadź klucz API Cortecs. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać model taki jak _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### DeepSeek + +1. Przejdź do [konsoli DeepSeek](https://platform.deepseek.com/), utwórz konto i kliknij **Utwórz nowy klucz API**. + +2. Uruchom polecenie `/connect` i wyszukaj **DeepSeek**. + + ```txt + /connect + ``` + +3. Wprowadź klucz API DeepSeek. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać model DeepSeek, np. _DeepSeek Reasoner_. + + ```txt + /models + ``` + +--- + +### Deep Infra + +1. Przejdź do [panelu Deep Infra](https://deepinfra.com/dash), utwórz konto i wygeneruj klucz API. + +2. Uruchom komendę `/connect` i wyszukaj **Deep Infra**. + + ```txt + /connect + ``` + +3. Wprowadź swój klucz API Deep Infra. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom komendę `/models`, aby wybrać model. + + ```txt + /models + ``` + +--- + +### Firmware + +1. Przejdź do [panelu oprogramowania sprzętowego](https://app.firmware.ai/signup), utwórz konto i wygeneruj klucz API. + +2. Uruchom polecenie `/connect` i wyszukaj **Oprogramowanie sprzętowe**. + + ```txt + /connect + ``` + +3. Wprowadź klucz API oprogramowania układowego. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom komendę `/models`, aby wybrać model. + + ```txt + /models + ``` + +--- + +### Fireworks AI + +1. Przejdź do [konsoli Fireworks AI](https://app.fireworks.ai/), utwórz konto i kliknij **Utwórz klucz API**. + +2. Uruchom polecenie `/connect` i wyszukaj **Fireworks AI**. + + ```txt + /connect + ``` + +3. Wprowadź klucz API programu Fireworks AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać model taki jak _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### GitLab Duo + +GitLab Duo zapewnia czat agentowy oparty na sztucznej inteligencji z natywnymi możliwościami wywoływania narzędzi za pośrednictwem Anthropic proxy GitLab. + +1. Uruchom komendę `/connect` i wybierz GitLab. + + ```txt + /connect + ``` + +2. Wybierz metodę uwierzytelniania: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### Using OAuth (Recommended) + + Wybierz **OAuth**, a Twoja przeglądarka otworzy się w celu autoryzacji. + + #### Using Personal Access Token + 1. Przejdź do [Ustawienia użytkownika GitLab > Tokeny dostępu](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. Click **Add new token** + 3. Name: `OpenCode`, Scopes: `api` + 4. Skopiuj token (zaczyna się od `glpat-`) + 5. Wpisz go w terminalu + +3. Uruchom komendę `/models`, aby zobaczyć dostępne modele. + + ```txt + /models + ``` + + Dostępne są trzy modele oparte na Claude: + - **duo-chat-haiku-4-5** (Domyślnie) - Szybkie odpowiedzi dla szybkich zadań + - **duo-chat-sonnet-4-5** - Zrównoważona wydajność dla większości przepływów pracy + - **duo-chat-opus-4-5** - Najbardziej zdolny do złożonej analizy + +:::note +Jeśli nie chcesz, możesz także określić zmienną środowiskową „GITLAB_TOKEN”. +to store token in opencode auth storage. +::: + +##### Self-Hosted GitLab + +:::note[compliance note] +OpenCode używa małego modelu do niektórych zadań AI, takich jak generowanie tytułu sesji. +Domyślnie jest skonfigurowany do używania gpt-5-nano, hostowanego przez Zen. Aby zablokować OpenCode +aby używać tylko własnej instancji hostowanej przez GitLab, dodaj następujące elementy do pliku +`opencode.json` plik. Zalecane jest również wyłączenie udostępniania sesji. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +W przypadku samodzielnie hostowanych instancji GitLab: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +Jeśli w Twojej instancji działa niestandardowa brama AI: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +Lub dodaj do swojego profilu bash: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +Twój administrator GitLab musi włączyć następujące opcje: + +1. [Platforma Duo Agent](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) dla użytkownika, grupy lub instancji +2. Feature flags (via Rails console): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### OAuth dla instancji hostowanych samodzielnie + +Aby Oauth mógł działać w przypadku Twojej instancji hostowanej samodzielnie, musisz utworzyć +nową aplikację (Ustawienia → Aplikacje) z +Adres URL wywołania zwrotnego `http://127.0.0.1:8080/callback` i następujące zakresy: + +- api (Uzyskaj dostęp do API w swoim imieniu) +- read_user (Przeczytaj swoje dane osobowe) +- read_repository (umożliwia dostęp do repozytorium tylko do odczytu) + +Then expose application ID as environment variable: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +More documentation on [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth) homepage. + +##### Configuration + +Customize through `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API Tools (Optional, but highly recommended) + +To access GitLab tools (merge requests, issues, pipelines, CI/CD, etc.): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +Ta wtyczka zapewnia kompleksowe możliwości zarządzania repozytorium GitLab, w tym recenzje MR, śledzenie problemów, monitorowanie rurociągów i inne. + +--- + +### GitHub Copilot + +Aby korzystać z subskrypcji GitHub Copilot z kodem opencode: + +:::note +Niektóre modele mogą wymagać [subskrypcji Pro+](https://github.com/features/copilot/plans), aby z nich korzystać. + +Niektóre modele należy włączyć ręcznie w [ustawieniach GitHub Copilot](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. Uruchom komendę `/connect` i wyszukaj GitHub Copilot. + + ```txt + /connect + ``` + +2. Przejdź do [github.com/login/device](https://github.com/login/device) i wpisz kod. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. Teraz uruchom polecenie `/models`, aby wybrać żądany model. + + ```txt + /models + ``` + +--- + +### Google Vertex AI + +Aby używać Google Vertex AI z OpenCode: + +1. Przejdź do **Model Garden** w Google Cloud Console i sprawdź + modele dostępne w Twoim regionie. + + :::note + Musisz mieć projekt Google Cloud z włączonym interfejsem API Vertex AI. + ::: + +2. Ustaw wymagane zmienne środowiskowe: + - `GOOGLE_CLOUD_PROJECT`: identyfikator Twojego projektu Google Cloud + - `VERTEX_LOCATION` (opcjonalnie): region Vertex AI (domyślnie `global`) + - Authentication (choose one): + - `GOOGLE_APPLICATION_CREDENTIALS`: Ścieżka do pliku klucza JSON konta usługi + - Uwierzytelnij się za pomocą interfejsu CLI gcloud: `gcloud auth application-default login` + + Set them while running opencode. + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + Lub dodaj je do swojego profilu bash. + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::tip +Region `global` poprawia dostępność i zmniejsza liczbę błędów bez dodatkowych kosztów. Użyj regionalnych punktów końcowych (np. `us-central1`) w celu spełnienia wymagań dotyczących miejsca przechowywania danych. [Dowiedz się więcej](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. Uruchom komendę `/models`, aby wybrać żądany model. + + ```txt + /models + ``` + +--- + +### Groq + +1. Przejdź do [konsoli Groq](https://console.groq.com/), kliknij **Utwórz klucz API** i skopiuj klucz. + +2. Uruchom komendę `/connect` i wyszukaj Groq. + + ```txt + /connect + ``` + +3. Wprowadź klucz API dla dostawcy. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać żądany. + + ```txt + /models + ``` + +--- + +### Hugging Face + +[Dostawcy wnioskowania o uścisku twarzy](https://huggingface.co/docs/inference-providers) zapewniają dostęp do otwartych modeli obsługiwanych przez ponad 17 dostawców. + +1. Przejdź do [Ustawień uścisku twarzy](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained), aby utworzyć token z uprawnieniami do wykonywania połączeń z dostawcami wnioskowania. + +2. Uruchom komendę `/connect` i wyszukaj **Przytulona twarz**. + + ```txt + /connect + ``` + +3. Wprowadź swój token Przytulającej Twarzy. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać model taki jak _Kimi-K2-Instruct_ lub _GLM-4.6_. + + ```txt + /models + ``` + +--- + +### Helicone + +[Helicone](https://helicone.ai) to platforma obserwowalności LLM, która zapewnia rejestrowanie, monitorowanie i analizy dla aplikacji AI. Helicone AI Gateway automatycznie kieruje Twoje żądania do odpowiedniego dostawcy w oparciu o model. + +1. Udaj się do [Helicone](https://helicone.ai), utwórz konto i wygeneruj klucz API ze swojego panelu. + +2. Uruchom komendę `/connect` i wyszukaj **Helicone**. + + ```txt + /connect + ``` + +3. Wprowadź swój klucz API Helicone. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom komendę `/models`, aby wybrać model. + + ```txt + /models + ``` + +Więcej dostawców i zaawansowanych funkcji, takich jak buforowanie i ograniczanie szybkości, znajdziesz w [dokumentacji Helicone](https://docs.helicone.ai). + +#### Optional Configs + +Jeśli zobaczysz funkcję lub model firmy Helicone, która nie jest konfigurowana automatycznie za pomocą kodu opencode, zawsze możesz ją skonfigurować samodzielnie. + +Oto [Katalog modeli Helicone](https://helicone.ai/models), będziesz go potrzebować, aby pobrać identyfikatory modeli, które chcesz dodać. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### Custom Headers + +Helicone obsługuje niestandardowe nagłówki dla funkcji takich jak buforowanie, śledzenie użytkowników i zarządzanie sesjami. Dodaj je do konfiguracji dostawcy za pomocą `options.headers`: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### Śledzenie sesji + +Funkcja [Sesje](https://docs.helicone.ai/features/sessions) firmy Helicone umożliwia grupowanie powiązanych żądań LLM. Użyj wtyczki [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session), aby automatycznie rejestrować każdą konwersację OpenCode jako sesję w Helicone. + +```bash +npm install -g opencode-helicone-session +``` + +Dodaj go do swojej konfiguracji. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +Wtyczka wstawia nagłówki `Helicone-Session-Id` i `Helicone-Session-Name` do Twoich żądań. Na stronie Sesje Helicone każda konwersacja OpenCode będzie wymieniona jako osobna sesja. + +##### Common Helicone headers + +| Header | Description | +| -------------------------- | ------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | Enable response caching (`true`/`false`) | +| `Helicone-User-Id` | Track metrics by user | +| `Helicone-Property-[Name]` | Add custom properties (e.g., `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | Powiąż żądania z wersjami podpowiedzi | + +Zobacz [Katalog nagłówków Helicone](https://docs.helicone.ai/helicone-headers/header-directory), aby poznać wszystkie dostępne nagłówki. + +--- + +### llama.cpp + +Możesz skonfigurować kod otwarty tak, aby korzystał z modeli lokalnych, za pomocą narzędzia llama-server [llama.cpp](https://github.com/ggml-org/llama.cpp) + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +W tym przykładzie: + +- `llama.cpp` to niestandardowy identyfikator dostawcy. Może to być dowolny ciąg znaków. +- `npm` określa pakiet, który ma być używany dla tego dostawcy. Tutaj `@ai-sdk/openai-compatible` jest używany dla dowolnego interfejsu API zgodnego z OpenAI. +- `name` to nazwa wyświetlana dostawcy w interfejsie użytkownika. +- `options.baseURL` jest punktem końcowym serwera lokalnego. +- `models` to mapa identyfikatorów modeli do ich konfiguracji. Nazwa modelu zostanie wyświetlona na liście wyboru modelu. + +--- + +### IO.NET + +IO.NET oferuje 17 modeli zoptymalizowanych pod kątem różnych zastosowań: + +1. Przejdź do [konsoli IO.NET](https://ai.io.net/), utwórz konto i wygeneruj klucz API. + +2. Uruchom komendę `/connect` i wyszukaj **IO.NET**. + + ```txt + /connect + ``` + +3. Wprowadź swój klucz API IO.NET. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom komendę `/models`, aby wybrać model. + + ```txt + /models + ``` + +--- + +### LM Studio + +Możesz skonfigurować kod otwarty tak, aby korzystał z modeli lokalnych poprzez LM Studio. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +W tym przykładzie: + +- `lmstudio` to niestandardowy identyfikator dostawcy. Może to być dowolny ciąg znaków. +- `npm` określa pakiet, który ma być używany dla tego dostawcy. Tutaj `@ai-sdk/openai-compatible` jest używany dla dowolnego interfejsu API zgodnego z OpenAI. +- `name` to nazwa wyświetlana dostawcy w interfejsie użytkownika. +- `options.baseURL` jest punktem końcowym serwera lokalnego. +- `models` to mapa identyfikatorów modeli do ich konfiguracji. Nazwa modelu zostanie wyświetlona na liście wyboru modelu. + +--- + +### Moonshot AI + +Aby użyć Kimi K2 z Moonshot AI: + +1. Przejdź do [konsoli Moonshot AI](https://platform.moonshot.ai/console), utwórz konto i kliknij **Utwórz klucz API**. + +2. Uruchom polecenie `/connect` i wyszukaj **Moonshot AI**. + + ```txt + /connect + ``` + +3. Wprowadź klucz API Moonshot. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom komendę `/models`, aby wybrać _Kimi K2_. + + ```txt + /models + ``` + +--- + +### MiniMax + +1. Przejdź do [Konsoli API MiniMax](https://platform.minimax.io/login), utwórz konto i wygeneruj klucz API. + +2. Uruchom komendę `/connect` i wyszukaj **MiniMax**. + + ```txt + /connect + ``` + +3. Wprowadź swój klucz API MiniMax. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom komendę `/models`, aby wybrać model taki jak _M2.1_. + + ```txt + /models + ``` + +--- + +### Nebius Token Factory + +1. Przejdź do [konsoli Nebius Token Factory](https://tokenfactory.nebius.com/), utwórz konto i kliknij **Dodaj klucz**. + +2. Uruchom komendę `/connect` i wyszukaj **Fabrykę tokenów Nebius**. + + ```txt + /connect + ``` + +3. Wprowadź klucz API Nebius Token Factory. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać model taki jak _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Ollama + +Możesz skonfigurować kod otwarty tak, aby korzystał z modeli lokalnych poprzez Ollamę. + +:::tip +Ollama może automatycznie skonfigurować się pod kątem OpenCode. Aby uzyskać szczegółowe informacje, zobacz [dokumentację integracji Ollama](https://docs.ollama.com/integrations/opencode). +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +W tym przykładzie: + +- `ollama` to niestandardowy identyfikator dostawcy. Może to być dowolny ciąg znaków. +- `npm` określa pakiet, który ma być używany dla tego dostawcy. Tutaj `@ai-sdk/openai-compatible` jest używany dla dowolnego interfejsu API zgodnego z OpenAI. +- `name` to nazwa wyświetlana dostawcy w interfejsie użytkownika. +- `options.baseURL` jest punktem końcowym serwera lokalnego. +- `models` to mapa identyfikatorów modeli do ich konfiguracji. Nazwa modelu zostanie wyświetlona na liście wyboru modelu. + +:::tip +Jeśli wywołania narzędzi nie działają, spróbuj zwiększyć `num_ctx` w Ollama. Zacznij około 16 tys. - 32 tys. +::: + +--- + +### Ollama Cloud + +Aby korzystać z Ollama Cloud z OpenCode: + +1. Udaj się do [https://ollama.com/](https://ollama.com/) i zaloguj się lub utwórz konto. + +2. Przejdź do **Ustawienia** > **Klucze** i kliknij **Dodaj klucz API**, aby wygenerować nowy klucz API. + +3. Skopiuj klucz API do użycia w OpenCode. + +4. Uruchom polecenie `/connect` i wyszukaj **Ollama Cloud**. + + ```txt + /connect + ``` + +5. Wprowadź swój klucz API Ollama Cloud. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **Ważne**: Przed użyciem modeli chmurowych w OpenCode musisz pobrać informacje o modelu lokalnie: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. Uruchom polecenie `/models`, aby wybrać model Ollama Cloud. + + ```txt + /models + ``` + +--- + +### OpenAI + +Zalecamy zarejestrowanie się w [ChatGPT Plus lub Pro](https://chatgpt.com/pricing). + +1. Po zarejestrowaniu się uruchom komendę `/connect` i wybierz OpenAI. + + ```txt + /connect + ``` + +2. Tutaj możesz wybrać opcję **ChatGPT Plus/Pro**, co spowoduje otwarcie przeglądarki + i poproś o uwierzytelnienie. + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. Teraz wszystkie modele OpenAI powinny być dostępne po użyciu polecenia `/models`. + + ```txt + /models + ``` + +##### Using API keys + +Jeśli posiadasz już klucz API, możesz wybrać opcję **Wprowadź klucz API ręcznie** i wkleić go w terminalu. + +--- + +### OpenCode Zen + +OpenCode Zen to lista przetestowanych i zweryfikowanych modeli udostępniona przez zespół OpenCode. [Dowiedz się więcej](/docs/zen). + +1. Zaloguj się do **OpenCode Zen** i kliknij **Utwórz klucz API**. + +2. Uruchom polecenie `/connect` i wyszukaj **OpenCode Zen**. + + ```txt + /connect + ``` + +3. Wprowadź klucz API OpenCode. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać model taki jak _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### OpenRouter + +1. Przejdź do [panelu OpenRouter](https://openrouter.ai/settings/keys), kliknij **Utwórz klucz API** i skopiuj klucz. + +2. Uruchom komendę `/connect` i wyszukaj OpenRouter. + + ```txt + /connect + ``` + +3. Wprowadź klucz API dla dostawcy. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Wiele modeli OpenRouter jest domyślnie załadowanych fabrycznie. Uruchom komendę `/models`, aby wybrać ten, który chcesz. + + ```txt + /models + ``` + + Możesz także dodać dodatkowe modele za pomocą konfiguracji opencode. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. Możesz je także dostosować za pomocą konfiguracji opencode. Oto przykład określenia dostawcy + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP AI Core + +SAP AI Core zapewnia dostęp do ponad 40 modeli z OpenAI, Anthropic, Google, Amazon, Meta, Mistral i AI21 za pośrednictwem ujednoliconej platformy. + +1. Przejdź do [SAP BTP Cockpit](https://account.hana.ondemand.com/), przejdź do instancji usługi SAP AI Core i utwórz klucz usługi. + + :::tip + Klucz usługi to obiekt JSON zawierający `clientid`, `clientsecret`, `url` i `serviceurls.AI_API_URL`. Instancję AI Core znajdziesz w sekcji **Usługi** > **Instancje i subskrypcje** w Kokpicie BTP. + ::: + +2. Uruchom polecenie `/connect` i wyszukaj **SAP AI Core**. + + ```txt + /connect + ``` + +3. Wpisz swój klucz usługi JSON. + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + Lub ustaw zmienną środowiskową `AICORE_SERVICE_KEY`: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + Lub dodaj go do swojego profilu bash: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. Opcjonalnie ustaw identyfikator wdrożenia i grupę zasobów: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::note + Te ustawienia są opcjonalne i należy je skonfigurować zgodnie z konfiguracją SAP AI Core. + ::: + +5. Uruchom polecenie `/models`, aby wybrać spośród ponad 40 dostępnych modeli. + + ```txt + /models + ``` + +--- + +### OVHcloud AI Endpoints + +1. Przejdź do [panelu OVHcloud](https://ovh.com/manager). Przejdź do sekcji `Public Cloud`, `AI & Machine Learning` > `AI Endpoints` i na karcie `API Keys` kliknij **Utwórz nowy klucz API**. + +2. Uruchom polecenie `/connect` i wyszukaj **Punkty końcowe AI OVHcloud**. + + ```txt + /connect + ``` + +3. Wpisz klucz API punktów końcowych AI OVHcloud. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać model taki jak _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Scaleway + +Aby używać [generatywnych interfejsów API Scaleway](https://www.scaleway.com/en/docs/generative-apis/) z kodem Opencode: + +1. Przejdź do [Ustawień uprawnień konsoli Scaleway](https://console.scaleway.com/iam/api-keys), aby wygenerować nowy klucz API. + +2. Uruchom komendę `/connect` i wyszukaj **Scaleway**. + + ```txt + /connect + ``` + +3. Wprowadź swój klucz API Scaleway. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom komendę `/models`, aby wybrać model taki jak _devstral-2-123b-instruct-2512_ lub _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Together AI + +1. Przejdź do [konsoli Razem AI](https://api.together.ai), utwórz konto i kliknij **Dodaj klucz**. + +2. Uruchom komendę `/connect` i wyszukaj **Razem AI**. + + ```txt + /connect + ``` + +3. Wprowadź klucz API Together AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać model taki jak _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Venice AI + +1. Przejdź do [konsoli Venice AI](https://venice.ai), utwórz konto i wygeneruj klucz API. + +2. Uruchom polecenie `/connect` i wyszukaj **Venice AI**. + + ```txt + /connect + ``` + +3. Wprowadź klucz API Wenecji AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać model taki jak _Llama 3.3 70B_. + + ```txt + /models + ``` + +--- + +### Vercel AI Gateway + +Vercel AI Gateway umożliwia dostęp do modeli z OpenAI, Anthropic, Google, xAI i innych za pośrednictwem ujednoliconego punktu końcowego. Modele oferowane są po cenie katalogowej bez marży. + +1. Przejdź do [panelu Vercel](https://vercel.com/), przejdź do karty **AI Gateway** i kliknij **Klucze API**, aby utworzyć nowy klucz API. + +2. Uruchom polecenie `/connect` i wyszukaj **Vercel AI Gateway**. + + ```txt + /connect + ``` + +3. Wprowadź klucz API Vercel AI Gateway. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom komendę `/models`, aby wybrać model. + + ```txt + /models + ``` + +Możesz także dostosować modele za pomocą konfiguracji opencode. Oto przykład określenia kolejności routingu dostawcy. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +Some useful routing options: + +| Opcja | Opis | +| ------------------- | ---------------------------------------------------------------------------- | +| `order` | Sekwencja dostawcy do wypróbowania | +| `only` | Restrict to specific providers | +| `zeroDataRetention` | Korzystaj wyłącznie z dostawców, którzy nie mają zasad przechowywania danych | + +--- + +### xAI + +1. Przejdź do [konsoli xAI](https://console.x.ai/), utwórz konto i wygeneruj klucz API. + +2. Uruchom komendę `/connect` i wyszukaj **xAI**. + + ```txt + /connect + ``` + +3. Wprowadź swój klucz API xAI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom polecenie `/models`, aby wybrać model taki jak _Grok Beta_. + + ```txt + /models + ``` + +--- + +### Z.AI + +1. Przejdź do [konsoli API Z.AI](https://z.ai/manage-apikey/apikey-list), utwórz konto i kliknij **Utwórz nowy klucz API**. + +2. Uruchom komendę `/connect` i wyszukaj **Z.AI**. + + ```txt + /connect + ``` + + Jeżeli jesteś abonentem **Planu kodowania GLM**, wybierz **Plan kodowania Z.AI**. + +3. Wpisz swój klucz API Z.AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Uruchom komendę `/models`, aby wybrać model taki jak _GLM-4.7_. + + ```txt + /models + ``` + +--- + +### ZenMux + +1. Przejdź do [panelu ZenMux](https://zenmux.ai/settings/keys), kliknij **Utwórz klucz API** i skopiuj klucz. + +2. Uruchom polecenie `/connect` i wyszukaj ZenMux. + + ```txt + /connect + ``` + +3. Wprowadź klucz API dla dostawcy. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Wiele modeli ZenMux jest domyślnie załadowanych fabrycznie. Uruchom komendę `/models`, aby wybrać żądany model. + + ```txt + /models + ``` + + Możesz także dodać dodatkowe modele za pomocą konfiguracji opencode. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## Niestandardowy dostawca + +Aby dodać dowolnego dostawcę **kompatybilnego z OpenAI**, którego nie ma na liście w poleceniu `/connect`: + +:::tip +Możesz użyć dowolnego dostawcy kompatybilnego z OpenAI z otwartym kodem. Większość nowoczesnych dostawców sztucznej inteligencji oferuje interfejsy API kompatybilne z OpenAI. +::: + +1. Uruchom polecenie `/connect` i przewiń w dół do **Inne**. + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. Wprowadź unikalny identyfikator dostawcy. + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note + Wybierz niezapomniany identyfikator, użyjesz go w swoim pliku konfiguracyjnym. + ::: + +3. Wprowadź klucz API dla dostawcy. + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. Utwórz lub zaktualizuj plik `opencode.json` w katalogu projektu: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + Oto opcje konfiguracji: + - **npm**: pakiet AI SDK do użycia, `@ai-sdk/openai-compatible` dla dostawców kompatybilnych z OpenAI + - **name**: Display name in UI. + - **modele**: Dostępne modele. + - **options.baseURL**: API endpoint URL. + - **options.apiKey**: Opcjonalnie ustaw klucz API, jeśli nie używasz autoryzacji. + - **options.headers**: Optionally set custom headers. + + Więcej o opcjach zaawansowanych w przykładzie poniżej. + +5. Uruchom polecenie `/models`, a niestandardowy dostawca i modele pojawią się na liście wyboru. + +--- + +##### Przykład + +Oto przykład ustawienia opcji `apiKey`, `headers` i modelu `limit`. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +Configuration details: + +- **apiKey**: Ustaw przy użyciu składni zmiennej `env`, [dowiedz się więcej](/docs/config#env-vars). +- **nagłówki**: niestandardowe nagłówki wysyłane z każdym żądaniem. +- **limit.context**: Maksymalna liczba żetonów wejściowych akceptowanych przez model. +- **limit.output**: Maksymalna liczba tokenów, które model może wygenerować. + +Pola `limit` pozwalają OpenCode zrozumieć, ile kontekstu pozostało. Standardowi dostawcy pobierają je automatycznie z models.dev. + +--- + +## Troubleshooting + +Jeśli masz problemy z konfiguracją dostawcy, sprawdź następujące elementy: + +1. **Sprawdź konfigurację uwierzytelniania**: Uruchom `opencode auth list`, aby sprawdzić, czy poświadczenia + dla dostawcy są dodawane do Twojej konfiguracji. + + Nie dotyczy to dostawców takich jak Amazon Bedrock, którzy w procesie uwierzytelniania opierają się na zmiennych środowiskowych. + +2. W przypadku dostawców niestandardowych sprawdź konfigurację kodu opencode i: + - Upewnij się, że identyfikator dostawcy użyty w poleceniu `/connect` jest zgodny z identyfikatorem w konfiguracji kodu opencode. + - Dla dostawcy używany jest właściwy pakiet npm. Na przykład użyj `@ai-sdk/cerebras` dla Cerebras. W przypadku wszystkich innych dostawców zgodnych z OpenAI użyj `@ai-sdk/openai-compatible`. + - Sprawdź, czy w polu `options.baseURL` użyto prawidłowego punktu końcowego API. diff --git a/packages/web/src/content/docs/pl/rules.mdx b/packages/web/src/content/docs/pl/rules.mdx new file mode 100644 index 000000000..361a8fa7c --- /dev/null +++ b/packages/web/src/content/docs/pl/rules.mdx @@ -0,0 +1,180 @@ +--- +title: Rules +description: Ustaw niestandardowe instrukcje dla opencode. +--- + +Możesz dostarczyć niestandardowe instrukcje do kodu opencode, tworząc plik `AGENTS.md`. Jest to podobne do zasad Cursora. Zawiera instrukcje, które zostaną uwzględnione w kontekście LLM, aby dostosować jego zachowanie do konkretnego projektu. + +--- + +## Inicjalizacja + +Aby utworzyć nowy plik `AGENTS.md`, możesz uruchomić komendę `/init` w otwartym kodzie. + +:::tip +Powinieneś zatwierdzić plik `AGENTS.md` swojego projektu w Git. +::: + +Spowoduje to przeskanowanie projektu i całej jego zawartości, aby zrozumieć, czego dotyczy projekt i wygenerować z nim plik `AGENTS.md`. Pomaga to otwartemu kodowi lepiej poruszać się po projekcie. + +Jeśli masz istniejący plik `AGENTS.md`, spróbujemy go dodać. + +--- + +## Przykład + +Możesz także po prostu utworzyć ten plik ręcznie. Oto przykład niektórych rzeczy, które można umieścić w pliku `AGENTS.md`. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +Dodajemy tutaj instrukcje dotyczące konkretnego projektu, które zostaną udostępnione całemu zespołowi. + +--- + +## Types + +opencode obsługuje także odczytywanie pliku `AGENTS.md` z wielu lokalizacji. A to służy różnym celom. + +### Project + +Umieść `AGENTS.md` w katalogu głównym projektu, aby uzyskać reguły specyficzne dla projektu. Mają one zastosowanie tylko wtedy, gdy pracujesz w tym katalogu lub jego podkatalogach. + +### Global + +Możesz także mieć reguły globalne w pliku `~/.config/opencode/AGENTS.md`. Jest to stosowane we wszystkich sesjach opencode. + +Ponieważ nie jest to wymagane dla Git ani udostępniane Twojemu zespołowi, zalecamy użycie tego do określenia wszelkich osobistych zasad, których powinien przestrzegać LLM. + +### Claude Code Compatibility + +W przypadku użytkowników migrujących z Claude Code OpenCode obsługuje konwencje plików Claude Code jako rozwiązania awaryjne: + +- **Zasady projektu**: `CLAUDE.md` w katalogu projektu (używane, jeśli nie istnieje `AGENTS.md`) +- **Zasady globalne**: `~/.claude/CLAUDE.md` (używane, jeśli nie istnieje `~/.config/opencode/AGENTS.md`) +- **Umiejętności**: `~/.claude/skills/` — szczegóły znajdziesz w [Umiejętnościach agenta](/docs/skills/) + +Aby wyłączyć kompatybilność z Claude Code, ustaw jedną z tych zmiennych środowiskowych: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## Precedence + +Po uruchomieniu opencode szuka plików reguł w następującej kolejności: + +1. **Pliki lokalne** poprzez przejście z bieżącego katalogu (`AGENTS.md`, `CLAUDE.md`) +2. **Plik globalny** w `~/.config/opencode/AGENTS.md` +3. **Plik Claude Code** w `~/.claude/CLAUDE.md` (chyba że wyłączony) + +Pierwszy pasujący plik wygrywa w każdej kategorii. Na przykład, jeśli masz zarówno `AGENTS.md`, jak i `CLAUDE.md`, używany jest tylko `AGENTS.md`. Podobnie `~/.config/opencode/AGENTS.md` ma pierwszeństwo przed `~/.claude/CLAUDE.md`. + +--- + +## Instrukcje niestandardowe + +Możesz określić niestandardowe pliki instrukcji w swoim `opencode.json` lub globalnym `~/.config/opencode/opencode.json`. Dzięki temu Ty i Twój zespół możecie ponownie wykorzystać istniejące reguły, zamiast duplikować je w pliku AGENTS.md. + +Przykład: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Możesz także użyć zdalnych adresów URL, aby załadować instrukcje z Internetu. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +Instrukcje zdalne są pobierane z 5-sekundowym limitem czasu. + +Wszystkie pliki instrukcji są łączone z plikami `AGENTS.md`. + +--- + +## Odwoływanie się do plików zewnętrznych + +Chociaż opencode nie analizuje automatycznie odniesień do plików w `AGENTS.md`, możesz osiągnąć podobną funkcjonalność na dwa sposoby: + +### Używanie opencode.json + +Zalecanym podejściem jest użycie pola `instructions` w `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Manual Instructions in AGENTS.md + +Możesz nauczyć opencode czytać pliki zewnętrzne, podając wyraźne instrukcje w swoim `AGENTS.md`. Oto praktyczny przykład: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +Takie podejście pozwala: + +- Twórz modułowe pliki reguł wielokrotnego użytku +- Share rules across projects via symlinks or git submodules +- Keep AGENTS.md concise while referencing detailed guidelines +- Upewnij się, że opencode ładuje pliki tylko wtedy, gdy są potrzebne do konkretnego zadania + +:::tip +W przypadku monorepo lub projektów ze wspólnymi standardami użycie `opencode.json` ze wzorami globalnymi (takimi jak `packages/*/AGENTS.md`) jest łatwiejsze w utrzymaniu niż instrukcje ręczne. +::: diff --git a/packages/web/src/content/docs/pl/sdk.mdx b/packages/web/src/content/docs/pl/sdk.mdx new file mode 100644 index 000000000..28ac06eb6 --- /dev/null +++ b/packages/web/src/content/docs/pl/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: Klient JS bezpieczny dla typu dla serwera opencode. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Pakiet SDK JS/TS z otwartym kodem zapewnia klienta bezpiecznego typu do interakcji z serwerem. +Użyj go do budowania integracji i programowej kontroli otwartego kodu. + +[Dowiedz się więcej](/docs/server) o działaniu serwera. Przykłady znajdziesz w [projektach](/docs/ecosystem#projects) stworzonych przez społeczność. + +--- + +## Zainstalować + +Zainstaluj pakiet SDK z npm: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## Utwórz klienta + +Utwórz instancję otwartego kodu: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +Spowoduje to uruchomienie zarówno serwera, jak i klienta + +#### Options + +| Opcja | Wpisz | Opis | Domyślne | +| ---------- | ------------- | ------------------------------ | ----------- | +| `hostname` | `string` | Nazwa hosta serwera | `127.0.0.1` | +| `port` | `number` | Port serwera | `4096` | +| `signal` | `AbortSignal` | Sygnał przerwania w celu anulowania | `undefined` | +| `timeout` | `number` | Limit czasu w ms dla uruchomienia serwera | `5000` | +| `config` | `Config` | Configuration object | `{}` | + +--- + +## Config + +Można przekazać obiekt konfiguracyjny, aby dostosować zachowanie. Instancja nadal pobiera `opencode.json`, ale możesz zastąpić lub dodać konfigurację bezpośrednio: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## Client only + +Jeśli masz już działającą instancję opencode, możesz utworzyć instancję klienta, aby się z nią połączyć: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### Options + +| Opcja | Wpisz | Opis | Domyślne | +| --------------- | ---------- | -------------------------------- | ----------------------- | +| `baseUrl` | `string` | Adres URL serwera | `http://localhost:4096` | +| `fetch` | `function` | Custom fetch implementation | `globalThis.fetch` | +| `parseAs` | `string` | Response parsing method | `auto` | +| `responseStyle` | `string` | Return style: `data` or `fields` | `fields` | +| `throwOnError` | `boolean` | Throw errors instead of return | `false` | + +--- + +## Types + +Zestaw SDK zawiera definicje TypeScript dla wszystkich typów API. Zaimportuj je bezpośrednio: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +Wszystkie typy są generowane na podstawie specyfikacji OpenAPI serwera i dostępne w pliku typów. + +--- + +## Errors + +SDK może generować błędy, które można przechwycić i obsłużyć: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## APIs + +Zestaw SDK udostępnia wszystkie interfejsy API serwera za pośrednictwem klienta bezpiecznego typu. + +--- + +### Global + +| Method | Description | Response | +| ----------------- | ------------------------------- | ------------------------------------ | +| `global.health()` | Sprawdź stan i wersję serwera | `{ healthy: true, version: string }` | + +--- + +#### Examples + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### App + +| Method | Description | Response | +| -------------- | ------------------------- | ------------------------------------------- | +| `app.log()` | Write a log entry | `boolean` | +| `app.agents()` | Lista wszystkich dostępnych agentów | Agent[] | + +--- + +#### Examples + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### Project + +| Method | Description | Response | +| ------------------- | ------------------- | --------------------------------------------- | +| `project.list()` | Lista wszystkich projektów | Projekt[] | +| `project.current()` | Get current project | Project | + +--- + +#### Examples + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### Path + +| Method | Description | Response | +| ------------ | ---------------- | ---------------------------------------- | +| `path.get()` | Get current path | Path | + +--- + +#### Examples + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### Config + +| Method | Description | Response | +| -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` | Get config info | Config | +| `config.providers()` | Lista dostawców i modeli domyślnych | `{ providers: `Dostawca[]`, default: { [key: string]: string } }` | + +--- + +#### Examples + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### Sessions + +| Method | Description | Notes | +| ---------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` | Lista sesji | Zwraca Sesja[] | +| `session.get({ path })` | Uzyskaj sesję | Zwraca Sesja | +| `session.children({ path })` | Lista sesji podrzędnych | Zwraca Sesja[] | +| `session.create({ body })` | Utwórz sesję | Zwraca Sesja | +| `session.delete({ path })` | Usuń sesję | Zwraca `boolean` | +| `session.update({ path, body })` | Aktualizuj właściwości sesji | Zwraca Sesja | +| `session.init({ path, body })` | Przeanalizuj aplikację i utwórz `AGENTS.md` | Zwraca `boolean` | +| `session.abort({ path })` | Przerwij trwającą sesję | Zwraca `boolean` | +| `session.share({ path })` | Udostępnij sesję | Zwraca Sesja | +| `session.unshare({ path })` | Cofnij udostępnianie sesji | Zwraca Sesja | +| `session.summarize({ path, body })` | Podsumowanie sesji | Zwraca `boolean` | +| `session.messages({ path })` | Lista wiadomości w sesji | Zwraca `{ info: `Wiadomość`, parts: `Część[]`}[]` | +| `session.message({ path })` | Uzyskaj szczegóły wiadomości | Zwraca `{ info: `Wiadomość`, parts: `Część[]`}` | +| `session.prompt({ path, body })` | Wyślij wiadomość | `body.noReply: true` zwraca UserMessage (tylko kontekst). Domyślnie zwraca AssistantMessage z odpowiedzią AI | +| `session.command({ path, body })` | Wyślij polecenie do sesji | Zwraca `{ info: `Wiadomość Asystenta`, parts: `Część[]`}` | +| `session.shell({ path, body })` | Uruchom polecenie powłoki | Zwraca Wiadomość Asystenta | +| `session.revert({ path, body })` | Przywróć wiadomość | Zwraca Sesja | +| `session.unrevert({ path })` | Przywróć przywrócone wiadomości | Zwraca Sesja | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | Respond to a permission request | Returns `boolean` | + +--- + +#### Examples + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### Files + +| Method | Description | Response | +| ------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `find.text({ query })` | Szukaj tekstu w plikach | Tablica obiektów dopasowania z `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `find.files({ query })` | Znajdź pliki i katalogi według nazwy | `string[]` (ścieżki) | +| `find.symbols({ query })` | Find workspace symbols | Symbol[] | +| `file.read({ query })` | Read a file | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | Uzyskaj status śledzonych plików | Plik[] | + +`find.files` supports a few optional query fields: + +- `type`: `"file"` or `"directory"` +- `directory`: zastąp katalog główny projektu dla wyszukiwania +- `limit`: max results (1–200) + +--- + +#### Examples + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +| Method | Description | Response | +| ------------------------------ | ------------------------- | --------- | +| `tui.appendPrompt({ body })` | Dołącz tekst do zachęty | `boolean` | +| `tui.openHelp()` | Otwórz okno pomocy | `boolean` | +| `tui.openSessions()` | Otwórz selektor sesji | `boolean` | +| `tui.openThemes()` | Otwórz selektor motywów | `boolean` | +| `tui.openModels()` | Otwórz selektor modelu | `boolean` | +| `tui.submitPrompt()` | Prześlij bieżący monit | `boolean` | +| `tui.clearPrompt()` | Wyczyść monit | `boolean` | +| `tui.executeCommand({ body })` | Wykonaj polecenie | `boolean` | +| `tui.showToast({ body })` | Pokaż powiadomienie tostowe | `boolean` | + +--- + +#### Examples + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### Auth + +| Method | Description | Response | +| ------------------- | ------------------------------ | --------- | +| `auth.set({ ... })` | Set authentication credentials | `boolean` | + +--- + +#### Examples + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### Events + +| Method | Description | Response | +| ------------------- | ------------------------- | ------------------------- | +| `event.subscribe()` | Strumień zdarzeń wysłanych przez serwer | Strumień zdarzeń wysłanych przez serwer | + +--- + +#### Examples + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/pl/server.mdx b/packages/web/src/content/docs/pl/server.mdx new file mode 100644 index 000000000..0c6bfb1eb --- /dev/null +++ b/packages/web/src/content/docs/pl/server.mdx @@ -0,0 +1,287 @@ +--- +title: Serwer +description: Interakcja z serwerem opencode za pośrednictwem protokołu HTTP. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Komenda `opencode serve` uruchamia bezgłowy serwer HTTP, który udostępnia punkt końcowy OpenAPI, z którego może korzystać klient opencode. + +--- + +### Użycie + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### Opcje + +| Flaga | Opis | Domyślne | +| --------------- | -------------------------------------------- | ---------------- | +| `--port` | Port nasłuchiwania | `4096` | +| `--hostname` | Nazwa hosta do nasłuchiwania | `127.0.0.1` | +| `--mdns` | Włącz wykrywanie mDNS | `false` | +| `--mdns-domain` | Niestandardowa nazwa domeny dla usługi mDNS | `opencode.local` | +| `--cors` | Dodatkowe originy przeglądarki do dozwolenia | `[]` | + +`--cors` można przekazać wiele razy: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### Uwierzytelnianie + +Ustaw `OPENCODE_SERVER_PASSWORD`, aby chronić serwer za pomocą podstawowego uwierzytelniania HTTP. Domyślną nazwą użytkownika jest `opencode` lub ustaw `OPENCODE_SERVER_USERNAME`, aby ją zastąpić. Dotyczy to zarówno `opencode serve`, jak i `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### How it works + +Kiedy uruchomisz `opencode`, uruchomi się TUI i serwer. Gdzie jest TUI +klient komunikujący się z serwerem. Serwer udostępnia specyfikację OpenAPI 3.1 +punkt końcowy. Ten punkt końcowy jest również używany do generowania [SDK](/docs/sdk). + +:::tip +Użyj serwera opencode do programowej interakcji z opencode. +::: + +Ta architektura umożliwia obsługę wielu klientów przez kod otwarty i programową interakcję z kodem otwartym. + +Możesz uruchomić `opencode serve`, aby uruchomić samodzielny serwer. Jeśli masz +opencode TUI działa, `opencode serve` uruchomi nowy serwer. + +--- + +#### Połącz się z istniejącym serwerem + +Po uruchomieniu TUI losowo przypisuje port i nazwę hosta. Zamiast tego możesz przekazać `--hostname` i `--port` [flagi](/docs/cli). Następnie użyj tego, aby połączyć się z serwerem. + +Punktu końcowego [`/tui`](#tui) można użyć do sterowania TUI przez serwer. Można na przykład wstępnie wypełnić lub uruchomić monit. Ta konfiguracja jest używana przez wtyczki OpenCode [IDE](/docs/ide). + +--- + +## Spec + +Serwer publikuje specyfikację OpenAPI 3.1, którą można obejrzeć pod adresem: + +``` +http://:/doc +``` + +Na przykład `http://localhost:4096/doc`. Użyj specyfikacji, aby wygenerować klientów lub sprawdzić typy żądań i odpowiedzi. Możesz też wyświetlić go w eksploratorze Swagger. + +--- + +## APIs + +Serwer opencode udostępnia następujące interfejsy API. + +--- + +### Global + +| Method | Path | Description | Response | +| ------ | ---------------- | ------------------------------ | ------------------------------------ | +| `GET` | `/global/health` | Uzyskaj stan i wersję serwera | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | Get global events (SSE stream) | Event stream | + +--- + +### Project + +| Method | Path | Description | Response | +| ------ | ------------------ | -------------------------- | --------------------------------------------- | +| `GET` | `/project` | Lista wszystkich projektów | Projekt[] | +| `GET` | `/project/current` | Pobierz bieżący projekt | Projekt | + +--- + +### Path & VCS + +| Method | Path | Description | Response | +| ------ | ------- | --------------------------------------------- | ------------------------------------------- | +| `GET` | `/path` | Pobierz bieżącą ścieżkę | Ścieżka | +| `GET` | `/vcs` | Uzyskaj informacje VCS dla bieżącego projektu | VcsInfo | + +--- + +### Instance + +| Method | Path | Description | Response | +| ------ | ------------------- | ---------------------- | --------- | +| `POST` | `/instance/dispose` | Usuń bieżącą instancję | `boolean` | + +--- + +### Config + +| Method | Path | Description | Response | +| ------- | ------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` | Get config info | Config | +| `PATCH` | `/config` | Update config | Config | +| `GET` | `/config/providers` | Lista dostawców i modeli domyślnych | `{ providers: `Dostawca[]`, default: { [key: string]: string } }` | + +--- + +### Dostawca + +| Method | Path | Description | Response | +| ------ | -------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` | Lista wszystkich dostawców | `{ all: `Dostawca[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | Uzyskaj metody uwierzytelniania dostawcy | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | Autoryzuj dostawcę za pomocą protokołu OAuth | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | Obsługa wywołania zwrotnego OAuth dla dostawcy | `boolean` | + +--- + +### Sessions + +| Method | Path | Description | Notes | +| -------- | ---------------------------------------- | ------------------------------------------- | -------------------------------------------------------------------------------- | +| `GET` | `/session` | Lista wszystkich sesji | Zwraca Sesja[] | +| `POST` | `/session` | Utwórz nową sesję | treść: `{ parentID?, title? }`, zwraca Sesja | +| `GET` | `/session/status` | Uzyskaj status sesji dla wszystkich sesji | Zwraca `{ [sessionID: string]: `Status sesji` }` | +| `GET` | `/session/:id` | Uzyskaj szczegóły sesji | Zwraca Sesja | +| `DELETE` | `/session/:id` | Usuń sesję i wszystkie jej dane | Zwraca `boolean` | +| `PATCH` | `/session/:id` | Aktualizuj właściwości sesji | treść: `{ title? }`, zwraca Sesja | +| `GET` | `/session/:id/children` | Pobierz sesje podrzędne sesji | Zwraca Sesja[] | +| `GET` | `/session/:id/todo` | Pobierz listę rzeczy do zrobienia dla sesji | Zwraca Do zrobienia[] | +| `POST` | `/session/:id/init` | Przeanalizuj aplikację i utwórz `AGENTS.md` | treść: `{ messageID, providerID, modelID }`, zwraca `boolean` | +| `POST` | `/session/:id/fork` | Rozwiń istniejącą sesję w wiadomości | treść: `{ messageID? }`, zwraca Sesja | +| `POST` | `/session/:id/abort` | Przerwij trwającą sesję | Zwraca `boolean` | +| `POST` | `/session/:id/share` | Udostępnij sesję | Zwraca Sesja | +| `DELETE` | `/session/:id/share` | Anuluj udostępnianie sesji | Zwraca Sesja | +| `GET` | `/session/:id/diff` | Pobierz różnicę dla tej sesji | zapytanie: `messageID?`, zwraca FileDiff[] | +| `POST` | `/session/:id/summarize` | Podsumuj sesję | treść: `{ providerID, modelID }`, zwraca `boolean` | +| `POST` | `/session/:id/revert` | Przywróć wiadomość | treść: `{ messageID, partID? }`, zwraca `boolean` | +| `POST` | `/session/:id/unrevert` | Przywróć wszystkie przywrócone wiadomości | Zwraca `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | Odpowiedz na prośbę o pozwolenie | treść: `{ response, remember? }`, zwraca `boolean` | + +--- + +### Messages + +| Method | Path | Description | Notes | +| ------ | --------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `GET` | `/session/:id/message` | Lista wiadomości w sesji | zapytanie: `limit?`, zwraca `{ info: `Wiadomość`, parts: `Część[]`}[]` | +| `POST` | `/session/:id/message` | Wyślij wiadomość i poczekaj na odpowiedź | treść: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, zwraca `{ info: `Wiadomość`, parts: `Część[]`}` | +| `GET` | `/session/:id/message/:messageID` | Uzyskaj szczegóły wiadomości | Zwraca `{ info: `Wiadomość`, parts: `Część[]`}` | +| `POST` | `/session/:id/prompt_async` | Wyślij wiadomość asynchronicznie (bez czekania) | treść: taka sama jak `/session/:id/message`, zwraca `204 No Content` | +| `POST` | `/session/:id/command` | Wykonaj polecenie ukośnika | treść: `{ messageID?, agent?, model?, command, arguments }`, zwraca `{ info: `Wiadomość`, parts: `Część[]`}` | +| `POST` | `/session/:id/shell` | Uruchom polecenie powłoki | treść: `{ agent, model?, command }`, zwraca `{ info: `Wiadomość`, parts: `Część[]`}` | + +--- + +### Komendy + +| Metoda | Ścieżka | Opis | Odpowiedź | +| ------ | ---------- | ------------------------ | ----------------------------------------------- | +| `GET` | `/command` | Lista wszystkich poleceń | Polecenie[] | + +--- + +### Pliki + +| Method | Path | Description | Response | +| ------ | ------------------------ | ------------------------------------ | ---------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | Szukaj tekstu w plikach | Tablica obiektów dopasowania z `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | Znajdź pliki i katalogi według nazwy | `string[]` (ścieżki) | +| `GET` | `/find/symbol?query=` | Find workspace symbols | Symbol[] | +| `GET` | `/file?path=` | Lista plików i katalogów | FileNode[] | +| `GET` | `/file/content?path=

` | Read a file | FileContent | +| `GET` | `/file/status` | Uzyskaj status śledzonych plików | Plik[] | + +#### `/find/file` query parameters + +- `query` (required) — search string (fuzzy match) +- `type` (optional) — limit results to `"file"` or `"directory"` +- `directory` (opcjonalnie) — zastąp katalog główny projektu dla wyszukiwania +- `limit` (optional) — max results (1–200) +- `dirs` (optional) — legacy flag (`"false"` returns only files) + +--- + +### Tools (Experimental) + +| Method | Path | Description | Response | +| ------ | ------------------------------------------- | -------------------------------------------- | ----------------------------------------------------------- | +| `GET` | `/experimental/tool/ids` | Lista wszystkich identyfikatorów narzędzi | Identyfikatory narzędzi | +| `GET` | `/experimental/tool?provider=

&model=` | Lista narzędzi ze schematami JSON dla modelu | Lista narzędzi | + +--- + +### LSP, Formatters & MCP + +| Method | Path | Description | Response | +| ------ | ------------ | ---------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | Uzyskaj status serwera LSP | LSPStatus[] | +| `GET` | `/formatter` | Get formatter status | FormatterStatus[] | +| `GET` | `/mcp` | Uzyskaj status serwera MCP | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | Dodaj dynamicznie serwer MCP | treść: `{ name, config }`, zwraca obiekt stanu MCP | + +--- + +### Agents + +| Method | Path | Description | Response | +| ------ | -------- | ----------------------------------- | ------------------------------------------- | +| `GET` | `/agent` | Lista wszystkich dostępnych agentów | Agent[] | + +--- + +### Logging + +| Method | Path | Description | Response | +| ------ | ------ | ------------------------------------------------------------ | --------- | +| `POST` | `/log` | Write log entry. Body: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| Method | Path | Description | Response | +| ------ | ----------------------- | -------------------------------------------- | ----------------------- | +| `POST` | `/tui/append-prompt` | Dołącz tekst do zachęty | `boolean` | +| `POST` | `/tui/open-help` | Otwórz okno pomocy | `boolean` | +| `POST` | `/tui/open-sessions` | Otwórz selektor sesji | `boolean` | +| `POST` | `/tui/open-themes` | Otwórz selektor motywów | `boolean` | +| `POST` | `/tui/open-models` | Otwórz selektor modelu | `boolean` | +| `POST` | `/tui/submit-prompt` | Prześlij bieżący monit | `boolean` | +| `POST` | `/tui/clear-prompt` | Wyczyść monit | `boolean` | +| `POST` | `/tui/execute-command` | Wykonaj polecenie (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | Pokaż toast (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | Poczekaj na następne żądanie kontroli | Obiekt żądania kontroli | +| `POST` | `/tui/control/response` | Respond to a control request (`{ body }`) | `boolean` | + +--- + +### Auth + +| Method | Path | Description | Response | +| ------ | ----------- | --------------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | Ustaw dane uwierzytelniające. Treść musi pasować do schematu dostawcy | `boolean` | + +--- + +### Events + +| Method | Path | Description | Response | +| ------ | -------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | +| `GET` | `/event` | Strumień zdarzeń wysyłanych przez serwer. Pierwsze wydarzenie to `server.connected`, następnie wydarzenia autobusowe | Strumień zdarzeń wysłanych przez serwer | + +--- + +### Docs + +| Method | Path | Description | Response | +| ------ | ------ | ------------------------ | ----------------------------------- | +| `GET` | `/doc` | Specyfikacja OpenAPI 3.1 | Strona HTML ze specyfikacją OpenAPI | diff --git a/packages/web/src/content/docs/pl/share.mdx b/packages/web/src/content/docs/pl/share.mdx new file mode 100644 index 000000000..0411571d3 --- /dev/null +++ b/packages/web/src/content/docs/pl/share.mdx @@ -0,0 +1,128 @@ +--- +title: Share +description: Udostępnij swoje rozmowy dotyczące OpenCode. +--- + +Funkcja udostępniania OpenCode umożliwia tworzenie publicznych linków do konwersacji OpenCode, dzięki czemu możesz współpracować z członkami zespołu lub uzyskać pomoc od innych. + +:::note +Udostępnione konwersacje są publicznie dostępne dla każdej osoby mającej link. +::: + +--- + +## How it works + +Kiedy udostępniasz rozmowę, OpenCode: + +1. Tworzy unikalny publiczny adres URL sesji +2. Synchronizuje historię rozmów z naszymi serwerami +3. Udostępnia rozmowę za pośrednictwem łącza do udostępniania — `opncd.ai/s/` + +--- + +## Sharing + +OpenCode obsługuje trzy tryby udostępniania, które kontrolują sposób udostępniania rozmów: + +--- + +### Ręczny (domyślny) + +Domyślnie OpenCode korzysta z ręcznego trybu udostępniania. Sesje nie są udostępniane automatycznie, ale możesz je udostępnić ręcznie za pomocą polecenia `/share`: + +``` +/share +``` + +Spowoduje to wygenerowanie unikalnego adresu URL, który zostanie skopiowany do schowka. + +Aby jawnie ustawić tryb ręczny w [pliku konfiguracyjnym] (./config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### Auto-share + +Możesz włączyć automatyczne udostępnianie dla wszystkich nowych rozmów, ustawiając opcję `share` na `"auto"` w [pliku konfiguracyjnym] (./config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +Po włączeniu automatycznego udostępniania każda nowa rozmowa będzie automatycznie udostępniana i generowany będzie link. + +--- + +### Disabled + +Możesz całkowicie wyłączyć udostępnianie, ustawiając opcję `share` na `"disabled"` w [pliku konfiguracyjnym] (./config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +Aby wymusić to w całym zespole dla danego projektu, dodaj go do `opencode.json` w swoim projekcie i sprawdź w Git. + +--- + +## Un-sharing + +Aby zatrzymać udostępnianie rozmowy i usunąć ją z dostępu publicznego: + +``` +/unshare +``` + +Spowoduje to usunięcie łącza udostępniania i danych związanych z rozmową. + +--- + +## Privacy + +There are a few things to keep in mind when sharing a conversation. + +--- + +### Data retention + +Udostępnione rozmowy pozostają dostępne, dopóki wyraźnie ich nie udostępnisz. Ten +includes: + +- Full conversation history +- Wszystkie wiadomości i odpowiedzi +- Metadane sesji + +--- + +### Recommendations + +- Udostępniaj tylko rozmowy, które nie zawierają poufnych informacji. +- Review conversation content before sharing. +- Unshare conversations when collaboration is complete. +- Unikaj udostępniania rozmów zawierających zastrzeżony kod lub poufne dane. +- W przypadku wrażliwych projektów całkowicie wyłącz udostępnianie. + +--- + +## Dla przedsiębiorstw + +W przypadku wdrożeń korporacyjnych funkcją udostępniania może być: + +- **Wyłączone** całkowicie ze względu na bezpieczeństwo +- **Restricted** to users authenticated through SSO only +- **Własny hosting** na własnej infrastrukturze + +[Dowiedz się więcej](/docs/enterprise) o używaniu kodu opencode w Twojej organizacji. diff --git a/packages/web/src/content/docs/pl/skills.mdx b/packages/web/src/content/docs/pl/skills.mdx new file mode 100644 index 000000000..1517a0c7b --- /dev/null +++ b/packages/web/src/content/docs/pl/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "Agent Skills" +description: "Define reusable behavior via SKILL.md definitions" +--- + +Umiejętności agenta pozwalają OpenCode odkryć instrukcje wielokrotnego użytku z repozytorium lub katalogu domowego. +Umiejętności są ładowane na żądanie za pośrednictwem natywnego narzędzia `skill` — agenci widzą dostępne umiejętności i w razie potrzeby mogą załadować pełną zawartość. + +--- + +## Place files + +Utwórz jeden folder na nazwę umiejętności i umieść w nim `SKILL.md`. +OpenCode searches these locations: + +- Project config: `.opencode/skills//SKILL.md` +- Global config: `~/.config/opencode/skills//SKILL.md` +- Project Claude-compatible: `.claude/skills//SKILL.md` +- Global Claude-compatible: `~/.claude/skills//SKILL.md` +- Project agent-compatible: `.agents/skills//SKILL.md` +- Global agent-compatible: `~/.agents/skills//SKILL.md` + +--- + +## Understand discovery + +W przypadku ścieżek lokalnych projektu OpenCode przechodzi od bieżącego katalogu roboczego, aż dotrze do drzewa roboczego git. +Ładuje po drodze dowolne pasujące `skills/*/SKILL.md` w `.opencode/` i dowolne pasujące `.claude/skills/*/SKILL.md` lub `.agents/skills/*/SKILL.md`. + +Ładowane są także definicje globalne z `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` i `~/.agents/skills/*/SKILL.md`. + +--- + +## Write frontmatter + +Każdy `SKILL.md` musi zaczynać się od treści YAML. +Only these fields are recognized: + +- `name` (required) +- `description` (required) +- `license` (optional) +- `compatibility` (optional) +- `metadata` (optional, string-to-string map) + +Unknown frontmatter fields are ignored. + +--- + +## Validate names + +`name` must: + +- Be 1–64 characters +- Należy używać małych liter alfanumerycznych i oddzielać je pojedynczym łącznikiem +- Nie zaczyna się ani nie kończy na `-` +- Not contain consecutive `--` +- Dopasuj nazwę katalogu zawierającą `SKILL.md` + +Equivalent regex: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## Follow length rules + +`description` must be 1-1024 characters. +Zadbaj o to, aby agent mógł dokonać prawidłowego wyboru. + +--- + +## Skorzystaj z przykładu + +Utwórz `.opencode/skills/git-release/SKILL.md` w ten sposób: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## Recognize tool description + +OpenCode wymienia dostępne umiejętności w opisie narzędzia `skill`. +Każdy wpis zawiera nazwę i opis umiejętności: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +Agent ładuje umiejętność wywołując narzędzie: + +``` +skill({ name: "git-release" }) +``` + +--- + +## Skonfiguruj uprawnienia + +Control which skills agents can access using pattern-based permissions in `opencode.json`: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Permission | Behavior | +| ---------- | ----------------------------------------- | +| `allow` | Skill loads immediately | +| `deny` | Skill hidden from agent, access rejected | +| `ask` | Użytkownik proszony o zatwierdzenie przed załadowaniem | + +Wzorce obsługują symbole wieloznaczne: `internal-*` odpowiada `internal-docs`, `internal-tools` itd. + +--- + +## Override per agent + +Nadaj konkretnym agentom inne uprawnienia niż globalne ustawienia domyślne. + +**Dla agentów niestandardowych** (w temacie agentów): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**Dla agentów wbudowanych** (w `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## Wyłącz narzędzie umiejętności + +Całkowicie wyłącz umiejętności agentów, którzy nie powinni ich używać: + +**Dla agentów celnych**: + +```yaml +--- +tools: + skill: false +--- +``` + +**W przypadku agentów wbudowanych**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +Jeśli opcja jest wyłączona, sekcja `` jest całkowicie pomijana. + +--- + +## Troubleshoot loading + +Jeśli umiejętność nie pojawi się: + +1. Verify `SKILL.md` is spelled in all caps +2. Sprawdź, czy frontmatter zawiera `name` i `description` +3. Ensure skill names are unique across all locations +4. Sprawdź uprawnienia — umiejętności z `deny` są ukryte przed agentami diff --git a/packages/web/src/content/docs/pl/themes.mdx b/packages/web/src/content/docs/pl/themes.mdx new file mode 100644 index 000000000..c3dd9ec81 --- /dev/null +++ b/packages/web/src/content/docs/pl/themes.mdx @@ -0,0 +1,369 @@ +--- +title: Themes +description: Wybierz wbudowany motyw lub zdefiniuj własny. +--- + +Dzięki OpenCode możesz wybrać jeden z kilku wbudowanych motywów, użyć motywu, który dostosowuje się do motywu terminala lub zdefiniować własny, niestandardowy motyw. + +Domyślnie OpenCode używa naszego własnego motywu `opencode`. + +--- + +## Terminal requirements + +Aby motywy wyświetlały się poprawnie z pełną paletą kolorów, Twój terminal musi obsługiwać **truecolor** (kolor 24-bitowy). Większość nowoczesnych terminali domyślnie obsługuje tę opcję, ale może być konieczne jej włączenie: + +- **Sprawdź wsparcie**: Uruchom `echo $COLORTERM` - powinno wypisać `truecolor` lub `24bit` +- **Włącz truecolor**: Ustaw zmienną środowiskową `COLORTERM=truecolor` w swoim profilu powłoki +- **Zgodność terminala**: Upewnij się, że emulator terminala obsługuje 24-bitowy kolor (większość nowoczesnych terminali, takich jak iTerm2, Alacritty, Kitty, Windows Terminal i najnowsze wersje terminala GNOME tak) + +Bez obsługi Truecolor motywy mogą pojawiać się ze zmniejszoną dokładnością kolorów lub wracać do najbliższego przybliżenia 256 kolorów. + +--- + +## Wbudowane motywy + +OpenCode ma kilka wbudowanych motywów. + +| Name | Description | +| ---------------------- | --------------------------------------------------------------------------------- | +| `system` | Dopasowuje się do koloru tła terminala | +| `tokyonight` | Na podstawie motywu [Tokyonight](https://github.com/folke/tokyonight.nvim) | +| `everforest` | Na podstawie motywu [Everforest](https://github.com/sainnhe/everforest) | +| `ayu` | Na podstawie ciemnego motywu [Ayu](https://github.com/ayu-theme) | +| `catppuccin` | Na podstawie motywu [Catppuccin](https://github.com/catppuccin) | +| `catppuccin-macchiato` | Na podstawie motywu [Catppuccin](https://github.com/catppuccin) | +| `gruvbox` | Na podstawie motywu [Gruvbox](https://github.com/morhetz/gruvbox) | +| `kanagawa` | Na podstawie motywu [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | +| `nord` | Na podstawie motywu [Nord](https://github.com/nordtheme/nord) | +| `matrix` | Hacker-style green on black theme | +| `one-dark` | Na podstawie ciemnego motywu [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) | + +Co więcej, stale dodajemy nowe motywy. + +--- + +## System theme + +Motyw `system` został zaprojektowany tak, aby automatycznie dostosowywał się do schematu kolorów terminala. W przeciwieństwie do tradycyjnych motywów, które używają stałych kolorów, motyw _system_: + +- **Generuje skalę szarości**: Tworzy niestandardową skalę szarości w oparciu o kolor tła terminala, zapewniając optymalny kontrast. +- **Używa kolorów ANSI**: Wykorzystuje standardowe kolory ANSI (0-15) do podświetlania składni i elementów interfejsu użytkownika, które odpowiadają palecie kolorów terminala. +- **Zachowuje ustawienia domyślne terminala**: Używa `none` dla kolorów tekstu i tła, aby zachować natywny wygląd terminala. + +Motyw systemu przeznaczony jest dla użytkowników, którzy: + +- Want OpenCode to match their terminal's appearance +- Użyj niestandardowych schematów kolorów terminali +- Prefer a consistent look across all terminal applications + +--- + +## Using a theme + +Możesz wybrać motyw, wywołując opcję wyboru motywu za pomocą polecenia `/theme`. Możesz też określić to w [config](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Custom themes + +OpenCode obsługuje elastyczny system motywów oparty na JSON, który pozwala użytkownikom łatwo tworzyć i dostosowywać motywy. + +--- + +### Hierarchy + +Motywy są ładowane z wielu katalogów w następującej kolejności, przy czym późniejsze katalogi zastępują wcześniejsze: + +1. **Wbudowane motywy** – są osadzone w formacie binarnym +2. **User config directory** - Defined in `~/.config/opencode/themes/*.json` or `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Katalog główny projektu** - Zdefiniowany w `/.opencode/themes/*.json` +4. **Current working directory** - Defined in `./.opencode/themes/*.json` + +Jeśli wiele katalogów zawiera motyw o tej samej nazwie, zostanie użyty motyw z katalogu o wyższym priorytecie. + +--- + +### Creating a theme + +Aby utworzyć niestandardowy motyw, utwórz plik JSON w jednym z katalogów motywów. + +W przypadku motywów dla całego użytkownika: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +Oraz dla tematów specyficznych dla projektu. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON format + +Motywy korzystają z elastycznego formatu JSON z obsługą: + +- **Hex colors**: `"#ffffff"` +- **ANSI colors**: `3` (0-255) +- **Color references**: `"primary"` or custom definitions +- **Dark/light variants**: `{"dark": "#000", "light": "#fff"}` +- **Brak koloru**: `"none"` - Używa domyślnego koloru terminala lub przezroczystości + +--- + +### Color definitions + +Sekcja `defs` jest opcjonalna i pozwala zdefiniować kolory wielokrotnego użytku, do których można się odwoływać w motywie. + +--- + +### Terminal defaults + +Wartość specjalna `"none"` może zostać użyta dla dowolnego koloru, aby przejąć domyślny kolor terminala. Jest to szczególnie przydatne do tworzenia motywów, które płynnie komponują się ze schematem kolorów terminala: + +- `"text": "none"` - Używa domyślnego koloru pierwszego planu terminala +- `"background": "none"` - Używa domyślnego koloru tła terminala + +--- + +### Przykład + +Here's an example of a custom theme: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/pl/tools.mdx b/packages/web/src/content/docs/pl/tools.mdx new file mode 100644 index 000000000..1c97c84ac --- /dev/null +++ b/packages/web/src/content/docs/pl/tools.mdx @@ -0,0 +1,379 @@ +--- +title: Tools +description: Zarządzaj narzędziami, z których może korzystać LLM. +--- + +Narzędzia umożliwiają LLM wykonywanie działań w bazie kodu. OpenCode ma zestaw wbudowanych narzędzi, ale możesz go rozszerzyć o [narzędzia niestandardowe](/docs/custom-tools) lub [serwery MCP](/docs/mcp-servers). + +Domyślnie wszystkie narzędzia są **włączone** i nie wymagają pozwolenia na uruchomienie. Możesz kontrolować zachowanie narzędzia poprzez [uprawnienia](/docs/permissions). + +--- + +## Skonfiguruj + +Użyj pola `permission` do kontrolowania zachowania narzędzia. Dla każdego narzędzia możesz zezwolić, odmówić lub wymagać zatwierdzenia. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +Możesz także używać symboli wieloznacznych do kontrolowania wielu narzędzi jednocześnie. Na przykład, aby wymagać zatwierdzenia wszystkich narzędzi z serwera MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[Dowiedz się więcej](/docs/permissions) o konfigurowaniu uprawnień. + +--- + +## Wbudowane + +Oto wszystkie wbudowane narzędzia dostępne w OpenCode. + +--- + +### bash + +Wykonuj polecenia powłoki w środowisku projektu. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +To narzędzie umożliwia LLM uruchamianie poleceń terminalowych, takich jak `npm install`, `git status` lub dowolne inne polecenie powłoki. + +--- + +### edit + +Modify existing files using exact string replacements. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +To narzędzie umożliwia precyzyjną edycję plików poprzez zastąpienie dokładnych dopasowań tekstu. Jest to główny sposób, w jaki LLM modyfikuje kod. + +--- + +### write + +Utwórz nowe pliki lub nadpisz istniejące. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Użyj tego, aby umożliwić LLM tworzenie nowych plików. Zastąpi istniejące pliki, jeśli już istnieją. + +:::note +Narzędzie `write` jest kontrolowane przez uprawnienie `edit`, które obejmuje wszystkie modyfikacje plików (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### read + +Przeczytaj zawartość pliku z bazy kodu. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +Narzędzie to odczytuje pliki i zwraca ich zawartość. Obsługuje czytanie określonych zakresów linii w przypadku dużych plików. + +--- + +### grep + +Search file contents using regular expressions. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Szybkie wyszukiwanie treści w całej bazie kodu. Obsługuje pełną składnię wyrażeń regularnych i filtrowanie wzorców plików. + +--- + +### glob + +Find files by pattern matching. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +Szukaj plików przy użyciu wzorców globalnych, takich jak `**/*.js` lub `src/**/*.ts`. Zwraca pasujące ścieżki plików posortowane według czasu modyfikacji. + +--- + +### lista + +Wyświetla listę plików i katalogów w podanej ścieżce. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +To narzędzie wyświetla zawartość katalogu. Akceptuje wzorce globalne do filtrowania wyników. + +--- + +### lsp (experimental) + +Wejdź w interakcję ze skonfigurowanymi serwerami LSP, aby uzyskać funkcje analizy kodu, takie jak definicje, odniesienia, informacje o najechaniu myszką i hierarchia połączeń. + +:::note +To narzędzie jest dostępne tylko wtedy, gdy `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (lub `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +Obsługiwane operacje obejmują `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` i `outgoingCalls`. + +Aby skonfigurować, które serwery LSP są dostępne dla Twojego projektu, zobacz [Serwery LSP](/docs/lsp). + +--- + +### patch + +Apply patches to files. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +To narzędzie stosuje pliki poprawek do bazy kodu. Przydatne do stosowania różnic i poprawek z różnych źródeł. + +:::note +Narzędzie `patch` jest kontrolowane przez uprawnienie `edit`, które obejmuje wszystkie modyfikacje plików (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### skill + +Załaduj [umiejętność](/docs/skills) (plik `SKILL.md`) i zwróć jej treść w rozmowie. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todowrite + +Zarządzaj listami rzeczy do zrobienia podczas sesji kodowania. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +Tworzy i aktualizuje listy zadań w celu śledzenia postępu podczas złożonych operacji. LLM wykorzystuje to do organizowania zadań wieloetapowych. + +:::note +To narzędzie jest domyślnie wyłączone dla podagentów, ale można je włączyć ręcznie. [Dowiedz się więcej](/docs/agents/#permissions) +::: + +--- + +### todoread + +Read existing todo lists. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +Odczytuje bieżący stan listy rzeczy do zrobienia. Używany przez LLM do śledzenia zadań oczekujących lub ukończonych. + +:::note +To narzędzie jest domyślnie wyłączone dla podagentów, ale można je włączyć ręcznie. [Dowiedz się więcej](/docs/agents/#permissions) +::: + +--- + +### webfetch + +Fetch web content. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +Umożliwia LLM pobieranie i odczytywanie stron internetowych. Przydatne do wyszukiwania dokumentacji lub wyszukiwania zasobów online. + +--- + +### websearch + +Wyszukaj informacje w Internecie. + +:::note +To narzędzie jest dostępne tylko w przypadku korzystania z dostawcy OpenCode lub gdy zmienna środowiskowa `OPENCODE_ENABLE_EXA` jest ustawiona na dowolną wartość prawdziwą (np. `true` lub `1`). + +To enable when launching OpenCode: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Przeszukuje Internet za pomocą Exa AI, aby znaleźć odpowiednie informacje w Internecie. Przydatne do badania tematów, znajdowania bieżących wydarzeń lub zbierania informacji wykraczających poza limit danych szkoleniowych. + +Nie jest wymagany żaden klucz API — narzędzie łączy się bezpośrednio z usługą MCP hostowaną przez Exa AI bez uwierzytelniania. + +:::tip +Użyj `websearch`, gdy chcesz znaleźć informacje (odkrycie), i `webfetch`, gdy musisz pobrać treść z określonego adresu URL (pobieranie). +::: + +--- + +### question + +Zadawaj pytania użytkownikowi podczas wykonywania. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +To narzędzie umożliwia LLM zadawanie pytań użytkownikowi podczas wykonywania zadania. Jest to przydatne dla: + +- Gathering user preferences or requirements +- Clarifying ambiguous instructions +- Getting decisions on implementation choices +- Offering choices about what direction to take + +Każde pytanie zawiera nagłówek, tekst pytania i listę opcji. Użytkownicy mogą wybierać spośród dostępnych opcji lub wpisać niestandardową odpowiedź. Jeśli pytań jest wiele, użytkownicy mogą nawigować między nimi przed przesłaniem wszystkich odpowiedzi. + +--- + +## Custom tools + +Niestandardowe narzędzia pozwalają zdefiniować własne funkcje, które LLM może wywołać. Są one zdefiniowane w pliku konfiguracyjnym i mogą wykonywać dowolny kod. + +[Więcej informacji](/docs/custom-tools) o tworzeniu narzędzi niestandardowych. + +--- + +## MCP servers + +Serwery MCP (Model Context Protocol) umożliwiają integrację zewnętrznych narzędzi i usług. Obejmuje to dostęp do baz danych, integracje API i usługi stron trzecich. + +[Dowiedz się więcej](/docs/mcp-servers) o konfigurowaniu serwerów MCP. + +--- + +## Internals + +Wewnętrznie narzędzia takie jak `grep`, `glob` i `list` używają pod maską [ripgrep](https://github.com/BurntSushi/ripgrep). Domyślnie ripgrep respektuje wzorce `.gitignore`, co oznacza, że ​​pliki i katalogi wymienione w Twoim `.gitignore` zostaną wykluczone z wyszukiwań i list. + +--- + +### Ignore patterns + +Aby uwzględnić pliki, które normalnie byłyby ignorowane, utwórz plik `.ignore` w katalogu głównym projektu. Ten plik może jawnie zezwalać na określone ścieżki. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +Na przykład ten plik `.ignore` pozwala ripgrepowi przeszukiwać katalogi `node_modules/`, `dist/` i `build/`, nawet jeśli są one wymienione w `.gitignore`. diff --git a/packages/web/src/content/docs/pl/troubleshooting.mdx b/packages/web/src/content/docs/pl/troubleshooting.mdx new file mode 100644 index 000000000..844d5b91f --- /dev/null +++ b/packages/web/src/content/docs/pl/troubleshooting.mdx @@ -0,0 +1,300 @@ +--- +title: Troubleshooting +description: Typowe problemy i sposoby ich rozwiązywania. +--- + +Aby debugować problemy z OpenCode, zacznij od sprawdzenia dzienników i danych lokalnych przechowywanych na dysku. + +--- + +## Logs + +Log files are written to: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: Naciśnij `WIN+R` i wklej `%USERPROFILE%\.local\share\opencode\log` + +Nazwy plików dziennika zawierają znaczniki czasu (np. `2025-01-09T123456.log`) i przechowywanych jest 10 ostatnich plików dziennika. + +Możesz ustawić poziom dziennika za pomocą opcji wiersza poleceń `--log-level`, aby uzyskać bardziej szczegółowe informacje debugowania. Na przykład `opencode --log-level DEBUG`. + +--- + +## Storage + +opencode przechowuje dane sesji i inne dane aplikacji na dysku pod adresem: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: Naciśnij `WIN+R` i wklej `%USERPROFILE%\.local\share\opencode` + +Ten katalog zawiera: + +- `auth.json` - Authentication data like API keys, OAuth tokens +- `log/` - Application logs +- `project/` — Dane specyficzne dla projektu, takie jak dane sesji i komunikatów + - Jeśli projekt znajduje się w repozytorium Git, jest on przechowywany w `.//storage/` + - If it is not a Git repo, it is stored in `./global/storage/` + +--- + +## Desktop app + +OpenCode Desktop uruchamia w tle lokalny serwer OpenCode (wózek boczny `opencode-cli`). Większość problemów jest spowodowana nieprawidłowo działającą wtyczką, uszkodzoną pamięcią podręczną lub złymi ustawieniami serwera. + +### Quick checks + +- Całkowicie zakończ i uruchom ponownie aplikację. +- Jeśli aplikacja wyświetli ekran błędu, kliknij **Uruchom ponownie** i skopiuj szczegóły błędu. +- Tylko macOS: menu `OpenCode` -> **Załaduj ponownie przeglądarkę internetową** (pomaga, jeśli interfejs użytkownika jest pusty/zawieszony). + +--- + +### Disable plugins + +Jeśli aplikacja komputerowa ulega awarii podczas uruchamiania, zawiesza się lub zachowuje się dziwnie, zacznij od wyłączenia wtyczek. + +#### Sprawdź konfigurację globalną + +Otwórz globalny plik konfiguracyjny i poszukaj klucza `plugin`. + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (or `~/.config/opencode/opencode.json`) +- **macOS/Linux** (older installs): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: Naciśnij `WIN+R` i wklej `%USERPROFILE%\.config\opencode\opencode.jsonc` + +Jeśli masz skonfigurowane wtyczki, tymczasowo je wyłącz, usuwając klucz lub ustawiając go na pustą tablicę: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### Check plugin directories + +OpenCode może także ładować lokalne wtyczki z dysku. Tymczasowo usuń je (lub zmień nazwę folderu) i uruchom ponownie aplikację komputerową: + +- **Global plugins** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: Naciśnij `WIN+R` i wklej `%USERPROFILE%\.config\opencode\plugins` +- **Wtyczki projektowe** (tylko jeśli używasz konfiguracji dla poszczególnych projektów) + - `/.opencode/plugins/` + +Jeśli aplikacja ponownie zacznie działać, włączaj ponownie wtyczki pojedynczo, aby dowiedzieć się, która powoduje problem. + +--- + +### Wyczyść pamięć podręczną + +Jeśli wyłączenie wtyczek nie pomoże (lub instalacja wtyczki utknęła), wyczyść pamięć podręczną, aby OpenCode mógł ją odbudować. + +1. Quit OpenCode Desktop completely. +2. Usuń katalog pamięci podręcznej: + +- **macOS**: Finder -> `Cmd+Shift+G` -> paste `~/.cache/opencode` +- **Linux**: usuń `~/.cache/opencode` (lub uruchom `rm -rf ~/.cache/opencode`) +- **Windows**: Naciśnij `WIN+R` i wklej `%USERPROFILE%\.cache\opencode` + +3. Restart OpenCode Desktop. + +--- + +### Napraw problemy z połączeniem z serwerem + +OpenCode Desktop może uruchomić własny serwer lokalny (domyślnie) lub połączyć się ze skonfigurowanym adresem URL serwera. + +Jeśli zobaczysz okno dialogowe **„Połączenie nie powiodło się”** (lub aplikacja nigdy nie wychodzi poza ekran powitalny), sprawdź, czy jest niestandardowy adres URL serwera. + +#### Wyczyść domyślny adres URL serwera na komputerze + +Na ekranie głównym kliknij nazwę serwera (z kropką stanu), aby otworzyć selektor serwerów. W sekcji **Serwer domyślny** kliknij **Wyczyść**. + +#### Usuń `server.port` / `server.hostname` ze swojej konfiguracji + +Jeśli Twój `opencode.json(c)` zawiera sekcję `server`, tymczasowo usuń ją i uruchom ponownie aplikację komputerową. + +#### Check environment variables + +Jeśli w swoim środowisku masz ustawiony `OPENCODE_PORT`, aplikacja komputerowa spróbuje użyć tego portu dla serwera lokalnego. + +- Rozbierz `OPENCODE_PORT` (lub wybierz wolny port) i uruchom ponownie. + +--- + +### Linux: Wayland / X11 issues + +On Linux, some Wayland setups can cause blank windows or compositor errors. + +- Jeśli korzystasz z Wayland, a aplikacja jest pusta/ ulega awarii, spróbuj uruchomić ją za pomocą `OC_ALLOW_WAYLAND=1`. +- Jeśli to pogorszy sprawę, usuń go i zamiast tego spróbuj uruchomić w sesji X11. + +--- + +### Windows: WebView2 runtime + +W systemie Windows OpenCode Desktop wymaga Microsoft Edge **WebView2 Runtime**. Jeśli aplikacja otwiera się w pustym oknie lub nie uruchamia się, zainstaluj/zaktualizuj WebView2 i spróbuj ponownie. + +--- + +### Windows: General performance issues + +Jeśli doświadczasz niskiej wydajności, problemów z dostępem do plików lub problemów z terminalem w systemie Windows, spróbuj użyć [WSL (podsystem Windows dla systemu Linux) (./windows-wsl). WSL zapewnia środowisko Linux, które płynniej współpracuje z funkcjami OpenCode. + +--- + +### Notifications not showing + +OpenCode Desktop only shows system notifications when: + +- powiadomienia są włączone dla OpenCode w ustawieniach systemu operacyjnego, oraz +- okno aplikacji nie jest aktywne. + +--- + +### Reset desktop app storage (last resort) + +Jeśli aplikacja nie uruchamia się i nie możesz wyczyścić ustawień w interfejsie użytkownika, zresetuj zapisany stan aplikacji komputerowej. + +1. Quit OpenCode Desktop. +2. Znajdź i usuń te pliki (znajdują się w katalogu danych aplikacji OpenCode Desktop): + +- `opencode.settings.dat` (domyślny adres URL serwera na komputerze stacjonarnym) +- `opencode.global.dat` i `opencode.workspace.*.dat` (stan interfejsu użytkownika, taki jak najnowsze serwery/projekty) + +Aby szybko znaleźć katalog: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (następnie wyszukaj nazwy plików powyżej) +- **Linux**: wyszukaj powyższe nazwy plików pod `~/.local/share` +- **Windows**: Naciśnij `WIN+R` -> `%APPDATA%` (następnie wyszukaj nazwy plików powyżej) + +--- + +## Getting help + +Jeśli masz problemy z OpenCode: + +1. **Report issues on GitHub** + + Najlepszym sposobem zgłaszania błędów lub zgłaszania żądań funkcji jest skorzystanie z naszego repozytorium GitHub: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + Przed utworzeniem nowego problemu przeszukaj istniejące i sprawdź, czy Twój problem nie został już zgłoszony. + +2. **Join our Discord** + + Aby uzyskać pomoc w czasie rzeczywistym i dyskusję społeczności, dołącz do naszego serwera Discord: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Common issues + +Oto kilka typowych problemów i sposobów ich rozwiązania. + +--- + +### OpenCode nie uruchamia się + +1. Sprawdź dzienniki pod kątem komunikatów o błędach +2. Spróbuj uruchomić z `--print-logs`, aby zobaczyć dane wyjściowe w terminalu +3. Upewnij się, że masz najnowszą wersję z `opencode upgrade` + +--- + +### Authentication issues + +1. Spróbuj ponownie uwierzytelnić się za pomocą polecenia `/connect` w TUI +2. Sprawdź, czy klucze API są ważne +3. Upewnij się, że Twoja sieć umożliwia połączenia z interfejsem API dostawcy + +--- + +### Model niedostępny + +1. Sprawdź, czy dokonałeś uwierzytelnienia u dostawcy +2. Sprawdź, czy nazwa modelu w konfiguracji jest poprawna +3. Some models may require specific access or subscriptions + +Jeśli napotkasz `ProviderModelNotFoundError`, najprawdopodobniej się mylisz +odwołując się gdzieś do modelu. +Models should be referenced like so: `/` + +Examples: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +Aby dowiedzieć się, do jakich modeli masz dostęp, uruchom `opencode models` + +--- + +### ProviderInitError + +Jeśli napotkasz błąd ProviderInitError, prawdopodobnie masz nieprawidłową lub uszkodzoną konfigurację. + +Aby rozwiązać ten problem: + +1. Najpierw sprawdź, czy Twój dostawca jest prawidłowo skonfigurowany, postępując zgodnie z [przewodnikiem dostawców](/docs/providers) +2. Jeśli problem będzie się powtarzał, spróbuj wyczyścić zapisaną konfigurację: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + W systemie Windows naciśnij `WIN+R` i usuń: `%USERPROFILE%\.local\share\opencode` + +3. Ponownie uwierzytelnij się u swojego dostawcy za pomocą polecenia `/connect` w TUI. + +--- + +### Problemy z AI_APICallError i pakietem dostawcy + +Jeśli napotkasz błędy wywołań API, może to wynikać z nieaktualnych pakietów dostawców. opencode dynamicznie instaluje pakiety dostawców (OpenAI, Anthropic, Google itp.) w razie potrzeby i przechowuje je lokalnie w pamięci podręcznej. + +Aby rozwiązać problemy z pakietem dostawcy: + +1. Wyczyść pamięć podręczną pakietu dostawcy: + + ```bash + rm -rf ~/.cache/opencode + ``` + + W systemie Windows naciśnij `WIN+R` i usuń: `%USERPROFILE%\.cache\opencode` + +2. Uruchom ponownie kod opencode, aby ponownie zainstalować najnowsze pakiety dostawców + +Zmusi to opencode do pobrania najnowszych wersji pakietów dostawców, co często rozwiązuje problemy ze zgodnością z parametrami modelu i zmianami API. + +--- + +### Copy/paste not working on Linux + +Aby funkcja kopiowania/wklejania działała, użytkownicy systemu Linux muszą mieć zainstalowane jedno z następujących narzędzi schowka: + +**Dla systemów X11:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**Dla systemów Wayland:** + +```bash +apt install -y wl-clipboard +``` + +**Dla środowisk bezgłowych:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode wykryje, czy używasz Waylanda i wolisz `wl-clipboard`, w przeciwnym razie spróbuje znaleźć narzędzia schowka w kolejności: `xclip` i `xsel`. diff --git a/packages/web/src/content/docs/pl/tui.mdx b/packages/web/src/content/docs/pl/tui.mdx new file mode 100644 index 000000000..8a5dbe7a7 --- /dev/null +++ b/packages/web/src/content/docs/pl/tui.mdx @@ -0,0 +1,390 @@ +--- +title: TUI +description: Korzystanie z interfejsu użytkownika terminala OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode zapewnia interaktywny interfejs terminala lub TUI do pracy nad projektami za pomocą LLM. + +Uruchomienie OpenCode uruchamia TUI dla bieżącego katalogu. + +```bash +opencode +``` + +Możesz też uruchomić go dla określonego katalogu roboczego. + +```bash +opencode /path/to/project +``` + +Gdy znajdziesz się w TUI, możesz wyświetlić monit za pomocą komunikatu. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## File references + +Możesz odwoływać się do plików w swoich wiadomościach, używając `@`. Spowoduje to rozmyte wyszukiwanie plików w bieżącym katalogu roboczym. + +:::tip +Możesz także użyć `@` do odwoływania się do plików w swoich wiadomościach. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +Zawartość pliku jest automatycznie dodawana do rozmowy. + +--- + +## Bash commands + +Rozpocznij wiadomość od `!`, aby uruchomić polecenie powłoki. + +```bash frame="none" +!ls -la +``` + +Dane wyjściowe polecenia są dodawane do konwersacji jako wynik narzędzia. + +--- + +## Komendy + +Korzystając z TUI OpenCode, możesz wpisać `/`, po którym następuje nazwa polecenia, aby szybko wykonać działania. Na przykład: + +```bash frame="none" +/help +``` + +Większość poleceń ma również skrót klawiszowy wykorzystujący `ctrl+x` jako klucz wiodący, gdzie `ctrl+x` jest domyślnym klawiszem wiodącym. [Dowiedz się więcej](/docs/keybinds). + +Oto wszystkie dostępne polecenia ukośnika: + +--- + +### connect + +Dodaj dostawcę do OpenCode. Umożliwia wybór dostępnych dostawców i dodanie ich kluczy API. + +```bash frame="none" +/connect +``` + +--- + +### compact + +Kompaktuj bieżącą sesję. _Alias_: `/summarize` + +```bash frame="none" +/compact +``` + +**Keybind:** `ctrl+x c` + +--- + +### details + +Toggle tool execution details. + +```bash frame="none" +/details +``` + +**Keybind:** `ctrl+x d` + +--- + +### editor + +Otwórz zewnętrzny edytor do tworzenia wiadomości. Używa edytora ustawionego w zmiennej środowiskowej `EDITOR`. [Dowiedz się więcej](#editor-setup). + +```bash frame="none" +/editor +``` + +**Keybind:** `ctrl+x e` + +--- + +### exit + +Exit OpenCode. _Aliases_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Keybind:** `ctrl+x q` + +--- + +### export + +Wyeksportuj bieżącą rozmowę do Markdown i otwórz ją w domyślnym edytorze. Używa edytora ustawionego w zmiennej środowiskowej `EDITOR`. [Dowiedz się więcej](#editor-setup). + +```bash frame="none" +/export +``` + +**Keybind:** `ctrl+x x` + +--- + +### help + +Pokaż okno pomocy. + +```bash frame="none" +/help +``` + +**Keybind:** `ctrl+x h` + +--- + +### init + +Utwórz lub zaktualizuj plik `AGENTS.md`. [Dowiedz się więcej](/docs/rules). + +```bash frame="none" +/init +``` + +**Keybind:** `ctrl+x i` + +--- + +### models + +Lista dostępnych modeli. + +```bash frame="none" +/models +``` + +**Keybind:** `ctrl+x m` + +--- + +### new + +Rozpocznij nową sesję. _Alias_: `/clear` + +```bash frame="none" +/new +``` + +**Keybind:** `ctrl+x n` + +--- + +### redo + +Ponów cofniętą wcześniej wiadomość. Dostępne tylko po użyciu `/undo`. + +:::tip +Any file changes will also be restored. +::: + +Wewnętrznie używa Git do zarządzania zmianami plików. Więc Twój projekt ** musi +be a Git repository**. + +```bash frame="none" +/redo +``` + +**Keybind:** `ctrl+x r` + +--- + +### sessions + +Wyświetl listę i przełączaj się między sesjami. _Aliasy_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Keybind:** `ctrl+x l` + +--- + +### share + +Udostępnij bieżącą sesję. [Dowiedz się więcej](/docs/share). + +```bash frame="none" +/share +``` + +**Keybind:** `ctrl+x s` + +--- + +### themes + +Lista dostępnych motywów. + +```bash frame="none" +/theme +``` + +**Keybind:** `ctrl+x t` + +--- + +### thinking + +Przełącz widoczność bloków myślenia/rozumowania w rozmowie. Po włączeniu tej opcji można zobaczyć proces wnioskowania modelu w przypadku modeli obsługujących myślenie rozszerzone. + +:::note +To polecenie kontroluje jedynie, czy bloki myślowe są **wyświetlane** - nie włącza ani nie wyłącza możliwości wnioskowania modelu. Aby przełączyć rzeczywiste możliwości wnioskowania, użyj `ctrl+t` do przełączania wariantów modelu. +::: + +```bash frame="none" +/thinking +``` + +--- + +### undo + +Cofnij ostatnią wiadomość w rozmowie. Usuwa najnowszą wiadomość użytkownika, wszystkie kolejne odpowiedzi i wszelkie zmiany w plikach. + +:::tip +Any file changes made will also be reverted. +::: + +Wewnętrznie używa Git do zarządzania zmianami plików. Więc Twój projekt ** musi +be a Git repository**. + +```bash frame="none" +/undo +``` + +**Keybind:** `ctrl+x u` + +--- + +### unshare + +Anuluj udostępnianie bieżącej sesji. [Dowiedz się więcej](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## Editor setup + +Zarówno polecenia `/editor`, jak i `/export` korzystają z edytora określonego w zmiennej środowiskowej `EDITOR`. + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + + Aby było to trwałe, dodaj to do swojego profilu powłoki; + `~/.bashrc`, `~/.zshrc`, etc. + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + + Aby ustawić tę opcję na stałe, użyj opcji **Właściwości systemu** > **Środowisko + Variables**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + + Aby uczynić to trwałym, dodaj to do swojego profilu PowerShell. + + + + +Popular editor options include: + +- `code` - Visual Studio Code +- `cursor` - Cursor +- `windsurf` - Windsurf +- `nvim` - Neovim editor +- `vim` - Vim editor +- `nano` - Nano editor +- `notepad` - Windows Notepad +- `subl` - Sublime Text + +:::note +Niektóre edytory, takie jak VS Code, należy uruchamiać z flagą `--wait`. +::: + +Niektórzy redaktorzy potrzebują argumentów wiersza poleceń, aby działać w trybie blokowania. Flaga `--wait` blokuje proces edytora aż do jego zamknięcia. + +--- + +## Skonfiguruj + +Możesz dostosować zachowanie TUI za pomocą pliku konfiguracyjnego OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### Options + +- `scroll_acceleration` — Włącz przyspieszenie przewijania w stylu macOS, aby zapewnić płynne, naturalne przewijanie. Po włączeniu prędkość przewijania wzrasta wraz z szybkimi gestami przewijania i pozostaje precyzyjna w przypadku wolniejszych ruchów. **To ustawienie ma pierwszeństwo przed `scroll_speed` i zastępuje je, gdy jest włączone.** +- `scroll_speed` - Kontroluje szybkość przewijania TUI podczas korzystania z poleceń przewijania (minimum: `1`). Wartość domyślna to `3`. **Uwaga: jest to ignorowane, jeśli `scroll_acceleration.enabled` jest ustawione na `true`.** + +--- + +## Customization + +Za pomocą palety poleceń (`ctrl+x h` lub `/help`) można dostosować różne aspekty widoku TUI. Te ustawienia są zachowywane po ponownym uruchomieniu. + +--- + +#### Username display + +Włącz lub wyłącz wyświetlanie Twojej nazwy użytkownika w wiadomościach na czacie. Dostęp do tego poprzez: + +- Paleta poleceń: Wyszukaj „nazwę użytkownika” lub „ukryj nazwę użytkownika” +- Ustawienie zostanie zapamiętane automatycznie i będzie pamiętane podczas sesji TUI diff --git a/packages/web/src/content/docs/pl/web.mdx b/packages/web/src/content/docs/pl/web.mdx new file mode 100644 index 000000000..689d22d7d --- /dev/null +++ b/packages/web/src/content/docs/pl/web.mdx @@ -0,0 +1,142 @@ +--- +title: Web +description: Korzystanie z OpenCode w przeglądarce. +--- + +OpenCode może działać jako aplikacja internetowa w przeglądarce, zapewniając takie same możliwości kodowania AI bez konieczności korzystania z terminala. + +![Sieć OpenCode - Nowa sesja](../../../assets/web/web-homepage-new-session.png) + +## Getting Started + +Uruchom interfejs sieciowy, uruchamiając: + +```bash +opencode web +``` + +Spowoduje to uruchomienie lokalnego serwera na `127.0.0.1` z losowo dostępnym portem i automatyczne otwarcie OpenCode w domyślnej przeglądarce. + +:::caution +Jeśli `OPENCODE_SERVER_PASSWORD` nie jest ustawione, serwer będzie niezabezpieczony. Jest to dobre rozwiązanie do użytku lokalnego, ale powinno być ustawione na dostęp do sieci. +::: + +:::tip[Windows Users] +Aby uzyskać najlepsze wyniki, uruchom `opencode web` z [WSL](/docs/windows-wsl) zamiast programu PowerShell. Zapewnia to prawidłowy dostęp do systemu plików i integrację terminala. +::: + +--- + +## Configuration + +Możesz skonfigurować serwer WWW za pomocą flag wiersza poleceń lub w [pliku konfiguracyjnym] (./config). + +### Port + +Domyślnie OpenCode wybiera dostępny port. Możesz określić port: + +```bash +opencode web --port 4096 +``` + +### Hostname + +Domyślnie serwer łączy się z `127.0.0.1` (tylko localhost). Aby udostępnić OpenCode w swojej sieci: + +```bash +opencode web --hostname 0.0.0.0 +``` + +Podczas korzystania z `0.0.0.0` OpenCode wyświetli zarówno adresy lokalne, jak i sieciowe: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### mDNS Discovery + +Włącz mDNS, aby Twój serwer był wykrywalny w sieci lokalnej: + +```bash +opencode web --mdns +``` + +To automatycznie ustawia nazwę hosta na `0.0.0.0` i anonsuje serwer jako `opencode.local`. + +Możesz dostosować nazwę domeny mDNS, aby uruchamiała wiele instancji w tej samej sieci: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +Aby zezwolić na dodatkowe domeny dla CORS (przydatne w przypadku niestandardowych interfejsów): + +```bash +opencode web --cors https://example.com +``` + +### Authentication + +Aby chronić dostęp, ustaw hasło za pomocą zmiennej środowiskowej `OPENCODE_SERVER_PASSWORD`: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +Domyślna nazwa użytkownika to `opencode`, ale można ją zmienić za pomocą `OPENCODE_SERVER_USERNAME`. + +--- + +## Korzystanie z interfejsu internetowego + +Po uruchomieniu interfejs sieciowy zapewnia dostęp do sesji OpenCode. + +### Sessions + +Przeglądaj sesje i zarządzaj nimi ze strony głównej. Możesz zobaczyć aktywne sesje i rozpocząć nowe. + +![OpenCode Web - Aktywna sesja](../../../assets/web/web-homepage-active-session.png) + +### Stan serwera + +Kliknij „Zobacz serwery”, aby wyświetlić podłączone serwery i ich status. + +![OpenCode Web - See Servers](../../../assets/web/web-homepage-see-servers.png) + +--- + +## Attaching a Terminal + +Możesz podłączyć terminal TUI do działającego serwera WWW: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +Umożliwia to jednoczesne korzystanie z interfejsu sieciowego i terminala, współdzieląc te same sesje i stan. + +--- + +## Config File + +Możesz także skonfigurować ustawienia serwera w pliku konfiguracyjnym `opencode.json`: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +Flagi wiersza poleceń mają pierwszeństwo przed ustawieniami pliku konfiguracyjnego. diff --git a/packages/web/src/content/docs/pl/windows-wsl.mdx b/packages/web/src/content/docs/pl/windows-wsl.mdx new file mode 100644 index 000000000..b930cf637 --- /dev/null +++ b/packages/web/src/content/docs/pl/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: Uruchamiaj OpenCode na Windows z WSL dla najlepszych efektow. +--- + +import { Steps } from "@astrojs/starlight/components" + +Chociaz OpenCode moze dzialac bezposrednio na Windows, dla najlepszych rezultatow zalecamy [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install). WSL zapewnia srodowisko Linuksa, ktore bardzo dobrze wspolpracuje z funkcjami OpenCode. + +:::tip[Dlaczego WSL?] +WSL oferuje lepsza wydajnosc systemu plikow, pelna obsluge terminala i zgodnosc z narzedziami developerskimi, na ktorych opiera sie OpenCode. +::: + +--- + +## Konfiguracja + + + +1. **Zainstaluj WSL** + + Jesli jeszcze tego nie zrobiles, [zainstaluj WSL](https://learn.microsoft.com/en-us/windows/wsl/install) wedlug oficjalnego przewodnika Microsoft. + +2. **Zainstaluj OpenCode w WSL** + + Po skonfigurowaniu WSL otworz terminal WSL i zainstaluj OpenCode jedna z [metod instalacji](/docs/). + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **Korzystaj z OpenCode przez WSL** + + Przejdz do katalogu projektu (pliki Windows sa dostepne przez `/mnt/c/`, `/mnt/d/` itd.) i uruchom OpenCode. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## Aplikacja desktopowa + serwer WSL + +Jesli wolisz aplikacje desktopowa OpenCode, ale chcesz uruchamiac serwer w WSL: + +1. **Uruchom serwer w WSL** z `--hostname 0.0.0.0`, aby zezwolic na polaczenia zewnetrzne: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Polacz aplikacje desktopowa** z `http://localhost:4096` + +:::note +Jesli `localhost` nie dziala w Twojej konfiguracji, polacz sie przez adres IP WSL (w WSL: `hostname -I`) i uzyj `http://:4096`. +::: + +:::caution +Przy uzyciu `--hostname 0.0.0.0` ustaw `OPENCODE_SERVER_PASSWORD`, aby zabezpieczyc serwer. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Klient web + WSL + +Dla najlepszej pracy w przegladarce na Windows: + +1. **Uruchamiaj `opencode web` w terminalu WSL**, a nie w PowerShell: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Otworz w przegladarce Windows** pod adresem `http://localhost:` (OpenCode wypisze URL) + +Uruchamianie `opencode web` z WSL zapewnia poprawny dostep do systemu plikow i integracje z terminalem, a nadal pozostaje dostepne z przegladarki Windows. + +--- + +## Dostep do plikow Windows + +WSL moze uzyskac dostep do wszystkich plikow Windows przez katalog `/mnt/`: + +- Dysk `C:` → `/mnt/c/` +- Dysk `D:` → `/mnt/d/` +- I tak dalej... + +Przyklad: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +Aby uzyskac najplynniejsza prace, rozwaz sklonowanie/skopiowanie repozytorium do systemu plikow WSL (np. do `~/code/`) i uruchamianie tam OpenCode. +::: + +--- + +## Wskazowki + +- Uruchamiaj OpenCode w WSL dla projektow zapisanych na dyskach Windows - dostep do plikow jest bezproblemowy +- Uzywaj [rozszerzenia WSL dla VS Code](https://code.visualstudio.com/docs/remote/wsl) razem z OpenCode, aby miec zintegrowany workflow +- Konfiguracja OpenCode i sesje sa przechowywane w srodowisku WSL pod `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/pl/zen.mdx b/packages/web/src/content/docs/pl/zen.mdx new file mode 100644 index 000000000..31f263e32 --- /dev/null +++ b/packages/web/src/content/docs/pl/zen.mdx @@ -0,0 +1,254 @@ +--- +title: Zen +description: Wyselekcjonowana lista modeli dostarczonych przez OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen to lista przetestowanych i zweryfikowanych modeli udostępniona przez zespół OpenCode. + +:::note +OpenCode Zen is currently in beta. +::: + +Zen działa jak każdy inny dostawca OpenCode. Logujesz się do OpenCode Zen i dostajesz +Twój klucz API. Jest **całkowicie opcjonalny** i nie musisz go używać, aby z niego korzystać +OpenCode. + +--- + +## Background + +There are a large number of models out there but only a few of +these models work well as coding agents. Additionally, most providers are +skonfigurowany bardzo różnie; więc otrzymujesz zupełnie inną wydajność i jakość. + +:::tip +Przetestowaliśmy wybraną grupę modeli i dostawców, którzy dobrze współpracują z OpenCode. +::: + +Jeśli więc używasz modelu za pośrednictwem czegoś takiego jak OpenRouter, nigdy nie będzie to możliwe +pewien, czy otrzymujesz najlepszą wersję modelu, jaki chcesz. + +Aby to naprawić, zrobiliśmy kilka rzeczy: + +1. Przetestowaliśmy wybraną grupę modeli i rozmawialiśmy z ich zespołami o tym, jak to zrobić + najlepiej je uruchom. +2. Następnie współpracowaliśmy z kilkoma dostawcami, aby upewnić się, że są one obsługiwane + correctly. +3. Na koniec porównaliśmy kombinację modelu/dostawcy i otrzymaliśmy wynik + z listą, którą z przyjemnością polecamy. + +OpenCode Zen to brama AI, która zapewnia dostęp do tych modeli. + +--- + +## How it works + +OpenCode Zen działa jak każdy inny dostawca OpenCode. + +1. Logujesz się do **OpenCode Zen**, dodajesz swoje rozliczenia + szczegóły i skopiuj klucz API. +2. Uruchamiasz polecenie `/connect` w TUI, wybierasz OpenCode Zen i wklejasz klucz API. +3. Uruchom `/models` w TUI, aby zobaczyć listę zalecanych przez nas modeli. + +Opłata jest pobierana za każde żądanie i możesz dodać kredyty do swojego konta. + +--- + +## Endpoints + +Dostęp do naszych modeli można również uzyskać za pośrednictwem następujących punktów końcowych interfejsu API. + +| Modelka | Identyfikator modelu | Punkt końcowy | Pakiet SDK AI | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Free | minimax-m2.1-free | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Free | glm-4.7-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Free | kimi-k2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +[Identyfikator modelu](/docs/config/#models) w konfiguracji OpenCode +używa formatu `opencode/`. Na przykład w przypadku Kodeksu GPT 5.2 zrobiłbyś to +użyj `opencode/gpt-5.2-codex` w swojej konfiguracji. + +--- + +### Models + +Pełną listę dostępnych modeli i ich metadane możesz pobrać z: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## Pricing + +Wspieramy model pay-as-you-go. Poniżej znajdują się ceny **za 1M tokenów**. + +| Modelka | Wejście | Wyjście | Odczyt w pamięci podręcznej | Zapis w pamięci podręcznej | +| --------------------------------- | ------ | ------ | ----------- | ------------ | +| Big Pickle | Free | Free | Free | - | +| MiniMax M2.1 Free | Free | Free | Free | - | +| MiniMax M2.1 | $0.30 | $1.20 | $0.10 | - | +| GLM 4.7 Free | Free | Free | Free | - | +| GLM 4.7 | $0.60 | $2.20 | $0.10 | - | +| GLM 4.6 | $0.60 | $2.20 | $0.10 | - | +| Kimi K2.5 Free | Free | Free | Free | - | +| Kimi K2.5 | $0.60 | $3.00 | $0.08 | - | +| Kimi K2 Thinking | $0.40 | $2.50 | - | - | +| Kimi K2 | $0.40 | $2.50 | - | - | +| Qwen3 Coder 480B | $0.45 | $1.50 | - | - | +| Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | +| Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | +| Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | +| Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | +| Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | - | +| Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | - | +| Gemini 3 Flash | $0.50 | $3.00 | $0.05 | - | +| GPT 5.2 | $1.75 | $14.00 | $0.175 | - | +| GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | - | +| GPT 5.1 | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | - | +| GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | - | +| GPT 5 | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Nano | Free | Free | Free | - | + +Możesz zauważyć _Claude Haiku 3.5_ w swojej historii użytkowania. To jest [model niskokosztowy](/docs/config/#models), który służy do generowania tytułów sesji. + +:::note +Opłaty za karty kredytowe są przenoszone na koszt (4,4% + 0,30 USD za transakcję); nie pobieramy żadnych dodatkowych opłat. +::: + +Darmowe modele: + +- GLM 4.7 Free jest dostępny na platformie OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas na zbieranie opinii i ulepszanie modelu. +- Kimi K2.5 Free jest dostępny na OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas na zbieranie opinii i ulepszanie modelu. +- MiniMax M2.1 Free jest dostępny na platformie OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas na zbieranie opinii i ulepszanie modelu. +- Big Pickle to ukryty model, który jest bezpłatny w OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas na zbieranie opinii i ulepszanie modelu. + +Skontaktuj się z nami, jeśli masz jakieś pytania. + +--- + +### Auto-reload + +Jeśli Twoje saldo spadnie poniżej 5 USD, Zen automatycznie doładuje 20 USD. + +Możesz zmienić kwotę automatycznego doładowania. Możesz także całkowicie wyłączyć automatyczne przeładowywanie. + +--- + +### Monthly limits + +Możesz także ustawić miesięczny limit wykorzystania dla całego obszaru roboczego i dla każdego z nich +członek Twojego zespołu. + +Załóżmy na przykład, że ustawiłeś miesięczny limit użytkowania na 20 USD, Zen nie będzie z niego korzystał +ponad 20 dolarów miesięcznie. Ale jeśli masz włączone automatyczne przeładowywanie, Zen może się skończyć +obciąży Cię kwotą wyższą niż 20 USD, jeśli saldo spadnie poniżej 5 USD. + +--- + +## Privacy + +Wszystkie nasze modele są hostowane w USA. Nasi dostawcy przestrzegają polityki zerowego przechowywania i nie wykorzystują Twoich danych do szkolenia modeli, z następującymi wyjątkami: + +- Big Pickle: W okresie bezpłatnym zebrane dane mogą zostać wykorzystane do udoskonalenia modelu. +- GLM 4.7 Bezpłatna: W okresie bezpłatnym zebrane dane mogą zostać wykorzystane do udoskonalenia modelu. +- Kimi K2.5 Free: W okresie bezpłatnym zebrane dane mogą zostać wykorzystane do udoskonalenia modelu. +- MiniMax M2.1 Free: W okresie bezpłatnym zebrane dane mogą zostać wykorzystane do udoskonalenia modelu. +- Interfejsy API OpenAI: żądania są przechowywane przez 30 dni zgodnie z [Zasadami dotyczącymi danych OpenAI](https://platform.openai.com/docs/guides/your-data). +- Interfejsy API Anthropic: żądania są przechowywane przez 30 dni zgodnie z [Zasadami dotyczącymi danych firmy Anthropic] (https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## Dla zespołów + +Zen świetnie sprawdza się także w zespołach. Możesz zapraszać członków zespołu, przypisywać role, zarządzać +modele, z których korzysta Twój zespół i nie tylko. + +:::note +Obszary robocze są obecnie bezpłatne dla zespołów w ramach wersji beta. +::: + +Zarządzanie obszarem roboczym jest obecnie bezpłatne dla zespołów w ramach wersji beta. Będziemy +wkrótce udostępnimy więcej szczegółów na temat cen. + +--- + +### Roles + +Możesz zapraszać członków zespołu do swojego obszaru roboczego i przypisywać role: + +- **Administrator**: Zarządzaj modelami, członkami, kluczami API i rozliczeniami +- **Członek**: Zarządzaj tylko własnymi kluczami API + +Administratorzy mogą także ustawić miesięczne limity wydatków dla każdego członka, aby utrzymać koszty pod kontrolą. + +--- + +### Dostęp do modelu + +Administratorzy mogą włączać i wyłączać określone modele w obszarze roboczym. Żądania skierowane do wyłączonego modelu zwrócą błąd. + +Jest to przydatne w przypadkach, gdy chcesz wyłączyć korzystanie z modelu, który +collects data. + +--- + +### Przynieś swój własny klucz + +Możesz używać własnych kluczy OpenAI lub Anthropic API, jednocześnie uzyskując dostęp do innych modeli w Zen. + +Kiedy używasz własnych kluczy, tokeny są rozliczane bezpośrednio przez dostawcę, a nie przez Zen. + +Na przykład Twoja organizacja może już mieć klucz do OpenAI lub Anthropic +i chcesz go używać zamiast tego, który zapewnia Zen. + +--- + +## Goals + +We created OpenCode Zen to: + +1. **Benchmark** najlepsze modele/dostawcy dla agentów kodujących. +2. Miej dostęp do opcji **najwyższej jakości**, a nie obniżaj wydajności ani nie kieruj się do tańszych dostawców. +3. Przekaż wszelkie **obniżki cen**, sprzedając po kosztach; więc jedyną marżą jest pokrycie naszych opłat manipulacyjnych. +4. Nie **nie blokuj**, umożliwiając używanie go z dowolnym innym agentem kodującym. I zawsze pozwalaj na korzystanie z OpenCode dowolnego innego dostawcy. diff --git a/packages/web/src/content/docs/pt-br/1-0.mdx b/packages/web/src/content/docs/pt-br/1-0.mdx new file mode 100644 index 000000000..21fdb8568 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/1-0.mdx @@ -0,0 +1,66 @@ +--- +title: Migrando para 1.0 +description: O que há de novo no OpenCode 1.0. +--- + +OpenCode 1.0 é uma reescrita completa do TUI. + +Mudamos do TUI baseado em go+bubbletea, que tinha problemas de desempenho e capacidade, para um framework interno (OpenTUI) escrito em zig+solidjs. + +O novo TUI funciona como o antigo, pois se conecta ao mesmo servidor opencode. + +--- + +## Atualizando + +Você não deve ser atualizado automaticamente para 1.0 se estiver usando uma versão anterior. No entanto, algumas versões mais antigas do OpenCode sempre pegam a mais recente. + +Para atualizar manualmente, execute + +```bash +$ opencode upgrade 1.0.0 +``` + +Para reverter para 0.x, execute + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## Mudanças na UX + +O histórico da sessão está mais comprimido, mostrando apenas os detalhes completos da edição e da ferramenta bash. + +Adicionamos uma barra de comandos pela qual quase tudo flui. Pressione ctrl+p para abri-la em qualquer contexto e veja tudo o que você pode fazer. + +Adicionada uma barra lateral de sessão (pode ser alternada) com informações úteis. + +Removemos algumas funcionalidades das quais não tínhamos certeza se alguém realmente usava. Se algo importante estiver faltando, por favor, abra uma issue e nós adicionaremos rapidamente. + +--- + +## Mudanças que quebram compatibilidade + +### Teclas de atalho renomeadas + +- messages_revert -> messages_undo +- switch_agent -> agent_cycle +- switch_agent_reverse -> agent_cycle_reverse +- switch_mode -> agent_cycle +- switch_mode_reverse -> agent_cycle_reverse + +### Teclas de atalho removidas + +- messages_layout_toggle +- messages_next +- messages_previous +- file_diff_toggle +- file_search +- file_close +- file_list +- app_help +- project_init +- tool_details +- thinking_blocks \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/acp.mdx b/packages/web/src/content/docs/pt-br/acp.mdx new file mode 100644 index 000000000..80c43e960 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/acp.mdx @@ -0,0 +1,156 @@ +--- +title: Suporte ACP +description: Use OpenCode em qualquer editor compatível com ACP. +--- + +OpenCode suporta o [Agent Client Protocol](https://agentclientprotocol.com) ou (ACP), permitindo que você o utilize diretamente em editores e IDEs compatíveis. + +:::tip +Para uma lista de editores e ferramentas que suportam ACP, confira o [relatório de progresso do ACP](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP é um protocolo aberto que padroniza a comunicação entre editores de código e agentes de codificação de IA. + +--- + +## Configurar + +Para usar OpenCode via ACP, configure seu editor para executar o comando `opencode acp`. + +O comando inicia o OpenCode como um subprocesso compatível com ACP que se comunica com seu editor via JSON-RPC através do stdio. + +Abaixo estão exemplos para editores populares que suportam ACP. + +--- + +### Zed + +Adicione à sua configuração do [Zed](https://zed.dev) (`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +Para abri-lo, use a ação `agent: new thread` na **Paleta de Comandos**. + +Você também pode vincular um atalho de teclado editando seu `keymap.json`: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### IDEs JetBrains + +Adicione ao seu acp.json do [JetBrains IDE](https://www.jetbrains.com/) de acordo com a [documentação](https://www.jetbrains.com/help/ai-assistant/acp.html): + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +Para abri-lo, use o novo agente 'OpenCode' no seletor de agentes do AI Chat. + +--- + +### Avante.nvim + +Adicione à sua configuração do [Avante.nvim](https://github.com/yetone/avante.nvim): + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +Se você precisar passar variáveis de ambiente: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +Para usar OpenCode como um agente ACP no [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim), adicione o seguinte à sua configuração do Neovim: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +Esta configuração configura o CodeCompanion para usar OpenCode como o agente ACP para chat. + +Se você precisar passar variáveis de ambiente (como `OPENCODE_API_KEY`), consulte [Configurando Adaptadores: Variáveis de Ambiente](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) na documentação do CodeCompanion.nvim para detalhes completos. + +## Suporte + +OpenCode funciona da mesma forma via ACP como funciona no terminal. Todos os recursos são suportados: + +:::note +Alguns comandos de barra integrados, como `/undo` e `/redo`, atualmente não são suportados. +::: + +- Ferramentas integradas (operações de arquivo, comandos de terminal, etc.) +- Ferramentas personalizadas e comandos de barra +- Servidores MCP configurados na sua configuração do OpenCode +- Regras específicas do projeto do `AGENTS.md` +- Formatadores e linters personalizados +- Sistema de agentes e permissões \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/agents.mdx b/packages/web/src/content/docs/pt-br/agents.mdx new file mode 100644 index 000000000..34903b3f6 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/agents.mdx @@ -0,0 +1,747 @@ +--- +title: Agentes +description: Configure e use agentes especializados. +--- + +Agentes são assistentes de IA especializados que podem ser configurados para tarefas e fluxos de trabalho específicos. Eles permitem que você crie ferramentas focadas com prompts, modelos e acesso a ferramentas personalizados. + +:::tip +Use o agente de planejamento para analisar código e revisar sugestões sem fazer alterações no código. +::: + +Você pode alternar entre agentes durante uma sessão ou invocá-los com a menção `@`. + +--- + +## Tipos + +Existem dois tipos de agentes no OpenCode; agentes primários e subagentes. + +--- + +### Agentes primários + +Agentes primários são os principais assistentes com os quais você interage diretamente. Você pode alternar entre eles usando a tecla **Tab** ou sua tecla de atalho configurada `switch_agent`. Esses agentes lidam com sua conversa principal. O acesso às ferramentas é configurado por meio de permissões — por exemplo, Build tem todas as ferramentas habilitadas, enquanto Plan é restrito. + +:::tip +Você pode usar a tecla **Tab** para alternar entre agentes primários durante uma sessão. +::: + +OpenCode vem com dois agentes primários integrados, **Build** e **Plan**. Vamos +ver isso abaixo. + +--- + +### Subagentes + +Subagentes são assistentes especializados que agentes primários podem invocar para tarefas específicas. Você também pode invocá-los manualmente mencionando-os com **@** em suas mensagens. + +OpenCode vem com dois subagentes integrados, **General** e **Explore**. Vamos ver isso abaixo. + +--- + +## Integrado + +OpenCode vem com dois agentes primários integrados e dois subagentes integrados. + +--- + +### Usar build + +_Modo_: `primary` + +Build é o agente primário **padrão** com todas as ferramentas habilitadas. Este é o agente padrão para trabalho de desenvolvimento onde você precisa de acesso total a operações de arquivo e comandos do sistema. + +--- + +### Usar plan + +_Modo_: `primary` + +Um agente restrito projetado para planejamento e análise. Usamos um sistema de permissões para lhe dar mais controle e evitar alterações não intencionais. +Por padrão, todos os seguintes estão configurados para `ask`: + +- `file edits`: Todas as gravações, patches e edições +- `bash`: Todos os comandos bash + +Este agente é útil quando você deseja que o LLM analise código, sugira alterações ou crie planos sem fazer modificações reais em seu código. + +--- + +### Usar general + +_Modo_: `subagent` + +Um agente de propósito geral para pesquisar questões complexas e executar tarefas em múltiplas etapas. Tem acesso total às ferramentas (exceto todo), portanto, pode fazer alterações em arquivos quando necessário. Use isso para executar várias unidades de trabalho em paralelo. + +--- + +### Usar explore + +_Modo_: `subagent` + +Um agente rápido e somente leitura para explorar bases de código. Não pode modificar arquivos. Use isso quando você precisar encontrar rapidamente arquivos por padrões, pesquisar código por palavras-chave ou responder perguntas sobre a base de código. + +--- + +### Usar compaction + +_Modo_: `primary` + +Agente de sistema oculto que compacta longos contextos em um resumo menor. Ele é executado automaticamente quando necessário e não é selecionável na interface. + +--- + +### Usar title + +_Modo_: `primary` + +Agente de sistema oculto que gera títulos curtos para sessões. Ele é executado automaticamente e não é selecionável na interface. + +--- + +### Usar summary + +_Modo_: `primary` + +Agente de sistema oculto que cria resumos de sessões. Ele é executado automaticamente e não é selecionável na interface. + +--- + +## Uso + +1. Para agentes primários, use a tecla **Tab** para alternar entre eles durante uma sessão. Você também pode usar sua tecla de atalho configurada `switch_agent`. + +2. Subagentes podem ser invocados: + - **Automaticamente** por agentes primários para tarefas especializadas com base em suas descrições. + - Manualmente mencionando um subagente em sua mensagem. Por exemplo. + + ```txt frame="none" + @general help me search for this function + ``` + +3. **Navegação entre sessões**: Quando subagentes criam suas próprias sessões filhas, você pode navegar entre a sessão pai e todas as sessões filhas usando: + - **\+Right** (ou sua tecla de atalho configurada `session_child_cycle`) para alternar para frente através de pai → child1 → child2 → ... → pai + - **\+Left** (ou sua tecla de atalho configurada `session_child_cycle_reverse`) para alternar para trás através de pai ← child1 ← child2 ← ... ← pai + + Isso permite que você mude perfeitamente entre a conversa principal e o trabalho especializado do subagente. + +--- + +## Configurar + +Você pode personalizar os agentes integrados ou criar os seus próprios através da configuração. Os agentes podem ser configurados de duas maneiras: + +--- + +### JSON + +Configure os agentes em seu arquivo de configuração `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Revisa o código em busca de melhores práticas e problemas potenciais", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "Você é um revisor de código. Foque em segurança, desempenho e manutenibilidade.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Markdown + +Você também pode definir agentes usando arquivos markdown. Coloque-os em: + +- Global: `~/.config/opencode/agents/` +- Por projeto: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Revisa o código em busca de qualidade e melhores práticas +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +Você está no modo de revisão de código. Foque em: + +- Qualidade do código e melhores práticas +- Bugs potenciais e casos extremos +- Implicações de desempenho +- Considerações de segurança + +Forneça feedback construtivo sem fazer alterações diretas. +``` + +O nome do arquivo markdown se torna o nome do agente. Por exemplo, `review.md` cria um agente `review`. + +--- + +## Opções + +Vamos analisar essas opções de configuração em detalhes. + +--- + +### Descrição + +Use a opção `description` para fornecer uma breve descrição do que o agente faz e quando usá-lo. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Revisa o código em busca de melhores práticas e problemas potenciais" + } + } +} +``` + +Esta é uma opção de configuração **obrigatória**. + +--- + +### Temperatura + +Controle a aleatoriedade e criatividade das respostas do LLM com a configuração `temperature`. + +Valores mais baixos tornam as respostas mais focadas e determinísticas, enquanto valores mais altos aumentam a criatividade e variabilidade. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Os valores de temperatura geralmente variam de 0.0 a 1.0: + +- **0.0-0.2**: Respostas muito focadas e determinísticas, ideais para análise de código e planejamento +- **0.3-0.5**: Respostas equilibradas com alguma criatividade, boas para tarefas de desenvolvimento gerais +- **0.6-1.0**: Respostas mais criativas e variadas, úteis para brainstorming e exploração + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Se nenhuma temperatura for especificada, o OpenCode usa padrões específicos do modelo; tipicamente 0 para a maioria dos modelos, 0.55 para modelos Qwen. + +--- + +### Máximo de etapas + +Controle o número máximo de iterações que um agente pode realizar antes de ser forçado a responder apenas com texto. Isso permite que usuários que desejam controlar custos definam um limite nas ações do agente. + +Se isso não for definido, o agente continuará a iterar até que o modelo decida parar ou o usuário interrompa a sessão. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Raciocínio rápido com iterações limitadas", + "prompt": "Você é um pensador rápido. Resolva problemas com o mínimo de etapas.", + "steps": 5 + } + } +} +``` + +Quando o limite é alcançado, o agente recebe um prompt especial do sistema instruindo-o a responder com um resumo de seu trabalho e tarefas recomendadas restantes. + +:::caution +O campo legado `maxSteps` está obsoleto. Use `steps` em vez disso. +::: + +--- + +### Desativar + +Defina como `true` para desativar o agente. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Prompt + +Especifique um arquivo de prompt do sistema personalizado para este agente com a configuração `prompt`. O arquivo de prompt deve conter instruções específicas para o propósito do agente. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Este caminho é relativo ao local onde o arquivo de configuração está localizado. Portanto, isso funciona tanto para a configuração global do OpenCode quanto para a configuração específica do projeto. + +--- + +### Modelo + +Use a configuração `model` para substituir o modelo para este agente. Útil para usar diferentes modelos otimizados para diferentes tarefas. Por exemplo, um modelo mais rápido para planejamento, um modelo mais capaz para implementação. + +:::tip +Se você não especificar um modelo, os agentes primários usam o [modelo configurado globalmente](/docs/config#models) enquanto subagentes usarão o modelo do agente primário que invocou o subagente. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +O ID do modelo em sua configuração do OpenCode usa o formato `provider/model-id`. Por exemplo, se você estiver usando [OpenCode Zen](/docs/zen), você usaria `opencode/gpt-5.1-codex` para GPT 5.1 Codex. + +--- + +### Ferramentas + +Controle quais ferramentas estão disponíveis neste agente com a configuração `tools`. Você pode habilitar ou desabilitar ferramentas específicas definindo-as como `true` ou `false`. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +A configuração específica do agente substitui a configuração global. +::: + +Você também pode usar curingas para controlar várias ferramentas ao mesmo tempo. Por exemplo, para desativar todas as ferramentas de um servidor MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[Saiba mais sobre ferramentas](/docs/tools). + +--- + +### Permissões + +Você pode configurar permissões para gerenciar quais ações um agente pode realizar. Atualmente, as permissões para as ferramentas `edit`, `bash` e `webfetch` podem ser configuradas para: + +- `"ask"` — Solicitar aprovação antes de executar a ferramenta +- `"allow"` — Permitir todas as operações sem aprovação +- `"deny"` — Desativar a ferramenta + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +Você pode substituir essas permissões por agente. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +Você também pode definir permissões em agentes Markdown. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Revisão de código sem edições +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Apenas analise o código e sugira alterações. +``` + +Você pode definir permissões para comandos bash específicos. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +Isso pode aceitar um padrão glob. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +E você também pode usar o curinga `*` para gerenciar permissões para todos os comandos. +Como a última regra correspondente tem precedência, coloque o curinga `*` primeiro e regras específicas depois. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[Saiba mais sobre permissões](/docs/permissions). + +--- + +### Modo + +Controle o modo do agente com a configuração `mode`. A opção `mode` é usada para determinar como o agente pode ser usado. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +A opção `mode` pode ser definida como `primary`, `subagent` ou `all`. Se nenhum `mode` for especificado, o padrão é `all`. + +--- + +### Oculto + +Oculte um subagente do menu de autocompletar `@` com `hidden: true`. Útil para subagentes internos que devem ser invocados apenas programaticamente por outros agentes através da ferramenta Task. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +Isso afeta apenas a visibilidade do usuário no menu de autocompletar. Agentes ocultos ainda podem ser invocados pelo modelo através da ferramenta Task, se as permissões permitirem. + +:::note +Aplica-se apenas a agentes `mode: subagent`. +::: + +--- + +### Permissões de tarefa + +Controle quais subagentes um agente pode invocar através da ferramenta Task com `permission.task`. Usa padrões globais para correspondência flexível. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +Quando definido como `deny`, o subagente é removido da descrição da ferramenta Task completamente, então o modelo não tentará invocá-lo. + +:::tip +As regras são avaliadas em ordem, e a **última regra correspondente vence**. No exemplo acima, `orchestrator-planner` corresponde a ambos `*` (deny) e `orchestrator-*` (allow), mas como `orchestrator-*` vem depois de `*`, o resultado é `allow`. +::: + +:::tip +Os usuários sempre podem invocar qualquer subagente diretamente através do menu de autocompletar `@`, mesmo que as permissões de tarefa do agente o neguem. +::: + +--- + +### Cor + +Personalize a aparência visual do agente na interface com a opção `color`. Isso afeta como o agente aparece na interface. + +Use uma cor hex válida (por exemplo, `#FF5733`) ou cor de tema: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### Top P + +Controle a diversidade das respostas com a opção `top_p`. Alternativa à temperatura para controlar a aleatoriedade. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +Os valores variam de 0.0 a 1.0. Valores mais baixos são mais focados, valores mais altos são mais diversos. + +--- + +### Adicional + +Quaisquer outras opções que você especificar em sua configuração de agente serão **passadas diretamente** para o provedor como opções de modelo. Isso permite que você use recursos e parâmetros específicos do provedor. + +Por exemplo, com os modelos de raciocínio da OpenAI, você pode controlar o esforço de raciocínio: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agente que usa alto esforço de raciocínio para problemas complexos", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +Essas opções adicionais são específicas do modelo e do provedor. Verifique a documentação do seu provedor para parâmetros disponíveis. + +:::tip +Execute `opencode models` para ver uma lista dos modelos disponíveis. +::: + +--- + +## Criar agentes + +Você pode criar novos agentes usando o seguinte comando: + +```bash +opencode agent create +``` + +Este comando interativo irá: + +1. Perguntar onde salvar o agente; global ou específico do projeto. +2. Descrição do que o agente deve fazer. +3. Gerar um prompt de sistema apropriado e identificador. +4. Permitir que você selecione quais ferramentas o agente pode acessar. +5. Finalmente, criar um arquivo markdown com a configuração do agente. + +--- + +## Casos de uso + +Aqui estão alguns casos de uso comuns para diferentes agentes. + +- **Agente Build**: Trabalho de desenvolvimento completo com todas as ferramentas habilitadas +- **Agente Plan**: Análise e planejamento sem fazer alterações +- **Agente Review**: Revisão de código com acesso somente leitura e ferramentas de documentação +- **Agente Debug**: Focado em investigação com ferramentas bash e de leitura habilitadas +- **Agente Docs**: Redação de documentação com operações de arquivo, mas sem comandos do sistema + +--- + +## Exemplos + +Aqui estão alguns agentes de exemplo que você pode achar úteis. + +:::tip +Você tem um agente que gostaria de compartilhar? [Envie um PR](https://github.com/anomalyco/opencode). +::: + +--- + +### Agente de documentação + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Escreve e mantém a documentação do projeto +mode: subagent +tools: + bash: false +--- + +Você é um redator técnico. Crie documentação clara e abrangente. + +Foque em: + +- Explicações claras +- Estrutura adequada +- Exemplos de código +- Linguagem amigável ao usuário +``` + +--- + +### Auditor de segurança + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Realiza auditorias de segurança e identifica vulnerabilidades +mode: subagent +tools: + write: false + edit: false +--- + +Você é um especialista em segurança. Foque em identificar problemas potenciais de segurança. + +Procure por: + +- Vulnerabilidades de validação de entrada +- Falhas de autenticação e autorização +- Riscos de exposição de dados +- Vulnerabilidades de dependência +- Problemas de segurança de configuração +``` \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/cli.mdx b/packages/web/src/content/docs/pt-br/cli.mdx new file mode 100644 index 000000000..9b5a5dff1 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/cli.mdx @@ -0,0 +1,601 @@ +--- +title: CLI +description: Opções e comandos da CLI do OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +A CLI do OpenCode, por padrão, inicia o [TUI](/docs/tui) quando executada sem argumentos. + +```bash +opencode +``` + +Mas também aceita comandos conforme documentado nesta página. Isso permite que você interaja com o OpenCode programaticamente. + +```bash +opencode run "Explique como closures funcionam em JavaScript" +``` + +--- + +### tui + +Inicie a interface de usuário do terminal do OpenCode. + +```bash +opencode [projeto] +``` + +#### Flags + +| Flag | Curto | Descrição | +| ------------ | ----- | ------------------------------------------- | +| `--continue` | `-c` | Continue a última sessão | +| `--session` | `-s` | ID da sessão para continuar | +| `--prompt` | | Prompt a ser usado | +| `--model` | `-m` | Modelo a ser usado na forma de provedor/modelo | +| `--agent` | | Agente a ser usado | +| `--port` | | Porta para escutar | +| `--hostname` | | Nome do host para escutar | + +--- + +## Comandos + +A CLI do OpenCode também possui os seguintes comandos. + +--- + +### agent + +Gerencie agentes para o OpenCode. + +```bash +opencode agent [comando] +``` + +--- + +### attach + +Anexe um terminal a um servidor backend do OpenCode já em execução, iniciado via comandos `serve` ou `web`. + +```bash +opencode attach [url] +``` + +Isso permite usar o TUI com um backend OpenCode remoto. Por exemplo: + +```bash +# Inicie o servidor backend para acesso web/móvel +opencode web --port 4096 --hostname 0.0.0.0 + +# Em outro terminal, anexe o TUI ao backend em execução +opencode attach http://10.20.30.40:4096 +``` + +#### Flags + +| Flag | Curto | Descrição | +| ----------- | ----- | -------------------------------- | +| `--dir` | | Diretório de trabalho para iniciar o TUI | +| `--session` | `-s` | ID da sessão para continuar | + +--- + +#### create + +Crie um novo agente com configuração personalizada. + +```bash +opencode agent create +``` + +Este comando irá guiá-lo na criação de um novo agente com um prompt de sistema personalizado e configuração de ferramentas. + +--- + +#### list + +Liste todos os agentes disponíveis. + +```bash +opencode agent list +``` + +--- + +### auth + +Comando para gerenciar credenciais e login para provedores. + +```bash +opencode auth [comando] +``` + +--- + +#### login + +O OpenCode é alimentado pela lista de provedores em [Models.dev](https://models.dev), então você pode usar `opencode auth login` para configurar chaves de API para qualquer provedor que você gostaria de usar. Isso é armazenado em `~/.local/share/opencode/auth.json`. + +```bash +opencode auth login +``` + +Quando o OpenCode é iniciado, ele carrega os provedores do arquivo de credenciais. E se houver chaves definidas em seus ambientes ou em um arquivo `.env` em seu projeto. + +--- + +#### list + +Lista todos os provedores autenticados conforme armazenado no arquivo de credenciais. + +```bash +opencode auth list +``` + +Ou a versão curta. + +```bash +opencode auth ls +``` + +--- + +#### logout + +Desconecta você de um provedor limpando-o do arquivo de credenciais. + +```bash +opencode auth logout +``` + +--- + +### github + +Gerencie o agente do GitHub para automação de repositórios. + +```bash +opencode github [comando] +``` + +--- + +#### install + +Instale o agente do GitHub em seu repositório. + +```bash +opencode github install +``` + +Isso configura o fluxo de trabalho necessário do GitHub Actions e o guia pelo processo de configuração. [Saiba mais](/docs/github). + +--- + +#### run + +Execute o agente do GitHub. Isso é tipicamente usado em GitHub Actions. + +```bash +opencode github run +``` + +##### Flags + +| Flag | Descrição | +| --------- | ------------------------------------- | +| `--event` | Evento simulado do GitHub para executar o agente | +| `--token` | Token de acesso pessoal do GitHub | + +--- + +### mcp + +Gerencie servidores do Protocolo de Contexto de Modelo. + +```bash +opencode mcp [comando] +``` + +--- + +#### add + +Adicione um servidor MCP à sua configuração. + +```bash +opencode mcp add +``` + +Este comando irá guiá-lo na adição de um servidor MCP local ou remoto. + +--- + +#### list + +Liste todos os servidores MCP configurados e seu status de conexão. + +```bash +opencode mcp list +``` + +Ou use a versão curta. + +```bash +opencode mcp ls +``` + +--- + +#### auth + +Autentique-se com um servidor MCP habilitado para OAuth. + +```bash +opencode mcp auth [nome] +``` + +Se você não fornecer um nome de servidor, será solicitado que você selecione entre os servidores disponíveis habilitados para OAuth. + +Você também pode listar servidores habilitados para OAuth e seu status de autenticação. + +```bash +opencode mcp auth list +``` + +Ou use a versão curta. + +```bash +opencode mcp auth ls +``` + +--- + +#### logout + +Remova credenciais OAuth para um servidor MCP. + +```bash +opencode mcp logout [nome] +``` + +--- + +#### debug + +Depure problemas de conexão OAuth para um servidor MCP. + +```bash +opencode mcp debug +``` + +--- + +### models + +Liste todos os modelos disponíveis dos provedores configurados. + +```bash +opencode models [provedor] +``` + +Este comando exibe todos os modelos disponíveis entre seus provedores configurados no formato `provedor/modelo`. + +Isso é útil para descobrir o nome exato do modelo a ser usado em [sua configuração](/docs/config/). + +Você pode opcionalmente passar um ID de provedor para filtrar modelos por esse provedor. + +```bash +opencode models anthropic +``` + +#### Flags + +| Flag | Descrição | +| ----------- | ---------------------------------------------------------- | +| `--refresh` | Atualiza o cache de modelos a partir do models.dev | +| `--verbose` | Use uma saída de modelo mais detalhada (inclui metadados como custos) | + +Use a flag `--refresh` para atualizar a lista de modelos em cache. Isso é útil quando novos modelos foram adicionados a um provedor e você deseja vê-los no OpenCode. + +```bash +opencode models --refresh +``` + +--- + +### run + +Execute o opencode em modo não interativo passando um prompt diretamente. + +```bash +opencode run [mensagem..] +``` + +Isso é útil para scripts, automação ou quando você deseja uma resposta rápida sem iniciar o TUI completo. Por exemplo. + +```bash "opencode run" +opencode run Explique o uso de contexto em Go +``` + +Você também pode se anexar a uma instância em execução do `opencode serve` para evitar tempos de inicialização a frio do servidor MCP em cada execução: + +```bash +# Inicie um servidor sem cabeça em um terminal +opencode serve + +# Em outro terminal, execute comandos que se anexam a ele +opencode run --attach http://localhost:4096 "Explique async/await em JavaScript" +``` + +#### Flags + +| Flag | Curto | Descrição | +| ------------ | ----- | ---------------------------------------------------------------- | +| `--command` | | O comando a ser executado, use mensagem para argumentos | +| `--continue` | `-c` | Continue a última sessão | +| `--session` | `-s` | ID da sessão para continuar | +| `--share` | | Compartilhe a sessão | +| `--model` | `-m` | Modelo a ser usado na forma de provedor/modelo | +| `--agent` | | Agente a ser usado | +| `--file` | `-f` | Arquivo(s) a serem anexados à mensagem | +| `--format` | | Formato: padrão (formatado) ou json (eventos JSON brutos) | +| `--title` | | Título para a sessão (usa o prompt truncado se nenhum valor for fornecido) | +| `--attach` | | Anexe a um servidor opencode em execução (por exemplo, http://localhost:4096) | +| `--port` | | Porta para o servidor local (padrão para porta aleatória) | + +--- + +### serve + +Inicie um servidor OpenCode sem cabeça para acesso à API. Confira a [documentação do servidor](/docs/server) para a interface HTTP completa. + +```bash +opencode serve +``` + +Isso inicia um servidor HTTP que fornece acesso à funcionalidade do opencode sem a interface TUI. Defina `OPENCODE_SERVER_PASSWORD` para habilitar a autenticação básica HTTP (o nome de usuário padrão é `opencode`). + +#### Flags + +| Flag | Descrição | +| ------------ | ------------------------------------------- | +| `--port` | Porta para escutar | +| `--hostname` | Nome do host para escutar | +| `--mdns` | Habilitar descoberta mDNS | +| `--cors` | Origem(ns) de navegador adicionais para permitir CORS | + +--- + +### session + +Gerencie sessões do OpenCode. + +```bash +opencode session [comando] +``` + +--- + +#### list + +Liste todas as sessões do OpenCode. + +```bash +opencode session list +``` + +##### Flags + +| Flag | Curto | Descrição | +| ------------- | ----- | ---------------------------------- | +| `--max-count` | `-n` | Limitar às N sessões mais recentes | +| `--format` | | Formato de saída: tabela ou json (tabela) | + +--- + +### stats + +Mostre o uso de tokens e estatísticas de custo para suas sessões do OpenCode. + +```bash +opencode stats +``` + +#### Flags + +| Flag | Descrição | +| ----------- | ------------------------------------------------------------------------- | +| `--days` | Mostre estatísticas dos últimos N dias (todo o tempo) | +| `--tools` | Número de ferramentas a serem mostradas (todas) | +| `--models` | Mostre a divisão do uso de modelos (oculto por padrão). Passe um número para mostrar os N principais | +| `--project` | Filtrar por projeto (todos os projetos, string vazia: projeto atual) | + +--- + +### export + +Exporte dados da sessão como JSON. + +```bash +opencode export [sessionID] +``` + +Se você não fornecer um ID de sessão, será solicitado que você selecione entre as sessões disponíveis. + +--- + +### import + +Importe dados da sessão de um arquivo JSON ou URL de compartilhamento do OpenCode. + +```bash +opencode import +``` + +Você pode importar de um arquivo local ou de uma URL de compartilhamento do OpenCode. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### web + +Inicie um servidor OpenCode sem cabeça com uma interface web. + +```bash +opencode web +``` + +Isso inicia um servidor HTTP e abre um navegador para acessar o OpenCode através de uma interface web. Defina `OPENCODE_SERVER_PASSWORD` para habilitar a autenticação básica HTTP (o nome de usuário padrão é `opencode`). + +#### Flags + +| Flag | Descrição | +| ------------ | ------------------------------------------- | +| `--port` | Porta para escutar | +| `--hostname` | Nome do host para escutar | +| `--mdns` | Habilitar descoberta mDNS | +| `--cors` | Origem(ns) de navegador adicionais para permitir CORS | + +--- + +### acp + +Inicie um servidor ACP (Protocolo de Cliente de Agente). + +```bash +opencode acp +``` + +Este comando inicia um servidor ACP que se comunica via stdin/stdout usando nd-JSON. + +#### Flags + +| Flag | Descrição | +| ------------ | ------------------- | +| `--cwd` | Diretório de trabalho | +| `--port` | Porta para escutar | +| `--hostname` | Nome do host para escutar | + +--- + +### uninstall + +Desinstale o OpenCode e remova todos os arquivos relacionados. + +```bash +opencode uninstall +``` + +#### Flags + +| Flag | Curto | Descrição | +| --------------- | ----- | ----------------------------------------- | +| `--keep-config` | `-c` | Manter arquivos de configuração | +| `--keep-data` | `-d` | Manter dados de sessão e snapshots | +| `--dry-run` | | Mostrar o que seria removido sem remover | +| `--force` | `-f` | Pular prompts de confirmação | + +--- + +### upgrade + +Atualiza o opencode para a versão mais recente ou uma versão específica. + +```bash +opencode upgrade [alvo] +``` + +Para atualizar para a versão mais recente. + +```bash +opencode upgrade +``` + +Para atualizar para uma versão específica. + +```bash +opencode upgrade v0.1.48 +``` + +#### Flags + +| Flag | Curto | Descrição | +| ---------- | ----- | --------------------------------------------------------------- | +| `--method` | `-m` | O método de instalação que foi usado; curl, npm, pnpm, bun, brew | + +--- + +## Flags Globais + +A CLI do opencode aceita as seguintes flags globais. + +| Flag | Curto | Descrição | +| -------------- | ----- | ---------------------------------- | +| `--help` | `-h` | Exibir ajuda | +| `--version` | `-v` | Imprimir número da versão | +| `--print-logs` | | Imprimir logs no stderr | +| `--log-level` | | Nível de log (DEBUG, INFO, WARN, ERROR) | + +--- + +## Variáveis de ambiente + +O OpenCode pode ser configurado usando variáveis de ambiente. + +| Variável | Tipo | Descrição | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | boolean | Compartilhar sessões automaticamente | +| `OPENCODE_GIT_BASH_PATH` | string | Caminho para o executável do Git Bash no Windows | +| `OPENCODE_CONFIG` | string | Caminho para o arquivo de configuração | +| `OPENCODE_CONFIG_DIR` | string | Caminho para o diretório de configuração | +| `OPENCODE_CONFIG_CONTENT` | string | Conteúdo de configuração json inline | +| `OPENCODE_DISABLE_AUTOUPDATE` | boolean | Desabilitar verificações de atualização automática | +| `OPENCODE_DISABLE_PRUNE` | boolean | Desabilitar a poda de dados antigos | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | boolean | Desabilitar atualizações automáticas do título do terminal | +| `OPENCODE_PERMISSION` | string | Configuração de permissões json inline | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | boolean | Desabilitar plugins padrão | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | boolean | Desabilitar downloads automáticos do servidor LSP | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | boolean | Habilitar modelos experimentais | +| `OPENCODE_DISABLE_AUTOCOMPACT` | boolean | Desabilitar compactação automática de contexto | +| `OPENCODE_DISABLE_CLAUDE_CODE` | boolean | Desabilitar leitura de `.claude` (prompt + habilidades) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | boolean | Desabilitar leitura de `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | boolean | Desabilitar carregamento de `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | boolean | Desabilitar busca de modelos de fontes remotas | +| `OPENCODE_FAKE_VCS` | string | Provedor VCS falso para fins de teste | +| `OPENCODE_DISABLE_FILETIME_CHECK` | boolean | Desabilitar verificação de tempo de arquivo para otimização | +| `OPENCODE_CLIENT` | string | Identificador do cliente (padrão é `cli`) | +| `OPENCODE_ENABLE_EXA` | boolean | Habilitar ferramentas de busca web Exa | +| `OPENCODE_SERVER_PASSWORD` | string | Habilitar autenticação básica para `serve`/`web` | +| `OPENCODE_SERVER_USERNAME` | string | Substituir nome de usuário de autenticação básica (padrão `opencode`) | +| `OPENCODE_MODELS_URL` | string | URL personalizada para buscar configuração de modelos | + +--- + +### Experimental + +Essas variáveis de ambiente habilitam recursos experimentais que podem mudar ou ser removidos. + +| Variável | Tipo | Descrição | +| ----------------------------------------------- | ------- | ------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | boolean | Habilitar todos os recursos experimentais | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | boolean | Habilitar descoberta de ícones | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | boolean | Desabilitar cópia ao selecionar no TUI | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | number | Tempo limite padrão para comandos bash em ms | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | number | Máximo de tokens de saída para respostas LLM | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | boolean | Habilitar monitoramento de arquivos para todo o diretório | +| `OPENCODE_EXPERIMENTAL_OXFMT` | boolean | Habilitar formatador oxfmt | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | boolean | Habilitar ferramenta LSP experimental | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | boolean | Desabilitar monitoramento de arquivos | +| `OPENCODE_EXPERIMENTAL_EXA` | boolean | Habilitar recursos experimentais do Exa | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | boolean | Habilitar verificação de tipo LSP experimental | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | boolean | Habilitar recursos experimentais de markdown | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | boolean | Habilitar modo de plano | \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/commands.mdx b/packages/web/src/content/docs/pt-br/commands.mdx new file mode 100644 index 000000000..8da6e5023 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/commands.mdx @@ -0,0 +1,322 @@ +--- +title: Comandos +description: Crie comandos personalizados para tarefas repetitivas. +--- + +Comandos personalizados permitem que você especifique um prompt que deseja executar quando esse comando for executado no TUI. + +```bash frame="none" +/meu-comando +``` + +Comandos personalizados são adicionais aos comandos integrados como `/init`, `/undo`, `/redo`, `/share`, `/help`. [Saiba mais](/docs/tui#commands). + +--- + +## Criar arquivos de comando + +Crie arquivos markdown no diretório `commands/` para definir comandos personalizados. + +Crie `.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Execute testes com cobertura +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Execute a suíte de testes completa com relatório de cobertura e mostre quaisquer falhas. +Concentre-se nos testes que falharam e sugira correções. +``` + +O frontmatter define as propriedades do comando. O conteúdo se torna o template. + +Use o comando digitando `/` seguido pelo nome do comando. + +```bash frame="none" +"/test" +``` + +--- + +## Configurar + +Você pode adicionar comandos personalizados através da configuração do OpenCode ou criando arquivos markdown no diretório `commands/`. + +--- + +### JSON + +Use a opção `command` na sua [configuração](/docs/config) do OpenCode: + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // Este se torna o nome do comando + "test": { + // Este é o prompt que será enviado ao LLM + "template": "Execute a suíte de testes completa com relatório de cobertura e mostre quaisquer falhas.\nConcentre-se nos testes que falharam e sugira correções.", + // Este é exibido como a descrição no TUI + "description": "Execute testes com cobertura", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Agora você pode executar este comando no TUI: + +```bash frame="none" +/test +``` + +--- + +### Markdown + +Você também pode definir comandos usando arquivos markdown. Coloque-os em: + +- Global: `~/.config/opencode/commands/` +- Por projeto: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Execute testes com cobertura +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Execute a suíte de testes completa com relatório de cobertura e mostre quaisquer falhas. +Concentre-se nos testes que falharam e sugira correções. +``` + +O nome do arquivo markdown se torna o nome do comando. Por exemplo, `test.md` permite que você execute: + +```bash frame="none" +/test +``` + +--- + +## Configuração do prompt + +Os prompts para os comandos personalizados suportam vários espaços reservados e sintaxes especiais. + +--- + +### Argumentos + +Passe argumentos para os comandos usando o espaço reservado `$ARGUMENTS`. + +```md title=".opencode/commands/component.md" +--- +description: Crie um novo componente +--- + +Crie um novo componente React chamado $ARGUMENTS com suporte a TypeScript. +Inclua tipagem adequada e estrutura básica. +``` + +Execute o comando com argumentos: + +```bash frame="none" +/component Botão +``` + +E `$ARGUMENTS` será substituído por `Botão`. + +Você também pode acessar argumentos individuais usando parâmetros posicionais: + +- `$1` - Primeiro argumento +- `$2` - Segundo argumento +- `$3` - Terceiro argumento +- E assim por diante... + +Por exemplo: + +```md title=".opencode/commands/create-file.md" +--- +description: Crie um novo arquivo com conteúdo +--- + +Crie um arquivo chamado $1 no diretório $2 +com o seguinte conteúdo: $3 +``` + +Execute o comando: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +Isso substitui: + +- `$1` por `config.json` +- `$2` por `src` +- `$3` por `{ "key": "value" }` + +--- + +### Saída do shell + +Use _!`comando`_ para injetar a saída do [comando bash](/docs/tui#bash-commands) no seu prompt. + +Por exemplo, para criar um comando personalizado que analisa a cobertura de testes: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analise a cobertura de testes +--- + +Aqui estão os resultados atuais dos testes: +!`npm test` + +Com base nesses resultados, sugira melhorias para aumentar a cobertura. +``` + +Ou para revisar alterações recentes: + +```md title=".opencode/commands/review-changes.md" +--- +description: Revise alterações recentes +--- + +Commits git recentes: +!`git log --oneline -10` + +Revise essas alterações e sugira quaisquer melhorias. +``` + +Os comandos são executados no diretório raiz do seu projeto e sua saída se torna parte do prompt. + +--- + +### Referências de arquivo + +Inclua arquivos no seu comando usando `@` seguido pelo nome do arquivo. + +```md title=".opencode/commands/review-component.md" +--- +description: Revise componente +--- + +Revise o componente em @src/components/Button.tsx. +Verifique problemas de desempenho e sugira melhorias. +``` + +O conteúdo do arquivo é incluído automaticamente no prompt. + +--- + +## Opções + +Vamos analisar as opções de configuração em detalhes. + +--- + +### Template + +A opção `template` define o prompt que será enviado ao LLM quando o comando for executado. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Execute a suíte de testes completa com relatório de cobertura e mostre quaisquer falhas.\nConcentre-se nos testes que falharam e sugira correções." + } + } +} +``` + +Esta é uma opção de configuração **obrigatória**. + +--- + +### Descrição + +Use a opção `description` para fornecer uma breve descrição do que o comando faz. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Execute testes com cobertura" + } + } +} +``` + +Isso é exibido como a descrição no TUI quando você digita o comando. + +--- + +### Agente + +Use a configuração `agent` para especificar opcionalmente qual [agente](/docs/agents) deve executar este comando. +Se este for um [subagente](/docs/agents/#subagents), o comando acionará uma invocação de subagente por padrão. +Para desativar esse comportamento, defina `subtask` como `false`. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +Esta é uma opção de configuração **opcional**. Se não especificado, o padrão é o seu agente atual. + +--- + +### Subtarefa + +Use o booleano `subtask` para forçar o comando a acionar uma invocação de [subagente](/docs/agents/#subagents). +Isso é útil se você quiser que o comando não polua seu contexto principal e **forçará** o agente a agir como um subagente, +mesmo que `mode` esteja definido como `primary` na configuração do [agente](/docs/agents). + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +Esta é uma opção de configuração **opcional**. + +--- + +### Modelo + +Use a configuração `model` para substituir o modelo padrão para este comando. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Esta é uma opção de configuração **opcional**. + +--- + +## Integrado + +opencode inclui vários comandos integrados como `/init`, `/undo`, `/redo`, `/share`, `/help`; [saiba mais](/docs/tui#commands). + +:::note +Comandos personalizados podem substituir comandos integrados. +::: + +Se você definir um comando personalizado com o mesmo nome, ele substituirá o comando integrado. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/config.mdx b/packages/web/src/content/docs/pt-br/config.mdx new file mode 100644 index 000000000..b9ef6f237 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/config.mdx @@ -0,0 +1,681 @@ +--- +title: Config +description: Usando a configuração JSON do OpenCode. +--- + +Você pode configurar o OpenCode usando um arquivo de configuração JSON. + +--- + +## Formato + +O OpenCode suporta os formatos **JSON** e **JSONC** (JSON com Comentários). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Configuração do tema + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## Localizações + +Você pode colocar sua configuração em algumas localizações diferentes e elas têm uma +ordem de precedência diferente. + +:::note +Os arquivos de configuração são **mesclados**, não substituídos. +::: + +Os arquivos de configuração são mesclados, não substituídos. As configurações das seguintes localizações de configuração são combinadas. Configurações posteriores substituem as anteriores apenas para chaves conflitantes. Configurações não conflitantes de todas as configurações são preservadas. + +Por exemplo, se sua configuração global define `theme: "opencode"` e `autoupdate: true`, e sua configuração de projeto define `model: "anthropic/claude-sonnet-4-5"`, a configuração final incluirá as três configurações. + +--- + +### Ordem de precedência + +As fontes de configuração são carregadas nesta ordem (fontes posteriores substituem as anteriores): + +1. **Configuração remota** (de `.well-known/opencode`) - padrões organizacionais +2. **Configuração global** (`~/.config/opencode/opencode.json`) - preferências do usuário +3. **Configuração personalizada** (`OPENCODE_CONFIG` var de ambiente) - substituições personalizadas +4. **Configuração do projeto** (`opencode.json` no projeto) - configurações específicas do projeto +5. **Diretórios `.opencode`** - agentes, comandos, plugins +6. **Configuração inline** (`OPENCODE_CONFIG_CONTENT` var de ambiente) - substituições em tempo de execução + +Isso significa que as configurações do projeto podem substituir os padrões globais, e as configurações globais podem substituir os padrões organizacionais remotos. + +:::note +Os diretórios `.opencode` e `~/.config/opencode` usam **nomes no plural** para subdiretórios: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/`, e `themes/`. Nomes no singular (por exemplo, `agent/`) também são suportados para compatibilidade retroativa. +::: + +--- + +### Remoto + +As organizações podem fornecer configuração padrão através do endpoint `.well-known/opencode`. Isso é buscado automaticamente quando você se autentica com um provedor que o suporta. + +A configuração remota é carregada primeiro, servindo como a camada base. Todas as outras fontes de configuração (global, projeto) podem substituir esses padrões. + +Por exemplo, se sua organização fornece servidores MCP que estão desativados por padrão: + +```json title="Configuração remota de .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +Você pode habilitar servidores específicos em sua configuração local: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### Global + +Coloque sua configuração global do OpenCode em `~/.config/opencode/opencode.json`. Use a configuração global para preferências de usuário, como temas, provedores ou atalhos de teclado. + +A configuração global substitui os padrões organizacionais remotos. + +--- + +### Por projeto + +Adicione `opencode.json` na raiz do seu projeto. A configuração do projeto tem a maior precedência entre os arquivos de configuração padrão - ela substitui tanto as configurações globais quanto as remotas. + +:::tip +Coloque a configuração específica do projeto na raiz do seu projeto. +::: + +Quando o OpenCode é iniciado, ele procura um arquivo de configuração no diretório atual ou sobe até o diretório Git mais próximo. + +Isso também é seguro para ser verificado no Git e usa o mesmo esquema que o global. + +--- + +### Caminho personalizado + +Especifique um caminho de arquivo de configuração personalizado usando a variável de ambiente `OPENCODE_CONFIG`. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +A configuração personalizada é carregada entre as configurações globais e do projeto na ordem de precedência. + +--- + +### Diretório personalizado + +Especifique um diretório de configuração personalizado usando a variável de ambiente `OPENCODE_CONFIG_DIR`. Este diretório será pesquisado por agentes, comandos, modos e plugins, assim como o diretório padrão `.opencode`, e deve seguir a mesma estrutura. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +O diretório personalizado é carregado após a configuração global e os diretórios `.opencode`, então ele **pode substituir** suas configurações. + +--- + +## Esquema + +O arquivo de configuração tem um esquema que está definido em [**`opencode.ai/config.json`**](https://opencode.ai/config.json). + +Seu editor deve ser capaz de validar e autocompletar com base no esquema. + +--- + +### TUI + +Você pode configurar as configurações específicas do TUI através da opção `tui`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +Opções disponíveis: + +- `scroll_acceleration.enabled` - Habilitar aceleração de rolagem estilo macOS. **Tem precedência sobre `scroll_speed`.** +- `scroll_speed` - Multiplicador de velocidade de rolagem personalizada (padrão: `3`, mínimo: `1`). Ignorado se `scroll_acceleration.enabled` for `true`. +- `diff_style` - Controlar a renderização de diffs. `"auto"` se adapta à largura do terminal, `"stacked"` sempre mostra uma coluna única. + +[Saiba mais sobre o uso do TUI aqui](/docs/tui). + +--- + +### Servidor + +Você pode configurar as configurações do servidor para os comandos `opencode serve` e `opencode web` através da opção `server`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +Opções disponíveis: + +- `port` - Porta para escutar. +- `hostname` - Nome do host para escutar. Quando `mdns` está habilitado e nenhum nome de host está definido, o padrão é `0.0.0.0`. +- `mdns` - Habilitar descoberta de serviço mDNS. Isso permite que outros dispositivos na rede descubram seu servidor OpenCode. +- `mdnsDomain` - Nome de domínio personalizado para o serviço mDNS. O padrão é `opencode.local`. Útil para executar várias instâncias na mesma rede. +- `cors` - Origens adicionais a serem permitidas para CORS ao usar o servidor HTTP de um cliente baseado em navegador. Os valores devem ser origens completas (esquema + host + porta opcional), por exemplo, `https://app.example.com`. + +[Saiba mais sobre o servidor aqui](/docs/server). + +--- + +### Ferramentas + +Você pode gerenciar as ferramentas que um LLM pode usar através da opção `tools`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[Saiba mais sobre ferramentas aqui](/docs/tools). + +--- + +### Modelos + +Você pode configurar os provedores e modelos que deseja usar em sua configuração do OpenCode através das opções `provider`, `model` e `small_model`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +A opção `small_model` configura um modelo separado para tarefas leves, como geração de títulos. Por padrão, o OpenCode tenta usar um modelo mais barato se um estiver disponível do seu provedor, caso contrário, ele recua para seu modelo principal. + +As opções do provedor podem incluir `timeout` e `setCacheKey`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - Tempo limite da solicitação em milissegundos (padrão: 300000). Defina como `false` para desabilitar. +- `setCacheKey` - Garantir que uma chave de cache seja sempre definida para o provedor designado. + +Você também pode configurar [modelos locais](/docs/models#local). [Saiba mais](/docs/models). + +--- + +#### Opções Específicas do Provedor + +Alguns provedores suportam opções de configuração adicionais além das configurações genéricas `timeout` e `apiKey`. + +##### Amazon Bedrock + +Amazon Bedrock suporta configuração específica da AWS: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - Região AWS para Bedrock (padrão para `AWS_REGION` var de ambiente ou `us-east-1`) +- `profile` - Perfil nomeado da AWS em `~/.aws/credentials` (padrão para `AWS_PROFILE` var de ambiente) +- `endpoint` - URL de endpoint personalizada para endpoints VPC. Este é um alias para a opção genérica `baseURL` usando terminologia específica da AWS. Se ambos forem especificados, `endpoint` tem precedência. + +:::note +Tokens Bearer (`AWS_BEARER_TOKEN_BEDROCK` ou `/connect`) têm precedência sobre a autenticação baseada em perfil. Veja [precedência de autenticação](/docs/providers#authentication-precedence) para detalhes. +::: + +[Saiba mais sobre a configuração do Amazon Bedrock](/docs/providers#amazon-bedrock). + +--- + +### Temas + +Você pode configurar o tema que deseja usar em sua configuração do OpenCode através da opção `theme`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[Saiba mais aqui](/docs/themes). + +--- + +### Agentes + +Você pode configurar agentes especializados para tarefas específicas através da opção `agent`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Revisa o código em busca de melhores práticas e problemas potenciais", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "Você é um revisor de código. Foque em segurança, desempenho e manutenibilidade.", + "tools": { + // Desabilitar ferramentas de modificação de arquivos para agente somente de revisão + "write": false, + "edit": false, + }, + }, + }, +} +``` + +Você também pode definir agentes usando arquivos markdown em `~/.config/opencode/agents/` ou `.opencode/agents/`. [Saiba mais aqui](/docs/agents). + +--- + +### Agente padrão + +Você pode definir o agente padrão usando a opção `default_agent`. Isso determina qual agente é usado quando nenhum é explicitamente especificado. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +O agente padrão deve ser um agente primário (não um subagente). Isso pode ser um agente embutido como `"build"` ou `"plan"`, ou um [agente personalizado](/docs/agents) que você definiu. Se o agente especificado não existir ou for um subagente, o OpenCode recuará para `"build"` com um aviso. + +Essa configuração se aplica a todas as interfaces: TUI, CLI (`opencode run`), aplicativo desktop e GitHub Action. + +--- + +### Compartilhamento + +Você pode configurar o recurso [share](/docs/share) através da opção `share`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +Isso aceita: + +- `"manual"` - Permitir compartilhamento manual via comandos (padrão) +- `"auto"` - Compartilhar novas conversas automaticamente +- `"disabled"` - Desabilitar compartilhamento completamente + +Por padrão, o compartilhamento é definido para o modo manual, onde você precisa compartilhar explicitamente as conversas usando o comando `/share`. + +--- + +### Comandos + +Você pode configurar comandos personalizados para tarefas repetitivas através da opção `command`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Execute a suíte de testes completa com relatório de cobertura e mostre quaisquer falhas.\nFoque nos testes que falharam e sugira correções.", + "description": "Executar testes com cobertura", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Crie um novo componente React chamado $ARGUMENTS com suporte a TypeScript.\nInclua tipagem adequada e estrutura básica.", + "description": "Criar um novo componente", + }, + }, +} +``` + +Você também pode definir comandos usando arquivos markdown em `~/.config/opencode/commands/` ou `.opencode/commands/`. [Saiba mais aqui](/docs/commands). + +--- + +### Atalhos de teclado + +Você pode personalizar seus atalhos de teclado através da opção `keybinds`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[Saiba mais aqui](/docs/keybinds). + +--- + +### Atualização automática + +O OpenCode fará o download automaticamente de quaisquer novas atualizações quando for iniciado. Você pode desabilitar isso com a opção `autoupdate`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +Se você não quiser atualizações, mas deseja ser notificado quando uma nova versão estiver disponível, defina `autoupdate` como `"notify"`. +Observe que isso só funciona se não foi instalado usando um gerenciador de pacotes como o Homebrew. + +--- + +### Formatadores + +Você pode configurar formatadores de código através da opção `formatter`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[Saiba mais sobre formatadores aqui](/docs/formatters). + +--- + +### Permissões + +Por padrão, o opencode **permite todas as operações** sem exigir aprovação explícita. Você pode mudar isso usando a opção `permission`. + +Por exemplo, para garantir que as ferramentas `edit` e `bash` exijam aprovação do usuário: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[Saiba mais sobre permissões aqui](/docs/permissions). + +--- + +### Compactação + +Você pode controlar o comportamento de compactação de contexto através da opção `compaction`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - Compactar automaticamente a sessão quando o contexto estiver cheio (padrão: `true`). +- `prune` - Remover saídas antigas de ferramentas para economizar tokens (padrão: `true`). + +--- + +### Observador + +Você pode configurar padrões de ignorar do observador de arquivos através da opção `watcher`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +Os padrões seguem a sintaxe glob. Use isso para excluir diretórios barulhentos da observação de arquivos. + +--- + +### Servidores MCP + +Você pode configurar servidores MCP que deseja usar através da opção `mcp`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[Saiba mais aqui](/docs/mcp-servers). + +--- + +### Plugins + +[Plugins](/docs/plugins) estendem o OpenCode com ferramentas, hooks e integrações personalizadas. + +Coloque arquivos de plugin em `.opencode/plugins/` ou `~/.config/opencode/plugins/`. Você também pode carregar plugins do npm através da opção `plugin`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[Saiba mais aqui](/docs/plugins). + +--- + +### Instruções + +Você pode configurar as instruções para o modelo que está usando através da opção `instructions`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Isso aceita um array de caminhos e padrões glob para arquivos de instrução. [Saiba mais sobre regras aqui](/docs/rules). + +--- + +### Provedores desabilitados + +Você pode desabilitar provedores que são carregados automaticamente através da opção `disabled_providers`. Isso é útil quando você deseja impedir que certos provedores sejam carregados, mesmo que suas credenciais estejam disponíveis. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +A opção `disabled_providers` tem prioridade sobre `enabled_providers`. +::: + +A opção `disabled_providers` aceita um array de IDs de provedores. Quando um provedor é desabilitado: + +- Ele não será carregado, mesmo que variáveis de ambiente estejam definidas. +- Ele não será carregado, mesmo que chaves de API estejam configuradas através do comando `/connect`. +- Os modelos do provedor não aparecerão na lista de seleção de modelos. + +--- + +### Provedores habilitados + +Você pode especificar uma lista de permissão de provedores através da opção `enabled_providers`. Quando definida, apenas os provedores especificados serão habilitados e todos os outros serão ignorados. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +Isso é útil quando você deseja restringir o OpenCode para usar apenas provedores específicos, em vez de desabilitá-los um a um. + +:::note +A opção `disabled_providers` tem prioridade sobre `enabled_providers`. +::: + +Se um provedor aparecer em `enabled_providers` e `disabled_providers`, a `disabled_providers` tem prioridade para compatibilidade retroativa. + +--- + +### Experimental + +A chave `experimental` contém opções que estão em desenvolvimento ativo. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::caution +Opções experimentais não são estáveis. Elas podem mudar ou ser removidas sem aviso prévio. +::: + +--- + +## Variáveis + +Você pode usar substituição de variáveis em seus arquivos de configuração para referenciar variáveis de ambiente e conteúdos de arquivos. + +--- + +### Variáveis de ambiente + +Use `{env:VARIABLE_NAME}` para substituir variáveis de ambiente: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +Se a variável de ambiente não estiver definida, ela será substituída por uma string vazia. + +--- + +### Arquivos + +Use `{file:path/to/file}` para substituir o conteúdo de um arquivo: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +Os caminhos dos arquivos podem ser: + +- Relativos ao diretório do arquivo de configuração +- Ou caminhos absolutos começando com `/` ou `~` + +Esses são úteis para: + +- Manter dados sensíveis, como chaves de API, em arquivos separados. +- Incluir grandes arquivos de instrução sem sobrecarregar sua configuração. +- Compartilhar trechos de configuração comuns entre vários arquivos de configuração. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/custom-tools.mdx b/packages/web/src/content/docs/pt-br/custom-tools.mdx new file mode 100644 index 000000000..6d2ad163e --- /dev/null +++ b/packages/web/src/content/docs/pt-br/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: Ferramentas Personalizadas +description: Crie ferramentas que o LLM pode chamar em opencode. +--- + +Ferramentas personalizadas são funções que você cria e que o LLM pode chamar durante as conversas. Elas funcionam junto com as [ferramentas integradas](/docs/tools) do opencode, como `read`, `write` e `bash`. + +--- + +## Criando uma ferramenta + +As ferramentas são definidas como arquivos **TypeScript** ou **JavaScript**. No entanto, a definição da ferramenta pode invocar scripts escritos em **qualquer linguagem** — TypeScript ou JavaScript é usado apenas para a definição da ferramenta em si. + +--- + +### Localização + +Elas podem ser definidas: + +- Localmente, colocando-as no diretório `.opencode/tools/` do seu projeto. +- Ou globalmente, colocando-as em `~/.config/opencode/tools/`. + +--- + +### Estrutura + +A maneira mais fácil de criar ferramentas é usando o helper `tool()`, que fornece segurança de tipo e validação. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Consultar o banco de dados do projeto", + args: { + query: tool.schema.string().describe("Consulta SQL a ser executada"), + }, + async execute(args) { + // Sua lógica de banco de dados aqui + return `Consulta executada: ${args.query}` + }, +}) +``` + +O **nome do arquivo** se torna o **nome da ferramenta**. O acima cria uma ferramenta `database`. + +--- + +#### Múltiplas ferramentas por arquivo + +Você também pode exportar várias ferramentas de um único arquivo. Cada exportação se torna **uma ferramenta separada** com o nome **`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Adicionar dois números", + args: { + a: tool.schema.number().describe("Primeiro número"), + b: tool.schema.number().describe("Segundo número"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiplicar dois números", + args: { + a: tool.schema.number().describe("Primeiro número"), + b: tool.schema.number().describe("Segundo número"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +Isso cria duas ferramentas: `math_add` e `math_multiply`. + +--- + +### Argumentos + +Você pode usar `tool.schema`, que é apenas [Zod](https://zod.dev), para definir tipos de argumentos. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("Consulta SQL a ser executada") +} +``` + +Você também pode importar [Zod](https://zod.dev) diretamente e retornar um objeto simples: + +```ts {6} +import { z } from "zod" + +export default { + description: "Descrição da ferramenta", + args: { + param: z.string().describe("Descrição do parâmetro"), + }, + async execute(args, context) { + // Implementação da ferramenta + return "resultado" + }, +} +``` + +--- + +### Contexto + +As ferramentas recebem contexto sobre a sessão atual: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Obter informações do projeto", + args: {}, + async execute(args, context) { + // Acessar informações do contexto + const { agent, sessionID, messageID, directory, worktree } = context + return `Agente: ${agent}, Sessão: ${sessionID}, Mensagem: ${messageID}, Diretório: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +Use `context.directory` para o diretório de trabalho da sessão. +Use `context.worktree` para a raiz do worktree do git. + +--- + +## Exemplos + +### Escreva uma ferramenta em Python + +Você pode escrever suas ferramentas em qualquer linguagem que desejar. Aqui está um exemplo que adiciona dois números usando Python. + +Primeiro, crie a ferramenta como um script Python: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +Em seguida, crie a definição da ferramenta que a invoca: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Adicionar dois números usando Python", + args: { + a: tool.schema.number().describe("Primeiro número"), + b: tool.schema.number().describe("Segundo número"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +Aqui estamos usando o utilitário [`Bun.$`](https://bun.com/docs/runtime/shell) para executar o script Python. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/ecosystem.mdx b/packages/web/src/content/docs/pt-br/ecosystem.mdx new file mode 100644 index 000000000..1913a4563 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: Ecossistema +description: Projetos e integrações construídos com OpenCode. +--- + +Uma coleção de projetos da comunidade construídos sobre o OpenCode. + +:::note +Quer adicionar seu projeto relacionado ao OpenCode a esta lista? Envie um PR. +::: + +Você também pode conferir [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) e [opencode.cafe](https://opencode.cafe), uma comunidade que agrega o ecossistema e a comunidade. + +--- + +## Plugins + +| Nome | Descrição | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | Execute automaticamente sessões do OpenCode em sandboxes isoladas do Daytona com sincronização git e pré-visualizações ao vivo | +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Injete automaticamente cabeçalhos de sessão Helicone para agrupamento de requisições | +| [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Auto-injetar tipos TypeScript/Svelte em leituras de arquivos com ferramentas de busca | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Use sua assinatura ChatGPT Plus/Pro em vez de créditos de API | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Use seu plano Gemini existente em vez de cobrança de API | +| [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Use os modelos gratuitos do Antigravity em vez de cobrança de API | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Isolamento de devcontainer multi-branch com clones rasos e portas atribuídas automaticamente | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Plugin Google Antigravity OAuth, com suporte para Google Search e manuseio de API mais robusto | +| [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Otimize o uso de tokens podando saídas de ferramentas obsoletas | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Adicione suporte nativo de pesquisa na web para provedores suportados com estilo fundamentado no Google | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Permite que agentes de IA executem processos em segundo plano em um PTY, enviando entrada interativa para eles. | +| [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Instruções para comandos de shell não interativos - evita travamentos de operações dependentes de TTY | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Acompanhe o uso do OpenCode com Wakatime | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Limpe tabelas markdown produzidas por LLMs | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | Edição de código 10x mais rápida com a API Morph Fast Apply e marcadores de edição preguiçosos | +| [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Agentes em segundo plano, ferramentas LSP/AST/MCP pré-construídas, agentes curados, compatível com Claude Code | +| [opencode-notificator](https://github.com/panta82/opencode-notificator) | Notificações de desktop e alertas sonoros para sessões do OpenCode | +| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Notificações de desktop e alertas sonoros para eventos de permissão, conclusão e erro | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | Nomeação automática de sessões Zellij com suporte de IA com base no contexto do OpenCode | +| [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Permite que agentes do OpenCode carreguem prompts sob demanda com descoberta e injeção de habilidades | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Memória persistente entre sessões usando Supermemory | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Revisão de plano interativa com anotação visual e compartilhamento privado/offline | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Estenda opencode /commands em um poderoso sistema de orquestração com controle de fluxo granular | +| [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Agende trabalhos recorrentes usando launchd (Mac) ou systemd (Linux) com sintaxe cron | +| [micode](https://github.com/vtemian/micode) | Fluxo de trabalho Estruturado Brainstorm → Planejar → Implementar com continuidade de sessão | +| [octto](https://github.com/vtemian/octto) | UI interativa do navegador para brainstorming de IA com formulários de múltiplas perguntas | +| [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Agentes em segundo plano estilo Claude Code com delegação assíncrona e persistência de contexto | +| [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Notificações nativas do OS para OpenCode – saiba quando as tarefas são concluídas | +| [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Conjunto de orquestração multi-agente – 16 componentes, uma instalação | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Worktrees git sem atrito para OpenCode | + +--- + +## Projetos + +| Nome | Descrição | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | Bot do Discord para controlar sessões do OpenCode, construído sobre o SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Plugin Neovim para prompts cientes do editor, construído sobre a API | +| [portal](https://github.com/hosenur/portal) | UI web mobile-first para OpenCode sobre Tailscale/VPN | +| [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | Template para construir plugins do OpenCode | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Frontend Neovim para opencode - um agente de codificação AI baseado em terminal | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Provedor Vercel AI SDK para usar OpenCode via @opencode-ai/sdk | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | Aplicativo Web / Desktop e Extensão do VS Code para OpenCode | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Plugin Obsidian que incorpora OpenCode na UI do Obsidian | +| [OpenWork](https://github.com/different-ai/openwork) | Uma alternativa de código aberto ao Claude Cowork, alimentada pelo OpenCode | +| [ocx](https://github.com/kdcokenny/ocx) | Gerenciador de extensões OpenCode com perfis portáteis e isolados. | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Aplicativo Desktop, Web, Mobile e Cliente Remoto para OpenCode | + +--- + +## Agentes + +| Nome | Descrição | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [Agentic](https://github.com/Cluster444/agentic) | Agentes e comandos de IA modulares para desenvolvimento estruturado | +| [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Configurações, prompts, agentes e plugins para fluxos de trabalho aprimorados | \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/enterprise.mdx b/packages/web/src/content/docs/pt-br/enterprise.mdx new file mode 100644 index 000000000..95671cfde --- /dev/null +++ b/packages/web/src/content/docs/pt-br/enterprise.mdx @@ -0,0 +1,166 @@ +--- +title: Empresa +description: Usando OpenCode com segurança em sua organização. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise é para organizações que desejam garantir que seu código e dados nunca deixem sua infraestrutura. Isso pode ser feito usando uma configuração centralizada que se integra ao seu SSO e gateway de IA interno. + +:::note +OpenCode não armazena nenhum de seus códigos ou dados de contexto. +::: + +Para começar com OpenCode Enterprise: + +1. Faça um teste internamente com sua equipe. +2. **Entre em contato conosco** para discutir opções de preços e implementação. + +--- + +## Teste + +OpenCode é de código aberto e não armazena nenhum de seus códigos ou dados de contexto, então seus desenvolvedores podem simplesmente [começar](/docs/) e realizar um teste. + +--- + +### Manipulação de dados + +**OpenCode não armazena seu código ou dados de contexto.** Todo o processamento acontece localmente ou através de chamadas diretas de API para seu provedor de IA. + +Isso significa que, enquanto você estiver usando um provedor em quem confia, ou um gateway de IA interno, você pode usar o OpenCode com segurança. + +A única ressalva aqui é o recurso opcional `/share`. + +--- + +#### Compartilhando conversas + +Se um usuário habilitar o recurso `/share`, a conversa e os dados associados a ela são enviados para o serviço que usamos para hospedar essas páginas de compartilhamento em opencode.ai. + +Os dados são atualmente servidos através da rede de borda do nosso CDN e são armazenados em cache na borda perto de seus usuários. + +Recomendamos que você desative isso para seu teste. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[Saiba mais sobre compartilhamento](/docs/share). + +--- + +### Propriedade do código + +**Você possui todo o código produzido pelo OpenCode.** Não há restrições de licenciamento ou reivindicações de propriedade. + +--- + +## Preços + +Usamos um modelo por assento para o OpenCode Enterprise. Se você tiver seu próprio gateway LLM, não cobramos pelos tokens usados. Para mais detalhes sobre preços e opções de implementação, **entre em contato conosco**. + +--- + +## Implantação + +Uma vez que você tenha concluído seu teste e esteja pronto para usar o OpenCode em sua organização, você pode **entrar em contato conosco** para discutir preços e opções de implementação. + +--- + +### Configuração Central + +Podemos configurar o OpenCode para usar uma única configuração central para toda a sua organização. + +Essa configuração centralizada pode se integrar ao seu provedor de SSO e garante que todos os usuários acessem apenas seu gateway de IA interno. + +--- + +### Integração SSO + +Através da configuração central, o OpenCode pode se integrar ao provedor de SSO de sua organização para autenticação. + +Isso permite que o OpenCode obtenha credenciais para seu gateway de IA interno através do seu sistema de gerenciamento de identidade existente. + +--- + +### Gateway de IA Interno + +Com a configuração central, o OpenCode também pode ser configurado para usar apenas seu gateway de IA interno. + +Você também pode desativar todos os outros provedores de IA, garantindo que todas as solicitações passem pela infraestrutura aprovada de sua organização. + +--- + +### Auto-hospedagem + +Embora recomendemos desativar as páginas de compartilhamento para garantir que seus dados nunca deixem sua organização, também podemos ajudá-lo a auto-hospedá-las em sua infraestrutura. + +Isso está atualmente em nosso roadmap. Se você estiver interessado, **nos avise**. + +--- + +## FAQ + +

+O que é OpenCode Enterprise? + +OpenCode Enterprise é para organizações que desejam garantir que seu código e dados nunca deixem sua infraestrutura. Isso pode ser feito usando uma configuração centralizada que se integra ao seu SSO e gateway de IA interno. + +
+ +
+Como posso começar com OpenCode Enterprise? + +Basta começar com um teste interno com sua equipe. O OpenCode, por padrão, não armazena seu código ou dados de contexto, facilitando o início. + +Depois, **entre em contato conosco** para discutir opções de preços e implementação. + +
+ +
+Como funciona a precificação empresarial? + +Oferecemos preços empresariais por assento. Se você tiver seu próprio gateway LLM, não cobramos pelos tokens usados. Para mais detalhes, **entre em contato conosco** para um orçamento personalizado com base nas necessidades de sua organização. + +
+ +
+Meus dados estão seguros com OpenCode Enterprise? + +Sim. O OpenCode não armazena seu código ou dados de contexto. Todo o processamento acontece localmente ou através de chamadas diretas de API para seu provedor de IA. Com a configuração central e a integração SSO, seus dados permanecem seguros dentro da infraestrutura de sua organização. + +
+ +
+Podemos usar nosso próprio registro NPM privado? + +O OpenCode suporta registros npm privados através do suporte nativo do arquivo `.npmrc` do Bun. Se sua organização usa um registro privado, como JFrog Artifactory, Nexus ou similar, certifique-se de que os desenvolvedores estejam autenticados antes de executar o OpenCode. + +Para configurar a autenticação com seu registro privado: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +Isso cria `~/.npmrc` com os detalhes de autenticação. O OpenCode irá automaticamente +capturar isso. + +:::caution +Você deve estar logado no registro privado antes de executar o OpenCode. +::: + +Alternativamente, você pode configurar manualmente um arquivo `.npmrc`: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Os desenvolvedores devem estar logados no registro privado antes de executar o OpenCode para garantir que os pacotes possam ser instalados a partir do seu registro empresarial. + +
\ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/formatters.mdx b/packages/web/src/content/docs/pt-br/formatters.mdx new file mode 100644 index 000000000..10f77b913 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: Formatadores +description: OpenCode usa formatadores específicos de linguagem. +--- + +OpenCode formata automaticamente arquivos após serem escritos ou editados usando formatadores específicos de linguagem. Isso garante que o código gerado siga os estilos de código do seu projeto. + +--- + +## Integrado + +OpenCode vem com vários formatadores integrados para linguagens e frameworks populares. Abaixo está uma lista dos formatadores, extensões de arquivo suportadas e comandos ou opções de configuração necessárias. + +| Formatador | Extensões | Requisitos | +| ------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| gofmt | .go | Comando `gofmt` disponível | +| mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | Comando `mix` disponível | +| prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, e [mais](https://prettier.io/docs/en/index.html) | Dependência `prettier` em `package.json` | +| biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, e [mais](https://biomejs.dev/) | Arquivo de configuração `biome.json(c)` | +| zig | .zig, .zon | Comando `zig` disponível | +| clang-format | .c, .cpp, .h, .hpp, .ino, e [mais](https://clang.llvm.org/docs/ClangFormat.html) | Arquivo de configuração `.clang-format` | +| ktlint | .kt, .kts | Comando `ktlint` disponível | +| ruff | .py, .pyi | Comando `ruff` disponível com configuração | +| rustfmt | .rs | Comando `rustfmt` disponível | +| cargofmt | .rs | Comando `cargo fmt` disponível | +| uv | .py, .pyi | Comando `uv` disponível | +| rubocop | .rb, .rake, .gemspec, .ru | Comando `rubocop` disponível | +| standardrb | .rb, .rake, .gemspec, .ru | Comando `standardrb` disponível | +| htmlbeautifier | .erb, .html.erb | Comando `htmlbeautifier` disponível | +| air | .R | Comando `air` disponível | +| dart | .dart | Comando `dart` disponível | +| ocamlformat | .ml, .mli | Comando `ocamlformat` disponível e arquivo de configuração `.ocamlformat` | +| terraform | .tf, .tfvars | Comando `terraform` disponível | +| gleam | .gleam | Comando `gleam` disponível | +| nixfmt | .nix | Comando `nixfmt` disponível | +| shfmt | .sh, .bash | Comando `shfmt` disponível | +| pint | .php | Dependência `laravel/pint` em `composer.json` | +| oxfmt (Experimental) | .js, .jsx, .ts, .tsx | Dependência `oxfmt` em `package.json` e uma [variável de ambiente experimental](/docs/cli/#experimental) | +| ormolu | .hs | Comando `ormolu` disponível | + +Portanto, se seu projeto tiver `prettier` em seu `package.json`, o OpenCode o usará automaticamente. + +--- + +## Como funciona + +Quando o OpenCode escreve ou edita um arquivo, ele: + +1. Verifica a extensão do arquivo em relação a todos os formatadores habilitados. +2. Executa o comando do formatador apropriado no arquivo. +3. Aplica as alterações de formatação automaticamente. + +Esse processo acontece em segundo plano, garantindo que seus estilos de código sejam mantidos sem etapas manuais. + +--- + +## Configurar + +Você pode personalizar os formatadores através da seção `formatter` em sua configuração do OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +Cada configuração de formatador suporta o seguinte: + +| Propriedade | Tipo | Descrição | +| ---------------- | -------- | ----------------------------------------------------- | +| `disabled` | boolean | Defina como `true` para desabilitar o formatador | +| `command` | string[] | O comando a ser executado para formatação | +| `environment` | object | Variáveis de ambiente a serem definidas ao executar o formatador | +| `extensions` | string[] | Extensões de arquivo que este formatador deve tratar | + +Vamos ver alguns exemplos. + +--- + +### Desabilitando formatadores + +Para desabilitar **todos** os formatadores globalmente, defina `formatter` como `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +Para desabilitar um **formatador específico**, defina `disabled` como `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Formatadores personalizados + +Você pode substituir os formatadores integrados ou adicionar novos especificando o comando, variáveis de ambiente e extensões de arquivo: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +O **placeholder `$FILE`** no comando será substituído pelo caminho do arquivo que está sendo formatado. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/github.mdx b/packages/web/src/content/docs/pt-br/github.mdx new file mode 100644 index 000000000..738361d75 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: Use OpenCode em problemas e pull-requests do GitHub. +--- + +OpenCode integra-se ao seu fluxo de trabalho do GitHub. Mencione `/opencode` ou `/oc` em seu comentário, e o OpenCode executará tarefas dentro do seu runner do GitHub Actions. + +--- + +## Recursos + +- **Triagem de problemas**: Peça ao OpenCode para analisar um problema e explicá-lo para você. +- **Corrigir e implementar**: Peça ao OpenCode para corrigir um problema ou implementar um recurso. E ele trabalhará em um novo branch e enviará um PR com todas as alterações. +- **Seguro**: O OpenCode é executado dentro dos runners do seu GitHub. + +--- + +## Instalação + +Execute o seguinte comando em um projeto que está em um repositório do GitHub: + +```bash +opencode github install +``` + +Isso o guiará pela instalação do aplicativo GitHub, criação do fluxo de trabalho e configuração de segredos. + +--- + +### Configuração Manual + +Ou você pode configurá-lo manualmente. + +1. **Instale o aplicativo GitHub** + + Acesse [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). Certifique-se de que está instalado no repositório de destino. + +2. **Adicione o fluxo de trabalho** + + Adicione o seguinte arquivo de fluxo de trabalho em `.github/workflows/opencode.yml` no seu repositório. Certifique-se de definir o `model` apropriado e as chaves de API necessárias em `env`. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **Armazene as chaves de API em segredos** + + Nas **configurações** da sua organização ou projeto, expanda **Segredos e variáveis** à esquerda e selecione **Ações**. E adicione as chaves de API necessárias. + +--- + +## Configuração + +- `model`: O modelo a ser usado com o OpenCode. Tem o formato de `provider/model`. Isso é **obrigatório**. +- `agent`: O agente a ser usado. Deve ser um agente primário. Retorna ao `default_agent` da configuração ou `"build"` se não encontrado. +- `share`: Se deve compartilhar a sessão do OpenCode. O padrão é **true** para repositórios públicos. +- `prompt`: Prompt personalizado opcional para substituir o comportamento padrão. Use isso para personalizar como o OpenCode processa solicitações. +- `token`: Token de acesso do GitHub opcional para realizar operações como criar comentários, confirmar alterações e abrir pull requests. Por padrão, o OpenCode usa o token de acesso da instalação do aplicativo GitHub OpenCode, então commits, comentários e pull requests aparecem como se fossem da aplicação. + + Alternativamente, você pode usar o [GITHUB_TOKEN](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) embutido do runner do GitHub Action sem instalar o aplicativo GitHub OpenCode. Apenas certifique-se de conceder as permissões necessárias em seu fluxo de trabalho: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + Você também pode usar um [token de acesso pessoal](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) se preferir. + +--- + +## Eventos Suportados + +O OpenCode pode ser acionado pelos seguintes eventos do GitHub: + +| Tipo de Evento | Acionado Por | Detalhes | +| --------------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | Comentário em um problema ou PR | Mencione `/opencode` ou `/oc` em seu comentário. O OpenCode lê o contexto e pode criar branches, abrir PRs ou responder. | +| `pull_request_review_comment` | Comentário em linhas de código específicas em um PR | Mencione `/opencode` ou `/oc` enquanto revisa o código. O OpenCode recebe o caminho do arquivo, números das linhas e contexto do diff. | +| `issues` | Problema aberto ou editado | Aciona automaticamente o OpenCode quando problemas são criados ou modificados. Requer entrada de `prompt`. | +| `pull_request` | PR aberto ou atualizado | Aciona automaticamente o OpenCode quando PRs são abertos, sincronizados ou reabertos. Útil para revisões automatizadas. | +| `schedule` | Cron baseado em agendamento | Execute o OpenCode em um cronograma. Requer entrada de `prompt`. A saída vai para logs e PRs (sem problema para comentar). | +| `workflow_dispatch` | Acionamento manual pela interface do GitHub | Acione o OpenCode sob demanda através da aba Ações. Requer entrada de `prompt`. A saída vai para logs e PRs. | + +### Exemplo de Agendamento + +Execute o OpenCode em um cronograma para realizar tarefas automatizadas: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Tarefa Agendada OpenCode + +on: + schedule: + - cron: "0 9 * * 1" # Toda segunda-feira às 9h UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Revise a base de código em busca de comentários TODO e crie um resumo. + Se você encontrar problemas que valem a pena serem abordados, abra um problema para rastreá-los. +``` + +Para eventos agendados, a entrada `prompt` é **obrigatória** uma vez que não há comentário para extrair instruções. Fluxos de trabalho agendados são executados sem um contexto de usuário para verificação de permissões, então o fluxo de trabalho deve conceder `contents: write` e `pull-requests: write` se você espera que o OpenCode crie branches ou PRs. + +--- + +### Exemplo de Pull Request + +Revise automaticamente PRs quando forem abertos ou atualizados: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Revise este pull request: + - Verifique se há problemas de qualidade de código + - Procure por bugs potenciais + - Sugira melhorias +``` + +Para eventos de `pull_request`, se nenhum `prompt` for fornecido, o OpenCode padrão será revisar o pull request. + +--- + +### Exemplo de Triagem de Problemas + +Triagem automática de novos problemas. Este exemplo filtra contas com mais de 30 dias para reduzir spam: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Triagem de Problemas + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Verificar idade da conta + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Revise este problema. Se houver uma correção clara ou documentos relevantes: + - Forneça links de documentação + - Adicione orientações de tratamento de erros para exemplos de código + Caso contrário, não comente. +``` + +Para eventos de `issues`, a entrada `prompt` é **obrigatória** uma vez que não há comentário para extrair instruções. + +--- + +## Prompts Personalizados + +Substitua o prompt padrão para personalizar o comportamento do OpenCode para seu fluxo de trabalho. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Revise este pull request: + - Verifique se há problemas de qualidade de código + - Procure por bugs potenciais + - Sugira melhorias +``` + +Isso é útil para impor critérios de revisão específicos, padrões de codificação ou áreas de foco relevantes para seu projeto. + +--- + +## Exemplos + +Aqui estão alguns exemplos de como você pode usar o OpenCode no GitHub. + +- **Explicar um problema** + + Adicione este comentário em um problema do GitHub. + + ``` + /opencode explain this issue + ``` + + O OpenCode lerá toda a conversa, incluindo todos os comentários, e responderá com uma explicação clara. + +- **Corrigir um problema** + + Em um problema do GitHub, diga: + + ``` + /opencode fix this + ``` + + E o OpenCode criará um novo branch, implementará as alterações e abrirá um PR com as mudanças. + +- **Revisar PRs e fazer alterações** + + Deixe o seguinte comentário em um PR do GitHub. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + O OpenCode implementará a alteração solicitada e a confirmará no mesmo PR. + +- **Revisar linhas de código específicas** + + Deixe um comentário diretamente nas linhas de código na aba "Files" do PR. O OpenCode detecta automaticamente o arquivo, os números das linhas e o contexto do diff para fornecer respostas precisas. + + ``` + [Comentário sobre linhas específicas na aba Files] + /oc add error handling here + ``` + + Ao comentar sobre linhas específicas, o OpenCode recebe: + - O arquivo exato sendo revisado + - As linhas específicas de código + - O contexto do diff ao redor + - Informações sobre números de linha + + Isso permite solicitações mais direcionadas sem precisar especificar caminhos de arquivos ou números de linhas manualmente. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/gitlab.mdx b/packages/web/src/content/docs/pt-br/gitlab.mdx new file mode 100644 index 000000000..0905b9bb2 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: Use OpenCode em problemas e solicitações de mesclagem do GitLab. +--- + +OpenCode se integra ao seu fluxo de trabalho do GitLab através do seu pipeline CI/CD do GitLab ou com o GitLab Duo. + +Em ambos os casos, o OpenCode será executado em seus runners do GitLab. + +--- + +## GitLab CI + +OpenCode funciona em um pipeline regular do GitLab. Você pode integrá-lo a um pipeline como um [componente CI](https://docs.gitlab.com/ee/ci/components/) + +Aqui estamos usando um componente CI/CD criado pela comunidade para OpenCode — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### Recursos + +- **Use configuração personalizada por trabalho**: Configure o OpenCode com um diretório de configuração personalizado, por exemplo `./config/#custom-directory` para habilitar ou desabilitar funcionalidades por invocação do OpenCode. +- **Configuração mínima**: O componente CI configura o OpenCode em segundo plano, você só precisa criar a configuração do OpenCode e o prompt inicial. +- **Flexível**: O componente CI suporta várias entradas para personalizar seu comportamento. + +--- + +### Configuração + +1. Armazene seu JSON de autenticação do OpenCode como variáveis de ambiente do tipo File em **Configurações** > **CI/CD** > **Variáveis**. Certifique-se de marcá-las como "Mascaradas e ocultas". +2. Adicione o seguinte ao seu arquivo `.gitlab-ci.yml`. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # O nome da variável para seu JSON de autenticação do OpenCode + command: optional-custom-command + message: "Seu prompt aqui" + ``` + +Para mais entradas e casos de uso [consulte a documentação](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) deste componente. + +--- + +## GitLab Duo + +OpenCode se integra ao seu fluxo de trabalho do GitLab. +Mencione `@opencode` em um comentário, e o OpenCode executará tarefas dentro do seu pipeline CI do GitLab. + +--- + +### Recursos + +- **Triagem de problemas**: Peça ao OpenCode para analisar um problema e explicá-lo para você. +- **Corrigir e implementar**: Peça ao OpenCode para corrigir um problema ou implementar uma funcionalidade. + Ele criará um novo branch e abrirá uma solicitação de mesclagem com as alterações. +- **Seguro**: O OpenCode é executado em seus runners do GitLab. + +--- + +### Configuração + +O OpenCode é executado em seu pipeline CI/CD do GitLab, aqui está o que você precisará para configurá-lo: + +:::tip +Consulte a [**documentação do GitLab**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) para instruções atualizadas. +::: + +1. Configure seu ambiente GitLab +2. Configure CI/CD +3. Obtenha uma chave de API do provedor de modelo de IA +4. Crie uma conta de serviço +5. Configure variáveis de CI/CD +6. Crie um arquivo de configuração de fluxo, aqui está um exemplo: + +
+ + Configuração de fluxo + + ```yaml + image: node:22-slim + commands: + - echo "Instalando opencode" + - npm install --global opencode-ai + - echo "Instalando glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configurando glab" + - echo $GITLAB_HOST + - echo "Criando configuração de autenticação do OpenCode" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configurando git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testando glab" + - glab issue list + - echo "Executando OpenCode" + - | + opencode run " + Você é um assistente de IA ajudando com operações do GitLab. + + Contexto: $AI_FLOW_CONTEXT + Tarefa: $AI_FLOW_INPUT + Evento: $AI_FLOW_EVENT + + Por favor, execute a tarefa solicitada usando as ferramentas disponíveis do GitLab. + Seja minucioso em sua análise e forneça explicações claras. + + + Por favor, use a CLI do glab para acessar dados do GitLab. A CLI do glab já foi autenticada. Você pode executar os comandos correspondentes. + + Se você for solicitado a resumir um MR ou problema ou a fornecer mais informações, então, por favor, poste uma nota de volta ao MR/Problema para que o usuário possa vê-la. + Você não precisa fazer commit ou push das alterações, isso será feito automaticamente com base nas alterações de arquivo que você fizer. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Verificando alterações no git e fazendo push se existirem" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Alterações no Git detectadas, adicionando e fazendo push..." + git add . + if git diff --cached --quiet; then + echo "Nenhuma alteração em estágio para fazer commit" + else + echo "Fazendo commit das alterações no branch: $CI_WORKLOAD_REF" + git commit --message "Alterações do Codex" + echo "Fazendo push das alterações para $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Alterações enviadas com sucesso" + fi + else + echo "Nenhuma alteração no git detectada, pulando push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +Você pode consultar a [documentação dos agentes da CLI do GitLab](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) para instruções detalhadas. + +--- + +### Exemplos + +Aqui estão alguns exemplos de como você pode usar o OpenCode no GitLab. + +:::tip +Você pode configurar para usar uma frase de gatilho diferente de `@opencode`. +::: + +- **Explicar um problema** + + Adicione este comentário em um problema do GitLab. + + ``` + @opencode explain this issue + ``` + + O OpenCode lerá o problema e responderá com uma explicação clara. + +- **Corrigir um problema** + + Em um problema do GitLab, diga: + + ``` + @opencode fix this + ``` + + O OpenCode criará um novo branch, implementará as alterações e abrirá uma solicitação de mesclagem com as alterações. + +- **Revisar solicitações de mesclagem** + + Deixe o seguinte comentário em uma solicitação de mesclagem do GitLab. + + ``` + @opencode review this merge request + ``` + + O OpenCode revisará a solicitação de mesclagem e fornecerá feedback. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/ide.mdx b/packages/web/src/content/docs/pt-br/ide.mdx new file mode 100644 index 000000000..9c6f3ee2d --- /dev/null +++ b/packages/web/src/content/docs/pt-br/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: A extensão OpenCode para VS Code, Cursor e outras IDEs +--- + +OpenCode integra-se com VS Code, Cursor ou qualquer IDE que suporte um terminal. Basta executar `opencode` no terminal para começar. + +--- + +## Uso + +- **Lançamento Rápido**: Use `Cmd+Esc` (Mac) ou `Ctrl+Esc` (Windows/Linux) para abrir o OpenCode em uma visualização de terminal dividido, ou focar em uma sessão de terminal existente se uma já estiver em execução. +- **Nova Sessão**: Use `Cmd+Shift+Esc` (Mac) ou `Ctrl+Shift+Esc` (Windows/Linux) para iniciar uma nova sessão de terminal OpenCode, mesmo que uma já esteja aberta. Você também pode clicar no botão OpenCode na interface. +- **Consciência de Contexto**: Compartilhe automaticamente sua seleção ou aba atual com o OpenCode. +- **Atalhos de Referência de Arquivo**: Use `Cmd+Option+K` (Mac) ou `Alt+Ctrl+K` (Linux/Windows) para inserir referências de arquivo. Por exemplo, `@File#L37-42`. + +--- + +## Instalação + +Para instalar o OpenCode no VS Code e forks populares como Cursor, Windsurf, VSCodium: + +1. Abra o VS Code +2. Abra o terminal integrado +3. Execute `opencode` - a extensão será instalada automaticamente + +Se, por outro lado, você quiser usar sua própria IDE ao executar `/editor` ou `/export` a partir do TUI, você precisará definir `export EDITOR="code --wait"`. [Saiba mais](/docs/tui/#editor-setup). + +--- + +### Instalação Manual + +Procure por **OpenCode** no Marketplace de Extensões e clique em **Instalar**. + +--- + +### Solução de Problemas + +Se a extensão falhar ao instalar automaticamente: + +- Certifique-se de que você está executando `opencode` no terminal integrado. +- Confirme se o CLI para sua IDE está instalado: + - Para VS Code: comando `code` + - Para Cursor: comando `cursor` + - Para Windsurf: comando `windsurf` + - Para VSCodium: comando `codium` + - Se não, execute `Cmd+Shift+P` (Mac) ou `Ctrl+Shift+P` (Windows/Linux) e procure por "Shell Command: Install 'code' command in PATH" (ou o equivalente para sua IDE) +- Certifique-se de que o VS Code tem permissão para instalar extensões \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/index.mdx b/packages/web/src/content/docs/pt-br/index.mdx new file mode 100644 index 000000000..cdc5f7d09 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/index.mdx @@ -0,0 +1,341 @@ +--- +title: Introdução +description: Comece com o OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) é um agente de codificação AI de código aberto. Está disponível como uma interface baseada em terminal, aplicativo desktop ou extensão de IDE. + +![OpenCode TUI com o tema opencode](../../../assets/lander/screenshot.png) + +Vamos começar. + +--- + +#### Pré-requisitos + +Para usar o OpenCode no seu terminal, você precisará de: + +1. Um emulador de terminal moderno como: + - [WezTerm](https://wezterm.org), multiplataforma + - [Alacritty](https://alacritty.org), multiplataforma + - [Ghostty](https://ghostty.org), Linux e macOS + - [Kitty](https://sw.kovidgoyal.net/kitty/), Linux e macOS + +2. Chaves de API para os provedores de LLM que você deseja usar. + +--- + +## Instalar + +A maneira mais fácil de instalar o OpenCode é através do script de instalação. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +Você também pode instalá-lo com os seguintes comandos: + +- **Usando Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **Usando Homebrew no macOS e Linux** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > Recomendamos usar o tap do OpenCode para as versões mais atualizadas. A fórmula oficial `brew install opencode` é mantida pela equipe do Homebrew e é atualizada com menos frequência. + +- **Usando Paru no Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### Windows + +:::tip[Recomendado: Use WSL] +Para a melhor experiência no Windows, recomendamos usar o [Windows Subsystem for Linux (WSL)](/docs/windows-wsl). Ele oferece melhor desempenho e total compatibilidade com os recursos do OpenCode. +::: + +- **Usando Chocolatey** + + ```bash + choco install opencode + ``` + +- **Usando Scoop** + + ```bash + scoop install opencode + ``` + +- **Usando NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **Usando Mise** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **Usando Docker** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +O suporte para instalar o OpenCode no Windows usando Bun está atualmente em andamento. + +Você também pode baixar o binário na seção [Releases](https://github.com/anomalyco/opencode/releases). + +--- + +## Configurar + +Com o OpenCode, você pode usar qualquer provedor de LLM configurando suas chaves de API. + +Se você é novo no uso de provedores de LLM, recomendamos usar o [OpenCode Zen](/docs/zen). +É uma lista selecionada de modelos que foram testados e verificados pela equipe do OpenCode. + +1. Execute o comando `/connect` no TUI, selecione opencode e acesse [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Faça login, adicione seus dados de cobrança e copie sua chave de API. + +3. Cole sua chave de API. + + ```txt + ┌ Chave de API + │ + │ + └ enter + ``` + +Alternativamente, você pode selecionar um dos outros provedores. [Saiba mais](/docs/providers#directory). + +--- + +## Inicializar + +Agora que você configurou um provedor, pode navegar até um projeto no qual deseja trabalhar. + +```bash +cd /caminho/para/projeto +``` + +E execute o OpenCode. + +```bash +opencode +``` + +Em seguida, inicialize o OpenCode para o projeto executando o seguinte comando. + +```bash frame="none" +/init +``` + +Isso fará com que o OpenCode analise seu projeto e crie um arquivo `AGENTS.md` na raiz do projeto. + +:::tip +Você deve commitar o arquivo `AGENTS.md` do seu projeto no Git. +::: + +Isso ajuda o OpenCode a entender a estrutura do projeto e os padrões de codificação utilizados. + +--- + +## Uso + +Agora você está pronto para usar o OpenCode para trabalhar em seu projeto. Sinta-se à vontade para perguntar qualquer coisa! + +Se você é novo no uso de um agente de codificação AI, aqui estão alguns exemplos que podem ajudar. + +--- + +### Fazer perguntas + +Você pode pedir ao OpenCode para explicar a base de código para você. + +:::tip +Use a tecla `@` para buscar arquivos no projeto. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +Como a autenticação é tratada em @packages/functions/src/api/index.ts +``` + +Isso é útil se houver uma parte da base de código na qual você não trabalhou. + +--- + +### Adicionar recursos + +Você pode pedir ao OpenCode para adicionar novos recursos ao seu projeto. Embora primeiro recomendemos pedir para ele criar um plano. + +1. **Criar um plano** + + O OpenCode tem um _Modo de Plano_ que desabilita sua capacidade de fazer alterações e, em vez disso, sugere _como_ implementará o recurso. + + Mude para ele usando a tecla **Tab**. Você verá um indicador para isso no canto inferior direito. + + ```bash frame="none" title="Mudar para o modo de plano" + + ``` + + Agora vamos descrever o que queremos que ele faça. + + ```txt frame="none" + Quando um usuário excluir uma nota, gostaríamos de marcá-la como excluída no banco de dados. + Em seguida, crie uma tela que mostre todas as notas recentemente excluídas. + A partir dessa tela, o usuário pode restaurar uma nota ou excluí-la permanentemente. + ``` + + Você quer dar ao OpenCode detalhes suficientes para entender o que você deseja. Ajuda conversar com ele como se você estivesse falando com um desenvolvedor júnior da sua equipe. + + :::tip + Dê ao OpenCode bastante contexto e exemplos para ajudá-lo a entender o que você deseja. + ::: + +2. **Iterar sobre o plano** + + Uma vez que ele lhe der um plano, você pode dar feedback ou adicionar mais detalhes. + + ```txt frame="none" + Gostaríamos de projetar essa nova tela usando um design que já usei antes. + [Imagem #1] Dê uma olhada nesta imagem e use-a como referência. + ``` + + :::tip + Arraste e solte imagens no terminal para adicioná-las ao prompt. + ::: + + O OpenCode pode escanear qualquer imagem que você fornecer e adicioná-la ao prompt. Você pode fazer isso arrastando e soltando uma imagem no terminal. + +3. **Construir o recurso** + + Uma vez que você se sinta confortável com o plano, volte para o _Modo de Construção_ pressionando a tecla **Tab** novamente. + + ```bash frame="none" + + ``` + + E peça para ele fazer as alterações. + + ```bash frame="none" + Parece bom! Vá em frente e faça as alterações. + ``` + +--- + +### Fazer alterações + +Para alterações mais simples, você pode pedir ao OpenCode para construí-las diretamente sem precisar revisar o plano primeiro. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +Precisamos adicionar autenticação à rota /settings. Dê uma olhada em como isso é tratado na rota /notes em @packages/functions/src/notes.ts e implemente a mesma lógica em @packages/functions/src/settings.ts +``` + +Você quer ter certeza de fornecer uma boa quantidade de detalhes para que o OpenCode faça as alterações corretas. + +--- + +### Desfazer alterações + +Vamos supor que você peça ao OpenCode para fazer algumas alterações. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Você pode refatorar a função em @packages/functions/src/api/index.ts? +``` + +Mas você percebe que não era isso que você queria. Você **pode desfazer** as alterações usando o comando `/undo`. + +```bash frame="none" +/undo +``` + +O OpenCode agora reverterá as alterações que você fez e mostrará sua mensagem original novamente. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Você pode refatorar a função em @packages/functions/src/api/index.ts? +``` + +A partir daqui, você pode ajustar o prompt e pedir ao OpenCode para tentar novamente. + +:::tip +Você pode executar `/undo` várias vezes para desfazer várias alterações. +::: + +Ou você **pode refazer** as alterações usando o comando `/redo`. + +```bash frame="none" +/redo +``` + +--- + +## Compartilhar + +As conversas que você tem com o OpenCode podem ser [compartilhadas com sua equipe](/docs/share). + +```bash frame="none" +/share +``` + +Isso criará um link para a conversa atual e o copiará para sua área de transferência. + +:::note +As conversas não são compartilhadas por padrão. +::: + +Aqui está uma [conversa de exemplo](https://opencode.ai/s/4XP1fce5) com o OpenCode. + +--- + +## Personalizar + +E é isso! Agora você é um profissional em usar o OpenCode. + +Para torná-lo seu, recomendamos [escolher um tema](/docs/themes), [personalizar os atalhos de teclado](/docs/keybinds), [configurar formatadores de código](/docs/formatters), [criar comandos personalizados](/docs/commands) ou brincar com a [configuração do OpenCode](/docs/config). \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/keybinds.mdx b/packages/web/src/content/docs/pt-br/keybinds.mdx new file mode 100644 index 000000000..36480510d --- /dev/null +++ b/packages/web/src/content/docs/pt-br/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: Atalhos de Teclado +description: Personalize seus atalhos de teclado. +--- + +OpenCode tem uma lista de atalhos de teclado que você pode personalizar através da configuração do OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## Tecla líder + +OpenCode usa uma tecla `leader` para a maioria dos atalhos de teclado. Isso evita conflitos no seu terminal. + +Por padrão, `ctrl+x` é a tecla líder e a maioria das ações requer que você primeiro pressione a tecla líder e depois o atalho. Por exemplo, para iniciar uma nova sessão, você primeiro pressiona `ctrl+x` e depois pressiona `n`. + +Você não precisa usar uma tecla líder para seus atalhos, mas recomendamos que o faça. + +--- + +## Desativar atalho + +Você pode desativar um atalho adicionando a tecla à sua configuração com um valor de "none". + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## Atalhos do prompt do desktop + +O prompt de entrada do aplicativo desktop OpenCode suporta atalhos comuns de estilo Readline/Emacs para edição de texto. Estes são embutidos e atualmente não são configuráveis via `opencode.json`. + +| Atalho | Ação | +| -------- | ---------------------------------------- | +| `ctrl+a` | Mover para o início da linha atual | +| `ctrl+e` | Mover para o final da linha atual | +| `ctrl+b` | Mover o cursor uma posição para trás | +| `ctrl+f` | Mover o cursor uma posição para frente | +| `alt+b` | Mover o cursor uma palavra para trás | +| `alt+f` | Mover o cursor uma palavra para frente | +| `ctrl+d` | Deletar o caractere sob o cursor | +| `ctrl+k` | Matar até o final da linha | +| `ctrl+u` | Matar até o início da linha | +| `ctrl+w` | Matar a palavra anterior | +| `alt+d` | Matar a próxima palavra | +| `ctrl+t` | Transpor caracteres | +| `ctrl+g` | Cancelar popovers / abortar resposta em execução | + +--- + +## Shift+Enter + +Alguns terminais não enviam teclas modificadoras com Enter por padrão. Você pode precisar configurar seu terminal para enviar `Shift+Enter` como uma sequência de escape. + +### Windows Terminal + +Abra seu `settings.json` em: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +Adicione isso ao array `actions` de nível raiz: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Adicione isso ao array `keybindings` de nível raiz: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Salve o arquivo e reinicie o Windows Terminal ou abra uma nova aba. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/lsp.mdx b/packages/web/src/content/docs/pt-br/lsp.mdx new file mode 100644 index 000000000..640de7901 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: Servidores LSP +description: OpenCode integra-se aos seus servidores LSP. +--- + +OpenCode integra-se ao seu Protocolo de Servidor de Linguagem (LSP) para ajudar o LLM a interagir com sua base de código. Ele usa diagnósticos para fornecer feedback ao LLM. + +--- + +## Integrado + +OpenCode vem com vários servidores LSP integrados para linguagens populares: + +| Servidor LSP | Extensões | Requisitos | +| ------------------ | ------------------------------------------------------------------- | ---------------------------------------------------------- | +| astro | .astro | Instala automaticamente para projetos Astro | +| bash | .sh, .bash, .zsh, .ksh | Instala automaticamente bash-language-server | +| clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Instala automaticamente para projetos C/C++ | +| csharp | .cs | `.NET SDK` instalado | +| clojure-lsp | .clj, .cljs, .cljc, .edn | Comando `clojure-lsp` disponível | +| dart | .dart | Comando `dart` disponível | +| deno | .ts, .tsx, .js, .jsx, .mjs | Comando `deno` disponível (detecta automaticamente deno.json/deno.jsonc) | +| elixir-ls | .ex, .exs | Comando `elixir` disponível | +| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | Dependência `eslint` no projeto | +| fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` instalado | +| gleam | .gleam | Comando `gleam` disponível | +| gopls | .go | Comando `go` disponível | +| hls | .hs, .lhs | Comando `haskell-language-server-wrapper` disponível | +| jdtls | .java | `Java SDK (versão 21+)` instalado | +| kotlin-ls | .kt, .kts | Instala automaticamente para projetos Kotlin | +| lua-ls | .lua | Instala automaticamente para projetos Lua | +| nixd | .nix | Comando `nixd` disponível | +| ocaml-lsp | .ml, .mli | Comando `ocamllsp` disponível | +| oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | Dependência `oxlint` no projeto | +| php intelephense | .php | Instala automaticamente para projetos PHP | +| prisma | .prisma | Comando `prisma` disponível | +| pyright | .py, .pyi | Dependência `pyright` instalada | +| ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | Comandos `ruby` e `gem` disponíveis | +| rust | .rs | Comando `rust-analyzer` disponível | +| sourcekit-lsp | .swift, .objc, .objcpp | `swift` instalado (`xcode` no macOS) | +| svelte | .svelte | Instala automaticamente para projetos Svelte | +| terraform | .tf, .tfvars | Instala automaticamente a partir de lançamentos do GitHub | +| tinymist | .typ, .typc | Instala automaticamente a partir de lançamentos do GitHub | +| typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | Dependência `typescript` no projeto | +| vue | .vue | Instala automaticamente para projetos Vue | +| yaml-ls | .yaml, .yml | Instala automaticamente o servidor yaml-language-server da Red Hat | +| zls | .zig, .zon | Comando `zig` disponível | + +Os servidores LSP são habilitados automaticamente quando uma das extensões de arquivo acima é detectada e os requisitos são atendidos. + +:::note +Você pode desabilitar os downloads automáticos do servidor LSP definindo a variável de ambiente `OPENCODE_DISABLE_LSP_DOWNLOAD` como `true`. +::: + +--- + +## Como Funciona + +Quando o opencode abre um arquivo, ele: + +1. Verifica a extensão do arquivo em relação a todos os servidores LSP habilitados. +2. Inicia o servidor LSP apropriado se não estiver em execução. + +--- + +## Configurar + +Você pode personalizar os servidores LSP através da seção `lsp` na sua configuração do opencode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Cada servidor LSP suporta o seguinte: + +| Propriedade | Tipo | Descrição | +| ------------------ | -------- | ------------------------------------------------- | +| `disabled` | boolean | Defina como `true` para desabilitar o servidor LSP | +| `command` | string[] | O comando para iniciar o servidor LSP | +| `extensions` | string[] | Extensões de arquivo que este servidor LSP deve manipular | +| `env` | object | Variáveis de ambiente a serem definidas ao iniciar o servidor | +| `initialization` | object | Opções de inicialização a serem enviadas ao servidor LSP | + +Vamos ver alguns exemplos. + +--- + +### Variáveis de ambiente + +Use a propriedade `env` para definir variáveis de ambiente ao iniciar o servidor LSP: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### Opções de inicialização + +Use a propriedade `initialization` para passar opções de inicialização ao servidor LSP. Estas são configurações específicas do servidor enviadas durante a solicitação `initialize` do LSP: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +As opções de inicialização variam de acordo com o servidor LSP. Verifique a documentação do seu servidor LSP para opções disponíveis. +::: + +--- + +### Desabilitando servidores LSP + +Para desabilitar **todos** os servidores LSP globalmente, defina `lsp` como `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +Para desabilitar um servidor LSP **específico**, defina `disabled` como `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Servidores LSP personalizados + +Você pode adicionar servidores LSP personalizados especificando o comando e as extensões de arquivo: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## Informações Adicionais + +### PHP Intelephense + +PHP Intelephense oferece recursos premium através de uma chave de licença. Você pode fornecer uma chave de licença colocando (apenas) a chave em um arquivo de texto em: + +- No macOS/Linux: `$HOME/intelephense/licence.txt` +- No Windows: `%USERPROFILE%/intelephense/licence.txt` + +O arquivo deve conter apenas a chave de licença sem conteúdo adicional. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/mcp-servers.mdx b/packages/web/src/content/docs/pt-br/mcp-servers.mdx new file mode 100644 index 000000000..894734443 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: Servidores MCP +description: Adicione ferramentas MCP locais e remotas. +--- + +Você pode adicionar ferramentas externas ao OpenCode usando o _Modelo de Contexto de Protocolo_, ou MCP. O OpenCode suporta servidores locais e remotos. + +Uma vez adicionadas, as ferramentas MCP estão automaticamente disponíveis para o LLM juntamente com as ferramentas integradas. + +--- + +#### Avisos + +Quando você usa um servidor MCP, ele adiciona ao contexto. Isso pode rapidamente se acumular se você tiver muitas ferramentas. Portanto, recomendamos ter cuidado com quais servidores MCP você usa. + +:::tip +Os servidores MCP adicionam ao seu contexto, então você deve ter cuidado com quais você habilita. +::: + +Certos servidores MCP, como o servidor MCP do GitHub, tendem a adicionar muitos tokens e podem facilmente exceder o limite de contexto. + +--- + +## Habilitar + +Você pode definir servidores MCP em sua [Configuração do OpenCode](https://opencode.ai/docs/config/) sob `mcp`. Adicione cada MCP com um nome único. Você pode se referir a esse MCP pelo nome ao solicitar ao LLM. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "nome-do-servidor-mcp": { + // ... + "enabled": true, + }, + "nome-do-outro-servidor-mcp": { + // ... + }, + }, +} +``` + +Você também pode desabilitar um servidor definindo `enabled` como `false`. Isso é útil se você quiser desabilitar temporariamente um servidor sem removê-lo de sua configuração. + +--- + +### Substituindo padrões remotos + +As organizações podem fornecer servidores MCP padrão através de seu endpoint `.well-known/opencode`. Esses servidores podem estar desabilitados por padrão, permitindo que os usuários optem pelos que precisam. + +Para habilitar um servidor específico da configuração remota da sua organização, adicione-o à sua configuração local com `enabled: true`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +Os valores da sua configuração local substituem os padrões remotos. Veja [precedência de configuração](/docs/config#precedence-order) para mais detalhes. + +--- + +## Local + +Adicione servidores MCP locais usando `type` como `"local"` dentro do objeto MCP. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "meu-servidor-mcp-local": { + "type": "local", + // Ou ["bun", "x", "meu-comando-mcp"] + "command": ["npx", "-y", "meu-comando-mcp"], + "enabled": true, + "environment": { + "MINHA_VAR_DE_ENV": "valor_da_var_de_env", + }, + }, + }, +} +``` + +O comando é como o servidor MCP local é iniciado. Você também pode passar uma lista de variáveis de ambiente. + +Por exemplo, aqui está como você pode adicionar o servidor MCP de teste [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_tudo": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +E para usá-lo, posso adicionar `use the mcp_tudo tool` aos meus prompts. + +```txt "mcp_tudo" +use the mcp_tudo tool to add the number 3 and 4 +``` + +--- + +#### Opções + +Aqui estão todas as opções para configurar um servidor MCP local. + +| Opção | Tipo | Requerido | Descrição | +| ------------ | ------- | --------- | --------------------------------------------------------------------------------- | +| `type` | String | S | Tipo de conexão do servidor MCP, deve ser `"local"`. | +| `command` | Array | S | Comando e argumentos para executar o servidor MCP. | +| `environment`| Object | | Variáveis de ambiente a serem definidas ao executar o servidor. | +| `enabled` | Boolean | | Habilitar ou desabilitar o servidor MCP na inicialização. | +| `timeout` | Number | | Tempo limite em ms para buscar ferramentas do servidor MCP. O padrão é 5000 (5 segundos). | + +--- + +## Remoto + +Adicione servidores MCP remotos definindo `type` como `"remote"`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "meu-mcp-remoto": { + "type": "remote", + "url": "https://meu-servidor-mcp.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MINHA_CHAVE_API" + } + } + } +} +``` + +O `url` é a URL do servidor MCP remoto e com a opção `headers` você pode passar uma lista de cabeçalhos. + +--- + +#### Opções + +| Opção | Tipo | Requerido | Descrição | +| -------- | ------- | --------- | --------------------------------------------------------------------------------- | +| `type` | String | S | Tipo de conexão do servidor MCP, deve ser `"remote"`. | +| `url` | String | S | URL do servidor MCP remoto. | +| `enabled`| Boolean | | Habilitar ou desabilitar o servidor MCP na inicialização. | +| `headers`| Object | | Cabeçalhos a serem enviados com a solicitação. | +| `oauth` | Object | | Configuração de autenticação OAuth. Veja a seção [OAuth](#oauth) abaixo. | +| `timeout`| Number | | Tempo limite em ms para buscar ferramentas do servidor MCP. O padrão é 5000 (5 segundos). | + +--- + +## OAuth + +O OpenCode lida automaticamente com a autenticação OAuth para servidores MCP remotos. Quando um servidor requer autenticação, o OpenCode irá: + +1. Detectar a resposta 401 e iniciar o fluxo OAuth +2. Usar **Registro Dinâmico de Cliente (RFC 7591)** se suportado pelo servidor +3. Armazenar tokens de forma segura para futuras solicitações + +--- + +### Automático + +Para a maioria dos servidores MCP habilitados para OAuth, nenhuma configuração especial é necessária. Basta configurar o servidor remoto: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "meu-servidor-oauth": { + "type": "remote", + "url": "https://mcp.exemplo.com/mcp" + } + } +} +``` + +Se o servidor requer autenticação, o OpenCode solicitará que você se autentique quando tentar usá-lo pela primeira vez. Se não, você pode [iniciar manualmente o fluxo](#authenticating) com `opencode mcp auth `. + +--- + +### Pré-registrado + +Se você tiver credenciais de cliente do provedor do servidor MCP, pode configurá-las: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "meu-servidor-oauth": { + "type": "remote", + "url": "https://mcp.exemplo.com/mcp", + "oauth": { + "clientId": "{env:MINHA_CHAVE_CLIENTE_MCP}", + "clientSecret": "{env:MINHA_CHAVE_SECRETA_MCP}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### Autenticando + +Você pode iniciar manualmente a autenticação ou gerenciar credenciais. + +Autentique-se com um servidor MCP específico: + +```bash +opencode mcp auth meu-servidor-oauth +``` + +Liste todos os servidores MCP e seu status de autenticação: + +```bash +opencode mcp list +``` + +Remova credenciais armazenadas: + +```bash +opencode mcp logout meu-servidor-oauth +``` + +O comando `mcp auth` abrirá seu navegador para autorização. Após você autorizar, o OpenCode armazenará os tokens de forma segura em `~/.local/share/opencode/mcp-auth.json`. + +--- + +#### Desabilitando OAuth + +Se você quiser desabilitar o OAuth automático para um servidor (por exemplo, para servidores que usam chaves de API em vez disso), defina `oauth` como `false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "meu-servidor-chave-api": { + "type": "remote", + "url": "https://mcp.exemplo.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MINHA_CHAVE_API}" + } + } + } +} +``` + +--- + +#### Opções de OAuth + +| Opção | Tipo | Descrição | +| -------------- | ----------------- | ------------------------------------------------------------------------------- | +| `oauth` | Object \| false | Objeto de configuração OAuth, ou `false` para desabilitar a detecção automática de OAuth. | +| `clientId` | String | ID do cliente OAuth. Se não fornecido, o registro dinâmico do cliente será tentado. | +| `clientSecret` | String | Segredo do cliente OAuth, se necessário pelo servidor de autorização. | +| `scope` | String | Escopos OAuth a serem solicitados durante a autorização. | + +#### Depuração + +Se um servidor MCP remoto estiver falhando na autenticação, você pode diagnosticar problemas com: + +```bash +# Ver status de autenticação para todos os servidores com capacidade OAuth +opencode mcp auth list + +# Depurar conexão e fluxo OAuth para um servidor específico +opencode mcp debug meu-servidor-oauth +``` + +O comando `mcp debug` mostra o status de autenticação atual, testa a conectividade HTTP e tenta o fluxo de descoberta OAuth. + +--- + +## Gerenciar + +Seus MCPs estão disponíveis como ferramentas no OpenCode, juntamente com ferramentas integradas. Portanto, você pode gerenciá-los através da configuração do OpenCode como qualquer outra ferramenta. + +--- + +### Global + +Isso significa que você pode habilitá-los ou desabilitá-los globalmente. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "meu-mcp-foo": { + "type": "local", + "command": ["bun", "x", "meu-comando-mcp-foo"] + }, + "meu-mcp-bar": { + "type": "local", + "command": ["bun", "x", "meu-comando-mcp-bar"] + } + }, + "tools": { + "meu-mcp-foo": false + } +} +``` + +Também podemos usar um padrão glob para desabilitar todos os MCPs correspondentes. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "meu-mcp-foo": { + "type": "local", + "command": ["bun", "x", "meu-comando-mcp-foo"] + }, + "meu-mcp-bar": { + "type": "local", + "command": ["bun", "x", "meu-comando-mcp-bar"] + } + }, + "tools": { + "meu-mcp*": false + } +} +``` + +Aqui estamos usando o padrão glob `meu-mcp*` para desabilitar todos os MCPs. + +--- + +### Por agente + +Se você tiver um grande número de servidores MCP, pode querer habilitá-los apenas por agente e desabilitá-los globalmente. Para fazer isso: + +1. Desabilite-o como uma ferramenta globalmente. +2. Em sua [configuração de agente](/docs/agents#tools), habilite o servidor MCP como uma ferramenta. + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "meu-mcp": { + "type": "local", + "command": ["bun", "x", "meu-comando-mcp"], + "enabled": true + } + }, + "tools": { + "meu-mcp*": false + }, + "agent": { + "meu-agente": { + "tools": { + "meu-mcp*": true + } + } + } +} +``` + +--- + +#### Padrões glob + +O padrão glob usa padrões simples de regex globbing: + +- `*` corresponde a zero ou mais de qualquer caractere (por exemplo, `"meu-mcp*"` corresponde a `meu-mcp_search`, `meu-mcp_list`, etc.) +- `?` corresponde exatamente a um caractere +- Todos os outros caracteres correspondem literalmente + +:::note +As ferramentas do servidor MCP são registradas com o nome do servidor como prefixo, então para desabilitar todas as ferramentas de um servidor, simplesmente use: + +``` +"mynome_do_servidor_mcp_*": false +``` + +::: + +--- + +## Exemplos + +Abaixo estão exemplos de alguns servidores MCP comuns. Você pode enviar um PR se quiser documentar outros servidores. + +--- + +### Sentry + +Adicione o [servidor MCP Sentry](https://mcp.sentry.dev) para interagir com seus projetos e problemas do Sentry. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +Após adicionar a configuração, autentique-se com o Sentry: + +```bash +opencode mcp auth sentry +``` + +Isso abrirá uma janela do navegador para completar o fluxo OAuth e conectar o OpenCode à sua conta do Sentry. + +Uma vez autenticado, você pode usar ferramentas do Sentry em seus prompts para consultar problemas, projetos e dados de erro. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Context7 + +Adicione o [servidor MCP Context7](https://github.com/upstash/context7) para pesquisar através de documentos. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +Se você se inscreveu para uma conta gratuita, pode usar sua chave de API e obter limites de taxa mais altos. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +Aqui estamos assumindo que você tem a variável de ambiente `CONTEXT7_API_KEY` definida. + +Adicione `use context7` aos seus prompts para usar o servidor MCP Context7. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +Alternativamente, você pode adicionar algo assim ao seu [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep by Vercel + +Adicione o [Grep by Vercel](https://grep.app) servidor MCP para pesquisar através de trechos de código no GitHub. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +Como nomeamos nosso servidor MCP como `gh_grep`, você pode adicionar `use the gh_grep tool` aos seus prompts para fazer o agente usá-lo. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +Alternativamente, você pode adicionar algo assim ao seu [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/models.mdx b/packages/web/src/content/docs/pt-br/models.mdx new file mode 100644 index 000000000..808ca031e --- /dev/null +++ b/packages/web/src/content/docs/pt-br/models.mdx @@ -0,0 +1,222 @@ +--- +title: Modelos +description: Configurando um provedor e modelo LLM. +--- + +OpenCode usa o [AI SDK](https://ai-sdk.dev/) e [Models.dev](https://models.dev) para suportar **75+ provedores LLM** e suporta a execução de modelos locais. + +--- + +## Provedores + +Os provedores mais populares são pré-carregados por padrão. Se você adicionou as credenciais para um provedor através do comando `/connect`, elas estarão disponíveis quando você iniciar o OpenCode. + +Saiba mais sobre [provedores](/docs/providers). + +--- + +## Selecione um modelo + +Depois de configurar seu provedor, você pode selecionar o modelo que deseja digitando: + +```bash frame="none" +/models +``` + +--- + +## Modelos recomendados + +Existem muitos modelos disponíveis, com novos modelos sendo lançados toda semana. + +:::tip +Considere usar um dos modelos que recomendamos. +::: + +No entanto, há apenas alguns deles que são bons tanto em gerar código quanto em chamar ferramentas. + +Aqui estão vários modelos que funcionam bem com o OpenCode, em nenhuma ordem específica. (Esta não é uma lista exaustiva nem necessariamente atualizada): + +- GPT 5.2 +- GPT 5.1 Codex +- Claude Opus 4.5 +- Claude Sonnet 4.5 +- Minimax M2.1 +- Gemini 3 Pro + +--- + +## Defina um padrão + +Para definir um desses como o modelo padrão, você pode definir a chave `model` na sua configuração do OpenCode. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Aqui, o ID completo é `provider_id/model_id`. Por exemplo, se você estiver usando [OpenCode Zen](/docs/zen), você usaria `opencode/gpt-5.1-codex` para GPT 5.1 Codex. + +Se você configurou um [provedor personalizado](/docs/providers#custom), o `provider_id` é a chave da parte `provider` da sua configuração, e o `model_id` é a chave de `provider.models`. + +--- + +## Configurar modelos + +Você pode configurar globalmente as opções de um modelo através da configuração. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Aqui estamos configurando as configurações globais para dois modelos integrados: `gpt-5` quando acessado via o provedor `openai`, e `claude-sonnet-4-20250514` quando acessado via o provedor `anthropic`. +Os nomes dos provedores e modelos integrados podem ser encontrados em [Models.dev](https://models.dev). + +Você também pode configurar essas opções para quaisquer agentes que estiver usando. A configuração do agente substitui quaisquer opções globais aqui. [Saiba mais](/docs/agents/#additional). + +Você também pode definir variantes personalizadas que estendem as integradas. As variantes permitem que você configure diferentes configurações para o mesmo modelo sem criar entradas duplicadas: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## Variantes + +Muitos modelos suportam várias variantes com diferentes configurações. O OpenCode vem com variantes padrão integradas para provedores populares. + +### Variantes integradas + +O OpenCode vem com variantes padrão para muitos provedores: + +**Anthropic**: + +- `high` - Orçamento de pensamento alto (padrão) +- `max` - Orçamento de pensamento máximo + +**OpenAI**: + +Varia por modelo, mas aproximadamente: + +- `none` - Sem raciocínio +- `minimal` - Esforço de raciocínio mínimo +- `low` - Baixo esforço de raciocínio +- `medium` - Esforço de raciocínio médio +- `high` - Alto esforço de raciocínio +- `xhigh` - Esforço de raciocínio extra alto + +**Google**: + +- `low` - Orçamento de esforço/token mais baixo +- `high` - Orçamento de esforço/token mais alto + +:::tip +Esta lista não é abrangente. Muitos outros provedores também têm padrões integrados. +::: + +### Variantes personalizadas + +Você pode substituir variantes existentes ou adicionar as suas: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### Ciclo de variantes + +Use a tecla de atalho `variant_cycle` para alternar rapidamente entre variantes. [Saiba mais](/docs/keybinds). + +--- + +## Carregando modelos + +Quando o OpenCode é iniciado, ele verifica modelos na seguinte ordem de prioridade: + +1. A flag de linha de comando `--model` ou `-m`. O formato é o mesmo que no arquivo de configuração: `provider_id/model_id`. + +2. A lista de modelos na configuração do OpenCode. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + O formato aqui é `provider/model`. + +3. O último modelo usado. + +4. O primeiro modelo usando uma prioridade interna. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/modes.mdx b/packages/web/src/content/docs/pt-br/modes.mdx new file mode 100644 index 000000000..02fb1e876 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/modes.mdx @@ -0,0 +1,328 @@ +--- +title: Modos +description: Modos diferentes para diferentes casos de uso. +--- + +:::caution +Os modos agora são configurados através da opção `agent` na configuração do opencode. A opção `mode` agora está obsoleta. [Saiba mais](/docs/agents). +::: + +Os modos no opencode permitem que você personalize o comportamento, as ferramentas e os prompts para diferentes casos de uso. + +Ele vem com dois modos integrados: **build** e **plan**. Você pode personalizar esses ou configurar os seus próprios através da configuração do opencode. + +Você pode alternar entre os modos durante uma sessão ou configurá-los no seu arquivo de configuração. + +--- + +## Integrado + +O opencode vem com dois modos integrados. + +--- + +### Build + +Build é o modo **padrão** com todas as ferramentas habilitadas. Este é o modo padrão para trabalho de desenvolvimento onde você precisa de acesso total a operações de arquivos e comandos do sistema. + +--- + +### Plan + +Um modo restrito projetado para planejamento e análise. No modo plan, as seguintes ferramentas estão desativadas por padrão: + +- `write` - Não pode criar novos arquivos +- `edit` - Não pode modificar arquivos existentes, exceto para arquivos localizados em `.opencode/plans/*.md` para detalhar o plano em si +- `patch` - Não pode aplicar patches +- `bash` - Não pode executar comandos de shell + +Este modo é útil quando você deseja que a IA analise o código, sugira alterações ou crie planos sem fazer modificações reais em sua base de código. + +--- + +## Alternando + +Você pode alternar entre modos durante uma sessão usando a tecla _Tab_. Ou sua tecla de atalho configurada `switch_mode`. + +Veja também: [Formatadores](/docs/formatters) para informações sobre configuração de formatação de código. + +--- + +## Configurar + +Você pode personalizar os modos integrados ou criar os seus próprios através da configuração. Os modos podem ser configurados de duas maneiras: + +### Configuração JSON + +Configure os modos no seu arquivo de configuração `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Configuração Markdown + +Você também pode definir modos usando arquivos markdown. Coloque-os em: + +- Global: `~/.config/opencode/modes/` +- Projeto: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +Você está no modo de revisão de código. Foque em: + +- Qualidade do código e melhores práticas +- Bugs potenciais e casos extremos +- Implicações de desempenho +- Considerações de segurança + +Forneça feedback construtivo sem fazer alterações diretas. +``` + +O nome do arquivo markdown se torna o nome do modo (por exemplo, `review.md` cria um modo `review`). + +Vamos analisar essas opções de configuração em detalhes. + +--- + +### Modelo + +Use a configuração `model` para substituir o modelo padrão para este modo. Útil para usar diferentes modelos otimizados para diferentes tarefas. Por exemplo, um modelo mais rápido para planejamento, um modelo mais capaz para implementação. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Temperatura + +Controle a aleatoriedade e a criatividade das respostas da IA com a configuração `temperature`. Valores mais baixos tornam as respostas mais focadas e determinísticas, enquanto valores mais altos aumentam a criatividade e a variabilidade. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Os valores de temperatura geralmente variam de 0.0 a 1.0: + +- **0.0-0.2**: Respostas muito focadas e determinísticas, ideais para análise de código e planejamento +- **0.3-0.5**: Respostas equilibradas com alguma criatividade, boas para tarefas de desenvolvimento geral +- **0.6-1.0**: Respostas mais criativas e variadas, úteis para brainstorming e exploração + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Se nenhuma temperatura for especificada, o opencode usa padrões específicos do modelo (geralmente 0 para a maioria dos modelos, 0.55 para modelos Qwen). + +--- + +### Prompt + +Especifique um arquivo de prompt do sistema personalizado para este modo com a configuração `prompt`. O arquivo de prompt deve conter instruções específicas para o propósito do modo. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Este caminho é relativo a onde o arquivo de configuração está localizado. Portanto, isso funciona tanto para a configuração global do opencode quanto para a configuração específica do projeto. + +--- + +### Ferramentas + +Controle quais ferramentas estão disponíveis neste modo com a configuração `tools`. Você pode habilitar ou desabilitar ferramentas específicas definindo-as como `true` ou `false`. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +Se nenhuma ferramenta for especificada, todas as ferramentas estão habilitadas por padrão. + +--- + +#### Ferramentas disponíveis + +Aqui estão todas as ferramentas que podem ser controladas através da configuração do modo. + +| Ferramenta | Descrição | +| ------------ | -------------------------- | +| `bash` | Executar comandos de shell | +| `edit` | Modificar arquivos existentes | +| `write` | Criar novos arquivos | +| `read` | Ler conteúdos de arquivos | +| `grep` | Pesquisar conteúdos de arquivos | +| `glob` | Encontrar arquivos por padrão | +| `list` | Listar conteúdos de diretório | +| `patch` | Aplicar patches a arquivos | +| `todowrite` | Gerenciar listas de tarefas | +| `todoread` | Ler listas de tarefas | +| `webfetch` | Buscar conteúdo da web | + +--- + +## Modos personalizados + +Você pode criar seus próprios modos personalizados adicionando-os à configuração. Aqui estão exemplos usando ambas as abordagens: + +### Usando configuração JSON + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Usando arquivos markdown + +Crie arquivos de modo em `.opencode/modes/` para modos específicos do projeto ou `~/.config/opencode/modes/` para modos globais: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +Você está no modo de depuração. Seu objetivo principal é ajudar a investigar e diagnosticar problemas. + +Foque em: + +- Compreender o problema através de uma análise cuidadosa +- Usar comandos bash para inspecionar o estado do sistema +- Ler arquivos e logs relevantes +- Pesquisar padrões e anomalias +- Fornecer explicações claras das descobertas + +Não faça alterações em arquivos. Apenas investigue e relate. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +Você está no modo de refatoração. Foque em melhorar a qualidade do código sem alterar a funcionalidade. + +Prioridades: + +- Melhorar a legibilidade e a manutenibilidade do código +- Aplicar convenções de nomenclatura consistentes +- Reduzir a duplicação de código +- Otimizar o desempenho onde apropriado +- Garantir que todos os testes continuem passando +``` + +--- + +### Casos de uso + +Aqui estão alguns casos de uso comuns para diferentes modos. + +- **Modo Build**: Trabalho de desenvolvimento completo com todas as ferramentas habilitadas +- **Modo Plan**: Análise e planejamento sem fazer alterações +- **Modo Review**: Revisão de código com acesso somente leitura e ferramentas de documentação +- **Modo Debug**: Focado em investigação com ferramentas bash e de leitura habilitadas +- **Modo Docs**: Redação de documentação com operações de arquivo, mas sem comandos do sistema + +Você também pode descobrir que diferentes modelos são bons para diferentes casos de uso. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/network.mdx b/packages/web/src/content/docs/pt-br/network.mdx new file mode 100644 index 000000000..0931b2b5b --- /dev/null +++ b/packages/web/src/content/docs/pt-br/network.mdx @@ -0,0 +1,57 @@ +--- +title: Rede +description: Configure proxies e certificados personalizados. +--- + +OpenCode suporta variáveis de ambiente de proxy padrão e certificados personalizados para ambientes de rede corporativa. + +--- + +## Proxy + +OpenCode respeita variáveis de ambiente de proxy padrão. + +```bash +# Proxy HTTPS (recomendado) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# Proxy HTTP (se HTTPS não estiver disponível) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Ignorar proxy para servidor local (obrigatório) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::caution +O TUI se comunica com um servidor HTTP local. Você deve ignorar o proxy para essa conexão para evitar loops de roteamento. +::: + +Você pode configurar a porta e o nome do host do servidor usando [flags da CLI](/docs/cli#run). + +--- + +### Autenticar + +Se o seu proxy requer autenticação básica, inclua as credenciais na URL. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::caution +Evite codificar senhas. Use variáveis de ambiente ou armazenamento seguro de credenciais. +::: + +Para proxies que requerem autenticação avançada como NTLM ou Kerberos, considere usar um LLM Gateway que suporte seu método de autenticação. + +--- + +## Certificados personalizados + +Se sua empresa usa CAs personalizadas para conexões HTTPS, configure o OpenCode para confiá-las. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +Isso funciona tanto para conexões de proxy quanto para acesso direto à API. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/permissions.mdx b/packages/web/src/content/docs/pt-br/permissions.mdx new file mode 100644 index 000000000..994e83de8 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: Permissões +description: Controle quais ações requerem aprovação para serem executadas. +--- + +OpenCode usa a configuração `permission` para decidir se uma determinada ação deve ser executada automaticamente, solicitar sua aprovação ou ser bloqueada. + +A partir da versão `v1.1.1`, a configuração booleana legada `tools` foi descontinuada e mesclada na `permission`. A antiga configuração `tools` ainda é suportada para compatibilidade retroativa. + +--- + +## Ações + +Cada regra de permissão se resolve em uma das seguintes opções: + +- `"allow"` — executar sem aprovação +- `"ask"` — solicitar aprovação +- `"deny"` — bloquear a ação + +--- + +## Configuração + +Você pode definir permissões globalmente (com `*`), e substituir ferramentas específicas. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +Você também pode definir todas as permissões de uma vez: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## Regras Granulares (Sintaxe de Objeto) + +Para a maioria das permissões, você pode usar um objeto para aplicar diferentes ações com base na entrada da ferramenta. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +As regras são avaliadas por correspondência de padrão, com a **última regra correspondente vencendo**. Um padrão comum é colocar a regra de captura `"*"` primeiro, e regras mais específicas depois. + +### Coringas + +Os padrões de permissão usam correspondência simples de coringas: + +- `*` corresponde a zero ou mais de qualquer caractere +- `?` corresponde exatamente a um caractere +- Todos os outros caracteres correspondem literalmente + +### Expansão do Diretório Home + +Você pode usar `~` ou `$HOME` no início de um padrão para referenciar seu diretório home. Isso é particularmente útil para regras de [`external_directory`](#external-directories). + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### Diretórios Externos + +Use `external_directory` para permitir chamadas de ferramentas que tocam em caminhos fora do diretório de trabalho onde o OpenCode foi iniciado. Isso se aplica a qualquer ferramenta que aceite um caminho como entrada (por exemplo, `read`, `edit`, `list`, `glob`, `grep` e muitos comandos `bash`). + +A expansão do home (como `~/...`) afeta apenas como um padrão é escrito. Não torna um caminho externo parte do espaço de trabalho atual, então caminhos fora do diretório de trabalho ainda devem ser permitidos via `external_directory`. + +Por exemplo, isso permite acesso a tudo sob `~/projects/personal/`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +Qualquer diretório permitido aqui herda os mesmos padrões do espaço de trabalho atual. Como [`read` padrão é `allow`](#defaults), leituras também são permitidas para entradas sob `external_directory`, a menos que sejam substituídas. Adicione regras explícitas quando uma ferramenta deve ser restrita nesses caminhos, como bloquear edições enquanto mantém leituras: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +Mantenha a lista focada em caminhos confiáveis e adicione regras adicionais de permissão ou negação conforme necessário para outras ferramentas (por exemplo, `bash`). + +--- + +## Permissões Disponíveis + +As permissões do OpenCode são indexadas pelo nome da ferramenta, além de alguns guardas de segurança: + +- `read` — leitura de um arquivo (corresponde ao caminho do arquivo) +- `edit` — todas as modificações de arquivo (cobre `edit`, `write`, `patch`, `multiedit`) +- `glob` — globbing de arquivos (corresponde ao padrão glob) +- `grep` — busca de conteúdo (corresponde ao padrão regex) +- `list` — listagem de arquivos em um diretório (corresponde ao caminho do diretório) +- `bash` — execução de comandos de shell (corresponde a comandos analisados como `git status --porcelain`) +- `task` — lançamento de subagentes (corresponde ao tipo de subagente) +- `skill` — carregamento de uma habilidade (corresponde ao nome da habilidade) +- `lsp` — execução de consultas LSP (atualmente não granular) +- `todoread`, `todowrite` — leitura/atualização da lista de tarefas +- `webfetch` — busca de uma URL (corresponde à URL) +- `websearch`, `codesearch` — busca na web/código (corresponde à consulta) +- `external_directory` — acionado quando uma ferramenta toca em caminhos fora do diretório de trabalho do projeto +- `doom_loop` — acionado quando a mesma chamada de ferramenta se repete 3 vezes com entrada idêntica + +--- + +## Padrões + +Se você não especificar nada, o OpenCode começa com padrões permissivos: + +- A maioria das permissões padrão é `"allow"`. +- `doom_loop` e `external_directory` padrão é `"ask"`. +- `read` é `"allow"`, mas arquivos `.env` são negados por padrão: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## O que “Ask” Faz + +Quando o OpenCode solicita aprovação, a interface oferece três resultados: + +- `once` — aprovar apenas esta solicitação +- `always` — aprovar futuras solicitações que correspondam aos padrões sugeridos (para o restante da sessão atual do OpenCode) +- `reject` — negar a solicitação + +O conjunto de padrões que `always` aprovaria é fornecido pela ferramenta (por exemplo, aprovações de bash normalmente incluem um prefixo de comando seguro como `git status*`). + +--- + +## Agentes + +Você pode substituir permissões por agente. As permissões do agente são mescladas com a configuração global, e as regras do agente têm precedência. [Saiba mais](/docs/agents#permissions) sobre permissões de agentes. + +:::note +Consulte a seção [Regras Granulares (Sintaxe de Objeto)](#granular-rules-object-syntax) acima para exemplos mais detalhados de correspondência de padrões. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +Você também pode configurar permissões de agentes em Markdown: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Revisão de código sem edições +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Apenas analise o código e sugira alterações. +``` + +:::tip +Use correspondência de padrões para comandos com argumentos. `"grep *"` permite `grep pattern file.txt`, enquanto `"grep"` sozinho o bloquearia. Comandos como `git status` funcionam para o comportamento padrão, mas requerem permissão explícita (como `"git status *"`) quando argumentos são passados. +::: \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/plugins.mdx b/packages/web/src/content/docs/pt-br/plugins.mdx new file mode 100644 index 000000000..af33e0777 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/plugins.mdx @@ -0,0 +1,384 @@ +--- +title: Plugins +description: Escreva seus próprios plugins para estender o OpenCode. +--- + +Plugins permitem que você estenda o OpenCode conectando-se a vários eventos e personalizando o comportamento. Você pode criar plugins para adicionar novos recursos, integrar-se a serviços externos ou modificar o comportamento padrão do OpenCode. + +Para exemplos, confira os [plugins](/docs/ecosystem#plugins) criados pela comunidade. + +--- + +## Usar um plugin + +Existem duas maneiras de carregar plugins. + +--- + +### De arquivos locais + +Coloque arquivos JavaScript ou TypeScript no diretório de plugins. + +- `.opencode/plugins/` - Plugins em nível de projeto +- `~/.config/opencode/plugins/` - Plugins globais + +Os arquivos nesses diretórios são carregados automaticamente na inicialização. + +--- + +### Do npm + +Especifique pacotes npm no seu arquivo de configuração. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +Pacotes npm regulares e escopados são suportados. + +Navegue pelos plugins disponíveis no [ecossistema](/docs/ecosystem#plugins). + +--- + +### Como os plugins são instalados + +**Plugins npm** são instalados automaticamente usando Bun na inicialização. Pacotes e suas dependências são armazenados em cache em `~/.cache/opencode/node_modules/`. + +**Plugins locais** são carregados diretamente do diretório de plugins. Para usar pacotes externos, você deve criar um `package.json` dentro do seu diretório de configuração (veja [Dependências](#dependencies)), ou publicar o plugin no npm e [adicioná-lo à sua configuração](/docs/config#plugins). + +--- + +### Ordem de carregamento + +Os plugins são carregados de todas as fontes e todos os hooks são executados em sequência. A ordem de carregamento é: + +1. Configuração global (`~/.config/opencode/opencode.json`) +2. Configuração do projeto (`opencode.json`) +3. Diretório de plugins global (`~/.config/opencode/plugins/`) +4. Diretório de plugins do projeto (`.opencode/plugins/`) + +Pacotes npm duplicados com o mesmo nome e versão são carregados uma vez. No entanto, um plugin local e um plugin npm com nomes semelhantes são carregados separadamente. + +--- + +## Criar um plugin + +Um plugin é um **módulo JavaScript/TypeScript** que exporta uma ou mais funções de plugin. Cada função recebe um objeto de contexto e retorna um objeto de hooks. + +--- + +### Dependências + +Plugins locais e ferramentas personalizadas podem usar pacotes npm externos. Adicione um `package.json` ao seu diretório de configuração com as dependências necessárias. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +O OpenCode executa `bun install` na inicialização para instalar esses pacotes. Seus plugins e ferramentas podem então importá-los. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### Estrutura básica + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin inicializado!") + + return { + // Implementações de hooks vão aqui + } +} +``` + +A função do plugin recebe: + +- `project`: As informações do projeto atual. +- `directory`: O diretório de trabalho atual. +- `worktree`: O caminho do worktree do git. +- `client`: Um cliente SDK do opencode para interagir com a IA. +- `$`: A [API shell](https://bun.com/docs/runtime/shell) do Bun para executar comandos. + +--- + +### Suporte a TypeScript + +Para plugins TypeScript, você pode importar tipos do pacote de plugin: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Implementações de hooks seguras em tipo + } +} +``` + +--- + +### Eventos + +Plugins podem se inscrever em eventos como visto abaixo na seção Exemplos. Aqui está uma lista dos diferentes eventos disponíveis. + +#### Eventos de Comando + +- `command.executed` + +#### Eventos de Arquivo + +- `file.edited` +- `file.watcher.updated` + +#### Eventos de Instalação + +- `installation.updated` + +#### Eventos LSP + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### Eventos de Mensagem + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### Eventos de Permissão + +- `permission.asked` +- `permission.replied` + +#### Eventos de Servidor + +- `server.connected` + +#### Eventos de Sessão + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### Eventos de Todo + +- `todo.updated` + +#### Eventos de Shell + +- `shell.env` + +#### Eventos de Ferramenta + +- `tool.execute.after` +- `tool.execute.before` + +#### Eventos TUI + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## Exemplos + +Aqui estão alguns exemplos de plugins que você pode usar para estender o opencode. + +--- + +### Enviar notificações + +Envie notificações quando certos eventos ocorrerem: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Enviar notificação ao concluir a sessão + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Sessão concluída!" with title "opencode"'` + } + }, + } +} +``` + +Estamos usando `osascript` para executar AppleScript no macOS. Aqui estamos usando para enviar notificações. + +:::note +Se você estiver usando o aplicativo desktop OpenCode, ele pode enviar notificações do sistema automaticamente quando uma resposta estiver pronta ou quando ocorrer um erro na sessão. +::: + +--- + +### Proteção .env + +Impeça o opencode de ler arquivos `.env`: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Não leia arquivos .env") + } + }, + } +} +``` + +--- + +### Injetar variáveis de ambiente + +Injete variáveis de ambiente em todas as execuções de shell (ferramentas de IA e terminais de usuário): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secreto" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### Ferramentas personalizadas + +Plugins também podem adicionar ferramentas personalizadas ao opencode: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "Esta é uma ferramenta personalizada", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Olá ${args.foo} de ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +O helper `tool` cria uma ferramenta personalizada que o opencode pode chamar. Ele aceita uma função de esquema Zod e retorna uma definição de ferramenta com: + +- `description`: O que a ferramenta faz +- `args`: Esquema Zod para os argumentos da ferramenta +- `execute`: Função que é executada quando a ferramenta é chamada + +Suas ferramentas personalizadas estarão disponíveis para o opencode junto com as ferramentas integradas. + +--- + +### Registro + +Use `client.app.log()` em vez de `console.log` para registro estruturado: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin inicializado", + extra: { foo: "bar" }, + }, + }) +} +``` + +Níveis: `debug`, `info`, `warn`, `error`. Veja a [documentação do SDK](https://opencode.ai/docs/sdk) para detalhes. + +--- + +### Hooks de compactação + +Personalize o contexto incluído quando uma sessão é compactada: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Injetar contexto adicional no prompt de compactação + output.context.push(` +## Contexto Personalizado + +Inclua qualquer estado que deve persistir entre as compactações: +- Status da tarefa atual +- Decisões importantes tomadas +- Arquivos sendo trabalhados ativamente +`) + }, + } +} +``` + +O hook `experimental.session.compacting` é acionado antes que o LLM gere um resumo de continuação. Use-o para injetar contexto específico de domínio que o prompt de compactação padrão poderia perder. + +Você também pode substituir o prompt de compactação completamente definindo `output.prompt`: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Substituir todo o prompt de compactação + output.prompt = ` +Você está gerando um prompt de continuação para uma sessão de enxame multi-agente. + +Resuma: +1. A tarefa atual e seu status +2. Quais arquivos estão sendo modificados e por quem +3. Quaisquer bloqueios ou dependências entre agentes +4. Os próximos passos para concluir o trabalho + +Formate como um prompt estruturado que um novo agente pode usar para retomar o trabalho. +` + }, + } +} +``` + +Quando `output.prompt` é definido, ele substitui completamente o prompt de compactação padrão. O array `output.context` é ignorado neste caso. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/providers.mdx b/packages/web/src/content/docs/pt-br/providers.mdx new file mode 100644 index 000000000..f10702e6f --- /dev/null +++ b/packages/web/src/content/docs/pt-br/providers.mdx @@ -0,0 +1,1881 @@ +--- +title: Provedores +description: Usando qualquer provedor LLM no OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode usa o [AI SDK](https://ai-sdk.dev/) e [Models.dev](https://models.dev) para suportar **75+ provedores LLM** e suporta a execução de modelos locais. + +Para adicionar um provedor, você precisa: + +1. Adicionar as chaves da API para o provedor usando o comando `/connect`. +2. Configurar o provedor na sua configuração do OpenCode. + +--- + +### Credenciais + +Quando você adiciona as chaves da API de um provedor com o comando `/connect`, elas são armazenadas em `~/.local/share/opencode/auth.json`. + +--- + +### Configuração + +Você pode personalizar os provedores através da seção `provider` na sua configuração do OpenCode. + +--- + +#### URL Base + +Você pode personalizar a URL base para qualquer provedor definindo a opção `baseURL`. Isso é útil ao usar serviços de proxy ou endpoints personalizados. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen é uma lista de modelos fornecidos pela equipe do OpenCode que foram testados e verificados para funcionar bem com o OpenCode. [Saiba mais](/docs/zen). + +:::tip +Se você é novo, recomendamos começar com o OpenCode Zen. +::: + +1. Execute o comando `/connect` no TUI, selecione opencode e acesse [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Faça login, adicione seus dados de cobrança e copie sua chave da API. + +3. Cole sua chave da API. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute `/models` no TUI para ver a lista de modelos que recomendamos. + + ```txt + /models + ``` + +Funciona como qualquer outro provedor no OpenCode e é completamente opcional. + +--- + +## Diretório + +Vamos olhar alguns dos provedores em detalhes. Se você gostaria de adicionar um provedor à lista, sinta-se à vontade para abrir um PR. + +:::note +Não vê um provedor aqui? Envie um PR. +::: + +--- + +### 302.AI + +1. Acesse o [console 302.AI](https://302.ai/), crie uma conta e gere uma chave da API. + +2. Execute o comando `/connect` e procure por **302.AI**. + + ```txt + /connect + ``` + +3. Insira sua chave da API 302.AI. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo. + + ```txt + /models + ``` + +--- + +### Amazon Bedrock + +Para usar o Amazon Bedrock com o OpenCode: + +1. Acesse o **Catálogo de Modelos** no console do Amazon Bedrock e solicite acesso aos modelos que você deseja. + + :::tip + Você precisa ter acesso ao modelo que deseja no Amazon Bedrock. + ::: + +2. **Configure a autenticação** usando um dos seguintes métodos: + + #### Variáveis de Ambiente (Início Rápido) + + Defina uma dessas variáveis de ambiente ao executar o opencode: + + ```bash + # Opção 1: Usando chaves de acesso da AWS + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Opção 2: Usando perfil nomeado da AWS + AWS_PROFILE=my-profile opencode + + # Opção 3: Usando token bearer do Bedrock + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + Ou adicione-as ao seu perfil bash: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### Arquivo de Configuração (Recomendado) + + Para configuração específica do projeto ou persistente, use `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **Opções disponíveis:** + - `region` - Região da AWS (ex: `us-east-1`, `eu-west-1`) + - `profile` - Perfil nomeado da AWS em `~/.aws/credentials` + - `endpoint` - URL de endpoint personalizada para endpoints VPC (alias para a opção genérica `baseURL`) + + :::tip + As opções do arquivo de configuração têm precedência sobre as variáveis de ambiente. + ::: + + #### Avançado: Endpoints VPC + + Se você estiver usando endpoints VPC para Bedrock: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::note + A opção `endpoint` é um alias para a opção genérica `baseURL`, usando terminologia específica da AWS. Se tanto `endpoint` quanto `baseURL` forem especificados, `endpoint` tem precedência. + ::: + + #### Métodos de Autenticação + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: Crie um usuário IAM e gere chaves de acesso no Console da AWS + - **`AWS_PROFILE`**: Use perfis nomeados de `~/.aws/credentials`. Primeiro configure com `aws configure --profile my-profile` ou `aws sso login` + - **`AWS_BEARER_TOKEN_BEDROCK`**: Gere chaves de API de longo prazo no console do Amazon Bedrock + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: Para EKS IRSA (IAM Roles for Service Accounts) ou outros ambientes Kubernetes com federação OIDC. Essas variáveis de ambiente são injetadas automaticamente pelo Kubernetes ao usar anotações de conta de serviço. + + #### Precedência de Autenticação + + O Amazon Bedrock usa a seguinte prioridade de autenticação: + 1. **Bearer Token** - variável de ambiente `AWS_BEARER_TOKEN_BEDROCK` ou token do comando `/connect` + 2. **Cadeia de Credenciais da AWS** - Perfil, chaves de acesso, credenciais compartilhadas, funções IAM, Tokens de Identidade da Web (EKS IRSA), metadados da instância + + :::note + Quando um token bearer é definido (via `/connect` ou `AWS_BEARER_TOKEN_BEDROCK`), ele tem precedência sobre todos os métodos de credenciais da AWS, incluindo perfis configurados. + ::: + +3. Execute o comando `/models` para selecionar o modelo que você deseja. + + ```txt + /models + ``` + +:::note +Para perfis de inferência personalizados, use o nome do modelo e do provedor na chave e defina a propriedade `id` para o arn. Isso garante o cache correto: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### Anthropic + +1. Depois de se inscrever, execute o comando `/connect` e selecione Anthropic. + + ```txt + /connect + ``` + +2. Aqui você pode selecionar a opção **Claude Pro/Max** e isso abrirá seu navegador e pedirá para você se autenticar. + + ```txt + ┌ Selecionar método de autenticação + │ + │ Claude Pro/Max + │ Criar uma chave da API + │ Inserir chave da API manualmente + └ + ``` + +3. Agora todos os modelos da Anthropic devem estar disponíveis quando você usar o comando `/models`. + + ```txt + /models + ``` + +:::info +Usar sua assinatura Claude Pro/Max no OpenCode não é oficialmente suportado pela [Anthropic](https://anthropic.com). +::: + +##### Usando chaves da API + +Você também pode selecionar **Criar uma chave da API** se não tiver uma assinatura Pro/Max. Isso também abrirá seu navegador e pedirá que você faça login na Anthropic e lhe dará um código que você pode colar no seu terminal. + +Ou, se você já tiver uma chave da API, pode selecionar **Inserir chave da API manualmente** e colá-la no seu terminal. + +--- + +### Azure OpenAI + +:::note +Se você encontrar erros "Desculpe, mas não posso ajudar com esse pedido", tente mudar o filtro de conteúdo de **DefaultV2** para **Default** em seu recurso Azure. +::: + +1. Acesse o [portal Azure](https://portal.azure.com/) e crie um recurso **Azure OpenAI**. Você precisará: + - **Nome do recurso**: Isso se torna parte do seu endpoint da API (`https://RESOURCE_NAME.openai.azure.com/`) + - **Chave da API**: Seja `KEY 1` ou `KEY 2` do seu recurso + +2. Vá para [Azure AI Foundry](https://ai.azure.com/) e implante um modelo. + + :::note + O nome da implantação deve corresponder ao nome do modelo para que o opencode funcione corretamente. + ::: + +3. Execute o comando `/connect` e procure por **Azure**. + + ```txt + /connect + ``` + +4. Insira sua chave da API. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +5. Defina o nome do seu recurso como uma variável de ambiente: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + Ou adicione ao seu perfil bash: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. Execute o comando `/models` para selecionar seu modelo implantado. + + ```txt + /models + ``` + +--- + +### Azure Cognitive Services + +1. Acesse o [portal Azure](https://portal.azure.com/) e crie um recurso **Azure OpenAI**. Você precisará: + - **Nome do recurso**: Isso se torna parte do seu endpoint da API (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) + - **Chave da API**: Seja `KEY 1` ou `KEY 2` do seu recurso + +2. Vá para [Azure AI Foundry](https://ai.azure.com/) e implante um modelo. + + :::note + O nome da implantação deve corresponder ao nome do modelo para que o opencode funcione corretamente. + ::: + +3. Execute o comando `/connect` e procure por **Azure Cognitive Services**. + + ```txt + /connect + ``` + +4. Insira sua chave da API. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +5. Defina o nome do seu recurso como uma variável de ambiente: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + Ou adicione ao seu perfil bash: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. Execute o comando `/models` para selecionar seu modelo implantado. + + ```txt + /models + ``` + +--- + +### Baseten + +1. Acesse o [Baseten](https://app.baseten.co/), crie uma conta e gere uma chave da API. + +2. Execute o comando `/connect` e procure por **Baseten**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Baseten. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo. + + ```txt + /models + ``` + +--- + +### Cerebras + +1. Acesse o [console Cerebras](https://inference.cerebras.ai/), crie uma conta e gere uma chave da API. + +2. Execute o comando `/connect` e procure por **Cerebras**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Cerebras. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### Cloudflare AI Gateway + +O Cloudflare AI Gateway permite que você acesse modelos do OpenAI, Anthropic, Workers AI e mais através de um endpoint unificado. Com [Faturamento Unificado](https://developers.cloudflare.com/ai-gateway/features/unified-billing/), você não precisa de chaves de API separadas para cada provedor. + +1. Acesse o [painel do Cloudflare](https://dash.cloudflare.com/), navegue até **AI** > **AI Gateway** e crie um novo gateway. + +2. Defina seu ID de Conta e ID de Gateway como variáveis de ambiente. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=seu-id-de-conta-de-32-caracteres + export CLOUDFLARE_GATEWAY_ID=seu-id-de-gateway + ``` + +3. Execute o comando `/connect` e procure por **Cloudflare AI Gateway**. + + ```txt + /connect + ``` + +4. Insira seu token da API do Cloudflare. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + + Ou defina como uma variável de ambiente. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=seu-token-da-api + ``` + +5. Execute o comando `/models` para selecionar um modelo. + + ```txt + /models + ``` + + Você também pode adicionar modelos através da sua configuração do opencode. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### Cortecs + +1. Acesse o [console Cortecs](https://cortecs.ai/), crie uma conta e gere uma chave da API. + +2. Execute o comando `/connect` e procure por **Cortecs**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Cortecs. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### DeepSeek + +1. Acesse o [console DeepSeek](https://platform.deepseek.com/), crie uma conta e clique em **Criar nova chave da API**. + +2. Execute o comando `/connect` e procure por **DeepSeek**. + + ```txt + /connect + ``` + +3. Insira sua chave da API DeepSeek. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo DeepSeek como _DeepSeek Reasoner_. + + ```txt + /models + ``` + +--- + +### Deep Infra + +1. Acesse o [painel Deep Infra](https://deepinfra.com/dash), crie uma conta e gere uma chave da API. + +2. Execute o comando `/connect` e procure por **Deep Infra**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Deep Infra. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo. + + ```txt + /models + ``` + +--- + +### Firmware + +1. Acesse o [painel Firmware](https://app.firmware.ai/signup), crie uma conta e gere uma chave da API. + +2. Execute o comando `/connect` e procure por **Firmware**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Firmware. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo. + + ```txt + /models + ``` + +--- + +### Fireworks AI + +1. Acesse o [console Fireworks AI](https://app.fireworks.ai/), crie uma conta e clique em **Criar Chave da API**. + +2. Execute o comando `/connect` e procure por **Fireworks AI**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Fireworks AI. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### GitLab Duo + +GitLab Duo fornece um chat agente com suporte a ferramentas nativas através do proxy da Anthropic do GitLab. + +1. Execute o comando `/connect` e selecione GitLab. + + ```txt + /connect + ``` + +2. Escolha seu método de autenticação: + + ```txt + ┌ Selecionar método de autenticação + │ + │ OAuth (Recomendado) + │ Token de Acesso Pessoal + └ + ``` + + #### Usando OAuth (Recomendado) + + Selecione **OAuth** e seu navegador abrirá para autorização. + + #### Usando Token de Acesso Pessoal + 1. Vá para [Configurações do Usuário do GitLab > Tokens de Acesso](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. Clique em **Adicionar novo token** + 3. Nome: `OpenCode`, Escopos: `api` + 4. Copie o token (começa com `glpat-`) + 5. Insira-o no terminal + +3. Execute o comando `/models` para ver os modelos disponíveis. + + ```txt + /models + ``` + + Três modelos baseados em Claude estão disponíveis: + - **duo-chat-haiku-4-5** (Padrão) - Respostas rápidas para tarefas rápidas + - **duo-chat-sonnet-4-5** - Desempenho equilibrado para a maioria dos fluxos de trabalho + - **duo-chat-opus-4-5** - Mais capaz para análises complexas + +:::note +Você também pode especificar a variável de ambiente 'GITLAB_TOKEN' se não quiser +armazenar o token no armazenamento de autenticação do opencode. +::: + +##### GitLab Auto-Hospedado + +:::note[nota de conformidade] +OpenCode usa um pequeno modelo para algumas tarefas de IA, como gerar o título da sessão. +Ele está configurado para usar gpt-5-nano por padrão, hospedado pela Zen. Para bloquear o OpenCode +para usar apenas sua própria instância hospedada do GitLab, adicione o seguinte ao seu +arquivo `opencode.json`. Também é recomendado desativar o compartilhamento de sessões. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +Para instâncias do GitLab auto-hospedadas: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +Se sua instância executar um AI Gateway personalizado: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +Ou adicione ao seu perfil bash: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +Seu administrador do GitLab deve habilitar o seguinte: + +1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) para o usuário, grupo ou instância +2. Flags de recurso (via console Rails): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### OAuth para instâncias auto-hospedadas + +Para fazer o OAuth funcionar para sua instância auto-hospedada, você precisa criar +um novo aplicativo (Configurações → Aplicativos) com a +URL de callback `http://127.0.0.1:8080/callback` e os seguintes escopos: + +- api (Acessar a API em seu nome) +- read_user (Ler suas informações pessoais) +- read_repository (Permite acesso somente leitura ao repositório) + +Em seguida, exponha o ID do aplicativo como variável de ambiente: + +```bash +export GITLAB_OAUTH_CLIENT_ID=seu_id_do_aplicativo_aqui +``` + +Mais documentação na página [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth). + +##### Configuração + +Personalize através do `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### Ferramentas da API do GitLab (Opcional, mas altamente recomendado) + +Para acessar ferramentas do GitLab (merge requests, issues, pipelines, CI/CD, etc.): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +Este plugin fornece capacidades abrangentes de gerenciamento de repositório do GitLab, incluindo revisões de MR, rastreamento de issues, monitoramento de pipelines e mais. + +--- + +### GitHub Copilot + +Para usar sua assinatura do GitHub Copilot com o opencode: + +:::note +Alguns modelos podem precisar de uma [assinatura Pro+](https://github.com/features/copilot/plans) para usar. + +Alguns modelos precisam ser habilitados manualmente nas suas [configurações do GitHub Copilot](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. Execute o comando `/connect` e procure por GitHub Copilot. + + ```txt + /connect + ``` + +2. Navegue até [github.com/login/device](https://github.com/login/device) e insira o código. + + ```txt + ┌ Login com GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Insira o código: 8F43-6FCF + │ + └ Aguardando autorização... + ``` + +3. Agora execute o comando `/models` para selecionar o modelo que você deseja. + + ```txt + /models + ``` + +--- + +### Google Vertex AI + +Para usar o Google Vertex AI com o OpenCode: + +1. Acesse o **Model Garden** no Console do Google Cloud e verifique os + modelos disponíveis na sua região. + + :::note + Você precisa ter um projeto do Google Cloud com a API Vertex AI habilitada. + ::: + +2. Defina as variáveis de ambiente necessárias: + - `GOOGLE_CLOUD_PROJECT`: Seu ID do projeto do Google Cloud + - `VERTEX_LOCATION` (opcional): A região para o Vertex AI (padrão é `global`) + - Autenticação (escolha uma): + - `GOOGLE_APPLICATION_CREDENTIALS`: Caminho para seu arquivo de chave JSON da conta de serviço + - Autentique usando o CLI gcloud: `gcloud auth application-default login` + + Defina-as ao executar o opencode. + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/caminho/para/service-account.json GOOGLE_CLOUD_PROJECT=seu-id-do-projeto opencode + ``` + + Ou adicione-as ao seu perfil bash. + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/caminho/para/service-account.json + export GOOGLE_CLOUD_PROJECT=seu-id-do-projeto + export VERTEX_LOCATION=global + ``` + +:::tip +A região `global` melhora a disponibilidade e reduz erros sem custo adicional. Use endpoints regionais (ex: `us-central1`) para requisitos de residência de dados. [Saiba mais](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. Execute o comando `/models` para selecionar o modelo que você deseja. + + ```txt + /models + ``` + +--- + +### Groq + +1. Acesse o [console Groq](https://console.groq.com/), clique em **Criar Chave da API** e copie a chave. + +2. Execute o comando `/connect` e procure por Groq. + + ```txt + /connect + ``` + +3. Insira a chave da API para o provedor. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar o que você deseja. + + ```txt + /models + ``` + +--- + +### Hugging Face + +[Provedores de Inferência Hugging Face](https://huggingface.co/docs/inference-providers) fornecem acesso a modelos abertos suportados por mais de 17 provedores. + +1. Acesse [configurações do Hugging Face](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) para criar um token com permissão para fazer chamadas para Provedores de Inferência. + +2. Execute o comando `/connect` e procure por **Hugging Face**. + + ```txt + /connect + ``` + +3. Insira seu token do Hugging Face. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _Kimi-K2-Instruct_ ou _GLM-4.6_. + + ```txt + /models + ``` + +--- + +### Helicone + +[Helicone](https://helicone.ai) é uma plataforma de observabilidade LLM que fornece registro, monitoramento e análises para suas aplicações de IA. O Helicone AI Gateway roteia suas solicitações para o provedor apropriado automaticamente com base no modelo. + +1. Acesse [Helicone](https://helicone.ai), crie uma conta e gere uma chave da API a partir do seu painel. + +2. Execute o comando `/connect` e procure por **Helicone**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Helicone. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo. + + ```txt + /models + ``` + +Para mais provedores e recursos avançados como cache e limitação de taxa, consulte a [documentação do Helicone](https://docs.helicone.ai). + +#### Configurações Opcionais + +Caso você veja um recurso ou modelo do Helicone que não está configurado automaticamente através do opencode, você sempre pode configurá-lo você mesmo. + +Aqui está o [Diretório de Modelos do Helicone](https://helicone.ai/models), você precisará disso para pegar os IDs dos modelos que deseja adicionar. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // ID do modelo (da página do diretório de modelos do Helicone) + "name": "GPT-4o", // Seu próprio nome personalizado para o modelo + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### Cabeçalhos Personalizados + +Helicone suporta cabeçalhos personalizados para recursos como cache, rastreamento de usuários e gerenciamento de sessões. Adicione-os à sua configuração do provedor usando `options.headers`: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### Rastreamento de Sessões + +O recurso [Sessões](https://docs.helicone.ai/features/sessions) do Helicone permite que você agrupe solicitações LLM relacionadas. Use o plugin [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) para registrar automaticamente cada conversa do OpenCode como uma sessão no Helicone. + +```bash +npm install -g opencode-helicone-session +``` + +Adicione-o à sua configuração. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +O plugin injeta os cabeçalhos `Helicone-Session-Id` e `Helicone-Session-Name` em suas solicitações. Na página de Sessões do Helicone, você verá cada conversa do OpenCode listada como uma sessão separada. + +##### Cabeçalhos Comuns do Helicone + +| Cabeçalho | Descrição | +| ----------------------------- | ----------------------------------------------------------- | +| `Helicone-Cache-Enabled` | Habilitar cache de resposta (`true`/`false`) | +| `Helicone-User-Id` | Rastrear métricas por usuário | +| `Helicone-Property-[Nome]` | Adicionar propriedades personalizadas (ex: `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | Associar solicitações com versões de prompt | + +Consulte o [Diretório de Cabeçalhos do Helicone](https://docs.helicone.ai/helicone-headers/header-directory) para todos os cabeçalhos disponíveis. + +--- + +### llama.cpp + +Você pode configurar o opencode para usar modelos locais através da utilidade llama-server do [llama.cpp](https://github.com/ggml-org/llama.cpp) + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +Neste exemplo: + +- `llama.cpp` é o ID do provedor personalizado. Isso pode ser qualquer string que você quiser. +- `npm` especifica o pacote a ser usado para este provedor. Aqui, `@ai-sdk/openai-compatible` é usado para qualquer API compatível com OpenAI. +- `name` é o nome exibido para o provedor na interface do usuário. +- `options.baseURL` é o endpoint para o servidor local. +- `models` é um mapa de IDs de modelos para suas configurações. O nome do modelo será exibido na lista de seleção de modelos. + +--- + +### IO.NET + +IO.NET oferece 17 modelos otimizados para vários casos de uso: + +1. Acesse o [console IO.NET](https://ai.io.net/), crie uma conta e gere uma chave da API. + +2. Execute o comando `/connect` e procure por **IO.NET**. + + ```txt + /connect + ``` + +3. Insira sua chave da API IO.NET. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo. + + ```txt + /models + ``` + +--- + +### LM Studio + +Você pode configurar o opencode para usar modelos locais através do LM Studio. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +Neste exemplo: + +- `lmstudio` é o ID do provedor personalizado. Isso pode ser qualquer string que você quiser. +- `npm` especifica o pacote a ser usado para este provedor. Aqui, `@ai-sdk/openai-compatible` é usado para qualquer API compatível com OpenAI. +- `name` é o nome exibido para o provedor na interface do usuário. +- `options.baseURL` é o endpoint para o servidor local. +- `models` é um mapa de IDs de modelos para suas configurações. O nome do modelo será exibido na lista de seleção de modelos. + +--- + +### Moonshot AI + +Para usar Kimi K2 do Moonshot AI: + +1. Acesse o [console Moonshot AI](https://platform.moonshot.ai/console), crie uma conta e clique em **Criar chave da API**. + +2. Execute o comando `/connect` e procure por **Moonshot AI**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Moonshot. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar _Kimi K2_. + + ```txt + /models + ``` + +--- + +### MiniMax + +1. Acesse o [MiniMax API Console](https://platform.minimax.io/login), crie uma conta e gere uma chave da API. + +2. Execute o comando `/connect` e procure por **MiniMax**. + + ```txt + /connect + ``` + +3. Insira sua chave da API MiniMax. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _M2.1_. + + ```txt + /models + ``` + +--- + +### Nebius Token Factory + +1. Acesse o [console Nebius Token Factory](https://tokenfactory.nebius.com/), crie uma conta e clique em **Adicionar Chave**. + +2. Execute o comando `/connect` e procure por **Nebius Token Factory**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Nebius Token Factory. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Ollama + +Você pode configurar o opencode para usar modelos locais através do Ollama. + +:::tip +Ollama pode se configurar automaticamente para o OpenCode. Consulte a [documentação de integração do Ollama](https://docs.ollama.com/integrations/opencode) para detalhes. +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +Neste exemplo: + +- `ollama` é o ID do provedor personalizado. Isso pode ser qualquer string que você quiser. +- `npm` especifica o pacote a ser usado para este provedor. Aqui, `@ai-sdk/openai-compatible` é usado para qualquer API compatível com OpenAI. +- `name` é o nome exibido para o provedor na interface do usuário. +- `options.baseURL` é o endpoint para o servidor local. +- `models` é um mapa de IDs de modelos para suas configurações. O nome do modelo será exibido na lista de seleção de modelos. + +:::tip +Se chamadas de ferramentas não estiverem funcionando, tente aumentar `num_ctx` no Ollama. Comece em torno de 16k - 32k. +::: + +--- + +### Ollama Cloud + +Para usar o Ollama Cloud com o OpenCode: + +1. Acesse [https://ollama.com/](https://ollama.com/) e faça login ou crie uma conta. + +2. Navegue até **Configurações** > **Chaves** e clique em **Adicionar Chave da API** para gerar uma nova chave da API. + +3. Copie a chave da API para uso no OpenCode. + +4. Execute o comando `/connect` e procure por **Ollama Cloud**. + + ```txt + /connect + ``` + +5. Insira sua chave da API do Ollama Cloud. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +6. **Importante**: Antes de usar modelos em nuvem no OpenCode, você deve puxar as informações do modelo localmente: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. Execute o comando `/models` para selecionar seu modelo do Ollama Cloud. + + ```txt + /models + ``` + +--- + +### OpenAI + +Recomendamos se inscrever para [ChatGPT Plus ou Pro](https://chatgpt.com/pricing). + +1. Depois de se inscrever, execute o comando `/connect` e selecione OpenAI. + + ```txt + /connect + ``` + +2. Aqui você pode selecionar a opção **ChatGPT Plus/Pro** e isso abrirá seu navegador e pedirá para você se autenticar. + + ```txt + ┌ Selecionar método de autenticação + │ + │ ChatGPT Plus/Pro + │ Inserir chave da API manualmente + └ + ``` + +3. Agora todos os modelos da OpenAI devem estar disponíveis quando você usar o comando `/models`. + + ```txt + /models + ``` + +##### Usando chaves da API + +Se você já tiver uma chave da API, pode selecionar **Inserir chave da API manualmente** e colá-la no seu terminal. + +--- + +### OpenCode Zen + +OpenCode Zen é uma lista de modelos testados e verificados fornecidos pela equipe do OpenCode. [Saiba mais](/docs/zen). + +1. Faça login em **OpenCode Zen** e clique em **Criar Chave da API**. + +2. Execute o comando `/connect` e procure por **OpenCode Zen**. + + ```txt + /connect + ``` + +3. Insira sua chave da API do OpenCode. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### OpenRouter + +1. Acesse o [painel OpenRouter](https://openrouter.ai/settings/keys), clique em **Criar Chave da API** e copie a chave. + +2. Execute o comando `/connect` e procure por OpenRouter. + + ```txt + /connect + ``` + +3. Insira a chave da API para o provedor. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Muitos modelos do OpenRouter são pré-carregados por padrão, execute o comando `/models` para selecionar o que você deseja. + + ```txt + /models + ``` + + Você também pode adicionar modelos adicionais através da sua configuração do opencode. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. Você também pode personalizá-los através da sua configuração do opencode. Aqui está um exemplo de especificar um provedor + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP AI Core + +SAP AI Core fornece acesso a mais de 40 modelos do OpenAI, Anthropic, Google, Amazon, Meta, Mistral e AI21 através de uma plataforma unificada. + +1. Vá para seu [SAP BTP Cockpit](https://account.hana.ondemand.com/), navegue até sua instância de serviço SAP AI Core e crie uma chave de serviço. + + :::tip + A chave de serviço é um objeto JSON contendo `clientid`, `clientsecret`, `url` e `serviceurls.AI_API_URL`. Você pode encontrar sua instância do AI Core em **Serviços** > **Instâncias e Assinaturas** no BTP Cockpit. + ::: + +2. Execute o comando `/connect` e procure por **SAP AI Core**. + + ```txt + /connect + ``` + +3. Insira seu JSON da chave de serviço. + + ```txt + ┌ Chave de serviço + │ + │ + └ enter + ``` + + Ou defina a variável de ambiente `AICORE_SERVICE_KEY`: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + Ou adicione ao seu perfil bash: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. Opcionalmente, defina o ID de implantação e o grupo de recursos: + + ```bash + AICORE_DEPLOYMENT_ID=seu-id-de-implantação AICORE_RESOURCE_GROUP=seu-grupo-de-recursos opencode + ``` + + :::note + Essas configurações são opcionais e devem ser configuradas de acordo com sua configuração do SAP AI Core. + ::: + +5. Execute o comando `/models` para selecionar entre mais de 40 modelos disponíveis. + + ```txt + /models + ``` + +--- + +### OVHcloud AI Endpoints + +1. Acesse o [painel OVHcloud](https://ovh.com/manager). Navegue até a seção `Nuvem Pública`, `IA & Aprendizado de Máquina` > `Endpoints de IA` e na aba `Chaves da API`, clique em **Criar uma nova chave da API**. + +2. Execute o comando `/connect` e procure por **OVHcloud AI Endpoints**. + + ```txt + /connect + ``` + +3. Insira sua chave da API OVHcloud AI Endpoints. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Scaleway + +Para usar [APIs Generativas Scaleway](https://www.scaleway.com/en/docs/generative-apis/) com o Opencode: + +1. Acesse as [configurações de IAM do Scaleway Console](https://console.scaleway.com/iam/api-keys) para gerar uma nova chave da API. + +2. Execute o comando `/connect` e procure por **Scaleway**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Scaleway. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _devstral-2-123b-instruct-2512_ ou _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Together AI + +1. Acesse o [console Together AI](https://api.together.ai), crie uma conta e clique em **Adicionar Chave**. + +2. Execute o comando `/connect` e procure por **Together AI**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Together AI. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Venice AI + +1. Acesse o [console Venice AI](https://venice.ai), crie uma conta e gere uma chave da API. + +2. Execute o comando `/connect` e procure por **Venice AI**. + + ```txt + /connect + ``` + +3. Insira sua chave da API Venice AI. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _Llama 3.3 70B_. + + ```txt + /models + ``` + +--- + +### Vercel AI Gateway + +O Vercel AI Gateway permite que você acesse modelos do OpenAI, Anthropic, Google, xAI e mais através de um endpoint unificado. Os modelos são oferecidos pelo preço de tabela, sem markup. + +1. Acesse o [painel Vercel](https://vercel.com/), navegue até a aba **AI Gateway** e clique em **Chaves da API** para criar uma nova chave da API. + +2. Execute o comando `/connect` e procure por **Vercel AI Gateway**. + + ```txt + /connect + ``` + +3. Insira sua chave da API do Vercel AI Gateway. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo. + + ```txt + /models + ``` + +Você também pode personalizar modelos através da sua configuração do opencode. Aqui está um exemplo de especificar a ordem de roteamento do provedor. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +Algumas opções de roteamento úteis: + +| Opção | Descrição | +| -------------------- | -------------------------------------------------- | +| `order` | Sequência de provedores a serem tentados | +| `only` | Restringir a provedores específicos | +| `zeroDataRetention` | Usar apenas provedores com políticas de retenção de dados zero | + +--- + +### xAI + +1. Acesse o [console xAI](https://console.x.ai/), crie uma conta e gere uma chave da API. + +2. Execute o comando `/connect` e procure por **xAI**. + + ```txt + /connect + ``` + +3. Insira sua chave da API xAI. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _Grok Beta_. + + ```txt + /models + ``` + +--- + +### Z.AI + +1. Acesse o [console da API Z.AI](https://z.ai/manage-apikey/apikey-list), crie uma conta e clique em **Criar uma nova chave da API**. + +2. Execute o comando `/connect` e procure por **Z.AI**. + + ```txt + /connect + ``` + + Se você estiver inscrito no **GLM Coding Plan**, selecione **Z.AI Coding Plan**. + +3. Insira sua chave da API Z.AI. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Execute o comando `/models` para selecionar um modelo como _GLM-4.7_. + + ```txt + /models + ``` + +--- + +### ZenMux + +1. Acesse o [painel ZenMux](https://zenmux.ai/settings/keys), clique em **Criar Chave da API** e copie a chave. + +2. Execute o comando `/connect` e procure por ZenMux. + + ```txt + /connect + ``` + +3. Insira a chave da API para o provedor. + + ```txt + ┌ Chave da API + │ + │ + └ enter + ``` + +4. Muitos modelos ZenMux são pré-carregados por padrão, execute o comando `/models` para selecionar o que você deseja. + + ```txt + /models + ``` + + Você também pode adicionar modelos adicionais através da sua configuração do opencode. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## Provedor personalizado + +Para adicionar qualquer provedor **compatível com OpenAI** que não esteja listado no comando `/connect`: + +:::tip +Você pode usar qualquer provedor compatível com OpenAI com o opencode. A maioria dos provedores de IA modernos oferece APIs compatíveis com OpenAI. +::: + +1. Execute o comando `/connect` e role para baixo até **Outro**. + + ```bash + $ /connect + + ┌ Adicionar credencial + │ + ◆ Selecionar provedor + │ ... + │ ● Outro + └ + ``` + +2. Insira um ID exclusivo para o provedor. + + ```bash + $ /connect + + ┌ Adicionar credencial + │ + ◇ Insira o id do provedor + │ myprovider + └ + ``` + + :::note + Escolha um ID memorável, você usará isso no seu arquivo de configuração. + ::: + +3. Insira sua chave da API para o provedor. + + ```bash + $ /connect + + ┌ Adicionar credencial + │ + ▲ Isso apenas armazena uma credencial para myprovider - você precisará configurá-la no opencode.json, verifique a documentação para exemplos. + │ + ◇ Insira sua chave da API + │ sk-... + └ + ``` + +4. Crie ou atualize seu arquivo `opencode.json` no diretório do seu projeto: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "Nome de Exibição do Meu Provedor de IA", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "Nome de Exibição do Meu Modelo" + } + } + } + } + } + ``` + + Aqui estão as opções de configuração: + - **npm**: Pacote do SDK de IA a ser usado, `@ai-sdk/openai-compatible` para provedores compatíveis com OpenAI + - **name**: Nome de exibição na interface do usuário. + - **models**: Modelos disponíveis. + - **options.baseURL**: URL do endpoint da API. + - **options.apiKey**: Defina opcionalmente a chave da API, se não estiver usando autenticação. + - **options.headers**: Defina opcionalmente cabeçalhos personalizados. + + Mais sobre as opções avançadas no exemplo abaixo. + +5. Execute o comando `/models` e seu provedor e modelos personalizados aparecerão na lista de seleção. + +--- + +##### Exemplo + +Aqui está um exemplo definindo as opções `apiKey`, `headers` e `limit` do modelo. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "Nome de Exibição do Meu Provedor de IA", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "Nome de Exibição do Meu Modelo", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +Detalhes da configuração: + +- **apiKey**: Definido usando a sintaxe de variável `env`, [saiba mais](/docs/config#env-vars). +- **headers**: Cabeçalhos personalizados enviados com cada solicitação. +- **limit.context**: Máximo de tokens de entrada que o modelo aceita. +- **limit.output**: Máximo de tokens que o modelo pode gerar. + +Os campos `limit` permitem que o OpenCode entenda quanto contexto você tem disponível. Provedores padrão puxam isso automaticamente do models.dev. + +--- + +## Solução de Problemas + +Se você estiver tendo problemas para configurar um provedor, verifique o seguinte: + +1. **Verifique a configuração de autenticação**: Execute `opencode auth list` para ver se as credenciais + para o provedor estão adicionadas à sua configuração. + + Isso não se aplica a provedores como Amazon Bedrock, que dependem de variáveis de ambiente para sua autenticação. + +2. Para provedores personalizados, verifique a configuração do opencode e: + - Certifique-se de que o ID do provedor usado no comando `/connect` corresponda ao ID na sua configuração do opencode. + - O pacote npm correto está sendo usado para o provedor. Por exemplo, use `@ai-sdk/cerebras` para Cerebras. E para todos os outros provedores compatíveis com OpenAI, use `@ai-sdk/openai-compatible`. + - Verifique se o endpoint da API correto está sendo usado no campo `options.baseURL`. diff --git a/packages/web/src/content/docs/pt-br/rules.mdx b/packages/web/src/content/docs/pt-br/rules.mdx new file mode 100644 index 000000000..8860db15e --- /dev/null +++ b/packages/web/src/content/docs/pt-br/rules.mdx @@ -0,0 +1,180 @@ +--- +title: Regras +description: Defina instruções personalizadas para opencode. +--- + +Você pode fornecer instruções personalizadas para opencode criando um arquivo `AGENTS.md`. Isso é semelhante às regras do Cursor. Ele contém instruções que serão incluídas no contexto do LLM para personalizar seu comportamento para o seu projeto específico. + +--- + +## Inicializar + +Para criar um novo arquivo `AGENTS.md`, você pode executar o comando `/init` no opencode. + +:::tip +Você deve commitar o arquivo `AGENTS.md` do seu projeto no Git. +::: + +Isso irá escanear seu projeto e todo o seu conteúdo para entender do que se trata o projeto e gerar um arquivo `AGENTS.md` com isso. Isso ajuda o opencode a navegar melhor pelo projeto. + +Se você já tiver um arquivo `AGENTS.md` existente, isso tentará adicionar a ele. + +--- + +## Exemplo + +Você também pode criar este arquivo manualmente. Aqui está um exemplo de algumas coisas que você pode colocar em um arquivo `AGENTS.md`. + +```markdown title="AGENTS.md" +# Projeto Monorepo SST v3 + +Este é um monorepo SST v3 com TypeScript. O projeto usa bun workspaces para gerenciamento de pacotes. + +## Estrutura do Projeto + +- `packages/` - Contém todos os pacotes do workspace (funções, núcleo, web, etc.) +- `infra/` - Definições de infraestrutura divididas por serviço (storage.ts, api.ts, web.ts) +- `sst.config.ts` - Configuração principal do SST com imports dinâmicos + +## Padrões de Código + +- Use TypeScript com o modo estrito habilitado +- O código compartilhado vai em `packages/core/` com a configuração de exports adequada +- Funções vão em `packages/functions/` +- A infraestrutura deve ser dividida em arquivos lógicos em `infra/` + +## Convenções de Monorepo + +- Importe módulos compartilhados usando nomes de workspace: `@my-app/core/example` +``` + +Estamos adicionando instruções específicas do projeto aqui e isso será compartilhado entre sua equipe. + +--- + +## Tipos + +O opencode também suporta a leitura do arquivo `AGENTS.md` de múltiplos locais. E isso serve a diferentes propósitos. + +### Projeto + +Coloque um `AGENTS.md` na raiz do seu projeto para regras específicas do projeto. Essas regras se aplicam apenas quando você está trabalhando neste diretório ou em seus subdiretórios. + +### Global + +Você também pode ter regras globais em um arquivo `~/.config/opencode/AGENTS.md`. Isso é aplicado em todas as sessões do opencode. + +Como isso não é commitado no Git ou compartilhado com sua equipe, recomendamos usar isso para especificar quaisquer regras pessoais que o LLM deve seguir. + +### Compatibilidade com Claude Code + +Para usuários migrando do Claude Code, o OpenCode suporta as convenções de arquivo do Claude Code como alternativas: + +- **Regras do projeto**: `CLAUDE.md` no diretório do seu projeto (usado se não existir `AGENTS.md`) +- **Regras globais**: `~/.claude/CLAUDE.md` (usado se não existir `~/.config/opencode/AGENTS.md`) +- **Habilidades**: `~/.claude/skills/` — veja [Habilidades do Agente](/docs/skills/) para detalhes + +Para desabilitar a compatibilidade com Claude Code, defina uma dessas variáveis de ambiente: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Desabilitar todo suporte a .claude +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Desabilitar apenas ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Desabilitar apenas .claude/skills +``` + +--- + +## Precedência + +Quando o opencode inicia, ele procura arquivos de regras nesta ordem: + +1. **Arquivos locais** percorrendo a partir do diretório atual (`AGENTS.md`, `CLAUDE.md`) +2. **Arquivo global** em `~/.config/opencode/AGENTS.md` +3. **Arquivo Claude Code** em `~/.claude/CLAUDE.md` (a menos que desabilitado) + +O primeiro arquivo correspondente vence em cada categoria. Por exemplo, se você tiver tanto `AGENTS.md` quanto `CLAUDE.md`, apenas `AGENTS.md` é usado. Da mesma forma, `~/.config/opencode/AGENTS.md` tem precedência sobre `~/.claude/CLAUDE.md`. + +--- + +## Instruções Personalizadas + +Você pode especificar arquivos de instrução personalizados no seu `opencode.json` ou no global `~/.config/opencode/opencode.json`. Isso permite que você e sua equipe reutilizem regras existentes em vez de ter que duplicá-las no AGENTS.md. + +Exemplo: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Você também pode usar URLs remotas para carregar instruções da web. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +Instruções remotas são buscadas com um tempo limite de 5 segundos. + +Todos os arquivos de instrução são combinados com seus arquivos `AGENTS.md`. + +--- + +## Referenciando Arquivos Externos + +Embora o opencode não analise automaticamente referências de arquivos em `AGENTS.md`, você pode alcançar funcionalidade semelhante de duas maneiras: + +### Usando opencode.json + +A abordagem recomendada é usar o campo `instructions` em `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Instruções Manuais em AGENTS.md + +Você pode ensinar o opencode a ler arquivos externos fornecendo instruções explícitas em seu `AGENTS.md`. Aqui está um exemplo prático: + +```markdown title="AGENTS.md" +# Regras do Projeto TypeScript + +## Carregamento de Arquivos Externos + +CRÍTICO: Quando você encontrar uma referência de arquivo (por exemplo, @rules/general.md), use sua ferramenta de Leitura para carregá-lo conforme necessário. Eles são relevantes para a TAREFA ESPECÍFICA em questão. + +Instruções: + +- NÃO carregue todas as referências de forma preemptiva - use carregamento sob demanda com base na necessidade real +- Quando carregado, trate o conteúdo como instruções obrigatórias que substituem os padrões +- Siga referências recursivamente quando necessário + +## Diretrizes de Desenvolvimento + +Para estilo de código TypeScript e melhores práticas: @docs/typescript-guidelines.md +Para arquitetura de componentes React e padrões de hooks: @docs/react-patterns.md +Para design de API REST e tratamento de erros: @docs/api-standards.md +Para estratégias de teste e requisitos de cobertura: @test/testing-guidelines.md + +## Diretrizes Gerais + +Leia o seguinte arquivo imediatamente, pois é relevante para todos os fluxos de trabalho: @rules/general-guidelines.md. +``` + +Essa abordagem permite que você: + +- Crie arquivos de regras modulares e reutilizáveis +- Compartilhe regras entre projetos via symlinks ou submódulos do git +- Mantenha o AGENTS.md conciso enquanto referencia diretrizes detalhadas +- Garanta que o opencode carregue arquivos apenas quando necessário para a tarefa específica + +:::tip +Para monorepos ou projetos com padrões compartilhados, usar `opencode.json` com padrões glob (como `packages/*/AGENTS.md`) é mais sustentável do que instruções manuais. +::: \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/sdk.mdx b/packages/web/src/content/docs/pt-br/sdk.mdx new file mode 100644 index 000000000..ec86081ce --- /dev/null +++ b/packages/web/src/content/docs/pt-br/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: Cliente JS seguro em tipos para o servidor opencode. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +O SDK JS/TS do opencode fornece um cliente seguro em tipos para interagir com o servidor. +Use-o para construir integrações e controlar o opencode programaticamente. + +[Saiba mais](/docs/server) sobre como o servidor funciona. Para exemplos, confira os [projetos](/docs/ecosystem#projects) construídos pela comunidade. + +--- + +## Instalar + +Instale o SDK a partir do npm: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## Criar cliente + +Crie uma instância do opencode: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +Isso inicia tanto um servidor quanto um cliente. + +#### Opções + +| Opção | Tipo | Descrição | Padrão | +|------------|--------------|---------------------------------|-------------| +| `hostname` | `string` | Nome do host do servidor | `127.0.0.1` | +| `port` | `number` | Porta do servidor | `4096` | +| `signal` | `AbortSignal`| Sinal de abortar para cancelamento | `undefined` | +| `timeout` | `number` | Tempo limite em ms para iniciar o servidor | `5000` | +| `config` | `Config` | Objeto de configuração | `{}` | + +--- + +## Configuração + +Você pode passar um objeto de configuração para personalizar o comportamento. A instância ainda pega seu `opencode.json`, mas você pode substituir ou adicionar configuração inline: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Servidor rodando em ${opencode.server.url}`) + +opencode.server.close() +``` + +## Apenas cliente + +Se você já tem uma instância do opencode em execução, pode criar uma instância de cliente para se conectar a ela: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### Opções + +| Opção | Tipo | Descrição | Padrão | +|----------------|------------|---------------------------------|---------------------------| +| `baseUrl` | `string` | URL do servidor | `http://localhost:4096` | +| `fetch` | `function` | Implementação de fetch personalizada | `globalThis.fetch` | +| `parseAs` | `string` | Método de análise da resposta | `auto` | +| `responseStyle`| `string` | Estilo de retorno: `data` ou `fields` | `fields` | +| `throwOnError` | `boolean` | Lançar erros em vez de retornar | `false` | + +--- + +## Tipos + +O SDK inclui definições TypeScript para todos os tipos da API. Importe-os diretamente: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +Todos os tipos são gerados a partir da especificação OpenAPI do servidor e estão disponíveis no arquivo de tipos. + +--- + +## Erros + +O SDK pode lançar erros que você pode capturar e tratar: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Falha ao obter a sessão:", (error as Error).message) +} +``` + +--- + +## APIs + +O SDK expõe todas as APIs do servidor através de um cliente seguro em tipos. + +--- + +### Global + +| Método | Descrição | Resposta | +|-------------------|-------------------------------|--------------------------------------| +| `global.health()` | Verificar a saúde e versão do servidor | `{ healthy: true, version: string }` | + +--- + +#### Exemplos + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### App + +| Método | Descrição | Resposta | +|-----------------|-------------------------|---------------------------------------------| +| `app.log()` | Escrever uma entrada de log | `boolean` | +| `app.agents()` | Listar todos os agentes disponíveis | Agent[] | + +--- + +#### Exemplos + +```javascript +// Escrever uma entrada de log +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operação concluída", + }, +}) + +// Listar agentes disponíveis +const agents = await client.app.agents() +``` + +--- + +### Projeto + +| Método | Descrição | Resposta | +|---------------------|-------------------|-----------------------------------------------| +| `project.list()` | Listar todos os projetos | Project[] | +| `project.current()` | Obter projeto atual | Project | + +--- + +#### Exemplos + +```javascript +// Listar todos os projetos +const projects = await client.project.list() + +// Obter projeto atual +const currentProject = await client.project.current() +``` + +--- + +### Caminho + +| Método | Descrição | Resposta | +|--------------|----------------|------------------------------------------| +| `path.get()` | Obter caminho atual | Path | + +--- + +#### Exemplos + +```javascript +// Obter informações do caminho atual +const pathInfo = await client.path.get() +``` + +--- + +### Configuração + +| Método | Descrição | Resposta | +|----------------------|---------------------------------|-------------------------------------------------------------------------------------------------------| +| `config.get()` | Obter informações de configuração | Config | +| `config.providers()` | Listar provedores e modelos padrão | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +#### Exemplos + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### Sessões + +| Método | Descrição | Notas | +|-----------------------------------------------------------|----------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------| +| `session.list()` | Listar sessões | Retorna Session[] | +| `session.get({ path })` | Obter sessão | Retorna Session | +| `session.children({ path })` | Listar sessões filhas | Retorna Session[] | +| `session.create({ body })` | Criar sessão | Retorna Session | +| `session.delete({ path })` | Deletar sessão | Retorna `boolean` | +| `session.update({ path, body })` | Atualizar propriedades da sessão | Retorna Session | +| `session.init({ path, body })` | Analisar app e criar `AGENTS.md` | Retorna `boolean` | +| `session.abort({ path })` | Abortar uma sessão em execução | Retorna `boolean` | +| `session.share({ path })` | Compartilhar sessão | Retorna Session | +| `session.unshare({ path })` | Descompartilhar sessão | Retorna Session | +| `session.summarize({ path, body })` | Resumir sessão | Retorna `boolean` | +| `session.messages({ path })` | Listar mensagens em uma sessão | Retorna `{ info: `Message`, parts: `Part[]`}[]` | +| `session.message({ path })` | Obter detalhes da mensagem | Retorna `{ info: `Message`, parts: `Part[]`}` | +| `session.prompt({ path, body })` | Enviar mensagem de prompt | `body.noReply: true` retorna UserMessage (apenas contexto). O padrão retorna AssistantMessage com resposta da IA | +| `session.command({ path, body })` | Enviar comando para a sessão | Retorna `{ info: `AssistantMessage`, parts: `Part[]`}` | +| `session.shell({ path, body })` | Executar um comando shell | Retorna AssistantMessage | +| `session.revert({ path, body })` | Reverter uma mensagem | Retorna Session | +| `session.unrevert({ path })` | Restaurar mensagens revertidas | Retorna Session | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | Responder a um pedido de permissão | Retorna `boolean` | + +--- + +#### Exemplos + +```javascript +// Criar e gerenciar sessões +const session = await client.session.create({ + body: { title: "Minha sessão" }, +}) + +const sessions = await client.session.list() + +// Enviar uma mensagem de prompt +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Olá!" }], + }, +}) + +// Injetar contexto sem acionar resposta da IA (útil para plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "Você é um assistente útil." }], + }, +}) +``` + +--- + +### Arquivos + +| Método | Descrição | Resposta | +|---------------------------|----------------------------------|---------------------------------------------------------------------------------------------| +| `find.text({ query })` | Pesquisar texto em arquivos | Array de objetos de correspondência com `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `find.files({ query })` | Encontrar arquivos e diretórios por nome | `string[]` (caminhos) | +| `find.symbols({ query })` | Encontrar símbolos no workspace | Symbol[] | +| `file.read({ query })` | Ler um arquivo | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | Obter status para arquivos rastreados | File[] | + +`find.files` suporta alguns campos de consulta opcionais: + +- `type`: `"file"` ou `"directory"` +- `directory`: substituir a raiz do projeto para a pesquisa +- `limit`: resultados máximos (1–200) + +--- + +#### Exemplos + +```javascript +// Pesquisar e ler arquivos +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +| Método | Descrição | Resposta | +|-------------------------------|-------------------------|-----------| +| `tui.appendPrompt({ body })` | Adicionar texto ao prompt | `boolean` | +| `tui.openHelp()` | Abrir o diálogo de ajuda | `boolean` | +| `tui.openSessions()` | Abrir o seletor de sessões | `boolean` | +| `tui.openThemes()` | Abrir o seletor de temas | `boolean` | +| `tui.openModels()` | Abrir o seletor de modelos | `boolean` | +| `tui.submitPrompt()` | Enviar o prompt atual | `boolean` | +| `tui.clearPrompt()` | Limpar o prompt | `boolean` | +| `tui.executeCommand({ body })` | Executar um comando | `boolean` | +| `tui.showToast({ body })` | Mostrar notificação toast | `boolean` | + +--- + +#### Exemplos + +```javascript +// Controlar a interface TUI +await client.tui.appendPrompt({ + body: { text: "Adicione isso ao prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Tarefa concluída", variant: "success" }, +}) +``` + +--- + +### Autenticação + +| Método | Descrição | Resposta | +|---------------------|------------------------------|-----------| +| `auth.set({ ... })` | Definir credenciais de autenticação | `boolean` | + +--- + +#### Exemplos + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "sua-chave-api" }, +}) +``` + +--- + +### Eventos + +| Método | Descrição | Resposta | +|---------------------|-------------------------|---------------------------| +| `event.subscribe()` | Fluxo de eventos enviados pelo servidor | Fluxo de eventos enviados pelo servidor | + +--- + +#### Exemplos + +```javascript +// Ouvir eventos em tempo real +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Evento:", event.type, event.properties) +} +``` \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/server.mdx b/packages/web/src/content/docs/pt-br/server.mdx new file mode 100644 index 000000000..433b38fe4 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/server.mdx @@ -0,0 +1,284 @@ +--- +title: Servidor +description: Interaja com o servidor opencode via HTTP. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +O comando `opencode serve` executa um servidor HTTP sem cabeça que expõe um endpoint OpenAPI que um cliente opencode pode usar. + +--- + +### Uso + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### Opções + +| Flag | Descrição | Padrão | +| --------------- | ----------------------------------- | ---------------- | +| `--port` | Porta para escutar | `4096` | +| `--hostname` | Nome do host para escutar | `127.0.0.1` | +| `--mdns` | Habilitar descoberta mDNS | `false` | +| `--mdns-domain` | Nome de domínio personalizado para o serviço mDNS | `opencode.local` | +| `--cors` | Origens adicionais de navegador a permitir | `[]` | + +`--cors` pode ser passado várias vezes: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### Autenticação + +Defina `OPENCODE_SERVER_PASSWORD` para proteger o servidor com autenticação básica HTTP. O nome de usuário padrão é `opencode`, ou defina `OPENCODE_SERVER_USERNAME` para substituí-lo. Isso se aplica tanto ao `opencode serve` quanto ao `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=sua-senha opencode serve +``` + +--- + +### Como funciona + +Quando você executa `opencode`, ele inicia um TUI e um servidor. Onde o TUI é o cliente que se comunica com o servidor. O servidor expõe um endpoint de especificação OpenAPI 3.1. Este endpoint também é usado para gerar um [SDK](/docs/sdk). + +:::tip +Use o servidor opencode para interagir com o opencode programaticamente. +::: + +Essa arquitetura permite que o opencode suporte múltiplos clientes e permite que você interaja com o opencode programaticamente. + +Você pode executar `opencode serve` para iniciar um servidor autônomo. Se você tiver o TUI do opencode em execução, `opencode serve` iniciará um novo servidor. + +--- + +#### Conectar a um servidor existente + +Quando você inicia o TUI, ele atribui aleatoriamente uma porta e um nome de host. Você pode passar os [flags](/docs/cli) `--hostname` e `--port`. Em seguida, use isso para se conectar ao seu servidor. + +O endpoint [`/tui`](#tui) pode ser usado para controlar o TUI através do servidor. Por exemplo, você pode preencher ou executar um prompt. Essa configuração é usada pelos plugins do OpenCode [IDE](/docs/ide). + +--- + +## Especificação + +O servidor publica uma especificação OpenAPI 3.1 que pode ser visualizada em: + +``` +http://:/doc +``` + +Por exemplo, `http://localhost:4096/doc`. Use a especificação para gerar clientes ou inspecionar tipos de requisição e resposta. Ou visualize em um explorador Swagger. + +--- + +## APIs + +O servidor opencode expõe as seguintes APIs. + +--- + +### Global + +| Método | Caminho | Descrição | Resposta | +| ------ | ------------------- | ------------------------------ | -------------------------------------- | +| `GET` | `/global/health` | Obter saúde e versão do servidor | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | Obter eventos globais (fluxo SSE) | Fluxo de eventos | + +--- + +### Projeto + +| Método | Caminho | Descrição | Resposta | +| ------ | --------------------- | --------------------------- | --------------------------------------------- | +| `GET` | `/project` | Listar todos os projetos | Project[] | +| `GET` | `/project/current` | Obter o projeto atual | Project | + +--- + +### Caminho & VCS + +| Método | Caminho | Descrição | Resposta | +| ------ | ---------- | ------------------------------------- | ------------------------------------------- | +| `GET` | `/path` | Obter o caminho atual | Path | +| `GET` | `/vcs` | Obter informações do VCS para o projeto atual | VcsInfo | + +--- + +### Instância + +| Método | Caminho | Descrição | Resposta | +| ------ | ---------------------- | ----------------------------- | --------- | +| `POST` | `/instance/dispose` | Descartar a instância atual | `boolean` | + +--- + +### Configuração + +| Método | Caminho | Descrição | Resposta | +| ------- | ---------------------- | -------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` | Obter informações de configuração | Config | +| `PATCH` | `/config` | Atualizar configuração | Config | +| `GET` | `/config/providers` | Listar provedores e modelos padrão | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +### Provedor + +| Método | Caminho | Descrição | Resposta | +| ------ | ----------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` | Listar todos os provedores | `{ all: `Provider[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | Obter métodos de autenticação do provedor | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | Autorizar um provedor usando OAuth | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | Lidar com o callback OAuth para um provedor | `boolean` | + +--- + +### Sessões + +| Método | Caminho | Descrição | Notas | +| -------- | -------------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------- | +| `GET` | `/session` | Listar todas as sessões | Retorna Session[] | +| `POST` | `/session` | Criar uma nova sessão | corpo: `{ parentID?, title? }`, retorna Session | +| `GET` | `/session/status` | Obter status da sessão para todas as sessões | Retorna `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | Obter detalhes da sessão | Retorna Session | +| `DELETE` | `/session/:id` | Deletar uma sessão e todos os seus dados | Retorna `boolean` | +| `PATCH` | `/session/:id` | Atualizar propriedades da sessão | corpo: `{ title? }`, retorna Session | +| `GET` | `/session/:id/children` | Obter as sessões filhas de uma sessão | Retorna Session[] | +| `GET` | `/session/:id/todo` | Obter a lista de tarefas para uma sessão | Retorna Todo[] | +| `POST` | `/session/:id/init` | Analisar o app e criar `AGENTS.md` | corpo: `{ messageID, providerID, modelID }`, retorna `boolean` | +| `POST` | `/session/:id/fork` | Fazer um fork de uma sessão existente em uma mensagem | corpo: `{ messageID? }`, retorna Session | +| `POST` | `/session/:id/abort` | Abortar uma sessão em execução | Retorna `boolean` | +| `POST` | `/session/:id/share` | Compartilhar uma sessão | Retorna Session | +| `DELETE` | `/session/:id/share` | Descompartilhar uma sessão | Retorna Session | +| `GET` | `/session/:id/diff` | Obter a diferença para esta sessão | query: `messageID?`, retorna FileDiff[] | +| `POST` | `/session/:id/summarize` | Resumir a sessão | corpo: `{ providerID, modelID }`, retorna `boolean` | +| `POST` | `/session/:id/revert` | Reverter uma mensagem | corpo: `{ messageID, partID? }`, retorna `boolean` | +| `POST` | `/session/:id/unrevert` | Restaurar todas as mensagens revertidas | Retorna `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | Responder a um pedido de permissão | corpo: `{ response, remember? }`, retorna `boolean` | + +--- + +### Mensagens + +| Método | Caminho | Descrição | Notas | +| ------ | ------------------------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` | Listar mensagens em uma sessão | query: `limit?`, retorna `{ info: `Message`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` | Enviar uma mensagem e aguardar resposta | corpo: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, retorna `{ info: `Message`, parts: `Part[]`}` | +| `GET` | `/session/:id/message/:messageID` | Obter detalhes da mensagem | Retorna `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/prompt_async` | Enviar uma mensagem assíncrona (sem espera) | corpo: igual a `/session/:id/message`, retorna `204 No Content` | +| `POST` | `/session/:id/command` | Executar um comando de barra | corpo: `{ messageID?, agent?, model?, command, arguments }`, retorna `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/shell` | Executar um comando shell | corpo: `{ agent, model?, command }`, retorna `{ info: `Message`, parts: `Part[]`}` | + +--- + +### Comandos + +| Método | Caminho | Descrição | Resposta | +| ------ | ------------- | ----------------- | --------------------------------------------- | +| `GET` | `/command` | Listar todos os comandos | Command[] | + +--- + +### Arquivos + +| Método | Caminho | Descrição | Resposta | +| ------ | ---------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | Pesquisar texto em arquivos | Array de objetos de correspondência com `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | Encontrar arquivos e diretórios por nome | `string[]` (caminhos) | +| `GET` | `/find/symbol?query=` | Encontrar símbolos do workspace | Symbol[] | +| `GET` | `/file?path=` | Listar arquivos e diretórios | FileNode[] | +| `GET` | `/file/content?path=

` | Ler um arquivo | FileContent | +| `GET` | `/file/status` | Obter status para arquivos rastreados | File[] | + +#### Parâmetros de consulta `/find/file` + +- `query` (obrigatório) — string de pesquisa (correspondência difusa) +- `type` (opcional) — limitar resultados a `"file"` ou `"directory"` +- `directory` (opcional) — substituir a raiz do projeto para a pesquisa +- `limit` (opcional) — resultados máximos (1–200) +- `dirs` (opcional) — flag legada (`"false"` retorna apenas arquivos) + +--- + +### Ferramentas (Experimental) + +| Método | Caminho | Descrição | Resposta | +| ------ | ----------------------------------------------- | -------------------------------------- | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` | Listar todos os IDs de ferramentas | ToolIDs | +| `GET` | `/experimental/tool?provider=

&model=` | Listar ferramentas com esquemas JSON para um modelo | ToolList | + +--- + +### LSP, Formatadores & MCP + +| Método | Caminho | Descrição | Resposta | +| ------ | ---------------- | ------------------------ | -------------------------------------------------------- | +| `GET` | `/lsp` | Obter status do servidor LSP | LSPStatus[] | +| `GET` | `/formatter` | Obter status do formatador | FormatterStatus[] | +| `GET` | `/mcp` | Obter status do servidor MCP | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | Adicionar servidor MCP dinamicamente | corpo: `{ name, config }`, retorna objeto de status MCP | + +--- + +### Agentes + +| Método | Caminho | Descrição | Resposta | +| ------ | ----------- | ----------------------- | ------------------------------------------- | +| `GET` | `/agent` | Listar todos os agentes disponíveis | Agent[] | + +--- + +### Registro + +| Método | Caminho | Descrição | Resposta | +| ------ | --------- | ---------------------------------------------------------- | --------- | +| `POST` | `/log` | Escrever entrada de log. Corpo: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| Método | Caminho | Descrição | Resposta | +| ------ | --------------------------- | ----------------------------------------- | ---------------------- | +| `POST` | `/tui/append-prompt` | Anexar texto ao prompt | `boolean` | +| `POST` | `/tui/open-help` | Abrir o diálogo de ajuda | `boolean` | +| `POST` | `/tui/open-sessions` | Abrir o seletor de sessões | `boolean` | +| `POST` | `/tui/open-themes` | Abrir o seletor de temas | `boolean` | +| `POST` | `/tui/open-models` | Abrir o seletor de modelos | `boolean` | +| `POST` | `/tui/submit-prompt` | Enviar o prompt atual | `boolean` | +| `POST` | `/tui/clear-prompt` | Limpar o prompt | `boolean` | +| `POST` | `/tui/execute-command` | Executar um comando (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | Mostrar toast (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | Aguardar o próximo pedido de controle | Objeto de pedido de controle | +| `POST` | `/tui/control/response` | Responder a um pedido de controle (`{ body }`) | `boolean` | + +--- + +### Auth + +| Método | Caminho | Descrição | Resposta | +| ------ | --------------- | ------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | Definir credenciais de autenticação. O corpo deve corresponder ao esquema do provedor | `boolean` | + +--- + +### Eventos + +| Método | Caminho | Descrição | Resposta | +| ------ | ----------- | --------------------------------------------------------------------------- | ------------------------- | +| `GET` | `/event` | Fluxo de eventos enviados pelo servidor. O primeiro evento é `server.connected`, depois eventos de bus | Fluxo de eventos enviados pelo servidor | + +--- + +### Docs + +| Método | Caminho | Descrição | Resposta | +| ------ | --------- | ----------------------- | --------------------------- | +| `GET` | `/doc` | Especificação OpenAPI 3.1 | Página HTML com a especificação OpenAPI | \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/share.mdx b/packages/web/src/content/docs/pt-br/share.mdx new file mode 100644 index 000000000..bb0d29e68 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/share.mdx @@ -0,0 +1,127 @@ +--- +title: Compartilhar +description: Compartilhe suas conversas do OpenCode. +--- + +O recurso de compartilhamento do OpenCode permite que você crie links públicos para suas conversas do OpenCode, para que você possa colaborar com colegas de equipe ou obter ajuda de outros. + +:::note +Conversas compartilhadas são acessíveis publicamente para qualquer pessoa com o link. +::: + +--- + +## Como funciona + +Quando você compartilha uma conversa, o OpenCode: + +1. Cria uma URL pública única para sua sessão +2. Sincroniza seu histórico de conversas com nossos servidores +3. Torna a conversa acessível através do link compartilhável — `opncd.ai/s/` + +--- + +## Compartilhamento + +O OpenCode suporta três modos de compartilhamento que controlam como as conversas são compartilhadas: + +--- + +### Manual (padrão) + +Por padrão, o OpenCode usa o modo de compartilhamento manual. As sessões não são compartilhadas automaticamente, mas você pode compartilhá-las manualmente usando o comando `/share`: + +``` +/share +``` + +Isso gerará uma URL única que será copiada para sua área de transferência. + +Para definir explicitamente o modo manual em seu [arquivo de configuração](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### Compartilhamento automático + +Você pode habilitar o compartilhamento automático para todas as novas conversas definindo a opção `share` como `"auto"` em seu [arquivo de configuração](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +Com o compartilhamento automático habilitado, cada nova conversa será compartilhada automaticamente e um link será gerado. + +--- + +### Desativado + +Você pode desativar o compartilhamento completamente definindo a opção `share` como `"disabled"` em seu [arquivo de configuração](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +Para impor isso em sua equipe para um determinado projeto, adicione-o ao `opencode.json` em seu projeto e faça o check-in no Git. + +--- + +## Cancelar compartilhamento + +Para parar de compartilhar uma conversa e removê-la do acesso público: + +``` +/unshare +``` + +Isso removerá o link de compartilhamento e excluirá os dados relacionados à conversa. + +--- + +## Privacidade + +Há algumas coisas a serem lembradas ao compartilhar uma conversa. + +--- + +### Retenção de dados + +Conversas compartilhadas permanecem acessíveis até que você as descompartilhe explicitamente. Isso inclui: + +- Histórico completo da conversa +- Todas as mensagens e respostas +- Metadados da sessão + +--- + +### Recomendações + +- Compartilhe apenas conversas que não contenham informações sensíveis. +- Revise o conteúdo da conversa antes de compartilhar. +- Descompartilhe conversas quando a colaboração estiver completa. +- Evite compartilhar conversas com código proprietário ou dados confidenciais. +- Para projetos sensíveis, desative o compartilhamento completamente. + +--- + +## Para empresas + +Para implantações empresariais, o recurso de compartilhamento pode ser: + +- **Desativado** completamente para conformidade de segurança +- **Restrito** a usuários autenticados apenas através de SSO +- **Auto-hospedado** em sua própria infraestrutura + +[Saiba mais](/docs/enterprise) sobre como usar o opencode em sua organização. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/skills.mdx b/packages/web/src/content/docs/pt-br/skills.mdx new file mode 100644 index 000000000..76f7c3b81 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "Habilidades do Agente" +description: "Defina comportamentos reutilizáveis via definições de SKILL.md" +--- + +As habilidades do agente permitem que o OpenCode descubra instruções reutilizáveis do seu repositório ou diretório pessoal. +As habilidades são carregadas sob demanda através da ferramenta nativa `skill`—os agentes veem as habilidades disponíveis e podem carregar o conteúdo completo quando necessário. + +--- + +## Colocar arquivos + +Crie uma pasta por nome de habilidade e coloque um `SKILL.md` dentro dela. +O OpenCode pesquisa nesses locais: + +- Configuração do projeto: `.opencode/skills//SKILL.md` +- Configuração global: `~/.config/opencode/skills//SKILL.md` +- Projeto compatível com Claude: `.claude/skills//SKILL.md` +- Global compatível com Claude: `~/.claude/skills//SKILL.md` +- Projeto compatível com agente: `.agents/skills//SKILL.md` +- Global compatível com agente: `~/.agents/skills//SKILL.md` + +--- + +## Entender a descoberta + +Para caminhos locais do projeto, o OpenCode sobe a partir do seu diretório de trabalho atual até alcançar a árvore de trabalho do git. +Ele carrega qualquer `skills/*/SKILL.md` correspondente em `.opencode/` e qualquer `.claude/skills/*/SKILL.md` ou `.agents/skills/*/SKILL.md` ao longo do caminho. + +As definições globais também são carregadas de `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` e `~/.agents/skills/*/SKILL.md`. + +--- + +## Escrever frontmatter + +Cada `SKILL.md` deve começar com frontmatter YAML. +Somente estes campos são reconhecidos: + +- `name` (obrigatório) +- `description` (obrigatório) +- `license` (opcional) +- `compatibility` (opcional) +- `metadata` (opcional, mapa de string para string) + +Campos de frontmatter desconhecidos são ignorados. + +--- + +## Validar nomes + +`name` deve: + +- Ter de 1 a 64 caracteres +- Ser alfanumérico em minúsculas com separadores de hífen simples +- Não começar ou terminar com `-` +- Não conter `--` consecutivos +- Combinar com o nome do diretório que contém `SKILL.md` + +Regex equivalente: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## Seguir regras de comprimento + +`description` deve ter de 1 a 1024 caracteres. +Mantenha-a específica o suficiente para que o agente escolha corretamente. + +--- + +## Usar um exemplo + +Crie `.opencode/skills/git-release/SKILL.md` assim: + +```markdown +--- +name: git-release +description: Crie lançamentos e changelogs consistentes +license: MIT +compatibility: opencode +metadata: + audience: mantenedores + workflow: github +--- + +## O que eu faço + +- Redigir notas de lançamento a partir de PRs mesclados +- Propor um aumento de versão +- Fornecer um comando `gh release create` copiável e colável + +## Quando me usar + +Use isso quando estiver preparando um lançamento marcado. +Faça perguntas esclarecedoras se o esquema de versionamento alvo não estiver claro. +``` + +--- + +## Reconhecer descrição da ferramenta + +O OpenCode lista as habilidades disponíveis na descrição da ferramenta `skill`. +Cada entrada inclui o nome e a descrição da habilidade: + +```xml + + + git-release + Crie lançamentos e changelogs consistentes + + +``` + +O agente carrega uma habilidade chamando a ferramenta: + +``` +skill({ name: "git-release" }) +``` + +--- + +## Configurar permissões + +Controle quais habilidades os agentes podem acessar usando permissões baseadas em padrões em `opencode.json`: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Permissão | Comportamento | +|------------|--------------------------------------------| +| `allow` | Habilidade carrega imediatamente | +| `deny` | Habilidade oculta do agente, acesso rejeitado | +| `ask` | Usuário solicitado para aprovação antes de carregar | + +Padrões suportam curingas: `internal-*` corresponde a `internal-docs`, `internal-tools`, etc. + +--- + +## Substituir por agente + +Dê a agentes específicos permissões diferentes das configurações globais padrão. + +**Para agentes personalizados** (no frontmatter do agente): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**Para agentes embutidos** (em `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## Desativar a ferramenta de habilidades + +Desative completamente as habilidades para agentes que não devem usá-las: + +**Para agentes personalizados**: + +```yaml +--- +tools: + skill: false +--- +``` + +**Para agentes embutidos**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +Quando desativado, a seção `` é omitida completamente. + +--- + +## Solucionar problemas de carregamento + +Se uma habilidade não aparecer: + +1. Verifique se `SKILL.md` está escrito em letras maiúsculas +2. Verifique se o frontmatter inclui `name` e `description` +3. Certifique-se de que os nomes das habilidades sejam únicos em todos os locais +4. Verifique as permissões—habilidades com `deny` estão ocultas dos agentes \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/themes.mdx b/packages/web/src/content/docs/pt-br/themes.mdx new file mode 100644 index 000000000..c0e789d04 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/themes.mdx @@ -0,0 +1,369 @@ +--- +title: Temas +description: Selecione um tema embutido ou defina o seu próprio. +--- + +Com o OpenCode, você pode selecionar um dos vários temas embutidos, usar um tema que se adapta ao tema do seu terminal ou definir seu próprio tema personalizado. + +Por padrão, o OpenCode usa nosso próprio tema `opencode`. + +--- + +## Requisitos do terminal + +Para que os temas sejam exibidos corretamente com sua paleta de cores completa, seu terminal deve suportar **truecolor** (cor de 24 bits). A maioria dos terminais modernos suporta isso por padrão, mas você pode precisar habilitar: + +- **Verificar suporte**: Execute `echo $COLORTERM` - deve retornar `truecolor` ou `24bit` +- **Habilitar truecolor**: Defina a variável de ambiente `COLORTERM=truecolor` no seu perfil de shell +- **Compatibilidade do terminal**: Certifique-se de que seu emulador de terminal suporta cores de 24 bits (a maioria dos terminais modernos, como iTerm2, Alacritty, Kitty, Windows Terminal e versões recentes do GNOME Terminal, suportam) + +Sem suporte a truecolor, os temas podem aparecer com precisão de cor reduzida ou voltar para a aproximação de 256 cores mais próxima. + +--- + +## Temas embutidos + +O OpenCode vem com vários temas embutidos. + +| Nome | Descrição | +| ---------------------- | ---------------------------------------------------------------------------- | +| `system` | Adapta-se à cor de fundo do seu terminal | +| `tokyonight` | Baseado no tema [Tokyonight](https://github.com/folke/tokyonight.nvim) | +| `everforest` | Baseado no tema [Everforest](https://github.com/sainnhe/everforest) | +| `ayu` | Baseado no tema escuro [Ayu](https://github.com/ayu-theme) | +| `catppuccin` | Baseado no tema [Catppuccin](https://github.com/catppuccin) | +| `catppuccin-macchiato` | Baseado no tema [Catppuccin](https://github.com/catppuccin) | +| `gruvbox` | Baseado no tema [Gruvbox](https://github.com/morhetz/gruvbox) | +| `kanagawa` | Baseado no tema [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | +| `nord` | Baseado no tema [Nord](https://github.com/nordtheme/nord) | +| `matrix` | Tema verde estilo hacker sobre fundo preto | +| `one-dark` | Baseado no tema escuro [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) | + +E mais, estamos constantemente adicionando novos temas. + +--- + +## Tema do sistema + +O tema `system` é projetado para se adaptar automaticamente ao esquema de cores do seu terminal. Ao contrário dos temas tradicionais que usam cores fixas, o tema _system_: + +- **Gera escala de cinza**: Cria uma escala de cinza personalizada com base na cor de fundo do seu terminal, garantindo contraste ideal. +- **Usa cores ANSI**: Aproveita as cores ANSI padrão (0-15) para destaque de sintaxe e elementos da interface, que respeitam a paleta de cores do seu terminal. +- **Preserva padrões do terminal**: Usa `none` para cores de texto e fundo para manter a aparência nativa do seu terminal. + +O tema do sistema é para usuários que: + +- Querem que o OpenCode corresponda à aparência do seu terminal +- Usam esquemas de cores de terminal personalizados +- Preferem uma aparência consistente em todos os aplicativos de terminal + +--- + +## Usando um tema + +Você pode selecionar um tema chamando a seleção de tema com o comando `/theme`. Ou você pode especificá-lo em sua [configuração](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Temas personalizados + +O OpenCode suporta um sistema de temas flexível baseado em JSON que permite aos usuários criar e personalizar temas facilmente. + +--- + +### Hierarquia + +Os temas são carregados de vários diretórios na seguinte ordem, onde diretórios posteriores substituem os anteriores: + +1. **Temas embutidos** - Estes estão incorporados no binário +2. **Diretório de configuração do usuário** - Definido em `~/.config/opencode/themes/*.json` ou `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Diretório raiz do projeto** - Definido em `/.opencode/themes/*.json` +4. **Diretório de trabalho atual** - Definido em `./.opencode/themes/*.json` + +Se vários diretórios contiverem um tema com o mesmo nome, o tema do diretório com maior prioridade será usado. + +--- + +### Criando um tema + +Para criar um tema personalizado, crie um arquivo JSON em um dos diretórios de tema. + +Para temas de usuário: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +E para temas específicos do projeto. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### Formato JSON + +Os temas usam um formato JSON flexível com suporte para: + +- **Cores Hex**: `"#ffffff"` +- **Cores ANSI**: `3` (0-255) +- **Referências de cor**: `"primary"` ou definições personalizadas +- **Variantes escuras/claras**: `{"dark": "#000", "light": "#fff"}` +- **Sem cor**: `"none"` - Usa a cor padrão do terminal ou transparente + +--- + +### Definições de cor + +A seção `defs` é opcional e permite que você defina cores reutilizáveis que podem ser referenciadas no tema. + +--- + +### Padrões do terminal + +O valor especial `"none"` pode ser usado para qualquer cor para herdar a cor padrão do terminal. Isso é particularmente útil para criar temas que se misturam perfeitamente com o esquema de cores do seu terminal: + +- `"text": "none"` - Usa a cor de primeiro plano padrão do terminal +- `"background": "none"` - Usa a cor de fundo padrão do terminal + +--- + +### Exemplo + +Aqui está um exemplo de um tema personalizado: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/tools.mdx b/packages/web/src/content/docs/pt-br/tools.mdx new file mode 100644 index 000000000..dd1c26a87 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/tools.mdx @@ -0,0 +1,379 @@ +--- +title: Ferramentas +description: Gerencie as ferramentas que um LLM pode usar. +--- + +As ferramentas permitem que o LLM execute ações em sua base de código. O OpenCode vem com um conjunto de ferramentas integradas, mas você pode estendê-lo com [ferramentas personalizadas](/docs/custom-tools) ou [servidores MCP](/docs/mcp-servers). + +Por padrão, todas as ferramentas estão **ativadas** e não precisam de permissão para serem executadas. Você pode controlar o comportamento das ferramentas através de [permissões](/docs/permissions). + +--- + +## Configurar + +Use o campo `permission` para controlar o comportamento das ferramentas. Você pode permitir, negar ou exigir aprovação para cada ferramenta. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +Você também pode usar curingas para controlar várias ferramentas ao mesmo tempo. Por exemplo, para exigir aprovação para todas as ferramentas de um servidor MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[Saiba mais](/docs/permissions) sobre como configurar permissões. + +--- + +## Integradas + +Aqui estão todas as ferramentas integradas disponíveis no OpenCode. + +--- + +### bash + +Execute comandos de shell no ambiente do seu projeto. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +Esta ferramenta permite que o LLM execute comandos de terminal como `npm install`, `git status` ou qualquer outro comando de shell. + +--- + +### edit + +Modifique arquivos existentes usando substituições de string exatas. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Esta ferramenta realiza edições precisas em arquivos substituindo correspondências de texto exatas. É a principal forma como o LLM modifica o código. + +--- + +### write + +Crie novos arquivos ou sobrescreva os existentes. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Use isso para permitir que o LLM crie novos arquivos. Ele sobrescreverá arquivos existentes se já existirem. + +:::note +A ferramenta `write` é controlada pela permissão `edit`, que cobre todas as modificações de arquivos (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### read + +Leia o conteúdo dos arquivos da sua base de código. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +Esta ferramenta lê arquivos e retorna seus conteúdos. Suporta a leitura de intervalos de linhas específicos para arquivos grandes. + +--- + +### grep + +Pesquise o conteúdo dos arquivos usando expressões regulares. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Busca rápida de conteúdo em sua base de código. Suporta a sintaxe completa de regex e filtragem de padrões de arquivos. + +--- + +### glob + +Encontre arquivos por correspondência de padrões. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +Pesquise arquivos usando padrões glob como `**/*.js` ou `src/**/*.ts`. Retorna caminhos de arquivos correspondentes ordenados por tempo de modificação. + +--- + +### list + +Liste arquivos e diretórios em um determinado caminho. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +Esta ferramenta lista o conteúdo do diretório. Aceita padrões glob para filtrar resultados. + +--- + +### lsp (experimental) + +Interaja com seus servidores LSP configurados para obter recursos de inteligência de código, como definições, referências, informações de hover e hierarquia de chamadas. + +:::note +Esta ferramenta está disponível apenas quando `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (ou `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +As operações suportadas incluem `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` e `outgoingCalls`. + +Para configurar quais servidores LSP estão disponíveis para seu projeto, veja [Servidores LSP](/docs/lsp). + +--- + +### patch + +Aplique patches a arquivos. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Esta ferramenta aplica arquivos de patch à sua base de código. Útil para aplicar diffs e patches de várias fontes. + +:::note +A ferramenta `patch` é controlada pela permissão `edit`, que cobre todas as modificações de arquivos (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### skill + +Carregue uma [skill](/docs/skills) (um arquivo `SKILL.md`) e retorne seu conteúdo na conversa. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todowrite + +Gerencie listas de tarefas durante sessões de codificação. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +Cria e atualiza listas de tarefas para acompanhar o progresso durante operações complexas. O LLM usa isso para organizar tarefas de múltiplas etapas. + +:::note +Esta ferramenta está desativada para subagentes por padrão, mas você pode ativá-la manualmente. [Saiba mais](/docs/agents/#permissions) +::: + +--- + +### todoread + +Leia listas de tarefas existentes. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +Lê o estado atual da lista de tarefas. Usado pelo LLM para acompanhar quais tarefas estão pendentes ou concluídas. + +:::note +Esta ferramenta está desativada para subagentes por padrão, mas você pode ativá-la manualmente. [Saiba mais](/docs/agents/#permissions) +::: + +--- + +### webfetch + +Busque conteúdo da web. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +Permite que o LLM busque e leia páginas da web. Útil para consultar documentação ou pesquisar recursos online. + +--- + +### websearch + +Pesquise na web por informações. + +:::note +Esta ferramenta está disponível apenas ao usar o provedor OpenCode ou quando a variável de ambiente `OPENCODE_ENABLE_EXA` está definida como qualquer valor verdadeiro (por exemplo, `true` ou `1`). + +Para habilitar ao iniciar o OpenCode: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Realiza buscas na web usando Exa AI para encontrar informações relevantes online. Útil para pesquisar tópicos, encontrar eventos atuais ou reunir informações além do limite de dados de treinamento. + +Nenhuma chave de API é necessária — a ferramenta se conecta diretamente ao serviço MCP hospedado da Exa AI sem autenticação. + +:::tip +Use `websearch` quando precisar encontrar informações (descoberta) e `webfetch` quando precisar recuperar conteúdo de uma URL específica (recuperação). +::: + +--- + +### question + +Faça perguntas ao usuário durante a execução. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +Esta ferramenta permite que o LLM faça perguntas ao usuário durante uma tarefa. É útil para: + +- Coletar preferências ou requisitos do usuário +- Esclarecer instruções ambíguas +- Obter decisões sobre escolhas de implementação +- Oferecer opções sobre qual direção seguir + +Cada pergunta inclui um cabeçalho, o texto da pergunta e uma lista de opções. Os usuários podem selecionar entre as opções fornecidas ou digitar uma resposta personalizada. Quando há várias perguntas, os usuários podem navegar entre elas antes de enviar todas as respostas. + +--- + +## Ferramentas personalizadas + +Ferramentas personalizadas permitem que você defina suas próprias funções que o LLM pode chamar. Estas são definidas em seu arquivo de configuração e podem executar código arbitrário. + +[Saiba mais](/docs/custom-tools) sobre como criar ferramentas personalizadas. + +--- + +## Servidores MCP + +Servidores MCP (Model Context Protocol) permitem que você integre ferramentas e serviços externos. Isso inclui acesso a bancos de dados, integrações de API e serviços de terceiros. + +[Saiba mais](/docs/mcp-servers) sobre como configurar servidores MCP. + +--- + +## Internos + +Internamente, ferramentas como `grep`, `glob` e `list` usam [ripgrep](https://github.com/BurntSushi/ripgrep) por trás dos panos. Por padrão, o ripgrep respeita padrões `.gitignore`, o que significa que arquivos e diretórios listados em seu `.gitignore` serão excluídos de buscas e listagens. + +--- + +### Padrões de ignorar + +Para incluir arquivos que normalmente seriam ignorados, crie um arquivo `.ignore` na raiz do seu projeto. Este arquivo pode permitir explicitamente certos caminhos. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +Por exemplo, este arquivo `.ignore` permite que o ripgrep busque dentro dos diretórios `node_modules/`, `dist/` e `build/`, mesmo que estejam listados em `.gitignore`. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/troubleshooting.mdx b/packages/web/src/content/docs/pt-br/troubleshooting.mdx new file mode 100644 index 000000000..2a6f4a576 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/troubleshooting.mdx @@ -0,0 +1,299 @@ +--- +title: Solução de Problemas +description: Problemas comuns e como resolvê-los. +--- + +Para depurar problemas com o OpenCode, comece verificando os logs e os dados locais que ele armazena no disco. + +--- + +## Logs + +Os arquivos de log são gravados em: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: Pressione `WIN+R` e cole `%USERPROFILE%\.local\share\opencode\log` + +Os arquivos de log são nomeados com timestamps (por exemplo, `2025-01-09T123456.log`) e os 10 arquivos de log mais recentes são mantidos. + +Você pode definir o nível de log com a opção de linha de comando `--log-level` para obter informações de depuração mais detalhadas. Por exemplo, `opencode --log-level DEBUG`. + +--- + +## Armazenamento + +opencode armazena dados de sessão e outros dados do aplicativo no disco em: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: Pressione `WIN+R` e cole `%USERPROFILE%\.local\share\opencode` + +Este diretório contém: + +- `auth.json` - Dados de autenticação como chaves de API, tokens OAuth +- `log/` - Logs do aplicativo +- `project/` - Dados específicos do projeto, como dados de sessão e mensagens + - Se o projeto estiver dentro de um repositório Git, ele é armazenado em `.//storage/` + - Se não for um repositório Git, ele é armazenado em `./global/storage/` + +--- + +## Aplicativo de Desktop + +OpenCode Desktop executa um servidor OpenCode local (o sidecar `opencode-cli`) em segundo plano. A maioria dos problemas é causada por um plugin com mau funcionamento, um cache corrompido ou uma configuração de servidor incorreta. + +### Verificações rápidas + +- Saia completamente do aplicativo e reinicie-o. +- Se o aplicativo mostrar uma tela de erro, clique em **Reiniciar** e copie os detalhes do erro. +- Apenas macOS: menu `OpenCode` -> **Recarregar Webview** (ajuda se a interface estiver em branco/congelada). + +--- + +### Desativar plugins + +Se o aplicativo de desktop estiver travando ao iniciar, pendurado ou se comportando de maneira estranha, comece desativando os plugins. + +#### Verifique a configuração global + +Abra seu arquivo de configuração global e procure uma chave `plugin`. + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (ou `~/.config/opencode/opencode.json`) +- **macOS/Linux** (instalações mais antigas): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: Pressione `WIN+R` e cole `%USERPROFILE%\.config\opencode\opencode.jsonc` + +Se você tiver plugins configurados, desative-os temporariamente removendo a chave ou definindo-a como um array vazio: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### Verifique os diretórios de plugins + +OpenCode também pode carregar plugins locais do disco. Mova-os temporariamente para fora do caminho (ou renomeie a pasta) e reinicie o aplicativo de desktop: + +- **Plugins globais** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: Pressione `WIN+R` e cole `%USERPROFILE%\.config\opencode\plugins` +- **Plugins de projeto** (apenas se você usar configuração por projeto) + - `/.opencode/plugins/` + +Se o aplicativo voltar a funcionar, reative os plugins um por um para descobrir qual está causando o problema. + +--- + +### Limpar o cache + +Se desativar plugins não ajudar (ou se a instalação de um plugin estiver travada), limpe o cache para que o OpenCode possa reconstruí-lo. + +1. Saia completamente do OpenCode Desktop. +2. Exclua o diretório de cache: + +- **macOS**: Finder -> `Cmd+Shift+G` -> cole `~/.cache/opencode` +- **Linux**: exclua `~/.cache/opencode` (ou execute `rm -rf ~/.cache/opencode`) +- **Windows**: Pressione `WIN+R` e cole `%USERPROFILE%\.cache\opencode` + +3. Reinicie o OpenCode Desktop. + +--- + +### Corrigir problemas de conexão com o servidor + +OpenCode Desktop pode iniciar seu próprio servidor local (padrão) ou conectar-se a uma URL de servidor que você configurou. + +Se você ver um diálogo **"Conexão Falhou"** (ou o aplicativo nunca passa da tela de inicialização), verifique se há uma URL de servidor personalizada. + +#### Limpar a URL do servidor padrão do desktop + +Na tela inicial, clique no nome do servidor (com o ponto de status) para abrir o seletor de Servidor. Na seção **Servidor padrão**, clique em **Limpar**. + +#### Remover `server.port` / `server.hostname` da sua configuração + +Se seu `opencode.json(c)` contiver uma seção `server`, remova-a temporariamente e reinicie o aplicativo de desktop. + +#### Verifique as variáveis de ambiente + +Se você tiver `OPENCODE_PORT` definido em seu ambiente, o aplicativo de desktop tentará usar essa porta para o servidor local. + +- Desfaça `OPENCODE_PORT` (ou escolha uma porta livre) e reinicie. + +--- + +### Linux: Problemas com Wayland / X11 + +No Linux, algumas configurações do Wayland podem causar janelas em branco ou erros de compositor. + +- Se você estiver no Wayland e o aplicativo estiver em branco/travando, tente iniciar com `OC_ALLOW_WAYLAND=1`. +- Se isso piorar as coisas, remova e tente iniciar sob uma sessão X11. + +--- + +### Windows: WebView2 runtime + +No Windows, o OpenCode Desktop requer o **WebView2 Runtime** do Microsoft Edge. Se o aplicativo abrir em uma janela em branco ou não iniciar, instale/atualize o WebView2 e tente novamente. + +--- + +### Windows: Problemas gerais de desempenho + +Se você estiver enfrentando desempenho lento, problemas de acesso a arquivos ou problemas no terminal no Windows, tente usar [WSL (Windows Subsystem for Linux)](/docs/windows-wsl). O WSL fornece um ambiente Linux que funciona de forma mais integrada com os recursos do OpenCode. + +--- + +### Notificações não aparecendo + +O OpenCode Desktop só mostra notificações do sistema quando: + +- as notificações estão habilitadas para o OpenCode nas configurações do seu sistema operacional, e +- a janela do aplicativo não está focada. + +--- + +### Redefinir o armazenamento do aplicativo de desktop (último recurso) + +Se o aplicativo não iniciar e você não conseguir limpar as configurações pela interface, redefina o estado salvo do aplicativo de desktop. + +1. Saia do OpenCode Desktop. +2. Encontre e exclua estes arquivos (eles estão no diretório de dados do aplicativo OpenCode Desktop): + +- `opencode.settings.dat` (URL do servidor padrão do desktop) +- `opencode.global.dat` e `opencode.workspace.*.dat` (estado da interface como servidores/projetos recentes) + +Para encontrar o diretório rapidamente: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (depois pesquise pelos nomes dos arquivos acima) +- **Linux**: pesquise em `~/.local/share` pelos nomes dos arquivos acima +- **Windows**: Pressione `WIN+R` -> `%APPDATA%` (depois pesquise pelos nomes dos arquivos acima) + +--- + +## Obtendo ajuda + +Se você estiver enfrentando problemas com o OpenCode: + +1. **Relatar problemas no GitHub** + + A melhor maneira de relatar bugs ou solicitar recursos é através do nosso repositório no GitHub: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + Antes de criar um novo problema, pesquise problemas existentes para ver se seu problema já foi relatado. + +2. **Junte-se ao nosso Discord** + + Para ajuda em tempo real e discussão da comunidade, junte-se ao nosso servidor Discord: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Problemas comuns + +Aqui estão alguns problemas comuns e como resolvê-los. + +--- + +### OpenCode não inicia + +1. Verifique os logs em busca de mensagens de erro +2. Tente executar com `--print-logs` para ver a saída no terminal +3. Certifique-se de que você tem a versão mais recente com `opencode upgrade` + +--- + +### Problemas de autenticação + +1. Tente reautenticar com o comando `/connect` na TUI +2. Verifique se suas chaves de API são válidas +3. Certifique-se de que sua rede permite conexões com a API do provedor + +--- + +### Modelo não disponível + +1. Verifique se você se autenticou com o provedor +2. Verifique se o nome do modelo em sua configuração está correto +3. Alguns modelos podem exigir acesso ou assinaturas específicas + +Se você encontrar `ProviderModelNotFoundError`, é mais provável que você esteja referenciando um modelo incorretamente em algum lugar. +Os modelos devem ser referenciados assim: `/` + +Exemplos: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +Para descobrir quais modelos você tem acesso, execute `opencode models` + +--- + +### ProviderInitError + +Se você encontrar um ProviderInitError, provavelmente você tem uma configuração inválida ou corrompida. + +Para resolver isso: + +1. Primeiro, verifique se seu provedor está configurado corretamente seguindo o [guia de provedores](/docs/providers) +2. Se o problema persistir, tente limpar sua configuração armazenada: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + No Windows, pressione `WIN+R` e exclua: `%USERPROFILE%\.local\share\opencode` + +3. Reautentique-se com seu provedor usando o comando `/connect` na TUI. + +--- + +### AI_APICallError e problemas com pacotes de provedores + +Se você encontrar erros de chamada de API, isso pode ser devido a pacotes de provedores desatualizados. opencode instala dinamicamente pacotes de provedores (OpenAI, Anthropic, Google, etc.) conforme necessário e os armazena em cache localmente. + +Para resolver problemas com pacotes de provedores: + +1. Limpe o cache do pacote de provedores: + + ```bash + rm -rf ~/.cache/opencode + ``` + + No Windows, pressione `WIN+R` e exclua: `%USERPROFILE%\.cache\opencode` + +2. Reinicie o opencode para reinstalar os pacotes de provedores mais recentes + +Isso forçará o opencode a baixar as versões mais recentes dos pacotes de provedores, o que muitas vezes resolve problemas de compatibilidade com parâmetros de modelo e alterações na API. + +--- + +### Copiar/colar não funciona no Linux + +Usuários do Linux precisam ter um dos seguintes utilitários de área de transferência instalados para que a funcionalidade de copiar/colar funcione: + +**Para sistemas X11:** + +```bash +apt install -y xclip +# ou +apt install -y xsel +``` + +**Para sistemas Wayland:** + +```bash +apt install -y wl-clipboard +``` + +**Para ambientes sem cabeça:** + +```bash +apt install -y xvfb +# e execute: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode detectará se você está usando Wayland e preferirá `wl-clipboard`, caso contrário, tentará encontrar ferramentas de área de transferência na ordem: `xclip` e `xsel`. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/tui.mdx b/packages/web/src/content/docs/pt-br/tui.mdx new file mode 100644 index 000000000..adee8ef1c --- /dev/null +++ b/packages/web/src/content/docs/pt-br/tui.mdx @@ -0,0 +1,387 @@ +--- +title: TUI +description: Usando a interface de usuário de terminal OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode fornece uma interface de terminal interativa ou TUI para trabalhar em seus projetos com um LLM. + +Executar OpenCode inicia o TUI para o diretório atual. + +```bash +opencode +``` + +Ou você pode iniciá-lo para um diretório de trabalho específico. + +```bash +opencode /caminho/para/projeto +``` + +Uma vez que você esteja no TUI, você pode solicitar com uma mensagem. + +```text +Me dê um resumo rápido da base de código. +``` + +--- + +## Referências de arquivos + +Você pode referenciar arquivos em suas mensagens usando `@`. Isso faz uma busca difusa de arquivos no diretório de trabalho atual. + +:::tip +Você também pode usar `@` para referenciar arquivos em suas mensagens. +::: + +```text "@packages/functions/src/api/index.ts" +Como a autenticação é tratada em @packages/functions/src/api/index.ts? +``` + +O conteúdo do arquivo é adicionado à conversa automaticamente. + +--- + +## Comandos Bash + +Comece uma mensagem com `!` para executar um comando de shell. + +```bash frame="none" +!ls -la +``` + +A saída do comando é adicionada à conversa como um resultado de ferramenta. + +--- + +## Comandos + +Ao usar o TUI do OpenCode, você pode digitar `/` seguido pelo nome de um comando para executar ações rapidamente. Por exemplo: + +```bash frame="none" +/help +``` + +A maioria dos comandos também possui atalhos usando `ctrl+x` como a tecla líder, onde `ctrl+x` é a tecla líder padrão. [Saiba mais](/docs/keybinds). + +Aqui estão todos os comandos de barra disponíveis: + +--- + +### connect + +Adicione um provedor ao OpenCode. Permite que você selecione entre os provedores disponíveis e adicione suas chaves de API. + +```bash frame="none" +/connect +``` + +--- + +### compact + +Compacte a sessão atual. _Alias_: `/summarize` + +```bash frame="none" +/compact +``` + +**Atalho:** `ctrl+x c` + +--- + +### details + +Alternar detalhes da execução da ferramenta. + +```bash frame="none" +/details +``` + +**Atalho:** `ctrl+x d` + +--- + +### editor + +Abra um editor externo para compor mensagens. Usa o editor definido na sua variável de ambiente `EDITOR`. [Saiba mais](#editor-setup). + +```bash frame="none" +/editor +``` + +**Atalho:** `ctrl+x e` + +--- + +### exit + +Saia do OpenCode. _Aliases_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Atalho:** `ctrl+x q` + +--- + +### export + +Exporte a conversa atual para Markdown e abra no seu editor padrão. Usa o editor definido na sua variável de ambiente `EDITOR`. [Saiba mais](#editor-setup). + +```bash frame="none" +/export +``` + +**Atalho:** `ctrl+x x` + +--- + +### help + +Mostre o diálogo de ajuda. + +```bash frame="none" +/help +``` + +**Atalho:** `ctrl+x h` + +--- + +### init + +Crie ou atualize o arquivo `AGENTS.md`. [Saiba mais](/docs/rules). + +```bash frame="none" +/init +``` + +**Atalho:** `ctrl+x i` + +--- + +### models + +Liste os modelos disponíveis. + +```bash frame="none" +/models +``` + +**Atalho:** `ctrl+x m` + +--- + +### new + +Inicie uma nova sessão. _Alias_: `/clear` + +```bash frame="none" +/new +``` + +**Atalho:** `ctrl+x n` + +--- + +### redo + +Refaça uma mensagem anteriormente desfeita. Disponível apenas após usar `/undo`. + +:::tip +Quaisquer alterações de arquivo também serão restauradas. +::: + +Internamente, isso usa Git para gerenciar as alterações de arquivo. Portanto, seu projeto **precisa ser um repositório Git**. + +```bash frame="none" +/redo +``` + +**Atalho:** `ctrl+x r` + +--- + +### sessions + +Liste e alterne entre sessões. _Aliases_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Atalho:** `ctrl+x l` + +--- + +### share + +Compartilhe a sessão atual. [Saiba mais](/docs/share). + +```bash frame="none" +/share +``` + +**Atalho:** `ctrl+x s` + +--- + +### themes + +Liste os temas disponíveis. + +```bash frame="none" +/theme +``` + +**Atalho:** `ctrl+x t` + +--- + +### thinking + +Alternar a visibilidade dos blocos de pensamento/razão na conversa. Quando ativado, você pode ver o processo de raciocínio do modelo para modelos que suportam pensamento estendido. + +:::note +Este comando apenas controla se os blocos de pensamento são **exibidos** - não ativa ou desativa as capacidades de raciocínio do modelo. Para alternar as capacidades reais de raciocínio, use `ctrl+t` para alternar entre variantes do modelo. +::: + +```bash frame="none" +/thinking +``` + +--- + +### undo + +Desfaça a última mensagem na conversa. Remove a mensagem mais recente do usuário, todas as respostas subsequentes e quaisquer alterações de arquivo. + +:::tip +Quaisquer alterações de arquivo feitas também serão revertidas. +::: + +Internamente, isso usa Git para gerenciar as alterações de arquivo. Portanto, seu projeto **precisa ser um repositório Git**. + +```bash frame="none" +/undo +``` + +**Atalho:** `ctrl+x u` + +--- + +### unshare + +Descompartilhe a sessão atual. [Saiba mais](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## Configuração do Editor + +Tanto os comandos `/editor` quanto `/export` usam o editor especificado na sua variável de ambiente `EDITOR`. + + + + ```bash + # Exemplo para nano ou vim + export EDITOR=nano + export EDITOR=vim + + # Para editores GUI, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # inclua --wait + export EDITOR="code --wait" + ``` + + Para torná-lo permanente, adicione isso ao seu perfil de shell; + `~/.bashrc`, `~/.zshrc`, etc. + + + + + ```bash + set EDITOR=notepad + + # Para editores GUI, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # inclua --wait + set EDITOR=code --wait + ``` + + Para torná-lo permanente, use **Propriedades do Sistema** > **Variáveis de Ambiente**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # Para editores GUI, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # inclua --wait + $env:EDITOR = "code --wait" + ``` + + Para torná-lo permanente, adicione isso ao seu perfil do PowerShell. + + + + +As opções de editor populares incluem: + +- `code` - Visual Studio Code +- `cursor` - Cursor +- `windsurf` - Windsurf +- `nvim` - Editor Neovim +- `vim` - Editor Vim +- `nano` - Editor Nano +- `notepad` - Bloco de Notas do Windows +- `subl` - Sublime Text + +:::note +Alguns editores como o VS Code precisam ser iniciados com a flag `--wait`. +::: + +Alguns editores precisam de argumentos de linha de comando para rodar em modo bloqueante. A flag `--wait` faz com que o processo do editor bloqueie até ser fechado. + +--- + +## Configurar + +Você pode personalizar o comportamento do TUI através do seu arquivo de configuração do OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### Opções + +- `scroll_acceleration` - Ative a aceleração de rolagem no estilo macOS para uma rolagem suave e natural. Quando ativado, a velocidade de rolagem aumenta com gestos de rolagem rápidos e permanece precisa para movimentos mais lentos. **Esta configuração tem precedência sobre `scroll_speed` e a substitui quando ativada.** +- `scroll_speed` - Controla quão rápido o TUI rola ao usar comandos de rolagem (mínimo: `1`). O padrão é `3`. **Nota: Isso é ignorado se `scroll_acceleration.enabled` estiver definido como `true`.** + +--- + +## Personalização + +Você pode personalizar vários aspectos da visualização do TUI usando a paleta de comandos (`ctrl+x h` ou `/help`). Essas configurações persistem entre reinicializações. + +--- + +#### Exibição do nome de usuário + +Alternar se seu nome de usuário aparece nas mensagens de chat. Acesse isso através de: + +- Paleta de comandos: Pesquise por "username" ou "hide username" +- A configuração persiste automaticamente e será lembrada entre as sessões do TUI \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/web.mdx b/packages/web/src/content/docs/pt-br/web.mdx new file mode 100644 index 000000000..393f683c2 --- /dev/null +++ b/packages/web/src/content/docs/pt-br/web.mdx @@ -0,0 +1,142 @@ +--- +title: Web +description: Usando OpenCode no seu navegador. +--- + +OpenCode pode ser executado como uma aplicação web no seu navegador, proporcionando a mesma poderosa experiência de codificação com IA sem precisar de um terminal. + +![OpenCode Web - Nova Sessão](../../../assets/web/web-homepage-new-session.png) + +## Começando + +Inicie a interface web executando: + +```bash +opencode web +``` + +Isso inicia um servidor local em `127.0.0.1` com uma porta aleatória disponível e abre automaticamente o OpenCode no seu navegador padrão. + +:::caution +Se `OPENCODE_SERVER_PASSWORD` não estiver definido, o servidor ficará sem segurança. Isso é aceitável para uso local, mas deve ser configurado para acesso à rede. +::: + +:::tip[Usuários do Windows] +Para a melhor experiência, execute `opencode web` a partir do [WSL](/docs/windows-wsl) em vez do PowerShell. Isso garante acesso adequado ao sistema de arquivos e integração com o terminal. +::: + +--- + +## Configuração + +Você pode configurar o servidor web usando flags de linha de comando ou no seu [arquivo de configuração](/docs/config). + +### Porta + +Por padrão, o OpenCode escolhe uma porta disponível. Você pode especificar uma porta: + +```bash +opencode web --port 4096 +``` + +### Nome do Host + +Por padrão, o servidor se vincula a `127.0.0.1` (apenas localhost). Para tornar o OpenCode acessível na sua rede: + +```bash +opencode web --hostname 0.0.0.0 +``` + +Ao usar `0.0.0.0`, o OpenCode exibirá endereços locais e de rede: + +``` + Acesso local: http://localhost:4096 + Acesso à rede: http://192.168.1.100:4096 +``` + +### Descoberta mDNS + +Ative o mDNS para tornar seu servidor descobrível na rede local: + +```bash +opencode web --mdns +``` + +Isso define automaticamente o nome do host como `0.0.0.0` e anuncia o servidor como `opencode.local`. + +Você pode personalizar o nome de domínio mDNS para executar várias instâncias na mesma rede: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +Para permitir domínios adicionais para CORS (útil para frontends personalizados): + +```bash +opencode web --cors https://example.com +``` + +### Autenticação + +Para proteger o acesso, defina uma senha usando a variável de ambiente `OPENCODE_SERVER_PASSWORD`: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +O nome de usuário padrão é `opencode`, mas pode ser alterado com `OPENCODE_SERVER_USERNAME`. + +--- + +## Usando a Interface Web + +Uma vez iniciada, a interface web fornece acesso às suas sessões do OpenCode. + +### Sessões + +Visualize e gerencie suas sessões a partir da página inicial. Você pode ver sessões ativas e iniciar novas. + +![OpenCode Web - Sessão Ativa](../../../assets/web/web-homepage-active-session.png) + +### Status do Servidor + +Clique em "Ver Servidores" para visualizar os servidores conectados e seu status. + +![OpenCode Web - Ver Servidores](../../../assets/web/web-homepage-see-servers.png) + +--- + +## Anexando um Terminal + +Você pode anexar um terminal TUI a um servidor web em execução: + +```bash +# Inicie o servidor web +opencode web --port 4096 + +# Em outro terminal, anexe o TUI +opencode attach http://localhost:4096 +``` + +Isso permite que você use tanto a interface web quanto o terminal simultaneamente, compartilhando as mesmas sessões e estado. + +--- + +## Arquivo de Configuração + +Você também pode configurar as configurações do servidor no seu arquivo de configuração `opencode.json`: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +As flags de linha de comando têm precedência sobre as configurações do arquivo de configuração. \ No newline at end of file diff --git a/packages/web/src/content/docs/pt-br/windows-wsl.mdx b/packages/web/src/content/docs/pt-br/windows-wsl.mdx new file mode 100644 index 000000000..654633b0e --- /dev/null +++ b/packages/web/src/content/docs/pt-br/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: Execute o OpenCode no Windows com WSL para melhor experiencia. +--- + +import { Steps } from "@astrojs/starlight/components" + +Embora o OpenCode possa rodar direto no Windows, recomendamos usar [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) para a melhor experiencia. O WSL oferece um ambiente Linux que funciona de forma integrada com os recursos do OpenCode. + +:::tip[Por que WSL?] +O WSL oferece melhor desempenho de sistema de arquivos, suporte completo a terminal e compatibilidade com as ferramentas de desenvolvimento das quais o OpenCode depende. +::: + +--- + +## Configuracao + + + +1. **Instale o WSL** + + Se ainda nao instalou, [instale o WSL](https://learn.microsoft.com/en-us/windows/wsl/install) usando o guia oficial da Microsoft. + +2. **Instale o OpenCode no WSL** + + Depois de configurar o WSL, abra o terminal do WSL e instale o OpenCode usando um dos [metodos de instalacao](/docs/). + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **Use o OpenCode pelo WSL** + + Va para o diretorio do seu projeto (acesse arquivos do Windows via `/mnt/c/`, `/mnt/d/` etc.) e execute o OpenCode. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## App desktop + servidor WSL + +Se voce prefere usar o app desktop do OpenCode, mas quer rodar o servidor no WSL: + +1. **Inicie o servidor no WSL** com `--hostname 0.0.0.0` para permitir conexoes externas: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Conecte o app desktop** em `http://localhost:4096` + +:::note +Se `localhost` nao funcionar no seu ambiente, conecte usando o IP do WSL (no WSL: `hostname -I`) e use `http://:4096`. +::: + +:::caution +Ao usar `--hostname 0.0.0.0`, defina `OPENCODE_SERVER_PASSWORD` para proteger o servidor. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Cliente web + WSL + +Para a melhor experiencia web no Windows: + +1. **Execute `opencode web` no terminal WSL** em vez do PowerShell: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Acesse pelo navegador do Windows** em `http://localhost:` (o OpenCode mostra a URL) + +Executar `opencode web` a partir do WSL garante acesso correto ao sistema de arquivos e integracao com o terminal, continuando acessivel no navegador do Windows. + +--- + +## Acessar arquivos do Windows + +O WSL pode acessar todos os arquivos do Windows pelo diretorio `/mnt/`: + +- Unidade `C:` → `/mnt/c/` +- Unidade `D:` → `/mnt/d/` +- E assim por diante... + +Exemplo: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +Para uma experiencia mais fluida, considere clonar/copiar seu repositorio para o sistema de arquivos do WSL (por exemplo em `~/code/`) e executar o OpenCode por la. +::: + +--- + +## Dicas + +- Mantenha o OpenCode rodando no WSL para projetos armazenados em unidades do Windows - o acesso aos arquivos fica fluido +- Use a [extensao WSL do VS Code](https://code.visualstudio.com/docs/remote/wsl) junto com o OpenCode para um fluxo de desenvolvimento integrado +- Sua configuracao e suas sessoes do OpenCode ficam armazenadas no ambiente WSL em `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/pt-br/zen.mdx b/packages/web/src/content/docs/pt-br/zen.mdx new file mode 100644 index 000000000..fe7d5d33b --- /dev/null +++ b/packages/web/src/content/docs/pt-br/zen.mdx @@ -0,0 +1,236 @@ +--- +title: Zen +description: Lista selecionada de modelos fornecidos pela OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen é uma lista de modelos testados e verificados fornecidos pela equipe da OpenCode. + +:::note +OpenCode Zen está atualmente em beta. +::: + +Zen funciona como qualquer outro provedor na OpenCode. Você faz login no OpenCode Zen e obtém sua chave de API. É **completamente opcional** e você não precisa usá-la para utilizar a OpenCode. + +--- + +## Contexto + +Existem um grande número de modelos disponíveis, mas apenas alguns desses modelos funcionam bem como agentes de codificação. Além disso, a maioria dos provedores é configurada de maneira muito diferente; portanto, você obtém desempenhos e qualidades muito diferentes. + +:::tip +Testamos um grupo selecionado de modelos e provedores que funcionam bem com a OpenCode. +::: + +Portanto, se você estiver usando um modelo através de algo como OpenRouter, você nunca pode ter certeza se está obtendo a melhor versão do modelo que deseja. + +Para resolver isso, fizemos algumas coisas: + +1. Testamos um grupo selecionado de modelos e conversamos com suas equipes sobre como executá-los da melhor forma. +2. Trabalhamos com alguns provedores para garantir que esses modelos estivessem sendo servidos corretamente. +3. Finalmente, realizamos benchmarks da combinação modelo/provedor e elaboramos uma lista que nos sentimos bem em recomendar. + +OpenCode Zen é um gateway de IA que lhe dá acesso a esses modelos. + +--- + +## Como funciona + +OpenCode Zen funciona como qualquer outro provedor na OpenCode. + +1. Você faz login no **OpenCode Zen**, adiciona seus dados de cobrança e copia sua chave de API. +2. Você executa o comando `/connect` na TUI, seleciona OpenCode Zen e cola sua chave de API. +3. Execute `/models` na TUI para ver a lista de modelos que recomendamos. + +Você é cobrado por solicitação e pode adicionar créditos à sua conta. + +--- + +## Endpoints + +Você também pode acessar nossos modelos através dos seguintes endpoints da API. + +| Modelo | ID do Modelo | Endpoint | Pacote AI SDK | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Free | minimax-m2.1-free | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Free | glm-4.7-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Free | kimi-k2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +O [id do modelo](/docs/config/#models) na sua configuração da OpenCode usa o formato `opencode/`. Por exemplo, para GPT 5.2 Codex, você usaria `opencode/gpt-5.2-codex` na sua configuração. + +--- + +### Modelos + +Você pode buscar a lista completa de modelos disponíveis e seus metadados em: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## Preços + +Nós suportamos um modelo de pagamento conforme o uso. Abaixo estão os preços **por 1M de tokens**. + +| Modelo | Entrada | Saída | Leitura em Cache | Escrita em Cache | +| --------------------------------- | ------ | ------ | ---------------- | ---------------- | +| Big Pickle | Grátis | Grátis | Grátis | - | +| MiniMax M2.1 Free | Grátis | Grátis | Grátis | - | +| MiniMax M2.1 | $0.30 | $1.20 | $0.10 | - | +| GLM 4.7 Free | Grátis | Grátis | Grátis | - | +| GLM 4.7 | $0.60 | $2.20 | $0.10 | - | +| GLM 4.6 | $0.60 | $2.20 | $0.10 | - | +| Kimi K2.5 Free | Grátis | Grátis | Grátis | - | +| Kimi K2.5 | $0.60 | $3.00 | $0.08 | - | +| Kimi K2 Thinking | $0.40 | $2.50 | - | - | +| Kimi K2 | $0.40 | $2.50 | - | - | +| Qwen3 Coder 480B | $0.45 | $1.50 | - | - | +| Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | +| Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | +| Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | +| Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | +| Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | - | +| Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | - | +| Gemini 3 Flash | $0.50 | $3.00 | $0.05 | - | +| GPT 5.2 | $1.75 | $14.00 | $0.175 | - | +| GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | - | +| GPT 5.1 | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | - | +| GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | - | +| GPT 5 | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Nano | Grátis | Grátis | Grátis | - | + +Você pode notar _Claude Haiku 3.5_ em seu histórico de uso. Este é um [modelo de baixo custo](/docs/config/#models) que é usado para gerar os títulos de suas sessões. + +:::note +As taxas de cartão de crédito são repassadas ao custo (4,4% + $0,30 por transação); não cobramos nada além disso. +::: + +Os modelos gratuitos: + +- GLM 4.7 Free está disponível na OpenCode por tempo limitado. A equipe está usando esse tempo para coletar feedback e melhorar o modelo. +- Kimi K2.5 Free está disponível na OpenCode por tempo limitado. A equipe está usando esse tempo para coletar feedback e melhorar o modelo. +- MiniMax M2.1 Free está disponível na OpenCode por tempo limitado. A equipe está usando esse tempo para coletar feedback e melhorar o modelo. +- Big Pickle é um modelo oculto que está gratuito na OpenCode por tempo limitado. A equipe está usando esse tempo para coletar feedback e melhorar o modelo. + +Entre em contato conosco se você tiver alguma dúvida. + +--- + +### Recarga automática + +Se seu saldo cair abaixo de $5, Zen recarregará automaticamente $20. + +Você pode alterar o valor da recarga automática. Você também pode desativar a recarga automática completamente. + +--- + +### Limites mensais + +Você também pode definir um limite de uso mensal para todo o espaço de trabalho e para cada membro de sua equipe. + +Por exemplo, digamos que você defina um limite de uso mensal de $20, Zen não usará mais de $20 em um mês. Mas se você tiver a recarga automática ativada, Zen pode acabar cobrando mais de $20 se seu saldo cair abaixo de $5. + +--- + +## Privacidade + +Todos os nossos modelos estão hospedados nos EUA. Nossos provedores seguem uma política de zero retenção e não usam seus dados para treinamento de modelos, com as seguintes exceções: + +- Big Pickle: Durante seu período gratuito, os dados coletados podem ser usados para melhorar o modelo. +- GLM 4.7 Free: Durante seu período gratuito, os dados coletados podem ser usados para melhorar o modelo. +- Kimi K2.5 Free: Durante seu período gratuito, os dados coletados podem ser usados para melhorar o modelo. +- MiniMax M2.1 Free: Durante seu período gratuito, os dados coletados podem ser usados para melhorar o modelo. +- APIs da OpenAI: As solicitações são retidas por 30 dias de acordo com as [Políticas de Dados da OpenAI](https://platform.openai.com/docs/guides/your-data). +- APIs da Anthropic: As solicitações são retidas por 30 dias de acordo com as [Políticas de Dados da Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## Para Equipes + +Zen também funciona muito bem para equipes. Você pode convidar colegas de equipe, atribuir funções, selecionar os modelos que sua equipe usa e muito mais. + +:::note +Os espaços de trabalho estão atualmente gratuitos para equipes como parte do beta. +::: + +Gerenciar seu espaço de trabalho é atualmente gratuito para equipes como parte do beta. Em breve, compartilharemos mais detalhes sobre os preços. + +--- + +### Funções + +Você pode convidar colegas de equipe para seu espaço de trabalho e atribuir funções: + +- **Admin**: Gerenciar modelos, membros, chaves de API e cobrança +- **Membro**: Gerenciar apenas suas próprias chaves de API + +Os administradores também podem definir limites de gastos mensais para cada membro para manter os custos sob controle. + +--- + +### Acesso ao modelo + +Os administradores podem habilitar ou desabilitar modelos específicos para o espaço de trabalho. Solicitações feitas a um modelo desabilitado retornarão um erro. + +Isso é útil para casos em que você deseja desabilitar o uso de um modelo que coleta dados. + +--- + +### Traga sua própria chave + +Você pode usar suas próprias chaves de API da OpenAI ou Anthropic enquanto ainda acessa outros modelos no Zen. + +Quando você usa suas próprias chaves, os tokens são cobrados diretamente pelo provedor, não pelo Zen. + +Por exemplo, sua organização pode já ter uma chave para OpenAI ou Anthropic e você deseja usar essa em vez da que o Zen fornece. + +--- + +## Objetivos + +Criamos o OpenCode Zen para: + +1. **Benchmark** os melhores modelos/provedores para agentes de codificação. +2. Ter acesso às opções de **mais alta qualidade** e não degradar o desempenho ou redirecionar para provedores mais baratos. +3. Repassar quaisquer **reduções de preço** vendendo ao custo; assim, a única margem é para cobrir nossas taxas de processamento. +4. Não ter **vinculação** permitindo que você o use com qualquer outro agente de codificação. E sempre permitir que você use qualquer outro provedor com a OpenCode também. \ No newline at end of file diff --git a/packages/web/src/content/docs/ru/1-0.mdx b/packages/web/src/content/docs/ru/1-0.mdx new file mode 100644 index 000000000..15b7d5f53 --- /dev/null +++ b/packages/web/src/content/docs/ru/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: Миграция на 1.0 +description: Что нового в OpenCode 1.0. +--- + +OpenCode 1.0 — это полная переработка TUI. + +Мы перешли от TUI на основе go+bubbletea, у которого были проблемы с производительностью и возможностями, к собственной платформе (OpenTUI), написанной на zig+solidjs. + +Новый TUI работает так же, как старый, поскольку подключается к тому же серверу открытого кода. + +--- + +## Обновление + +Вам не следует автоматически обновляться до версии 1.0, если вы в настоящее время используете предыдущую версию. +версия. Однако некоторые старые версии OpenCode всегда используют последние версии. + +Чтобы обновить вручную, запустите + +```bash +$ opencode upgrade 1.0.0 +``` + +Чтобы вернуться к версии 0.x, запустите + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## UX-изменения + +История сеанса более сжата и показывает только полную информацию об инструментах редактирования и bash. + +Мы добавили панель команд, через которую проходит почти все. Нажмите ctrl+p, чтобы вызвать его в любом контексте и увидеть все, что вы можете сделать. + +Добавлена ​​боковая панель сеанса (можно переключать) с полезной информацией. + +Мы удалили некоторые функции, которые, как мы не были уверены, кто-то действительно использовал. Если что-то важное отсутствует, пожалуйста, откройте проблему, и мы быстро добавим ее обратно. + +--- + +## Критические изменения + +### Сочетания клавиш переименованы + +- messages_revert -> messages_undo +- переключатель_агент -> агент_цикл +- switch_agent_reverse -> Agent_cycle_reverse +- переключатель_режим -> агент_цикл +- switch_mode_reverse -> Agent_cycle_reverse + +### Привязки клавиш удалены. + +- messages_layout_toggle +- messages_next +- messages_previous +- file_diff_toggle +- file_search +- file_close +- список_файлов +- app_help +- project_init +- инструмент_детали +- думающие_блоки diff --git a/packages/web/src/content/docs/ru/acp.mdx b/packages/web/src/content/docs/ru/acp.mdx new file mode 100644 index 000000000..0b63b2580 --- /dev/null +++ b/packages/web/src/content/docs/ru/acp.mdx @@ -0,0 +1,156 @@ +--- +title: Поддержка АСР +description: Используйте OpenCode в любом ACP-совместимом редакторе. +--- + +OpenCode поддерживает [Протокол агента-клиента](https://agentclientprotocol.com) или (ACP), что позволяет использовать его непосредственно в совместимых редакторах и IDE. + +:::кончик +Список редакторов и инструментов, поддерживающих ACP, можно найти в [отчете о ходе работы ACP](https://zed.dev/blog/acp-progress-report#available-now). +::: + +ACP — это открытый протокол, который стандартизирует связь между редакторами кода и агентами кодирования ИИ. + +--- + +## Настроить + +Чтобы использовать OpenCode через ACP, настройте свой редактор для запуска команды `opencode acp`. + +Команда запускает OpenCode как ACP-совместимый подпроцесс, который взаимодействует с вашим редактором через JSON-RPC через stdio. + +Ниже приведены примеры популярных редакторов, поддерживающих ACP. + +--- + +### Зед + +Добавьте в конфигурацию [Zed](https://zed.dev) (`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +Чтобы открыть его, используйте действие `agent: new thread` в **Палитре команд**. + +Вы также можете привязать сочетание клавиш, отредактировав свой `keymap.json`: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### IDE JetBrains + +Добавьте в свою [JetBrains IDE](https://www.jetbrains.com/) acp.json в соответствии с [документацией](https://www.jetbrains.com/help/ai-assistant/acp.html): + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +Чтобы открыть его, используйте новый агент OpenCode в селекторе агентов AI Chat. + +--- + +### Аванте.nvim + +Добавьте в свою конфигурацию [Avante.nvim](https://github.com/yetone/avante.nvim): + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +Если вам нужно передать переменные среды: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### КодКомпаньон.nvim + +Чтобы использовать OpenCode в качестве агента ACP в [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim), добавьте в конфигурацию Neovim следующее: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +Эта конфигурация настраивает CodeCompanion для использования OpenCode в качестве агента ACP для чата. + +Если вам нужно передать переменные среды (например, `OPENCODE_API_KEY`), обратитесь к разделу [Настройка адаптеров: переменные среды](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) в документации CodeCompanion.nvim для получения полной информации. + +## Поддерживать + +OpenCode через ACP работает так же, как и в терминале. Поддерживаются все функции: + +:::примечание +Некоторые встроенные команды слэша, такие как `/undo` и `/redo`, в настоящее время не поддерживаются. +::: + +- Встроенные инструменты (файловые операции, команды терминала и т. д.) +- Пользовательские инструменты и команды слэша +- Серверы MCP, настроенные в вашей конфигурации OpenCode +- Правила для конкретного проекта из `AGENTS.md` +- Пользовательские форматтеры и линтеры +- Агенты и система разрешений diff --git a/packages/web/src/content/docs/ru/agents.mdx b/packages/web/src/content/docs/ru/agents.mdx new file mode 100644 index 000000000..3b71a5f6f --- /dev/null +++ b/packages/web/src/content/docs/ru/agents.mdx @@ -0,0 +1,747 @@ +--- +title: Агенты +description: Настройте и используйте специализированные агенты. +--- + +Агенты — это специализированные ИИ-помощники, которых можно настроить для конкретных задач и рабочих процессов. Они позволяют создавать специализированные инструменты с настраиваемыми подсказками, моделями и доступом к инструментам. + +:::кончик +Используйте агент плана для анализа кода и просмотра предложений без внесения каких-либо изменений в код. +::: + +Вы можете переключаться между агентами во время сеанса или вызывать их с помощью упоминания `@`. + +--- + +## Типы + +В OpenCode есть два типа агентов; Первичные агенты и субагенты. + +--- + +### Первичные агенты + +Первичные агенты — это основные помощники, с которыми вы взаимодействуете напрямую. Вы можете переключаться между ними, используя клавишу **Tab** или настроенную привязку клавиш `switch_agent`. Эти агенты ведут ваш основной разговор. Доступ к инструментам настраивается с помощью разрешений — например, при сборке все инструменты включены, а при планировании — ограничены. + +:::кончик +Вы можете использовать клавишу **Tab** для переключения между основными агентами во время сеанса. +::: + +OpenCode поставляется с двумя встроенными основными агентами: **Build** и **Plan**. Хорошо +посмотрите на это ниже. + +--- + +### Субагенты + +Субагенты — это специализированные помощники, которых основные агенты могут вызывать для выполнения определенных задач. Вы также можете вызвать их вручную, **@ упомянув** их в своих сообщениях. + +OpenCode поставляется с двумя встроенными субагентами: **General** и **Explore**. Мы рассмотрим это ниже. + +--- + +## Встроенный + +OpenCode поставляется с двумя встроенными основными агентами и двумя встроенными субагентами. + +--- + +### Используйте сборку + +_Режим_: `primary` + +Build — основной агент **по умолчанию** со всеми включенными инструментами. Это стандартный агент для разработки, где вам необходим полный доступ к файловым операциям и системным командам. + +--- + +### Использовать план + +_Режим_: `primary` + +Агент с ограниченным доступом, предназначенный для планирования и анализа. Мы используем систему разрешений, чтобы предоставить вам больше контроля и предотвратить непреднамеренные изменения. +По умолчанию для всех следующих параметров установлено значение `ask`: + +- `file edits`: Все записи, исправления и изменения. +- `bash`: все команды bash. + +Этот агент полезен, если вы хотите, чтобы LLM анализировал код, предлагал изменения или создавал планы без внесения каких-либо фактических изменений в вашу кодовую базу. + +--- + +### Используйте общие + +_Режим_: `subagent` + +Универсальный агент для исследования сложных вопросов и выполнения многоэтапных задач. Имеет полный доступ к инструментам (кроме задач), поэтому при необходимости может вносить изменения в файлы. Используйте это для параллельного выполнения нескольких единиц работы. + +--- + +### Используйте исследование + +_Режим_: `subagent` + +Быстрый агент только для чтения для изучения кодовых баз. Невозможно изменить файлы. Используйте это, когда вам нужно быстро найти файлы по шаблонам, выполнить поиск кода по ключевым словам или ответить на вопросы о кодовой базе. + +--- + +### Используйте уплотнение + +_Режим_: `primary` + +Скрытый системный агент, который сжимает длинный контекст в меньшее резюме. Он запускается автоматически при необходимости и не может быть выбран в пользовательском интерфейсе. + +--- + +### Использовать заголовок + +_Режим_: `primary` + +Скрытый системный агент, генерирующий короткие заголовки сессий. Он запускается автоматически и не может быть выбран в пользовательском интерфейсе. + +--- + +### Использовать сводку + +_Режим_: `primary` + +Скрытый системный агент, создающий сводки сеансов. Он запускается автоматически и не может быть выбран в пользовательском интерфейсе. + +--- + +## Использование + +1. Для основных агентов используйте клавишу **Tab** для переключения между ними во время сеанса. Вы также можете использовать настроенную привязку клавиш `switch_agent`. + +2. Субагенты могут быть вызваны: + - **Автоматически** основными агентами для выполнения специализированных задач на основе их описаний. + - Вручную, **@ упомянув** субагента в своем сообщении. Например. + + ```txt frame="none" + @general help me search for this function + ``` + +3. **Навигация между сеансами**. Когда субагенты создают свои собственные дочерние сеансы, вы можете перемещаться между родительским сеансом и всеми дочерними сеансами, используя: + - **\+Right** (или настроенная вами комбинация клавиш `session_child_cycle`) для перехода вперед через родительский элемент → дочерний элемент1 → дочерний элемент2 → ... → родительский элемент. + - **\+Left** (или настроенная вами комбинация клавиш `session_child_cycle_reverse`) для перехода назад по родительскому элементу ← дочерний элемент1 ← дочерний элемент2 ← ... ← родительский элемент + + Это позволяет плавно переключаться между основным разговором и работой специализированного субагента. + +--- + +## Настроить + +Вы можете настроить встроенные агенты или создать свои собственные посредством настройки. Агенты можно настроить двумя способами: + +--- + +### JSON + +Настройте агентов в файле конфигурации `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Уценка + +Вы также можете определить агентов, используя файлы уценки. Поместите их в: + +- Глобальный: `~/.config/opencode/agents/` +- Для каждого проекта: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Имя файла уценки становится именем агента. Например, `review.md` создает агент `review`. + +--- + +## Параметры + +Давайте рассмотрим эти параметры конфигурации подробно. + +--- + +### Описание + +Используйте опцию `description`, чтобы предоставить краткое описание того, что делает агент и когда его использовать. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +Это **обязательный** параметр конфигурации. + +--- + +### Температура + +Контролируйте случайность и креативность ответов LLM с помощью конфигурации `temperature`. + +Более низкие значения делают ответы более целенаправленными и детерминированными, а более высокие значения повышают креативность и вариативность. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Значения температуры обычно находятся в диапазоне от 0,0 до 1,0: + +- **0,0–0,2**: очень целенаправленные и детерминированные ответы, идеальные для анализа кода и планирования. +- **0,3–0,5**: сбалансированные ответы с некоторой креативностью, подходят для общих задач развития. +- **0,6–1,0**: более творческие и разнообразные ответы, полезные для мозгового штурма и исследования. + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Если температура не указана, OpenCode использует значения по умолчанию, специфичные для модели; обычно 0 для большинства моделей, 0,55 для моделей Qwen. + +--- + +### Максимальное количество шагов + +Управляйте максимальным количеством агентных итераций, которые агент может выполнить, прежде чем ему придется отвечать только текстом. Это позволяет пользователям, желающим контролировать расходы, устанавливать лимит на агентские действия. + +Если этот параметр не установлен, агент будет продолжать выполнять итерацию до тех пор, пока модель не решит остановиться или пока пользователь не прервет сеанс. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +При достижении лимита агент получает специальную системную подсказку с указанием в ответ краткой информации о своей работе и рекомендуемых оставшихся задачах. + +:::осторожность +Устаревшее поле `maxSteps` устарело. Вместо этого используйте `steps`. +::: + +--- + +### Запрещать + +Установите `true`, чтобы отключить агент. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Быстрый + +Укажите собственный файл системных приглашений для этого агента с помощью конфигурации `prompt`. Файл подсказки должен содержать инструкции, специфичные для целей агента. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Этот путь указан относительно того, где находится файл конфигурации. Таким образом, это работает как для глобальной конфигурации OpenCode, так и для конфигурации конкретного проекта. + +--- + +### Модель + +Используйте конфигурацию `model`, чтобы переопределить модель этого агента. Полезно для использования разных моделей, оптимизированных под разные задачи. Например, более быстрая модель планирования и более эффективная модель реализации. + +:::кончик +Если вы не укажете модель, основные агенты будут использовать глобально настроенную модель](/docs/config#models), а субагенты будут использовать модель основного агента, вызвавшего субагент. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +Идентификатор модели в вашей конфигурации OpenCode использует формат `provider/model-id`. Например, если вы используете [OpenCode Zen](/docs/zen), вы должны использовать `opencode/gpt-5.1-codex` для кодекса GPT 5.1. + +--- + +### Инструменты + +Контролируйте, какие инструменты доступны в этом агенте, с помощью конфигурации `tools`. Вы можете включить или отключить определенные инструменты, установив для них значение `true` или `false`. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::примечание +Конфигурация, специфичная для агента, переопределяет глобальную конфигурацию. +::: + +Вы также можете использовать подстановочные знаки для одновременного управления несколькими инструментами. Например, чтобы отключить все инструменты с сервера MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[Подробнее об инструментах](/docs/tools). + +--- + +### Разрешения + +Вы можете настроить разрешения, чтобы управлять действиями, которые может выполнять агент. В настоящее время разрешения для инструментов `edit`, `bash` и `webfetch` можно настроить на: + +- `"ask"` — Запросить подтверждение перед запуском инструмента. +- `"allow"` — Разрешить все операции без одобрения. +- `"deny"` — отключить инструмент + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +Вы можете переопределить эти разрешения для каждого агента. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +Вы также можете установить разрешения в агентах Markdown. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +Вы можете установить разрешения для определенных команд bash. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +Это может использовать шаблон глобуса. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +Вы также можете использовать подстановочный знак `*` для управления разрешениями для всех команд. +Поскольку последнее правило сопоставления имеет приоритет, сначала поместите подстановочный знак `*`, а затем конкретные правила. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[Подробнее о разрешениях](/docs/permissions). + +--- + +### Режим + +Управляйте режимом агента с помощью конфигурации `mode`. Опция `mode` используется для определения того, как можно использовать агент. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +Опция `mode` может быть установлена ​​на `primary`, `subagent` или `all`. Если `mode` не указан, по умолчанию используется `all`. + +--- + +### Скрытый + +Скройте субагент из меню автозаполнения `@` с помощью `hidden: true`. Полезно для внутренних субагентов, которые другие агенты должны вызывать только программно с помощью инструмента Task. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +Это влияет только на видимость пользователя в меню автозаполнения. Скрытые агенты по-прежнему могут быть вызваны моделью с помощью инструмента «Задачи», если разрешения позволяют. + +:::примечание +Применяется только к агентам `mode: subagent`. +::: + +--- + +### Разрешения задач + +Управляйте тем, какие субагенты агент может вызывать с помощью инструмента задач с помощью `permission.task`. Использует шаблоны glob для гибкого сопоставления. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +Если установлено значение `deny`, субагент полностью удаляется из описания инструмента «Задача», поэтому модель не будет пытаться его вызвать. + +:::кончик +Правила оцениваются по порядку, и **побеждает последнее подходящее правило**. В приведенном выше примере `orchestrator-planner` соответствует как `*` (запретить), так и `orchestrator-*` (разрешить), но поскольку `orchestrator-*` идет после `*`, результатом будет `allow`. +::: + +:::кончик +Пользователи всегда могут вызвать любой субагент напрямую через меню автозаполнения `@`, даже если разрешения задач агента запрещают это. +::: + +--- + +### Цвет + +Настройте внешний вид агента в пользовательском интерфейсе с помощью параметра `color`. Это влияет на то, как агент будет отображаться в интерфейсе. + +Используйте допустимый шестнадцатеричный цвет (например, `#FF5733`) или цвет темы: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### Топ П + +Управляйте разнообразием ответов с помощью опции `top_p`. Альтернатива температуре для контроля случайности. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +Значения варьируются от 0,0 до 1,0. Низкие ценности более целенаправленны, высшие ценности более разнообразны. + +--- + +### Дополнительный + +Любые другие параметры, указанные вами в конфигурации вашего агента, будут **передаваться напрямую** поставщику в качестве параметров модели. Это позволяет использовать функции и параметры, специфичные для поставщика. + +Например, с помощью моделей рассуждения OpenAI вы можете контролировать усилия по рассуждению: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +Эти дополнительные параметры зависят от модели и поставщика. Проверьте документацию вашего провайдера на наличие доступных параметров. + +:::кончик +Запустите `opencode models`, чтобы просмотреть список доступных моделей. +::: + +--- + +## Создание агентов + +Вы можете создать новых агентов, используя следующую команду: + +```bash +opencode agent create +``` + +Эта интерактивная команда: + +1. Спросить, где сохранить агента; глобальный или специфичный для проекта. +2. Описание того, что должен делать агент. +3. Создайте соответствующее системное приглашение и идентификатор. +4. Позволяет вам выбрать, к каким инструментам может получить доступ агент. +5. Наконец, создайте файл уценки с конфигурацией агента. + +--- + +## Варианты использования + +Вот несколько распространенных случаев использования различных агентов. + +- **Агент сборки**: полная работа по разработке со всеми включенными инструментами. +- **Агент планирования**: анализ и планирование без внесения изменений. +- **Агент проверки**: проверка кода с доступом только для чтения и инструментами документирования. +- **Агент отладки**: сосредоточен на исследовании с включенными инструментами bash и чтения. +- **Агент документов**: запись документации с помощью файловых операций, но без системных команд. + +--- + +## Примеры + +Вот несколько примеров агентов, которые могут оказаться вам полезными. + +:::кончик +У вас есть агент, которым вы хотели бы поделиться? [Отправьте PR](https://github.com/anomalyco/opencode). +::: + +--- + +### Агент документации + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### Аудитор безопасности + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/ru/cli.mdx b/packages/web/src/content/docs/ru/cli.mdx new file mode 100644 index 000000000..34588844a --- /dev/null +++ b/packages/web/src/content/docs/ru/cli.mdx @@ -0,0 +1,601 @@ +--- +title: интерфейс командной строки +description: Параметры и команда OpenCode CLI. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +Интерфейс командной строки OpenCode по умолчанию запускает [TUI](/docs/tui) при запуске без каких-либо аргументов. + +```bash +opencode +``` + +Но он также принимает команды, описанные на этой странице. Это позволяет вам программно взаимодействовать с OpenCode. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### туй + +Запустите пользовательский интерфейс терминала OpenCode. + +```bash +opencode [project] +``` + +#### Флаги + +| Флаг | Короткий | Описание | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | Продолжить последний сеанс | +| `--session` | `-s` | Идентификатор сеанса для продолжения | +| `--prompt` | | Подскажите использовать | +| `--model` | `-m` | Модель для использования в виде поставщика/модели. | +| `--agent` | | Агент для использования | +| `--port` | | Порт для прослушивания | +| `--hostname` | | Имя хоста для прослушивания | + +--- + +## Команды + +Интерфейс командной строки OpenCode также имеет следующие команды. + +--- + +### агент + +Управляйте агентами для OpenCode. + +```bash +opencode agent [command] +``` + +--- + +### прикреплять + +Подключите терминал к уже работающему внутреннему серверу OpenCode, запущенному с помощью команд `serve` или `web`. + +```bash +opencode attach [url] +``` + +Это позволяет использовать TUI с удаленным сервером OpenCode. Например: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### Флаги + +| Флаг | Короткий | Описание | +| ----------- | ----- | --------------------------------- | +| `--dir` | | Рабочий каталог для запуска TUI | +| `--session` | `-s` | Идентификатор сеанса для продолжения | + +--- + +#### создавать + +Создайте нового агента с пользовательской конфигурацией. + +```bash +opencode agent create +``` + +Эта команда поможет вам создать новый агент с настраиваемой системной подсказкой и настройкой инструмента. + +--- + +#### список + +Перечислите всех доступных агентов. + +```bash +opencode agent list +``` + +--- + +### авторизация + +Команда для управления учетными данными и входом в систему для провайдеров. + +```bash +opencode auth [command] +``` + +--- + +#### авторизоваться + +OpenCode основан на списке поставщиков по адресу [Models.dev](https://models.dev)), поэтому вы можете использовать `opencode auth login` для настройки ключей API для любого поставщика, которого вы хотите использовать. Это хранится в `~/.local/share/opencode/auth.json`. + +```bash +opencode auth login +``` + +Когда OpenCode запускается, он загружает поставщиков из файла учетных данных. И если в ваших средах определены какие-либо ключи или файл `.env` в вашем проекте. + +--- + +#### список + +Перечисляет всех проверенных поставщиков, которые хранятся в файле учетных данных. + +```bash +opencode auth list +``` + +Или короткая версия. + +```bash +opencode auth ls +``` + +--- + +#### выход из системы + +Выключает вас из провайдера, удаляя его из файла учетных данных. + +```bash +opencode auth logout +``` + +--- + +### github + +Управляйте агентом GitHub для автоматизации репозитория. + +```bash +opencode github [command] +``` + +--- + +#### установить + +Установите агент GitHub в свой репозиторий. + +```bash +opencode github install +``` + +Это настроит необходимый рабочий процесс GitHub Actions и проведет вас через процесс настройки. [Подробнее](/docs/github). + +--- + +#### бегать + +Запустите агент GitHub. Обычно это используется в действиях GitHub. + +```bash +opencode github run +``` + +##### Флаги + +| Флаг | Описание | +| --------- | -------------------------------------- | +| `--event` | Имитирующее событие GitHub для запуска агента | +| `--token` | Токен личного доступа GitHub | + +--- + +### мкп + +Управляйте серверами протокола контекста модели. + +```bash +opencode mcp [command] +``` + +--- + +#### добавлять + +Добавьте сервер MCP в свою конфигурацию. + +```bash +opencode mcp add +``` + +Эта команда поможет вам добавить локальный или удаленный сервер MCP. + +--- + +#### список + +Перечислите все настроенные серверы MCP и состояние их подключения. + +```bash +opencode mcp list +``` + +Или используйте короткую версию. + +```bash +opencode mcp ls +``` + +--- + +#### авторизация + +Аутентификация с помощью сервера MCP с поддержкой OAuth. + +```bash +opencode mcp auth [name] +``` + +Если вы не укажете имя сервера, вам будет предложено выбрать один из доступных серверов с поддержкой OAuth. + +Вы также можете перечислить серверы с поддержкой OAuth и их статус аутентификации. + +```bash +opencode mcp auth list +``` + +Или используйте короткую версию. + +```bash +opencode mcp auth ls +``` + +--- + +#### выход из системы + +Удалите учетные данные OAuth для сервера MCP. + +```bash +opencode mcp logout [name] +``` + +--- + +#### отлаживать + +Отладка проблем с подключением OAuth для сервера MCP. + +```bash +opencode mcp debug +``` + +--- + +### модели + +Перечислите все доступные модели от настроенных поставщиков. + +```bash +opencode models [provider] +``` + +Эта команда отображает все модели, доступные у настроенных вами поставщиков, в формате `provider/model`. + +Это полезно для определения точного названия модели, которое будет использоваться в [вашем config](/docs/config/). + +При желании вы можете передать идентификатор поставщика, чтобы фильтровать модели по этому поставщику. + +```bash +opencode models anthropic +``` + +#### Флаги + +| Флаг | Описание | +| ----------- | ------------------------------------------------------------ | +| `--refresh` | Обновите кеш моделей на сайте models.dev. | +| `--verbose` | Используйте более подробный вывод модели (включая метаданные, такие как затраты). | + +Используйте флаг `--refresh` для обновления списка кэшированных моделей. Это полезно, когда к поставщику добавлены новые модели и вы хотите увидеть их в OpenCode. + +```bash +opencode models --refresh +``` + +--- + +### бегать + +Запустите открытый код в неинтерактивном режиме, передав приглашение напрямую. + +```bash +opencode run [message..] +``` + +Это полезно для создания сценариев, автоматизации или когда вам нужен быстрый ответ без запуска полного TUI. Например. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +Вы также можете подключиться к работающему экземпляру `opencode serve`, чтобы избежать холодной загрузки сервера MCP при каждом запуске: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### Флаги + +| Флаг | Короткий | Описание | +| ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | | Команда для запуска, используйте сообщение для аргументов | +| `--continue` | `-c` | Продолжить последний сеанс | +| `--session` | `-s` | Идентификатор сеанса для продолжения | +| `--share` | | Поделиться сеансом | +| `--model` | `-m` | Модель для использования в виде поставщика/модели. | +| `--agent` | | Агент для использования | +| `--file` | `-f` | Файл(ы) для прикрепления к сообщению | +| `--format` | | Формат: по умолчанию (отформатированный) или json (необработанные события JSON). | +| `--title` | | Название сеанса (использует усеченное приглашение, если значение не указано) | +| `--attach` | | Подключитесь к работающему серверу открытого кода (например, http://localhost:4096) | +| `--port` | | Порт локального сервера (по умолчанию случайный порт) | + +--- + +### служить + +Запустите автономный сервер OpenCode для доступа к API. Полный HTTP-интерфейс можно найти в [server docs](/docs/server). + +```bash +opencode serve +``` + +При этом запускается HTTP-сервер, который обеспечивает доступ API к функциям открытого кода без интерфейса TUI. Установите `OPENCODE_SERVER_PASSWORD`, чтобы включить базовую аутентификацию HTTP (имя пользователя по умолчанию — `opencode`). + +#### Флаги + +| Флаг | Описание | +| ------------ | ------------------------------------------ | +| `--port` | Порт для прослушивания | +| `--hostname` | Имя хоста для прослушивания | +| `--mdns` | Включить обнаружение mDNS | +| `--cors` | Дополнительные источники браузера, позволяющие разрешить CORS | + +--- + +### сессия + +Управляйте сессиями OpenCode. + +```bash +opencode session [command] +``` + +--- + +#### список + +Перечислите все сеансы OpenCode. + +```bash +opencode session list +``` + +##### Флаги + +| Флаг | Короткий | Описание | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` | Ограничить N последних сеансов. | +| `--format` | | Формат вывода: таблица или json (таблица) | + +--- + +### статистика + +Покажите статистику использования токенов и затрат для ваших сеансов OpenCode. + +```bash +opencode stats +``` + +#### Флаги + +| Флаг | Описание | +| ----------- | --------------------------------------------------------------------------- | +| `--days` | Показать статистику за последние N дней (все время) | +| `--tools` | Количество инструментов для отображения (все) | +| `--models` | Показать разбивку по использованию модели (по умолчанию скрыто). Передайте номер, чтобы показать верхнюю N | +| `--project` | Фильтровать по проекту (все проекты, пустая строка: текущий проект) | + +--- + +### экспорт + +Экспортируйте данные сеанса в формате JSON. + +```bash +opencode export [sessionID] +``` + +Если вы не укажете идентификатор сеанса, вам будет предложено выбрать один из доступных сеансов. + +--- + +### импортировать + +Импортируйте данные сеанса из файла JSON или URL-адреса общего ресурса OpenCode. + +```bash +opencode import +``` + +Вы можете импортировать из локального файла или URL-адреса общего ресурса OpenCode. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### сеть + +Запустите автономный сервер OpenCode с веб-интерфейсом. + +```bash +opencode web +``` + +При этом запускается HTTP-сервер и открывается веб-браузер для доступа к OpenCode через веб-интерфейс. Установите `OPENCODE_SERVER_PASSWORD`, чтобы включить базовую аутентификацию HTTP (имя пользователя по умолчанию — `opencode`). + +#### Флаги + +| Флаг | Описание | +| ------------ | ------------------------------------------ | +| `--port` | Порт для прослушивания | +| `--hostname` | Имя хоста для прослушивания | +| `--mdns` | Включить обнаружение mDNS | +| `--cors` | Дополнительные источники браузера, позволяющие разрешить CORS | + +--- + +### акп + +Запустите сервер ACP (агент-клиентский протокол). + +```bash +opencode acp +``` + +Эта команда запускает сервер ACP, который обменивается данными через stdin/stdout с использованием nd-JSON. + +#### Флаги + +| Флаг | Описание | +| ------------ | --------------------- | +| `--cwd` | Рабочий каталог | +| `--port` | Порт для прослушивания | +| `--hostname` | Имя хоста для прослушивания | + +--- + +### удалить + +Удалите OpenCode и удалите все связанные файлы. + +```bash +opencode uninstall +``` + +#### Флаги + +| Флаг | Короткий | Описание | +| --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` | Сохраняйте файлы конфигурации | +| `--keep-data` | `-d` | Храните данные сеанса и снимки | +| `--dry-run` | | Покажите, что было бы удалено без удаления | +| `--force` | `-f` | Пропустить запросы подтверждения | + +--- + +### обновление + +Обновляет открытый код до последней версии или определенной версии. + +```bash +opencode upgrade [target] +``` + +Чтобы обновиться до последней версии. + +```bash +opencode upgrade +``` + +Для обновления до определенной версии. + +```bash +opencode upgrade v0.1.48 +``` + +#### Флаги + +| Флаг | Короткий | Описание | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` | Используемый метод установки; локон, НПМ, ПНПМ, булочка, заваривание | + +--- + +## Глобальные флаги + +Интерфейс командной строки открытого кода принимает следующие глобальные флаги. + +| Флаг | Короткий | Описание | +| -------------- | ----- | ------------------------------------ | +| `--help` | `-h` | Отобразить справку | +| `--version` | `-v` | Распечатать номер версии | +| `--print-logs` | | Печать журналов в stderr | +| `--log-level` | | Уровень журнала (ОТЛАДКА, ИНФОРМАЦИЯ, ПРЕДУПРЕЖДЕНИЕ, ОШИБКА) | + +--- + +## Переменные среды + +OpenCode можно настроить с помощью переменных среды. + +| Переменная | Тип | Описание | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | логическое значение | Автоматически делиться сеансами | +| `OPENCODE_GIT_BASH_PATH` | нить | Путь к исполняемому файлу Git Bash в Windows | +| `OPENCODE_CONFIG` | нить | Путь к файлу конфигурации | +| `OPENCODE_CONFIG_DIR` | нить | Путь к каталогу конфигурации | +| `OPENCODE_CONFIG_CONTENT` | нить | Встроенное содержимое конфигурации json | +| `OPENCODE_DISABLE_AUTOUPDATE` | логическое значение | Отключить автоматическую проверку обновлений | +| `OPENCODE_DISABLE_PRUNE` | логическое значение | Отключить удаление старых данных | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | логическое значение | Отключить автоматическое обновление названия терминала | +| `OPENCODE_PERMISSION` | нить | Встроенная конфигурация разрешений json | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | логическое значение | Отключить плагины по умолчанию | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | логическое значение | Отключить автоматическую загрузку LSP-сервера | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | логическое значение | Включить экспериментальные модели | +| `OPENCODE_DISABLE_AUTOCOMPACT` | логическое значение | Отключить автоматическое сжатие контекста | +| `OPENCODE_DISABLE_CLAUDE_CODE` | логическое значение | Отключить чтение из `.claude` (подсказка + навыки) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | логическое значение | Отключить чтение `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | логическое значение | Отключить загрузку `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | логическое значение | Отключить получение моделей из удаленных источников | +| `OPENCODE_FAKE_VCS` | нить | Поддельный поставщик VCS для целей тестирования | +| `OPENCODE_DISABLE_FILETIME_CHECK` | логическое значение | Отключить проверку времени файла для оптимизации | +| `OPENCODE_CLIENT` | нить | Идентификатор клиента (по умолчанию `cli`) | +| `OPENCODE_ENABLE_EXA` | логическое значение | Включить инструменты веб-поиска Exa | +| `OPENCODE_SERVER_PASSWORD` | нить | Включить базовую аутентификацию для `serve`/`web` | +| `OPENCODE_SERVER_USERNAME` | нить | Переопределить имя пользователя базовой аутентификации (по умолчанию `opencode`) | +| `OPENCODE_MODELS_URL` | нить | Пользовательский URL-адрес для получения конфигурации модели | + +--- + +### Экспериментальный + +Эти переменные среды позволяют использовать экспериментальные функции, которые могут быть изменены или удалены. + +| Переменная | Тип | Описание | +| ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | логическое значение | Включить все экспериментальные функции | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | логическое значение | Включить обнаружение значков | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | логическое значение | Отключить копирование при выборе в TUI | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | число | Таймаут по умолчанию для команд bash в мс | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | число | Максимальное количество токенов вывода для ответов LLM | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | логическое значение | Включить просмотр файлов для всего каталога | +| `OPENCODE_EXPERIMENTAL_OXFMT` | логическое значение | Включить форматтер oxfmt | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | логическое значение | Включить экспериментальный инструмент LSP | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | логическое значение | Отключить просмотрщик файлов | +| `OPENCODE_EXPERIMENTAL_EXA` | логическое значение | Включить экспериментальные функции Exa | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | логическое значение | Включить экспериментальную проверку типа LSP | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | логическое значение | Включить экспериментальные функции уценки | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | логическое значение | Включить режим плана | diff --git a/packages/web/src/content/docs/ru/commands.mdx b/packages/web/src/content/docs/ru/commands.mdx new file mode 100644 index 000000000..044a087c0 --- /dev/null +++ b/packages/web/src/content/docs/ru/commands.mdx @@ -0,0 +1,323 @@ +--- +title: Команды +description: Создавайте собственные команды для повторяющихся задач. +--- + +Пользовательские команды позволяют указать подсказку, которую вы хотите запускать при выполнении этой команды в TUI. + +```bash frame="none" +/my-command +``` + +Пользовательские команды дополняют встроенные команды, такие как `/init`, `/undo`, `/redo`, `/share`, `/help`. [Подробнее](/docs/tui#commands). + +--- + +## Создание командных файлов + +Создайте файлы уценки в каталоге `commands/` для определения пользовательских команд. + +Создайте `.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Фронтальная часть определяет свойства команды. Содержимое становится шаблоном. + +Используйте команду, набрав `/`, а затем имя команды. + +```bash frame="none" +"/test" +``` + +--- + +## Настроить + +Вы можете добавлять собственные команды через конфигурацию OpenCode или создав файлы уценки в каталоге `commands/`. + +--- + +### JSON + +Используйте опцию `command` в вашем OpenCode [config](/docs/config): + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Теперь вы можете запустить эту команду в TUI: + +```bash frame="none" +/test +``` + +--- + +### Уценка + +Вы также можете определять команды, используя файлы уценки. Поместите их в: + +- Глобальный: `~/.config/opencode/commands/` +- Для каждого проекта: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Имя файла уценки становится именем команды. Например, `test.md` позволяет +ты бежишь: + +```bash frame="none" +/test +``` + +--- + +## Подскажите конфигурацию + +Подсказки для пользовательских команд поддерживают несколько специальных заполнителей и синтаксиса. + +--- + +### Аргументы + +Передавайте аргументы командам, используя заполнитель `$ARGUMENTS`. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +Запустите команду с аргументами: + +```bash frame="none" +/component Button +``` + +И `$ARGUMENTS` будет заменен на `Button`. + +Вы также можете получить доступ к отдельным аргументам, используя позиционные параметры: + +- `$1` — первый аргумент +- `$2` — Второй аргумент +- `$3` — Третий аргумент +- И так далее... + +Например: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +Запустите команду: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +Это заменяет: + +- `$1` с `config.json` +- `$2` с `src` +- `$3` с `{ "key": "value" }` + +--- + +### Вывод оболочки + +Используйте _!`command`_, чтобы ввести вывод команды bash](/docs/tui#bash-commands) в приглашение. + +Например, чтобы создать пользовательскую команду, которая анализирует тестовое покрытие: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +Или просмотреть последние изменения: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +Команды выполняются в корневом каталоге вашего проекта, и их вывод становится частью приглашения. + +--- + +### Ссылки на файлы + +Включите файлы в свою команду, используя `@`, за которым следует имя файла. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +Содержимое файла автоматически включается в приглашение. + +--- + +## Параметры + +Рассмотрим варианты конфигурации подробнее. + +--- + +### Шаблон + +Параметр `template` определяет приглашение, которое будет отправлено в LLM при выполнении команды. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +Это **обязательный** параметр конфигурации. + +--- + +### Описание + +Используйте опцию `description`, чтобы предоставить краткое описание того, что делает команда. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +Это отображается в виде описания в TUI при вводе команды. + +--- + +### Агент + +Используйте конфигурацию `agent`, чтобы дополнительно указать, какой [агент](/docs/agents) должен выполнить эту команду. +Если это [subagent](/docs/agents/#subagents), команда по умолчанию инициирует вызов субагента. +Чтобы отключить это поведение, установите для `subtask` значение `false`. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +Это **необязательный** параметр конфигурации. Если не указано, по умолчанию используется текущий агент. + +--- + +### Подзадача + +Используйте логическое значение `subtask`, чтобы заставить команду инициировать вызов [subagent](/docs/agents/#subagents). +Это полезно, если вы хотите, чтобы команда не загрязняла ваш основной контекст и **заставляла** агента действовать как субагент. +даже если для `mode` установлено значение `primary` в конфигурации [agent](/docs/agents). + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +Это **необязательный** параметр конфигурации. + +--- + +### Модель + +Используйте конфигурацию `model`, чтобы переопределить модель по умолчанию для этой команды. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Это **необязательный** параметр конфигурации. + +--- + +## Встроенный + +открытый код включает несколько встроенных команд, таких как `/init`, `/undo`, `/redo`, `/share`, `/help`; [подробнее](/docs/tui#commands). + +:::примечание +Пользовательские команды могут переопределять встроенные команды. +::: + +Если вы определите пользовательскую команду с тем же именем, она переопределит встроенную команду. diff --git a/packages/web/src/content/docs/ru/config.mdx b/packages/web/src/content/docs/ru/config.mdx new file mode 100644 index 000000000..e8f6b490f --- /dev/null +++ b/packages/web/src/content/docs/ru/config.mdx @@ -0,0 +1,685 @@ +--- +title: Конфигурация +description: Использование конфигурации OpenCode JSON. +--- + +Вы можете настроить OpenCode, используя файл конфигурации JSON. + +--- + +## Формат + +OpenCode поддерживает форматы **JSON** и **JSONC** (JSON с комментариями). + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## Локации + +Вы можете разместить свою конфигурацию в нескольких разных местах, и у них есть +разный порядок старшинства. + +:::примечание +Файлы конфигурации **объединяются**, а не заменяются. +::: + +Файлы конфигурации объединяются, а не заменяются. Настройки из следующих мест конфигурации объединяются. Более поздние конфигурации переопределяют предыдущие только в случае конфликта ключей. Неконфликтные настройки из всех конфигов сохраняются. + +Например, если ваша глобальная конфигурация устанавливает `theme: "opencode"` и `autoupdate: true`, а конфигурация вашего проекта устанавливает `model: "anthropic/claude-sonnet-4-5"`, окончательная конфигурация будет включать все три параметра. + +--- + +### Порядок приоритета + +Источники конфигурации загружаются в следующем порядке (более поздние источники переопределяют более ранние): + +1. **Удаленная конфигурация** (от `.well-known/opencode`) – организационные настройки по умолчанию. +2. **Глобальная конфигурация** (`~/.config/opencode/opencode.json`) — настройки пользователя. +3. **Пользовательская конфигурация** (`OPENCODE_CONFIG` env var) – пользовательские переопределения +4. **Конфигурация проекта** (`opencode.json` в проекте) — настройки, специфичные для проекта. +5. **Каталоги `.opencode`** — агенты, команды, плагины +6. **Встроенная конфигурация** (`OPENCODE_CONFIG_CONTENT` env var) – переопределяет время выполнения + +Это означает, что конфигурации проекта могут переопределять глобальные настройки по умолчанию, а глобальные конфигурации могут переопределять настройки по умолчанию для удаленной организации. + +:::примечание +В каталогах `.opencode` и `~/.config/opencode` для подкаталогов используются **множественные имена**: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/` и `themes/`. Единственные имена (например, `agent/`) также поддерживаются для обратной совместимости. +::: + +--- + +### Удаленный + +Организации могут предоставить конфигурацию по умолчанию через конечную точку `.well-known/opencode`. Он извлекается автоматически при аутентификации у провайдера, который его поддерживает. + +Удаленная конфигурация загружается первой и служит базовым слоем. Все остальные источники конфигурации (глобальные, проектные) могут переопределить эти значения по умолчанию. + +Например, если ваша организация предоставляет серверы MCP, которые по умолчанию отключены: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +Вы можете включить определенные серверы в локальной конфигурации: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### Глобальный + +Поместите глобальную конфигурацию OpenCode в `~/.config/opencode/opencode.json`. Используйте глобальную конфигурацию для общепользовательских настроек, таких как темы, поставщики или привязки клавиш. + +Глобальная конфигурация переопределяет настройки по умолчанию для удаленной организации. + +--- + +### За проект + +Добавьте `opencode.json` в корень вашего проекта. Конфигурация проекта имеет наивысший приоритет среди стандартных файлов конфигурации — она переопределяет как глобальные, так и удаленные конфигурации. + +:::кончик +Поместите конфигурацию конкретного проекта в корень вашего проекта. +::: + +Когда OpenCode запускается, он ищет файл конфигурации в текущем каталоге или переходит к ближайшему каталогу Git. + +Его также можно безопасно зарегистрировать в Git, и он использует ту же схему, что и глобальная. + +--- + +### Пользовательский путь + +Укажите собственный путь к файлу конфигурации, используя переменную среды `OPENCODE_CONFIG`. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +Пользовательская конфигурация загружается между глобальными и проектными конфигурациями в порядке приоритета. + +--- + +### Пользовательский каталог + +Укажите пользовательский каталог конфигурации, используя `OPENCODE_CONFIG_DIR`. +переменная среды. В этом каталоге будет осуществляться поиск агентов, команд, +режимы и плагины, такие как стандартный каталог `.opencode`, и должны +следовать той же структуре. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +Пользовательский каталог загружается после каталогов global config и `.opencode`, поэтому он **может переопределить** их настройки. + +--- + +## Схема + +Файл конфигурации имеет схему, определенную в [**`opencode.ai/config.json`**](https://opencode.ai/config.json). + +Ваш редактор должен иметь возможность проверять и автозаполнять данные на основе схемы. + +--- + +### ТУИ + +Вы можете настроить параметры TUI с помощью опции `tui`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +Доступные варианты: + +- `scroll_acceleration.enabled` — включить ускорение прокрутки в стиле MacOS. **Имеет приоритет над `scroll_speed`.** +- `scroll_speed` — пользовательский множитель скорости прокрутки (по умолчанию: `3`, минимум: `1`). Игнорируется, если `scroll_acceleration.enabled` равен `true`. +- `diff_style` — управление рендерингом различий. `"auto"` адаптируется к ширине терминала, `"stacked"` всегда отображает один столбец. + +[Подробнее об использовании TUI можно узнать здесь](/docs/tui). + +--- + +### Сервер + +Вы можете настроить параметры сервера для команд `opencode serve` и `opencode web` с помощью опции `server`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +Доступные варианты: + +- `port` — порт для прослушивания. +- `hostname` — имя хоста для прослушивания. Если `mdns` включен и имя хоста не задано, по умолчанию используется `0.0.0.0`. +- `mdns` — включить обнаружение службы mDNS. Это позволит другим устройствам в сети обнаружить ваш сервер OpenCode. +- `mdnsDomain` — собственное доменное имя для службы mDNS. По умолчанию `opencode.local`. Полезно для запуска нескольких экземпляров в одной сети. +- `cors` — дополнительные источники, позволяющие использовать CORS при использовании HTTP-сервера из браузерного клиента. Значения должны быть полными источниками (схема + хост + дополнительный порт), например `https://app.example.com`. + +[Подробнее о сервере можно узнать здесь](/docs/server). + +--- + +### Инструменты + +Вы можете управлять инструментами, которые LLM может использовать, с помощью опции `tools`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[Подробнее об инструментах можно узнать здесь](/docs/tools). + +--- + +### Модели + +Вы можете настроить поставщиков и модели, которые хотите использовать в своей конфигурации OpenCode, с помощью параметров `provider`, `model` и `small_model`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +Опция `small_model` настраивает отдельную модель для облегченных задач, таких как создание заголовков. По умолчанию OpenCode пытается использовать более дешевую модель, если она доступна у вашего провайдера, в противном случае он возвращается к вашей основной модели. + +Опции провайдера могут включать `timeout` и `setCacheKey`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` — таймаут запроса в миллисекундах (по умолчанию: 300000). Установите `false` для отключения. +- `setCacheKey` — убедитесь, что ключ кэша всегда установлен для назначенного поставщика. + +Вы также можете настроить [локальные модели](/docs/models#local). [Подробнее ](/docs/models). + +--- + +#### Параметры, зависящие от поставщика + +Некоторые поставщики поддерживают дополнительные параметры конфигурации помимо общих настроек `timeout` и `apiKey`. + +##### Амазонка + +Amazon Bedrock поддерживает конфигурацию, специфичную для AWS: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` — регион AWS для Bedrock (по умолчанию переменная среды `AWS_REGION` или `us-east-1`) +- `profile` — именованный профиль AWS из `~/.aws/credentials` (по умолчанию переменная окружения `AWS_PROFILE`) +- `endpoint` — URL-адрес пользовательской конечной точки для конечных точек VPC. Это псевдоним общего параметра `baseURL`, использующий терминологию, специфичную для AWS. Если указаны оба параметра, `endpoint` имеет приоритет. + +:::примечание +Токены носителя (`AWS_BEARER_TOKEN_BEDROCK` или `/connect`) имеют приоритет над аутентификацией на основе профиля. Подробности см. в [приоритет аутентификации](/docs/providers#authentication-precedence). +::: + +[Подробнее о конфигурации Amazon Bedrock](/docs/providers#amazon-bedrock). + +--- + +### Темы + +Вы можете настроить тему, которую хотите использовать, в конфигурации OpenCode с помощью опции `theme`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[Подробнее здесь](/docs/themes). + +--- + +### Агенты + +Вы можете настроить специализированные агенты для конкретных задач с помощью опции `agent`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +Вы также можете определить агентов, используя файлы уценки в `~/.config/opencode/agents/` или `.opencode/agents/`. [Подробнее здесь](/docs/agents). + +--- + +### Агент по умолчанию + +Вы можете установить агента по умолчанию, используя опцию `default_agent`. Это определяет, какой агент используется, если ни один из них не указан явно. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +Агент по умолчанию должен быть основным агентом (а не субагентом). Это может быть встроенный агент, например `"build"` или `"plan"`, или [пользовательский агент](/docs/agents), который вы определили. Если указанный агент не существует или является субагентом, OpenCode вернется к `"build"` с предупреждением. + +Этот параметр применяется ко всем интерфейсам: TUI, CLI (`opencode run`), настольному приложению и действию GitHub. + +--- + +### Совместное использование + +Функцию [share](/docs/share) можно настроить с помощью опции `share`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +Это занимает: + +- `"manual"` — разрешить общий доступ вручную с помощью команд (по умолчанию). +- `"auto"` — автоматически делиться новыми беседами. +- `"disabled"` — полностью отключить общий доступ + +По умолчанию общий доступ установлен в ручной режим, в котором вам необходимо явно делиться разговорами с помощью команды `/share`. + +--- + +### Команды + +Вы можете настроить собственные команды для повторяющихся задач с помощью опции `command`. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +Вы также можете определять команды, используя файлы уценки в `~/.config/opencode/commands/` или `.opencode/commands/`. [Подробнее здесь](/docs/commands). + +--- + +### Сочетания клавиш + +Вы можете настроить привязки клавиш с помощью опции `keybinds`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[Подробнее здесь](/docs/keybinds). + +--- + +### Автообновление + +OpenCode автоматически загрузит все новые обновления при запуске. Вы можете отключить это с помощью опции `autoupdate`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +Если вы не хотите получать обновления, но хотите получать уведомления о появлении новой версии, установите для `autoupdate` значение `"notify"`. +Обратите внимание, что это работает только в том случае, если оно было установлено без использования менеджера пакетов, такого как Homebrew. + +--- + +### Форматеры + +Вы можете настроить форматировщики кода с помощью опции `formatter`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[Подробнее о форматтерах можно узнать здесь](/docs/formatters). + +--- + +### Разрешения + +По умолчанию открытый код **разрешает все операции**, не требуя явного разрешения. Вы можете изменить это, используя опцию `permission`. + +Например, чтобы гарантировать, что инструменты `edit` и `bash` требуют одобрения пользователя: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[Подробнее о разрешениях можно узнать здесь](/docs/permissions). + +--- + +### Уплотнение + +Вы можете управлять поведением сжатия контекста с помощью опции `compaction`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` — автоматически сжимать сеанс при заполнении контекста (по умолчанию: `true`). +- `prune` — удалить старые выходные данные инструмента для сохранения токенов (по умолчанию: `true`). + +--- + +### наблюдатель + +Вы можете настроить шаблоны игнорирования средства отслеживания файлов с помощью опции `watcher`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +Шаблоны соответствуют синтаксису glob. Используйте это, чтобы исключить зашумленные каталоги из просмотра файлов. + +--- + +### MCP-серверы + +Вы можете настроить серверы MCP, которые хотите использовать, с помощью опции `mcp`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[Подробнее здесь](/docs/mcp-servers). + +--- + +### Плагины + +[Плагины](/docs/plugins) расширяют OpenCode с помощью пользовательских инструментов, перехватчиков и интеграций. + +Поместите файлы плагина в `.opencode/plugins/` или `~/.config/opencode/plugins/`. Вы также можете загружать плагины из npm с помощью опции `plugin`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[Подробнее здесь](/docs/plugins). + +--- + +### Инструкции + +Вы можете настроить инструкции для используемой вами модели с помощью опции `instructions`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Для этого требуется массив путей и шаблонов glob для файлов инструкций. [Узнать больше +о правилах здесь ](/docs/rules). + +--- + +### Отключенные провайдеры + +Вы можете отключить поставщиков, которые загружаются автоматически, с помощью опции `disabled_providers`. Это полезно, если вы хотите запретить загрузку определенных поставщиков, даже если их учетные данные доступны. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::примечание +`disabled_providers` имеет приоритет над `enabled_providers`. +::: + +Опция `disabled_providers` принимает массив идентификаторов поставщиков. Когда провайдер отключен: + +- Он не будет загружен, даже если установлены переменные среды. +- Он не будет загружен, даже если ключи API настроены с помощью команды `/connect`. +- Модели поставщика не появятся в списке выбора моделей. + +--- + +### Включенные провайдеры + +Вы можете указать белый список поставщиков с помощью опции `enabled_providers`. Если этот параметр установлен, будут включены только указанные поставщики, а все остальные будут игнорироваться. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +Это полезно, если вы хотите ограничить OpenCode использованием только определенных поставщиков, а не отключать их по одному. + +:::примечание +`disabled_providers` имеет приоритет над `enabled_providers`. +::: + +Если поставщик указан как в `enabled_providers`, так и в `disabled_providers`, `disabled_providers` имеет приоритет для обратной совместимости. + +--- + +### Экспериментальный + +Ключ `experimental` содержит параметры, находящиеся в активной разработке. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::осторожность +Экспериментальные варианты не стабильны. Они могут быть изменены или удалены без предварительного уведомления. +::: + +--- + +## Переменные + +Вы можете использовать подстановку переменных в файлах конфигурации для ссылки на переменные среды и содержимое файлов. + +--- + +### переменные окружения + +Используйте `{env:VARIABLE_NAME}` для замены переменных среды: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +Если переменная среды не установлена, она будет заменена пустой строкой. + +--- + +### Файлы + +Используйте `{file:path/to/file}` для замены содержимого файла: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +Пути к файлам могут быть: + +- Относительно каталога файла конфигурации +- Или абсолютные пути, начинающиеся с `/` или `~`. + +Они полезны для: + +- Хранение конфиденциальных данных, таких как ключи API, в отдельных файлах. +- Включая большие файлы инструкций, не загромождая вашу конфигурацию. +- Совместное использование общих фрагментов конфигурации в нескольких файлах конфигурации. diff --git a/packages/web/src/content/docs/ru/custom-tools.mdx b/packages/web/src/content/docs/ru/custom-tools.mdx new file mode 100644 index 000000000..eb035c2e3 --- /dev/null +++ b/packages/web/src/content/docs/ru/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: Пользовательские инструменты +description: Создавайте инструменты, которые LLM может вызывать в открытом коде. +--- + +Пользовательские инструменты — это создаваемые вами функции, которые LLM может вызывать во время разговоров. Они работают вместе со [встроенными инструментами ](/docs/tools) открытого кода, такими как `read`, `write` и `bash`. + +--- + +## Создание инструмента + +Инструменты определяются как файлы **TypeScript** или **JavaScript**. Однако определение инструмента может вызывать сценарии, написанные на **любом языке** — TypeScript или JavaScript используются только для самого определения инструмента. + +--- + +### Расположение + +Их можно определить: + +- Локально, поместив их в каталог `.opencode/tools/` вашего проекта. +- Или глобально, поместив их в `~/.config/opencode/tools/`. + +--- + +### Структура + +Самый простой способ создания инструментов — использовать помощник `tool()`, который обеспечивает безопасность типов и проверку. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +**имя файла** становится **именем инструмента**. Вышеупомянутое создает инструмент `database`. + +--- + +#### Несколько инструментов в файле + +Вы также можете экспортировать несколько инструментов из одного файла. Каждый экспорт становится **отдельным инструментом** с именем **`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +При этом создаются два инструмента: `math_add` и `math_multiply`. + +--- + +### Аргументы + +Вы можете использовать `tool.schema`, то есть просто [Zod](https://zod.dev), для определения типов аргументов. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +Вы также можете импортировать [Zod](https://zod.dev) напрямую и вернуть простой объект: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### Контекст + +Инструменты получают контекст текущего сеанса: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +Используйте `context.directory` для рабочего каталога сеанса. +Используйте `context.worktree` для корня рабочего дерева git. + +--- + +## Примеры + +### Напишите инструмент на Python + +Вы можете писать свои инструменты на любом языке, который захотите. Вот пример сложения двух чисел с использованием Python. + +Сначала создайте инструмент как скрипт Python: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +Затем создайте определение инструмента, которое его вызывает: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +Здесь мы используем утилиту [`Bun.$`](https://bun.com/docs/runtime/shell) для запуска скрипта Python. diff --git a/packages/web/src/content/docs/ru/ecosystem.mdx b/packages/web/src/content/docs/ru/ecosystem.mdx new file mode 100644 index 000000000..a244c1445 --- /dev/null +++ b/packages/web/src/content/docs/ru/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: Экосистема +description: Проекты и интеграции, созданные с помощью OpenCode. +--- + +Коллекция проектов сообщества, построенных на OpenCode. + +:::примечание +Хотите добавить свой проект, связанный с OpenCode, в этот список? Разместите пиар. +::: + +Вы также можете посетить [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) и [opencode.cafe](https://opencode.cafe) — сообщество, объединяющее экосистему и сообщество. + +--- + +## Плагины + +| Имя | Описание | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | Автоматически запускайте сеансы OpenCode в изолированных песочницах Daytona с синхронизацией git и предварительным просмотром в реальном времени. | +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Автоматически внедрять заголовки сеансов Helicone для группировки запросов. | +| [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Автоматическое внедрение типов TypeScript/Svelte в файлы, считываемые с помощью инструментов поиска. | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Используйте подписку ChatGPT Plus/Pro вместо кредитов API. | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Используйте существующий план Gemini вместо выставления счетов через API. | +| [opencode-антигравитация-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Используйте бесплатные модели Антигравити вместо выставления счетов через API. | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Многоветвевая изоляция контейнеров разработки с мелкими клонами и автоматическим назначением портов. | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Плагин Google Antigradity OAuth с поддержкой поиска Google и более надежной обработкой API. | +| [opencode-динамический-контекст-обрезка](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Оптимизируйте использование токенов за счет сокращения выходных данных устаревших инструментов. | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Добавьте встроенную поддержку веб-поиска для поддерживаемых поставщиков в стиле Google. | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Позволяет агентам ИИ запускать фоновые процессы в PTY и отправлять им интерактивные данные. | +| [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Инструкции для неинтерактивных команд оболочки — предотвращают зависания из-за операций, зависящих от TTY. | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Отслеживайте использование OpenCode с помощью Wakatime | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Очистка таблиц уценок, созданных LLM | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | Редактирование кода в 10 раз быстрее с помощью API Morph Fast Apply и маркеров отложенного редактирования. | +| [о-мой-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Фоновые агенты, встроенные инструменты LSP/AST/MCP, курируемые агенты, совместимость с Claude Code | +| [уведомитель открытого кода](https://github.com/panta82/opencode-notificator) | Уведомления на рабочем столе и звуковые оповещения для сеансов OpenCode | +| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Уведомления на рабочем столе и звуковые оповещения о разрешениях, завершении и событиях ошибок. | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | Автоматическое именование сеансов Zellij на основе искусственного интеллекта на основе контекста OpenCode. | +| [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Разрешить агентам OpenCode отложенную загрузку подсказок по требованию с обнаружением и внедрением навыков. | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Постоянная память между сеансами с использованием Supermemory | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Интерактивный обзор плана с визуальными аннотациями и возможностью совместного использования в частном или автономном режиме. | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Расширьте открытый код/команды до мощной системы оркестровки с детальным управлением потоком данных. | +| [opencode-планировщик](https://github.com/different-ai/opencode-scheduler) | Планируйте повторяющиеся задания с помощью launchd (Mac) или systemd (Linux) с синтаксисом cron. | +| [микоде](https://github.com/vtemian/micode) | Структурированный мозговой штурм → План → Реализация рабочего процесса с непрерывностью сеанса | +| [октто](https://github.com/vtemian/octto) | Интерактивный пользовательский интерфейс браузера для мозгового штурма с помощью искусственного интеллекта с формами из нескольких вопросов | +| [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Фоновые агенты в стиле Claude Code с асинхронным делегированием и сохранением контекста. | +| [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Встроенные уведомления ОС для OpenCode — узнайте, когда задачи завершены | +| [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Комплексный пакет многоагентной оркестровки — 16 компонентов, одна установка | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Рабочие деревья git с нулевым трением для OpenCode | + +--- + +## Проекты + +| Имя | Описание | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [StreeX 1 | Discord-бот для управления сессиями OpenCode, построенный на SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Плагин Neovim для подсказок с поддержкой редактора, созданный на основе API | +| [портал](https://github.com/hosenur/portal) | Мобильный веб-интерфейс для OpenCode через Tailscale/VPN | +| [шаблон плагина с открытым кодом](https://github.com/zenobi-us/opencode-plugin-template/) | Шаблон для создания плагинов OpenCode | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Интерфейс Neovim для открытого кода — агент кодирования искусственного интеллекта на базе терминала | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Поставщик Vercel AI SDK для использования OpenCode через @opencode-ai/sdk | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | Веб-приложение или настольное приложение и расширение VS Code для OpenCode | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Плагин Obsidian, встраивающий OpenCode в пользовательский интерфейс Obsidian. | +| [OpenWork](https://github.com/different-ai/openwork) | Альтернатива Claude Cowork с открытым исходным кодом на базе OpenCode. | +| [ocx](https://github.com/kdcokenny/ocx) | Менеджер расширений OpenCode с переносимыми изолированными профилями. | +| [КодNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Настольное, веб-, мобильное и удаленное клиентское приложение для OpenCode | + +--- + +## Агенты + +| Имя | Описание | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [Агентный](https://github.com/Cluster444/agentic) | Модульные ИИ-агенты и команды для структурированной разработки | +| [opencode-агенты](https://github.com/darrenhinde/opencode-agents) | Конфигурации, подсказки, агенты и плагины для улучшения рабочих процессов. | diff --git a/packages/web/src/content/docs/ru/enterprise.mdx b/packages/web/src/content/docs/ru/enterprise.mdx new file mode 100644 index 000000000..e29879792 --- /dev/null +++ b/packages/web/src/content/docs/ru/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: Предприятие +description: Безопасное использование OpenCode в вашей организации. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise предназначен для организаций, которые хотят быть уверены, что их код и данные никогда не покинут инфраструктуру. Это можно сделать с помощью централизованной конфигурации, которая интегрируется с вашим единым входом и внутренним шлюзом AI. + +:::примечание +OpenCode не хранит ваш код или контекстные данные. +::: + +Чтобы начать работу с OpenCode Enterprise: + +1. Проведите испытание внутри своей команды. +2. **Свяжитесь с нами**, чтобы обсудить цены и варианты внедрения. + +--- + +## Пробный + +OpenCode имеет открытый исходный код и не хранит ваш код или контекстные данные, поэтому ваши разработчики могут просто [приступить к работе](/docs/) и провести пробную версию. + +--- + +### Обработка данных + +**OpenCode не хранит ваш код или контекстные данные.** Вся обработка происходит локально или посредством прямых вызовов API к вашему провайдеру ИИ. + +Это означает, что пока вы используете поставщика, которому доверяете, или внутреннего +Шлюз AI позволяет безопасно использовать OpenCode. + +Единственное предостережение — это дополнительная функция `/share`. + +--- + +#### Обмен беседами + +Если пользователь включает функцию `/share`, разговор и связанные с ним данные отправляются в службу, которую мы используем для размещения этих общих страниц на opencode.ai. + +В настоящее время данные передаются через периферийную сеть нашей CDN и кэшируются на периферии рядом с вашими пользователями. + +Мы рекомендуем вам отключить эту функцию для пробной версии. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[Подробнее о совместном использовании](/docs/share). + +--- + +### Владение кодом + +**Вы являетесь владельцем всего кода, созданного OpenCode.** Никаких лицензионных ограничений или претензий на право собственности нет. + +--- + +## Цены + +Мы используем модель «на рабочее место» для OpenCode Enterprise. Если у вас есть собственный шлюз LLM, мы не взимаем плату за используемые токены. Для получения более подробной информации о ценах и вариантах реализации **свяжитесь с нами**. + +--- + +## Развертывание + +После завершения пробной версии и готовности использовать OpenCode на +вашей организации, вы можете **связаться с нами**, чтобы обсудить +цены и варианты реализации. + +--- + +### Центральная конфигурация + +Мы можем настроить OpenCode для использования единой центральной конфигурации для всей вашей организации. + +Эта централизованная конфигурация может интегрироваться с вашим поставщиком единого входа и гарантирует всем пользователям доступ только к вашему внутреннему шлюзу AI. + +--- + +### Интеграция единого входа + +Через центральную конфигурацию OpenCode может интегрироваться с провайдером единого входа вашей организации для аутентификации. + +Это позволяет OpenCode получать учетные данные для вашего внутреннего шлюза AI через существующую систему управления идентификацией. + +--- + +### Внутренний шлюз AI + +Благодаря центральной конфигурации OpenCode также можно настроить на использование только вашего внутреннего шлюза AI. + +Вы также можете отключить всех других поставщиков ИИ, гарантируя, что все запросы будут проходить через утвержденную инфраструктуру вашей организации. + +--- + +### Самостоятельный хостинг + +Хотя мы рекомендуем отключить страницы общего доступа, чтобы гарантировать, что ваши данные никогда не исчезнут. +вашей организации, мы также можем помочь вам самостоятельно разместить их в вашей инфраструктуре. + +В настоящее время это находится в нашей дорожной карте. Если вам интересно, **дайте нам знать**. + +--- + +## Часто задаваемые вопросы + +

+Что такое OpenCode Enterprise? + +OpenCode Enterprise предназначен для организаций, которые хотят быть уверены, что их код и данные никогда не покинут инфраструктуру. Это можно сделать с помощью централизованной конфигурации, которая интегрируется с вашим единым входом и внутренним шлюзом AI. + +
+ +
+Как начать работу с OpenCode Enterprise? + +Просто начните с внутреннего испытания со своей командой. OpenCode по умолчанию не сохраняет ваш код или контекстные данные, что упрощает начало работы. + +Затем **свяжитесь с нами**, чтобы обсудить цены и варианты внедрения. + +
+ +
+Как работает корпоративное ценообразование? + +Мы предлагаем корпоративные цены за рабочее место. Если у вас есть собственный шлюз LLM, мы не взимаем плату за используемые токены. Для получения более подробной информации **свяжитесь с нами**, чтобы получить индивидуальное предложение, соответствующее потребностям вашей организации. + +
+ +
+Защищены ли мои данные с помощью OpenCode Enterprise? + +Да. OpenCode не хранит ваш код или контекстные данные. Вся обработка происходит локально или посредством прямых вызовов API вашего провайдера ИИ. Благодаря централизованной настройке и интеграции единого входа ваши данные остаются в безопасности в инфраструктуре вашей организации. + +
+ +
+Можем ли мы использовать собственный частный реестр NPM? + +OpenCode поддерживает частные реестры npm посредством встроенной поддержки файлов `.npmrc` Bun. Если ваша организация использует частный реестр, такой как JFrog Artifactory, Nexus или аналогичный, убедитесь, что разработчики прошли аутентификацию перед запуском OpenCode. + +Чтобы настроить аутентификацию с помощью вашего частного реестра: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +При этом создается `~/.npmrc` с данными аутентификации. OpenCode автоматически +возьми это. + +:::осторожность +Перед запуском OpenCode вы должны войти в частный реестр. +::: + +Альтернативно вы можете вручную настроить файл `.npmrc`: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Разработчики должны войти в частный реестр перед запуском OpenCode, чтобы гарантировать возможность установки пакетов из корпоративного реестра. + +
diff --git a/packages/web/src/content/docs/ru/formatters.mdx b/packages/web/src/content/docs/ru/formatters.mdx new file mode 100644 index 000000000..d0479327b --- /dev/null +++ b/packages/web/src/content/docs/ru/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: Форматеры +description: OpenCode использует средства форматирования, специфичные для языка. +--- + +OpenCode автоматически форматирует файлы после их записи или редактирования с использованием средств форматирования для конкретного языка. Это гарантирует, что создаваемый код будет соответствовать стилям кода вашего проекта. + +--- + +## Встроенный + +OpenCode поставляется с несколькими встроенными форматировщиками для популярных языков и платформ. Ниже приведен список форматтеров, поддерживаемых расширений файлов, а также необходимых команд или параметров конфигурации. + +| форматтер | Расширения | Требования | +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| правительство | .идти | Доступна команда `gofmt` | +| смешивание | .ex, .exs, .bias, .heex, .bend, .neex, .sface | Доступна команда `mix` | +| красивее | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml и [подробнее](https://prettier.io/docs/en/index.html) | Зависимость `prettier` в `package.json` | +| биом | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml и [подробнее](https://biomejs.dev/) | Конфигурационный файл `biome.json(c)` | +| зигзаг | .zig, .zon | Доступна команда `zig` | +| clang-формат | .c, .cpp, .h, .hpp, .ino и [подробнее](https://clang.llvm.org/docs/ClangFormat.html) | Конфигурационный файл `.clang-format` | +| ктлинт | .кт, .ктс | Доступна команда `ktlint` | +| ерш | .py, .pyi | Команда `ruff` доступна в конфигурации | +| ржавчина | .rs | Доступна команда `rustfmt` | +| грузовой контейнер | .rs | Доступна команда `cargo fmt` | +| уф | .py, .pyi | Доступна команда `uv` | +| рубокоп | .rb, .rake, .gemspec, .ru | Доступна команда `rubocop` | +| стандартный RB | .rb, .rake, .gemspec, .ru | Доступна команда `standardrb` | +| htmlbeautifier | .erb, .html.erb | Доступна команда `htmlbeautifier` | +| воздух | .Р | Доступна команда `air` | +| дротик | .dart | Доступна команда `dart` | +| ocamlformat | .мл, .мли | Доступна команда `ocamlformat` и файл конфигурации `.ocamlformat`. | +| терраформировать | .tf, .tfvars | Доступна команда `terraform` | +| светиться | .блеск | Доступна команда `gleam` | +| никсфмт | .nix | Доступна команда `nixfmt` | +| шфмт | .sh, .bash | Доступна команда `shfmt` | +| пинта | .php | Зависимость `laravel/pint` в `composer.json` | +| oxfmt (экспериментальный) | .js, .jsx, .ts, .tsx | Зависимость `oxfmt` в `package.json` и [экспериментальная переменная окружения flag](/docs/cli/#experimental) | +| ормол | .hs | Доступна команда `ormolu` | + +Поэтому, если ваш проект имеет `prettier` в вашем `package.json`, OpenCode автоматически его использует. + +--- + +## Как это работает + +Когда OpenCode записывает или редактирует файл, он: + +1. Проверяет расширение файла по всем включенным средствам форматирования. +2. Запускает соответствующую команду форматирования файла. +3. Автоматически применяет изменения форматирования. + +Этот процесс происходит в фоновом режиме, обеспечивая сохранение стилей кода без каких-либо действий вручную. + +--- + +## Настроить + +Вы можете настроить форматтеры через раздел `formatter` в конфигурации OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +Каждая конфигурация форматтера поддерживает следующее: + +| Свойство | Тип | Описание | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` | логическое значение | Установите для этого параметра значение `true`, чтобы отключить форматтер. | +| `command` | нить[] | Команда для форматирования | +| `environment` | объект | Переменные среды, которые необходимо установить при запуске средства форматирования | +| `extensions` | нить[] | Расширения файлов, которые должен обрабатывать этот форматтер | + +Давайте посмотрим на несколько примеров. + +--- + +### Отключение форматтеров + +Чтобы глобально отключить **все** средства форматирования, установите для `formatter` значение `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +Чтобы отключить **конкретный** форматтер, установите для `disabled` значение `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Пользовательские форматтеры + +Вы можете переопределить встроенные средства форматирования или добавить новые, указав команду, переменные среды и расширения файлов: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +Заполнитель **`$FILE`** в команде будет заменен путем к форматируемому файлу. diff --git a/packages/web/src/content/docs/ru/github.mdx b/packages/web/src/content/docs/ru/github.mdx new file mode 100644 index 000000000..0e5bfb525 --- /dev/null +++ b/packages/web/src/content/docs/ru/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: Используйте OpenCode в задачах и пул-реквестах GitHub. +--- + +OpenCode интегрируется с вашим рабочим процессом GitHub. Упомяните `/opencode` или `/oc` в своем комментарии, и OpenCode выполнит задачи в вашем средстве выполнения действий GitHub. + +--- + +## Функции + +- **Сортировка проблем**. Попросите OpenCode разобраться в проблеме и объяснить ее вам. +- **Исправить и внедрить**. Попросите OpenCode исправить проблему или реализовать функцию. И будет работать в новой ветке и подавать ПР со всеми изменениями. +- **Безопасность**: OpenCode запускается внутри бегунов вашего GitHub. + +--- + +## Установка + +Запустите следующую команду в проекте, который находится в репозитории GitHub: + +```bash +opencode github install +``` + +Это поможет вам установить приложение GitHub, создать рабочий процесс и настроить секреты. + +--- + +### Ручная настройка + +Или вы можете настроить его вручную. + +1. **Установите приложение GitHub** + + Перейдите на [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). Убедитесь, что он установлен в целевом репозитории. + +2. **Добавьте рабочий процесс** + + Добавьте следующий файл рабочего процесса в `.github/workflows/opencode.yml` в своем репозитории. Обязательно установите соответствующий `model` и необходимые ключи API в `env`. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **Храните ключи API в секрете** + + В **настройках** вашей организации или проекта разверните **Секреты и переменные** слева и выберите **Действия**. И добавьте необходимые ключи API. + +--- + +## Конфигурация + +- `model`: модель для использования с OpenCode. Принимает формат `provider/model`. Это **обязательно**. +- `agent`: используемый агент. Должен быть основным агентом. Возвращается к `default_agent` из конфигурации или к `"build"`, если не найден. +- `share`: следует ли предоставлять общий доступ к сеансу OpenCode. По умолчанию **true** для общедоступных репозиториев. +- `prompt`: дополнительный настраиваемый запрос для переопределения поведения по умолчанию. Используйте это, чтобы настроить обработку запросов OpenCode. +- `token`: дополнительный токен доступа GitHub для выполнения таких операций, как создание комментариев, фиксация изменений и открытие запросов на включение. По умолчанию OpenCode использует токен доступа к установке из приложения OpenCode GitHub, поэтому фиксации, комментарии и запросы на включение отображаются как исходящие из приложения. + + Кроме того, вы можете использовать [встроенный `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) средства запуска действий GitHub без установки приложения OpenCode GitHub. Просто не забудьте предоставить необходимые разрешения в вашем рабочем процессе: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + Вы также можете использовать [токены личного доступа](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT), если предпочитаете. + +--- + +## Поддерживаемые события + +OpenCode может быть запущен следующими событиями GitHub: + +| Тип события | Инициировано | Подробности | +| ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | Комментарий к проблеме или PR | Упомяните `/opencode` или `/oc` в своем комментарии. OpenCode считывает контекст и может создавать ветки, открывать PR или отвечать. | +| `pull_request_review_comment` | Комментируйте конкретные строки кода в PR. | Упоминайте `/opencode` или `/oc` при просмотре кода. OpenCode получает путь к файлу, номера строк и контекст сравнения. | +| `issues` | Проблема открыта или отредактирована | Автоматически запускать OpenCode при создании или изменении проблем. Требуется ввод `prompt`. | +| `pull_request` | PR открыт или обновлен | Автоматически запускать OpenCode при открытии, синхронизации или повторном открытии PR. Полезно для автоматических обзоров. | +| `schedule` | Расписание на основе Cron | Запускайте OpenCode по расписанию. Требуется ввод `prompt`. Вывод поступает в журналы и PR (комментариев нет). | +| `workflow_dispatch` | Ручной триггер из пользовательского интерфейса GitHub | Запускайте OpenCode по требованию на вкладке «Действия». Требуется ввод `prompt`. Вывод идет в логи и PR. | + +### Пример расписания + +Запускайте OpenCode по расписанию для выполнения автоматизированных задач: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +Для запланированных событий вход `prompt` **обязателен**, поскольку нет комментария, из которого можно было бы извлечь инструкции. Запланированные рабочие процессы выполняются без пользовательского контекста для проверки разрешений, поэтому рабочий процесс должен предоставлять `contents: write` и `pull-requests: write`, если вы ожидаете, что OpenCode будет создавать ветки или PR. + +--- + +### Пример запроса на включение + +Автоматически просматривать PR при их открытии или обновлении: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Если для событий `pull_request` не указан `prompt`, OpenCode по умолчанию проверяет запрос на включение. + +--- + +### Пример сортировки проблем + +Автоматически сортируйте новые проблемы. В этом примере фильтруется учетные записи старше 30 дней, чтобы уменьшить количество спама: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +Для событий `issues` вход `prompt` **обязателен**, поскольку нет комментария, из которого можно было бы извлечь инструкции. + +--- + +## Пользовательские подсказки + +Переопределите приглашение по умолчанию, чтобы настроить поведение OpenCode для вашего рабочего процесса. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Это полезно для обеспечения соблюдения конкретных критериев проверки, стандартов кодирования или приоритетных областей, имеющих отношение к вашему проекту. + +--- + +## Примеры + +Вот несколько примеров того, как вы можете использовать OpenCode в GitHub. + +- **Объясните проблему** + + Добавьте этот комментарий в выпуск GitHub. + + ``` + /opencode explain this issue + ``` + + OpenCode прочитает всю ветку, включая все комментарии, и ответит с четким объяснением. + +- **Исправить проблему** + + В выпуске GitHub скажите: + + ``` + /opencode fix this + ``` + + А OpenCode создаст новую ветку, внедрит изменения и откроет PR с изменениями. + +- **Проверьте запросы на запросы и внесите изменения** + + Оставьте следующий комментарий к пиару на GitHub. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + OpenCode внедрит запрошенное изменение и зафиксирует его в том же PR. + +- **Просмотрите отдельные строки кода** + + Оставляйте комментарии непосредственно к строкам кода на вкладке «Файлы» PR. OpenCode автоматически определяет файл, номера строк и контекст различий, чтобы предоставить точные ответы. + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + При комментировании определенных строк OpenCode получает: + - Точный файл, который просматривается + - Конкретные строки кода + - Окружающий контекст различий + - Информация о номере строки + + Это позволяет выполнять более целевые запросы без необходимости вручную указывать пути к файлам или номера строк. diff --git a/packages/web/src/content/docs/ru/gitlab.mdx b/packages/web/src/content/docs/ru/gitlab.mdx new file mode 100644 index 000000000..ce8999777 --- /dev/null +++ b/packages/web/src/content/docs/ru/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: Используйте OpenCode в задачах GitLab и мерж-реквестах. +--- + +OpenCode интегрируется с вашим рабочим процессом GitLab через конвейер GitLab CI/CD или с GitLab Duo. + +В обоих случаях OpenCode будет работать на ваших программах GitLab. + +--- + +## ГитЛаб. + +OpenCode работает в обычном конвейере GitLab. Вы можете встроить его в конвейер как [CI-компонент](https://docs.gitlab.com/ee/ci/components/) + +Здесь мы используем созданный сообществом компонент CI/CD для OpenCode — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### Функции + +- **Использовать пользовательскую конфигурацию для каждого задания**. Настройте OpenCode с помощью пользовательского каталога конфигурации, например `./config/#custom-directory`, чтобы включать или отключать функциональность для каждого вызова OpenCode. +- **Минимальная настройка**: компонент CI настраивает OpenCode в фоновом режиме, вам нужно только создать конфигурацию OpenCode и начальное приглашение. +- **Гибкость**: компонент CI поддерживает несколько входных данных для настройки его поведения. + +--- + +### Настраивать + +1. Сохраните JSON аутентификации OpenCode как переменные среды CI типа файла в разделе **Настройки** > **CI/CD** > **Переменные**. Обязательно пометьте их как «Замаскированные и скрытые». +2. Добавьте следующее в файл `.gitlab-ci.yml`. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +Дополнительные сведения и варианты использования см. в документации ](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) для этого компонента. + +--- + +## GitLab Дуэт + +OpenCode интегрируется с вашим рабочим процессом GitLab. +Упомяните `@opencode` в комментарии, и OpenCode выполнит задачи в вашем конвейере GitLab CI. + +--- + +### Функции + +- **Сортировка проблем**. Попросите OpenCode разобраться в проблеме и объяснить ее вам. +- **Исправить и внедрить**. Попросите OpenCode исправить проблему или реализовать функцию. + Он создаст новую ветку и создаст мерж-реквест с изменениями. +- **Безопасность**: OpenCode работает на ваших программах GitLab. + +--- + +### Настраивать + +OpenCode работает в вашем конвейере GitLab CI/CD. Вот что вам понадобится для его настройки: + +:::кончик +Ознакомьтесь с [**документацией GitLab**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) для получения актуальных инструкций. +::: + +1. Настройте свою среду GitLab +2. Настройка CI/CD +3. Получите ключ API поставщика моделей ИИ +4. Создать учетную запись службы +5. Настройка переменных CI/CD +6. Создайте файл конфигурации потока, вот пример: + +
+ + Конфигурация потока + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +Подробные инструкции можно найти в документации по агентам GitLab CLI](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/). + +--- + +### Примеры + +Вот несколько примеров того, как вы можете использовать OpenCode в GitLab. + +:::кончик +Вы можете настроить использование триггерной фразы, отличной от `@opencode`. +::: + +- **Объясните проблему** + + Добавьте этот комментарий в выпуск GitLab. + + ``` + @opencode explain this issue + ``` + + OpenCode прочитает проблему и ответит с четким объяснением. + +- **Исправить проблему** + + В выпуске GitLab скажите: + + ``` + @opencode fix this + ``` + + OpenCode создаст новую ветку, внедрит изменения и откроет мерж-реквест с изменениями. + +- **Просмотр мерж-реквестов** + + Оставьте следующий комментарий к мерж-реквесту GitLab. + + ``` + @opencode review this merge request + ``` + + OpenCode рассмотрит мерж-реквест и предоставит отзыв. diff --git a/packages/web/src/content/docs/ru/ide.mdx b/packages/web/src/content/docs/ru/ide.mdx new file mode 100644 index 000000000..62ea3bbdc --- /dev/null +++ b/packages/web/src/content/docs/ru/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: Расширение OpenCode для VS Code, Cursor и других IDE. +--- + +OpenCode интегрируется с VS Code, Cursor или любой IDE, поддерживающей терминал. Просто запустите `opencode` в терминале, чтобы начать. + +--- + +## Использование + +- **Быстрый запуск**: используйте `Cmd+Esc` (Mac) или `Ctrl+Esc` (Windows/Linux), чтобы открыть OpenCode в разделенном представлении терминала, или сосредоточьте внимание на существующем сеансе терминала, если он уже запущен. +- **Новый сеанс**: используйте `Cmd+Shift+Esc` (Mac) или `Ctrl+Shift+Esc` (Windows/Linux), чтобы начать новый сеанс терминала OpenCode, даже если он уже открыт. Вы также можете нажать кнопку OpenCode в пользовательском интерфейсе. +- **Узнавание контекста**: автоматически делитесь своим текущим выбором или вкладкой с помощью OpenCode. +- **File Reference Shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references. Например, `@File#L37-42`. + +--- + +## Установка + +Чтобы установить OpenCode на VS Code и популярные форки, такие как Cursor, Windsurf, VSCodium: + +1. Открыть код VS +2. Откройте встроенный терминал +3. Запустите `opencode` - расширение установится автоматически. + +С другой стороны, если вы хотите использовать собственную IDE при запуске `/editor` или `/export` из TUI, вам необходимо установить `export EDITOR="code --wait"`. [Подробнее](/docs/tui/#editor-setup). + +--- + +### Ручная установка + +Найдите **OpenCode** в магазине расширений и нажмите **Установить**. + +--- + +### Поиск неисправностей + +Если расширение не устанавливается автоматически: + +- Убедитесь, что вы используете `opencode` во встроенном терминале. +- Убедитесь, что CLI для вашей IDE установлен: + - Для кода VS: команда `code`. + - Для курсора: команда `cursor`. + - Для виндсерфинга: команда `windsurf`. + - Для VSCodium: команда `codium`. + - Если нет, запустите `Cmd+Shift+P` (Mac) или `Ctrl+Shift+P` (Windows/Linux) и найдите «Команда оболочки: установите команду «код» в PATH» (или эквивалент для вашей IDE). +- Убедитесь, что у VS Code есть разрешение на установку расширений. diff --git a/packages/web/src/content/docs/ru/index.mdx b/packages/web/src/content/docs/ru/index.mdx new file mode 100644 index 000000000..58b022cba --- /dev/null +++ b/packages/web/src/content/docs/ru/index.mdx @@ -0,0 +1,359 @@ +--- +title: Введение +description: Начните работу с OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) — это агент кодирования искусственного интеллекта с открытым исходным кодом. Он доступен в виде интерфейса на базе терминала, настольного приложения или расширения IDE. + +![OpenCode TUI с темой открытого кода](../../../assets/lander/screenshot.png) + +Давайте начнем. + +--- + +#### Предварительные условия + +Чтобы использовать OpenCode в вашем терминале, вам понадобится: + +1. Современный эмулятор терминала, например: + - [WezTerm](https://wezterm.org), кроссплатформенный + - [Alacritty](https://alacritty.org), кроссплатформенный + - [Ghostty](https://ghostty.org), Linux и macOS + - [Kitty](https://sw.kovidgoyal.net/kitty/), Linux и macOS + +2. Ключи API для поставщиков LLM, которых вы хотите использовать. + +--- + +## Установить + +Самый простой способ установить OpenCode — через сценарий установки. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +Вы также можете установить его с помощью следующих команд: + +- **Использование Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **Использование Homebrew в macOS и Linux** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > Мы рекомендуем использовать кран OpenCode для получения самых последних версий. Официальная формула `brew install opencode` поддерживается командой Homebrew и обновляется реже. + +- **Использование Paru в Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### Окна + +:::tip[Рекомендуется: используйте WSL] +Для наилучшей работы в Windows мы рекомендуем использовать [Подсистема Windows для Linux (WSL)](/docs/windows-wsl). Он обеспечивает лучшую производительность и полную совместимость с функциями OpenCode. +::: + +- **Используя шоколадный** + + ```bash + choco install opencode + ``` + +- **Использование Scoop** + + ```bash + scoop install opencode + ``` + +- **Использование NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **Использование Мизе** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **Использование Docker** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +В настоящее время находится поддержка установки OpenCode в Windows с помощью Bun. + +Вы также можете получить двоичный файл из файла [Releases](https://github.com/anomalyco/opencode/releases). + +--- + +## Настроить + +С OpenCode вы можете использовать любого поставщика LLM, настроив его ключи API. + +Если вы новичок в использовании поставщиков LLM, мы рекомендуем использовать [OpenCode Zen](/docs/zen). +Это тщательно подобранный список моделей, протестированных и проверенных OpenCode. +команда. + +1. Запустите команду `/connect` в TUI, выберите opencode и перейдите по адресу [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Войдите в систему, добавьте свои платежные данные и скопируйте ключ API. + +3. Вставьте свой ключ API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +Альтернативно вы можете выбрать одного из других поставщиков. [Подробнее](/docs/providers#directory). + +--- + +## Инициализировать + +Теперь, когда вы настроили поставщика, вы можете перейти к проекту, который +над которым вы хотите работать. + +```bash +cd /path/to/project +``` + +И запустите OpenCode. + +```bash +opencode +``` + +Затем инициализируйте OpenCode для проекта, выполнив следующую команду. + +```bash frame="none" +/init +``` + +Это позволит OpenCode проанализировать ваш проект и создать файл `AGENTS.md` в +корень проекта. + +:::кончик +Вам следует зафиксировать файл `AGENTS.md` вашего проекта в Git. +::: + +Это помогает OpenCode понять структуру проекта и шаблоны кодирования. +использовал. + +--- + +## Использование + +Теперь вы готовы использовать OpenCode для работы над своим проектом. Не стесняйтесь спрашивать это +что-либо! + +Если вы новичок в использовании агента кодирования ИИ, вот несколько примеров, которые могут вам помочь. +помощь. + +--- + +### Задавайте вопросы + +Вы можете попросить OpenCode объяснить вам кодовую базу. + +:::кончик +Используйте ключ `@` для нечеткого поиска файлов в проекте. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +Это полезно, если есть часть кодовой базы, над которой вы не работали. + +--- + +### Добавить функции + +Вы можете попросить OpenCode добавить новые функции в ваш проект. Хотя мы сначала рекомендуем попросить его создать план. + +1. **Составьте план** + + OpenCode имеет _режим планирования_, который отключает возможность вносить изменения и + вместо этого предложите _как_ реализовать эту функцию. + + Переключитесь на него с помощью клавиши **Tab**. Вы увидите индикатор этого в правом нижнем углу. + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + Теперь давайте опишем, что мы хотим от него. + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + Вы хотите предоставить OpenCode достаточно подробностей, чтобы понять, чего вы хотите. Это помогает + поговорить с ним так, как будто вы разговариваете с младшим разработчиком в своей команде. + + :::кончик + Дайте OpenCode много контекста и примеров, чтобы помочь ему понять, что вы + хотеть. + ::: + +2. **Итерация плана** + + Как только он предоставит вам план, вы можете оставить ему отзыв или добавить более подробную информацию. + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::кончик + Перетащите изображения в терминал, чтобы добавить их в подсказку. + ::: + + OpenCode может сканировать любые изображения, которые вы ему предоставляете, и добавлять их в командную строку. Ты можешь + сделайте это, перетащив изображение в терминал. + +3. **Создайте функцию** + + Как только вы почувствуете себя комфортно с планом, вернитесь в _режим сборки_, + снова нажав клавишу **Tab**. + + ```bash frame="none" + + ``` + + И попросить его внести изменения. + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### Внести изменения + +Для более простых изменений вы можете попросить OpenCode создать его напрямую. +без необходимости предварительного рассмотрения плана. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +Вы хотите убедиться, что вы предоставляете достаточно деталей, чтобы OpenCode сделал правильный выбор. +изменения. + +--- + +### Отменить изменения + +Допустим, вы просите OpenCode внести некоторые изменения. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Но ты понимаешь, что это не то, чего ты хотел. Вы **можете отменить** изменения +с помощью команды `/undo`. + +```bash frame="none" +/undo +``` + +OpenCode теперь отменит внесенные вами изменения и покажет исходное сообщение. +снова. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Отсюда вы можете настроить подсказку и попросить OpenCode повторить попытку. + +:::кончик +Вы можете запустить `/undo` несколько раз, чтобы отменить несколько изменений. +::: + +Или вы **можете повторить** изменения с помощью команды `/redo`. + +```bash frame="none" +/redo +``` + +--- + +## Делиться + +Разговоры, которые вы ведете с OpenCode, можно [поделиться с вашим +команда](/docs/share). + +```bash frame="none" +/share +``` + +Это создаст ссылку на текущий разговор и скопирует ее в буфер обмена. + +:::примечание +По умолчанию общий доступ к беседам не предоставляется. +::: + +Вот [пример диалога](https://opencode.ai/s/4XP1fce5) с OpenCode. + +--- + +## Настроить + +И все! Теперь вы профессионал в использовании OpenCode. + +Чтобы создать свою собственную, мы рекомендуем [выбрать тему](/docs/themes), [настроить привязки клавиш](/docs/keybinds), [настроить средства форматирования кода](/docs/formatters), [создать собственные команды](/docs/commands) или поиграться с файлом [OpenCode config](/docs/config). diff --git a/packages/web/src/content/docs/ru/keybinds.mdx b/packages/web/src/content/docs/ru/keybinds.mdx new file mode 100644 index 000000000..43707f098 --- /dev/null +++ b/packages/web/src/content/docs/ru/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: Сочетания клавиш +description: Настройте свои сочетания клавиш. +--- + +OpenCode имеет список сочетаний клавиш, которые вы можете настроить через конфигурацию OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## Ключ лидера + +OpenCode использует клавишу `leader` для большинства сочетаний клавиш. Это позволяет избежать конфликтов в вашем терминале. + +По умолчанию `ctrl+x` является ведущей клавишей, и для большинства действий требуется сначала нажать ведущую клавишу, а затем сочетание клавиш. Например, чтобы начать новый сеанс, сначала нажмите `ctrl+x`, а затем нажмите `n`. + +Вам не обязательно использовать выносную клавишу для привязок клавиш, но мы рекомендуем это сделать. + +--- + +## Отключить привязку клавиш + +Вы можете отключить привязку клавиш, добавив ключ в свою конфигурацию со значением «none». + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## Ярлыки команд на рабочем столе + +Ввод приглашения настольного приложения OpenCode поддерживает распространенные сочетания клавиш в стиле Readline/Emacs для редактирования текста. Они встроены и в настоящее время не настраиваются через `opencode.json`. + +| Ярлык | Действие | +| -------- | ---------------------------------------- | +| `ctrl+a` | Перейти к началу текущей строки | +| `ctrl+e` | Перейти к концу текущей строки | +| `ctrl+b` | Переместить курсор на один символ назад | +| `ctrl+f` | Переместить курсор на один символ вперед | +| `alt+b` | Переместить курсор на одно слово назад | +| `alt+f` | Переместить курсор вперед на одно слово | +| `ctrl+d` | Удалить символ под курсором | +| `ctrl+k` | Убить до конца строки | +| `ctrl+u` | Убить до начала строки | +| `ctrl+w` | Убить предыдущее слово | +| `alt+d` | Убить следующее слово | +| `ctrl+t` | Транспонировать символы | +| `ctrl+g` | Отменить всплывающие окна/прервать выполнение ответа | + +--- + +## Shift+Ввод + +Некоторые терминалы по умолчанию не отправляют клавиши-модификаторы с Enter. Возможно, вам придется настроить терминал на отправку `Shift+Enter` в качестве escape-последовательности. + +### Терминал Windows + +Откройте свой `settings.json` по адресу: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +Добавьте это в массив `actions` корневого уровня: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Добавьте это в массив `keybindings` корневого уровня: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Сохраните файл и перезапустите терминал Windows или откройте новую вкладку. diff --git a/packages/web/src/content/docs/ru/lsp.mdx b/packages/web/src/content/docs/ru/lsp.mdx new file mode 100644 index 000000000..b37c055ac --- /dev/null +++ b/packages/web/src/content/docs/ru/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: ЛСП Серверы +description: OpenCode интегрируется с вашими серверами LSP. +--- + +OpenCode интегрируется с вашим протоколом языкового сервера (LSP), чтобы помочь LLM взаимодействовать с вашей кодовой базой. Он использует диагностику для предоставления обратной связи LLM. + +--- + +## Встроенный + +OpenCode поставляется с несколькими встроенными LSP-серверами для популярных языков: + +| ЛСП Сервер | Расширения | Требования | +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +| астро | .astro | Автоматическая установка для проектов Astro | +| бить | .sh, .bash, .zsh, .ksh | Автоматически устанавливает сервер языка bash | +| лязг | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Автоматическая установка для проектов C/C++. | +| csharp | .cs | `.NET SDK` установлен | +| Clojure-LSP | .clj, .cljs, .cljc, .edn | Доступна команда `clojure-lsp` | +| дротик | .dart | Доступна команда `dart` | +| дено | .ts, .tsx, .js, .jsx, .mjs | Доступна команда `deno` (автоматически определяет deno.json/deno.jsonc) | +| эликсир-ls | .ex, .exs | Доступна команда `elixir` | +| эслинт | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | Зависимость `eslint` в проекте | +| fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` установлен | +| светиться | .блеск | Доступна команда `gleam` | +| гоплс | .идти | Доступна команда `go` | +| хлс | .hs, .lhs | Доступна команда `haskell-language-server-wrapper` | +| jdtls | .java | `Java SDK (version 21+)` установлен | +| Котлин-LS | .кт, .ктс | Автоматическая установка для проектов Kotlin | +| Луа-ЛС | .lua | Автоматическая установка для проектов Lua | +| снег | .nix | Доступна команда `nixd` | +| ocaml-lsp | .мл, .мли | Доступна команда `ocamllsp` | +| бычья линта | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | Зависимость `oxlint` в проекте | +| PHP | .php | Автоматическая установка для проектов PHP | +| призма | .prisma | Доступна команда `prisma` | +| пирит | .py, .pyi | Установлена ​​зависимость `pyright` | +| рубин-lsp (рубокоп) | .rb, .rake, .gemspec, .ru | Доступны команды `ruby` и `gem`. | +| ржавчина | .rs | Доступна команда `rust-analyzer` | +| исходный комплект-lsp | .swift, .objc, .objcpp | `swift` установлен (`xcode` в macOS) | +| стройный | .стройный | Автоматическая установка для проектов Svelte | +| терраформировать | .tf, .tfvars | Автоматическая установка из выпусков GitHub | +| tinymist | .тип, .типк | Автоматическая установка из выпусков GitHub | +| машинопись | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | Зависимость `typescript` в проекте | +| вид | .vue | Автоматическая установка для проектов Vue | +| Ямл-лс | .yaml, .yml | Автоматически устанавливает Red Hat yaml-language-server | +| Злс | .zig, .zon | Доступна команда `zig` | + +Серверы LSP автоматически включаются при обнаружении одного из указанных выше расширений файлов и выполнении требований. + +:::примечание +Вы можете отключить автоматическую загрузку LSP-сервера, установив для переменной среды `OPENCODE_DISABLE_LSP_DOWNLOAD` значение `true`. +::: + +--- + +## Как это работает + +Когда opencode открывает файл, он: + +1. Проверяет расширение файла на всех включенных серверах LSP. +2. Запускает соответствующий сервер LSP, если он еще не запущен. + +--- + +## Настроить + +Вы можете настроить серверы LSP через раздел `lsp` в конфигурации открытого кода. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Каждый LSP-сервер поддерживает следующее: + +| Свойство | Тип | Описание | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` | логическое значение | Установите для этого параметра значение `true`, чтобы отключить сервер LSP. | +| `command` | нить[] | Команда запуска LSP-сервера | +| `extensions` | нить[] | Расширения файлов, которые должен обрабатывать этот сервер LSP | +| `env` | объект | Переменные среды, которые нужно установить при запуске сервера | +| `initialization` | объект | Параметры инициализации для отправки на сервер LSP | + +Давайте посмотрим на несколько примеров. + +--- + +### Переменные среды + +Используйте свойство `env` для установки переменных среды при запуске сервера LSP: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### Параметры инициализации + +Используйте свойство `initialization` для передачи параметров инициализации на LSP-сервер. Это настройки, специфичные для сервера, отправляемые во время запроса LSP `initialize`: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::примечание +Параметры инициализации зависят от сервера LSP. Проверьте документацию вашего LSP-сервера на наличие доступных опций. +::: + +--- + +### Отключение LSP-серверов + +Чтобы отключить **все** LSP-серверы глобально, установите для `lsp` значение `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +Чтобы отключить **конкретный** LSP-сервер, установите для `disabled` значение `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Пользовательские LSP-серверы + +Вы можете добавить собственные LSP-серверы, указав команду и расширения файлов: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## Дополнительная информация + +### PHP Intelephense + +PHP Intelephense предлагает дополнительные функции через лицензионный ключ. Вы можете предоставить лицензионный ключ, поместив (только) ключ в текстовый файл по адресу: + +- В macOS/Linux: `$HOME/intelephense/licence.txt` +- В Windows: `%USERPROFILE%/intelephense/licence.txt` + +Файл должен содержать только лицензионный ключ без какого-либо дополнительного содержимого. diff --git a/packages/web/src/content/docs/ru/mcp-servers.mdx b/packages/web/src/content/docs/ru/mcp-servers.mdx new file mode 100644 index 000000000..8996ae56f --- /dev/null +++ b/packages/web/src/content/docs/ru/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: MCP-серверы +description: Добавьте локальные и удаленные инструменты MCP. +--- + +Вы можете добавить внешние инструменты в OpenCode, используя _Model Context Protocol_ или MCP. OpenCode поддерживает как локальные, так и удаленные серверы. + +После добавления инструменты MCP автоматически становятся доступными для LLM наряду со встроенными инструментами. + +--- + +#### Предостережения + +Когда вы используете сервер MCP, он добавляет контекст. Это может быстро сложиться, если у вас много инструментов. Поэтому мы рекомендуем быть осторожными с тем, какие серверы MCP вы используете. + +:::кончик +Серверы MCP добавляются к вашему контексту, поэтому будьте осторожны с тем, какие из них вы включаете. +::: + +Некоторые серверы MCP, такие как сервер MCP GitHub, имеют тенденцию добавлять много токенов и могут легко превысить ограничение контекста. + +--- + +## Давать возможность + +Вы можете определить серверы MCP в своем [OpenCode Config](https://opencode.ai/docs/config/) в разделе `mcp`. Добавьте каждому MCP уникальное имя. Вы можете обратиться к этому MCP по имени при запросе LLM. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +Вы также можете отключить сервер, установив для `enabled` значение `false`. Это полезно, если вы хотите временно отключить сервер, не удаляя его из конфигурации. + +--- + +### Переопределение удаленных настроек по умолчанию + +Организации могут предоставлять серверы MCP по умолчанию через свою конечную точку `.well-known/opencode`. Эти серверы могут быть отключены по умолчанию, что позволяет пользователям выбирать те, которые им нужны. + +Чтобы включить определенный сервер из удаленной конфигурации вашей организации, добавьте его в локальную конфигурацию с помощью `enabled: true`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +Значения вашей локальной конфигурации переопределяют удаленные значения по умолчанию. Дополнительную информацию см. в [config Priorce](/docs/config#precedence-order). + +--- + +## Местный + +Добавьте локальные серверы MCP с помощью `type` в `"local"` внутри объекта MCP. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +Эта команда запускает локальный сервер MCP. Вы также можете передать список переменных среды. + +Например, вот как можно добавить тестовый сервер [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +И чтобы использовать его, я могу добавить `use the mcp_everything tool` в свои подсказки. + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### Параметры + +Вот все варианты настройки локального сервера MCP. + +| Вариант | Тип | Необходимый | Описание | +| ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | Нить | Да | Тип подключения к серверу MCP должен быть `"local"`. | +| `command` | Множество | Да | Команда и аргументы для запуска сервера MCP. | +| `environment` | Объект | | Переменные среды, которые необходимо установить при запуске сервера. | +| `enabled` | логическое значение | | Включите или отключите сервер MCP при запуске. | +| `timeout` | Число | | Тайм-аут в мс для получения инструментов с сервера MCP. По умолчанию 5000 (5 секунд). | + +--- + +## Удаленный + +Добавьте удаленные серверы MCP, установив для `type` значение `"remote"`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` — это URL-адрес удаленного сервера MCP, а с помощью параметра `headers` вы можете передать список заголовков. + +--- + +#### Параметры + +| Вариант | Тип | Необходимый | Описание | +| --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | Нить | Да | Тип подключения к серверу MCP должен быть `"remote"`. | +| `url` | Нить | Да | URL-адрес удаленного сервера MCP. | +| `enabled` | логическое значение | | Включите или отключите сервер MCP при запуске. | +| `headers` | Объект | | Заголовки для отправки с запросом. | +| `oauth` | Объект | | Конфигурация аутентификации OAuth. См. раздел [OAuth](#oauth) ниже. | +| `timeout` | Число | | Тайм-аут в мс для получения инструментов с сервера MCP. По умолчанию 5000 (5 секунд). | + +--- + +## OAuth + +OpenCode автоматически обрабатывает аутентификацию OAuth для удаленных серверов MCP. Когда серверу требуется аутентификация, OpenCode: + +1. Обнаружьте ответ 401 и инициируйте поток OAuth. +2. Используйте **Динамическую регистрацию клиента (RFC 7591)**, если это поддерживается сервером. +3. Надежно храните токены для будущих запросов + +--- + +### Автоматический + +Для большинства серверов MCP с поддержкой OAuth не требуется никакой специальной настройки. Просто настройте удаленный сервер: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +Если сервер требует аутентификации, OpenCode предложит вам пройти аутентификацию при первой попытке его использования. Если нет, вы можете [вручную запустить поток ](#authenticating) с помощью `opencode mcp auth `. + +--- + +### Предварительная регистрация + +Если у вас есть учетные данные клиента от поставщика сервера MCP, вы можете их настроить: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### Аутентификация + +Вы можете вручную активировать аутентификацию или управлять учетными данными. + +Аутентификация с помощью определенного сервера MCP: + +```bash +opencode mcp auth my-oauth-server +``` + +Перечислите все серверы MCP и их статус аутентификации: + +```bash +opencode mcp list +``` + +Удалить сохраненные учетные данные: + +```bash +opencode mcp logout my-oauth-server +``` + +Команда `mcp auth` откроет ваш браузер для авторизации. После того как вы авторизуетесь, OpenCode надежно сохранит токены в `~/.local/share/opencode/mcp-auth.json`. + +--- + +#### Отключение OAuth + +Если вы хотите отключить автоматический OAuth для сервера (например, для серверов, которые вместо этого используют ключи API), установите для `oauth` значение `false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### Параметры OAuth + +| Вариант | Тип | Описание | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` | Объект \ | ЛОЖЬ | Объект конфигурации OAuth или `false`, чтобы отключить автоматическое обнаружение OAuth. | +| `clientId` | Нить | Идентификатор клиента OAuth. Если этот параметр не указан, будет предпринята попытка динамической регистрации клиента. | +| `clientSecret` | Нить | Секрет клиента OAuth, если этого требует сервер авторизации. | +| `scope` | Нить | Области OAuth для запроса во время авторизации. | + +#### Отладка + +Если удаленный сервер MCP не может аутентифицироваться, вы можете диагностировать проблемы с помощью: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +Команда `mcp debug` показывает текущий статус аутентификации, проверяет соединение HTTP и пытается выполнить поток обнаружения OAuth. + +--- + +## Управлять + +Ваши MCP доступны в виде инструментов OpenCode наряду со встроенными инструментами. Таким образом, вы можете управлять ими через конфигурацию OpenCode, как и любым другим инструментом. + +--- + +### Глобальный + +Это означает, что вы можете включать или отключать их глобально. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +Мы также можем использовать шаблон glob, чтобы отключить все соответствующие MCP. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +Здесь мы используем шаблон `my-mcp*` для отключения всех MCP. + +--- + +### За агента + +Если у вас большое количество серверов MCP, вы можете включить их только для каждого агента и отключить глобально. Для этого: + +1. Отключите его как инструмент глобально. +2. В вашей [конфигурации агента](/docs/agents#tools) включите сервер MCP в качестве инструмента. + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### Шаблоны глобусов + +Шаблон glob использует простые шаблоны подстановки регулярных выражений: + +- `*` соответствует нулю или более любого символа (например, `"my-mcp*"` соответствует `my-mcp_search`, `my-mcp_list` и т. д.). +- `?` соответствует ровно одному символу. +- Все остальные символы совпадают буквально + +:::примечание +Инструменты сервера MCP регистрируются с именем сервера в качестве префикса, поэтому, чтобы отключить все инструменты для сервера, просто используйте: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## Примеры + +Ниже приведены примеры некоторых распространенных серверов MCP. Вы можете отправить PR, если хотите документировать другие серверы. + +--- + +### Часовой + +Добавьте [сервер Sentry MCP](https://mcp.sentry.dev) для взаимодействия с вашими проектами и проблемами Sentry. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +После добавления конфигурации пройдите аутентификацию с помощью Sentry: + +```bash +opencode mcp auth sentry +``` + +Откроется окно браузера для завершения процесса OAuth и подключения OpenCode к вашей учетной записи Sentry. + +После аутентификации вы можете использовать инструменты Sentry в своих подсказках для запроса данных о проблемах, проектах и ​​ошибках. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Контекст7 + +Добавьте [сервер Context7 MCP](https://github.com/upstash/context7) для поиска в документах. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +Если вы зарегистрировали бесплатную учетную запись, вы можете использовать свой ключ API и получить более высокие ограничения скорости. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +Здесь мы предполагаем, что у вас установлена ​​переменная среды `CONTEXT7_API_KEY`. + +Добавьте `use context7` в запросы на использование сервера Context7 MCP. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +Альтернативно вы можете добавить что-то подобное в свой файл [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Греп от Верселя + +Добавьте сервер MCP [Grep от Vercel](https://grep.app) для поиска по фрагментам кода на GitHub. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +Поскольку мы назвали наш сервер MCP `gh_grep`, вы можете добавить `use the gh_grep tool` в свои запросы, чтобы агент мог его использовать. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +Альтернативно вы можете добавить что-то подобное в свой файл [AGENTS.md](/docs/rules/). + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/ru/models.mdx b/packages/web/src/content/docs/ru/models.mdx new file mode 100644 index 000000000..3420c5fa6 --- /dev/null +++ b/packages/web/src/content/docs/ru/models.mdx @@ -0,0 +1,223 @@ +--- +title: Модели +description: Настройка поставщика и модели LLM. +--- + +OpenCode использует [AI SDK](https://ai-sdk.dev/) и [Models.dev](https://models.dev) для поддержки **более 75 поставщиков LLM** и поддерживает запуск локальных моделей. + +--- + +## Провайдеры + +Большинство популярных провайдеров предварительно загружены по умолчанию. Если вы добавили учетные данные для поставщика с помощью команды `/connect`, они будут доступны при запуске OpenCode. + +Узнайте больше о [providers](/docs/providers). + +--- + +## Выберите модель + +После того, как вы настроили своего провайдера, вы можете выбрать нужную модель, введя: + +```bash frame="none" +/models +``` + +--- + +## Рекомендуемые модели + +Моделей очень много, новые выходят каждую неделю. + +:::кончик +Рассмотрите возможность использования одной из моделей, которые мы рекомендуем. +::: + +Однако лишь немногие из них хороши как в генерации кода, так и в вызове инструментов. + +Вот несколько моделей, которые хорошо работают с OpenCode (в произвольном порядке). (Это не исчерпывающий список и не обязательно актуальный): + +- GPT 5.2 +- Кодекс GPT 5.1 +- Закрыть работу 4.5 +- Клод Сонет 4.5 +- Минимакс М2.1 +- Близнецы 3 Про + +--- + +## Установить значение по умолчанию + +Чтобы установить одну из них в качестве модели по умолчанию, вы можете установить ключ `model` в вашем +Конфигурация OpenCode. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Здесь полный идентификатор `provider_id/model_id`. Например, если вы используете [OpenCode Zen](/docs/zen), вы должны использовать `opencode/gpt-5.1-codex` для кодекса GPT 5.1. + +Если вы настроили [пользовательский поставщик](/docs/providers#custom), `provider_id` — это ключ из части `provider` вашей конфигурации, а `model_id` — это ключ из `provider.models`. + +--- + +## Настройка моделей + +Вы можете глобально настроить параметры модели через файл config. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Здесь мы настраиваем глобальные параметры для двух встроенных моделей: `gpt-5` при доступе через поставщика `openai` и `claude-sonnet-4-20250514` при доступе через поставщика `anthropic`. +Названия встроенных поставщиков и моделей можно найти на сайте [Models.dev](https://models.dev). + +Вы также можете настроить эти параметры для любых используемых вами агентов. Конфигурация агента переопределяет любые глобальные параметры здесь. [Подробнее](/docs/agents/#additional). + +Вы также можете определить собственные варианты, расширяющие встроенные. Варианты позволяют настраивать разные параметры для одной и той же модели без создания повторяющихся записей: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## Варианты + +Многие модели поддерживают несколько вариантов с разными конфигурациями. OpenCode поставляется со встроенными вариантами по умолчанию для популярных провайдеров. + +### Встроенные варианты + +OpenCode поставляется с вариантами по умолчанию для многих провайдеров: + +**Антропный**: + +- `high` — Бюджет с высоким мышлением (по умолчанию) +- `max` — Максимальный бюджет мышления + +**Открытый AI**: + +Зависит от модели, но примерно: + +- `none` — Никаких рассуждений. +- `minimal` — Минимальные усилия рассуждения +- `low` — Низкие усилия по рассуждению. +- `medium` – средние усилия рассуждения. +- `high` — Большие усилия по рассуждению. +- `xhigh` — сверхвысокие мыслительные усилия. + +**Google**: + +- `low` – меньший бюджет усилий/токенов. +- `high` — более высокий бюджет усилий/токенов + +:::кончик +Этот список не является исчерпывающим. Многие другие провайдеры также имеют встроенные настройки по умолчанию. +::: + +### Пользовательские варианты + +Вы можете переопределить существующие варианты или добавить свои собственные: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### Варианты цикла + +Используйте сочетание клавиш `variant_cycle` для быстрого переключения между вариантами. [Подробнее ](/docs/keybinds). + +--- + +## Загрузка моделей + +Когда OpenCode запускается, он проверяет модели в следующем порядке приоритета: + +1. Флаг командной строки `--model` или `-m`. Формат тот же, что и в файле конфигурации: `provider_id/model_id`. + +2. Список моделей в конфигурации OpenCode. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + Здесь используется формат `provider/model`. + +3. Последняя использованная модель. + +4. Первая модель, использующая внутренний приоритет. diff --git a/packages/web/src/content/docs/ru/modes.mdx b/packages/web/src/content/docs/ru/modes.mdx new file mode 100644 index 000000000..19fe35be1 --- /dev/null +++ b/packages/web/src/content/docs/ru/modes.mdx @@ -0,0 +1,331 @@ +--- +title: Режимы +description: Различные режимы для разных случаев использования. +--- + +:::осторожность +Режимы теперь настраиваются с помощью опции `agent` в конфигурации открытого кода. +Опция `mode` устарела. [Подробнее ](/docs/agents). +::: + +Режимы в открытом коде позволяют настраивать поведение, инструменты и подсказки для различных вариантов использования. + +Он имеет два встроенных режима: **сборка** и **планирование**. Вы можете настроить +эти или настройте свои собственные через конфигурацию открытого кода. + +Вы можете переключаться между режимами во время сеанса или настраивать их в своем файле конфигурации. + +--- + +## Встроенный + +opencode имеет два встроенных режима. + +--- + +### Строить + +Сборка — это режим **по умолчанию** со всеми включенными инструментами. Это стандартный режим разработки, в котором вам необходим полный доступ к файловым операциям и системным командам. + +--- + +### План + +Ограниченный режим, предназначенный для планирования и анализа. В режиме плана по умолчанию отключены следующие инструменты: + +- `write` – невозможно создавать новые файлы. +- `edit` – невозможно изменить существующие файлы, за исключением файлов, расположенных по адресу `.opencode/plans/*.md`, для детализации самого плана. +- `patch` – невозможно применить исправления. +- `bash` — невозможно выполнить команды оболочки. + +Этот режим полезен, если вы хотите, чтобы ИИ анализировал код, предлагал изменения или создавал планы без внесения каких-либо фактических изменений в вашу кодовую базу. + +--- + +## Переключение + +Переключаться между режимами можно во время сеанса с помощью клавиши _Tab_. Или настроенную вами привязку клавиш `switch_mode`. + +См. также: [Formatters](/docs/formatters) для получения информации о конфигурации форматирования кода. + +--- + +## Настроить + +Вы можете настроить встроенные режимы или создать свои собственные посредством настройки. Режимы можно настроить двумя способами: + +### Конфигурация JSON + +Настройте режимы в файле конфигурации `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Конфигурация уценки + +Вы также можете определить режимы, используя файлы уценки. Поместите их в: + +- Глобальный: `~/.config/opencode/modes/` +- Проект: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Имя файла уценки становится именем режима (например, `review.md` создает режим `review`). + +Давайте рассмотрим эти параметры конфигурации подробно. + +--- + +### Модель + +Используйте конфигурацию `model`, чтобы переопределить модель по умолчанию для этого режима. Полезно для использования разных моделей, оптимизированных под разные задачи. Например, более быстрая модель планирования и более эффективная модель реализации. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Температура + +Управляйте случайностью и креативностью ответов ИИ с помощью конфигурации `temperature`. Более низкие значения делают ответы более целенаправленными и детерминированными, а более высокие значения повышают креативность и вариативность. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Значения температуры обычно находятся в диапазоне от 0,0 до 1,0: + +- **0,0–0,2**: очень целенаправленные и детерминированные ответы, идеальные для анализа кода и планирования. +- **0,3–0,5**: сбалансированные ответы с некоторой креативностью, подходят для общих задач развития. +- **0,6–1,0**: более творческие и разнообразные ответы, полезные для мозгового штурма и исследования. + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Если температура не указана, открытый код использует значения по умолчанию для конкретной модели (обычно 0 для большинства моделей, 0,55 для моделей Qwen). + +--- + +### Быстрый + +Укажите собственный файл системных подсказок для этого режима с помощью конфигурации `prompt`. Файл подсказки должен содержать инструкции, специфичные для целей режима. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Этот путь указан относительно того, где находится файл конфигурации. Так что это работает для +как глобальная конфигурация открытого кода, так и конфигурация конкретного проекта. + +--- + +### Инструменты + +Контролируйте, какие инструменты доступны в этом режиме, с помощью конфигурации `tools`. Вы можете включить или отключить определенные инструменты, установив для них значение `true` или `false`. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +Если инструменты не указаны, все инструменты включены по умолчанию. + +--- + +#### Доступные инструменты + +Вот всеми инструментами можно управлять через конфигурацию режима. + +| Инструмент | Описание | +| ----------- | ----------------------- | +| ХХ0ГГ | Выполнение команд оболочки | +| ХХ0ГГ | Изменить существующие файлы | +| ХХ0ГГ | Создание новых файлов | +| ХХ0ГГ | Чтение содержимого файла | +| ХХ0ГГ | Поиск содержимого файла | +| ХХ0ГГ | Найти файлы по шаблону | +| ХХ0ГГ | Вывести содержимое каталога | +| ХХ0ГГ | Применение патчей к файлам | +| ХХ0ГГ | Управляйте списками дел | +| ХХ0ГГ | Чтение списков дел | +| ХХ0ГГ | Получить веб-контент | + +--- + +## Пользовательские режимы + +Вы можете создавать свои собственные режимы, добавляя их в конфигурацию. Вот примеры использования обоих подходов: + +### Использование конфигурации JSON + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Использование файлов уценки + +Создайте файлы режимов в `.opencode/modes/` для режимов, специфичных для проекта, или в `~/.config/opencode/modes/` для глобальных режимов: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### Варианты использования + +Вот несколько распространенных случаев использования различных режимов. + +- **Режим сборки**: полная работа по разработке со всеми включенными инструментами. +- **Режим планирования**: анализ и планирование без внесения изменений. +- **Режим проверки**: проверка кода с доступом только для чтения и инструментами документирования. +- **Режим отладки**: сосредоточен на исследовании с включенными инструментами bash и чтения. +- **Режим «Документы»**: запись документации с использованием файловых операций, но без системных команд. + +Вы также можете обнаружить, что разные модели подходят для разных случаев использования. diff --git a/packages/web/src/content/docs/ru/network.mdx b/packages/web/src/content/docs/ru/network.mdx new file mode 100644 index 000000000..795031d36 --- /dev/null +++ b/packages/web/src/content/docs/ru/network.mdx @@ -0,0 +1,57 @@ +--- +title: Сеть +description: Настройте прокси и пользовательские сертификаты. +--- + +OpenCode поддерживает стандартные переменные среды прокси-сервера и пользовательские сертификаты для сетевых сред предприятия. + +--- + +## Прокси + +OpenCode учитывает стандартные переменные среды прокси. + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::осторожность +TUI взаимодействует с локальным HTTP-сервером. Вы должны обойти прокси-сервер для этого соединения, чтобы избежать петель маршрутизации. +::: + +Вы можете настроить порт и имя хоста сервера, используя [CLI flags](/docs/cli#run). + +--- + +### Аутентификация + +Если ваш прокси-сервер требует базовой аутентификации, включите учетные данные в URL-адрес. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::осторожность +Избегайте жесткого кодирования паролей. Используйте переменные среды или безопасное хранилище учетных данных. +::: + +Для прокси-серверов, требующих расширенной аутентификации, например NTLM или Kerberos, рассмотрите возможность использования шлюза LLM, поддерживающего ваш метод аутентификации. + +--- + +## Таможенные сертификаты + +Если ваше предприятие использует собственные центры сертификации для HTTPS-соединений, настройте OpenCode, чтобы доверять им. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +Это работает как для прокси-соединений, так и для прямого доступа к API. diff --git a/packages/web/src/content/docs/ru/permissions.mdx b/packages/web/src/content/docs/ru/permissions.mdx new file mode 100644 index 000000000..104aaf657 --- /dev/null +++ b/packages/web/src/content/docs/ru/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: Разрешения +description: Контролируйте, какие действия требуют одобрения для выполнения. +--- + +OpenCode использует конфигурацию `permission`, чтобы решить, должно ли данное действие выполняться автоматически, запрашивать вас или блокироваться. + +Начиная с `v1.1.1`, устаревшая логическая конфигурация `tools` устарела и была объединена с `permission`. Старая конфигурация `tools` по-прежнему поддерживается для обеспечения обратной совместимости. + +--- + +## Действия + +Каждое правило разрешения разрешается в одно из: + +- `"allow"` — запуск без одобрения +- `"ask"` — запрос на одобрение +- `"deny"` — заблокировать действие + +--- + +## Конфигурация + +Вы можете устанавливать разрешения глобально (с помощью `*`) и переопределять определенные инструменты. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +Вы также можете установить все разрешения одновременно: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## Детальные правила (синтаксис объекта) + +Для большинства разрешений вы можете использовать объект для применения различных действий на основе входных данных инструмента. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +Правила оцениваются по шаблону, при этом **выигрывает последнее совпадающее правило**. Обычно сначала ставится универсальное правило `"*"`, а после него — более конкретные правила. + +### Подстановочные знаки + +В шаблонах разрешений используется простое сопоставление с подстановочными знаками: + +- `*` соответствует нулю или более любого символа. +- `?` соответствует ровно одному символу +- Все остальные символы совпадают буквально + +### Расширение домашнего каталога + +Вы можете использовать `~` или `$HOME` в начале шаблона для ссылки на ваш домашний каталог. Это особенно полезно для правил [`external_directory`](#external-directories). + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### Внешние каталоги + +Используйте `external_directory`, чтобы разрешить вызовы инструментов, затрагивающие пути за пределами рабочего каталога, в котором был запущен OpenCode. Это применимо к любому инструменту, который принимает путь в качестве входных данных (например, `read`, `edit`, `list`, `glob`, `grep` и многие команды `bash`). + +Расширение дома (например, `~/...`) влияет только на запись шаблона. Он не делает внешний путь частью текущего рабочего пространства, поэтому пути за пределами рабочего каталога все равно должны быть разрешены через `external_directory`. + +Например, это позволяет получить доступ ко всему, что находится под `~/projects/personal/`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +Любой каталог, разрешенный здесь, наследует те же настройки по умолчанию, что и текущая рабочая область. Поскольку для [`read` по умолчанию установлено значение `allow`](#defaults), чтение также разрешено для записей под `external_directory`, если оно не переопределено. Добавьте явные правила, когда инструмент должен быть ограничен в этих путях, например, блокировать редактирование при сохранении чтения: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +Держите список сосредоточенным на доверенных путях и добавляйте дополнительные правила разрешения или запрета по мере необходимости для других инструментов (например, `bash`). + +--- + +## Доступные разрешения + +Разрешения OpenCode привязаны к имени инструмента, а также к нескольким мерам безопасности: + +- `read` — чтение файла (соответствует пути к файлу) +- `edit` — все модификации файлов (охватывает `edit`, `write`, `patch`, `multiedit`) +- `glob` — подстановка файла (соответствует шаблону подстановки) +- `grep` — поиск по контенту (соответствует шаблону регулярного выражения) +- `list` — список файлов в каталоге (соответствует пути к каталогу) +- `bash` — запуск команд оболочки (соответствует проанализированным командам, например `git status --porcelain`) +- `task` — запуск субагентов (соответствует типу субагента) +- `skill` — загрузка навыка (соответствует названию навыка) +- `lsp` — выполнение запросов LSP (в настоящее время не детализированных) +- `todoread`, `todowrite` — чтение/обновление списка дел. +- `webfetch` — получение URL-адреса (соответствует URL-адресу) +- `websearch`, `codesearch` — поиск в сети/коде (соответствует запросу) +- `external_directory` — срабатывает, когда инструмент касается путей за пределами рабочего каталога проекта. +- `doom_loop` — срабатывает, когда один и тот же вызов инструмента повторяется 3 раза с одинаковым вводом. + +--- + +## По умолчанию + +Если вы ничего не укажете, OpenCode запустится с разрешенных значений по умолчанию: + +- Большинство разрешений по умолчанию имеют значение `"allow"`. +- `doom_loop` и `external_directory` по умолчанию равны `"ask"`. +- `read` — это `"allow"`, но файлы `.env` по умолчанию запрещены: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## Что означает «Спросить» + +Когда OpenCode запрашивает одобрение, пользовательский интерфейс предлагает три результата: + +- `once` — утвердить только этот запрос +- `always` — одобрять будущие запросы, соответствующие предложенным шаблонам (до конца текущего сеанса OpenCode). +- `reject` — отклонить запрос + +Набор шаблонов, которые одобрит `always`, предоставляется инструментом (например, утверждения bash обычно включают в белый список безопасный префикс команды, такой как `git status*`). + +--- + +## Агенты + +Вы можете переопределить разрешения для каждого агента. Разрешения агента объединяются с глобальной конфигурацией, и правила агента имеют приоритет. [Подробнее](/docs/agents#permissions) о разрешениях агента. + +:::примечание +Более подробные примеры сопоставления с образцом см. в разделе [Детальные правила (синтаксис объекта)](#granular-rules-object-syntax) выше. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +Вы также можете настроить разрешения агента в Markdown: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::кончик +Используйте сопоставление с образцом для команд с аргументами. `"grep *"` разрешает `grep pattern file.txt`, а сам `"grep"` блокирует его. Такие команды, как `git status`, работают по умолчанию, но требуют явного разрешения (например, `"git status *"`) при передаче аргументов. +::: diff --git a/packages/web/src/content/docs/ru/plugins.mdx b/packages/web/src/content/docs/ru/plugins.mdx new file mode 100644 index 000000000..7b47eee78 --- /dev/null +++ b/packages/web/src/content/docs/ru/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: Плагины +description: Напишите свои собственные плагины для расширения OpenCode. +--- + +Плагины позволяют расширять OpenCode, подключаясь к различным событиям и настраивая поведение. Вы можете создавать плагины для добавления новых функций, интеграции с внешними сервисами или изменения поведения OpenCode по умолчанию. + +Для примера ознакомьтесь с [plugins](/docs/ecosystem#plugins), созданными сообществом. + +--- + +## Используйте плагин + +Есть два способа загрузки плагинов. + +--- + +### Из локальных файлов + +Поместите файлы JavaScript или TypeScript в каталог плагина. + +- `.opencode/plugins/` – плагины уровня проекта. +- `~/.config/opencode/plugins/` — глобальные плагины + +Файлы в этих каталогах автоматически загружаются при запуске. + +--- + +### Из НПМ + +Укажите пакеты npm в файле конфигурации. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +Поддерживаются как обычные, так и ограниченные пакеты npm. + +Просмотрите доступные плагины в папке [ecosystem](/docs/ecosystem#plugins). + +--- + +### Как устанавливаются плагины + +**Плагины npm** устанавливаются автоматически с помощью Bun при запуске. Пакеты и их зависимости кэшируются в `~/.cache/opencode/node_modules/`. + +**Локальные плагины** загружаются непосредственно из каталога плагинов. Чтобы использовать внешние пакеты, вы должны создать `package.json` в своем каталоге конфигурации (см. [Зависимости](#dependencies)) или опубликовать плагин в npm и [добавить его в свой config](/docs/config#plugins). + +--- + +### Порядок загрузки + +Плагины загружаются из всех источников, и все хуки запускаются последовательно. Порядок загрузки следующий: + +1. Глобальная конфигурация (`~/.config/opencode/opencode.json`) +2. Конфигурация проекта (`opencode.json`) +3. Глобальный каталог плагинов (`~/.config/opencode/plugins/`) +4. Каталог плагинов проекта (`.opencode/plugins/`) + +Дубликаты пакетов npm с тем же именем и версией загружаются один раз. Однако локальный плагин и плагин npm со схожими именами загружаются отдельно. + +--- + +## Создать плагин + +Плагин — это **модуль JavaScript/TypeScript**, который экспортирует один или несколько плагинов. +функции. Каждая функция получает объект контекста и возвращает объект перехватчика. + +--- + +### Зависимости + +Локальные плагины и специальные инструменты могут использовать внешние пакеты npm. Добавьте `package.json` в каталог конфигурации с необходимыми вам зависимостями. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode запускает `bun install` при запуске для их установки. Затем ваши плагины и инструменты смогут импортировать их. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### Базовая структура + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +Функция плагина получает: + +- `project`: Текущая информация о проекте. +- `directory`: текущий рабочий каталог. +- `worktree`: путь к рабочему дереву git. +- `client`: клиент SDK с открытым кодом для взаимодействия с ИИ. +- `$`: [оболочка API](https://bun.com/docs/runtime/shell) Бана для выполнения команд. + +--- + +### Поддержка TypeScript + +Для плагинов TypeScript вы можете импортировать типы из пакета плагина: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### События + +Плагины могут подписываться на события, как показано ниже в разделе «Примеры». Вот список различных доступных событий. + +#### Командные события + +- ХХ0ГГ + +#### События файла + +- ХХ0ГГ +- ХХ0ГГ + +#### События установки + +- ХХ0ГГ + +#### События ЛСП + +- ХХ0ГГ +- ХХ0ГГ + +#### События сообщений + +- ХХ0ГГ +- ХХ0ГГ +- ХХ0ГГ +- ХХ0ГГ + +#### События разрешения + +- ХХ0ГГ +- ХХ0ГГ + +#### События сервера + +- ХХ0ГГ + +#### События сессии + +- ХХ0ГГ +- ХХ0ГГ +- ХХ0ГГ +- ХХ0ГГ +- ХХ0ГГ +- ХХ0ГГ +- ХХ0ГГ +- ХХ0ГГ + +#### События + +- ХХ0ГГ + +#### События оболочки + +- ХХ0ГГ + +#### События инструмента + +- ХХ0ГГ +- ХХ0ГГ + +#### Мероприятия ТУИ + +- ХХ0ГГ +- ХХ0ГГ +- ХХ0ГГ + +--- + +## Примеры + +Вот несколько примеров плагинов, которые вы можете использовать для расширения открытого кода. + +--- + +### Отправлять уведомления + +Отправляйте уведомления при возникновении определенных событий: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +Мы используем `osascript` для запуска AppleScript на macOS. Здесь мы используем его для отправки уведомлений. + +:::примечание +Если вы используете настольное приложение OpenCode, оно может автоматически отправлять системные уведомления, когда ответ готов или когда возникает ошибка сеанса. +::: + +--- + +### защита .env + +Запретите открытому коду читать файлы `.env`: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### Внедрение переменных среды + +Внедряйте переменные среды во все процессы выполнения оболочки (инструменты искусственного интеллекта и пользовательские терминалы): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### Пользовательские инструменты + +Плагины также могут добавлять в открытый код собственные инструменты: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +Помощник `tool` создает собственный инструмент, который может вызывать открытый код. Он принимает функцию схемы Zod и возвращает определение инструмента: + +- `description`: Что делает инструмент +- `args`: схема Zod для аргументов инструмента. +- `execute`: функция, которая запускается при вызове инструмента. + +Ваши пользовательские инструменты будут доступны для открытия кода наряду со встроенными инструментами. + +--- + +### Ведение журнала + +Используйте `client.app.log()` вместо `console.log` для структурированного ведения журнала: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +Уровни: `debug`, `info`, `warn`, `error`. Подробности см. в документации SDK](https://opencode.ai/docs/sdk). + +--- + +### Уплотняющие крюки + +Настройте контекст, включаемый при сжатии сеанса: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +Хук `experimental.session.compacting` срабатывает до того, как LLM сгенерирует сводку продолжения. Используйте его для внедрения контекста, специфичного для домена, который будет пропущен при запросе на сжатие по умолчанию. + +Вы также можете полностью заменить запрос на уплотнение, установив `output.prompt`: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +Если установлен `output.prompt`, он полностью заменяет приглашение на сжатие по умолчанию. Массив `output.context` в этом случае игнорируется. diff --git a/packages/web/src/content/docs/ru/providers.mdx b/packages/web/src/content/docs/ru/providers.mdx new file mode 100644 index 000000000..c7d001dd1 --- /dev/null +++ b/packages/web/src/content/docs/ru/providers.mdx @@ -0,0 +1,1889 @@ +--- +title: Провайдеры +description: Использование любого провайдера LLM в OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode использует [AI SDK](https://ai-sdk.dev/) и [Models.dev](https://models.dev) для поддержки **более 75 поставщиков LLM** и поддерживает запуск локальных моделей. + +Чтобы добавить провайдера, вам необходимо: + +1. Добавьте ключи API для провайдера с помощью команды `/connect`. +2. Настройте провайдера в вашей конфигурации OpenCode. + +--- + +### Реквизиты для входа + +Когда вы добавляете ключи API провайдера с помощью команды `/connect`, они сохраняются +в XX0ГГ. + +--- + +### Конфигурация + +Вы можете настроить поставщиков через раздел `provider` в вашем OpenCode. +конфиг. + +--- + +#### Базовый URL + +Вы можете настроить базовый URL-адрес для любого провайдера, установив параметр `baseURL`. Это полезно при использовании прокси-сервисов или пользовательских конечных точек. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## Открытый код Нет + +OpenCode Zen — это список моделей, предоставленный командой OpenCode, которые были +протестировано и проверено на хорошую работу с OpenCode. [Подробнее](/docs/zen). + +:::кончик +Если вы новичок, мы рекомендуем начать с OpenCode Zen. +::: + +1. Запустите команду `/connect` в TUI, выберите opencode и перейдите по адресу [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. Войдите в систему, добавьте свои платежные данные и скопируйте ключ API. + +3. Вставьте свой ключ API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите `/models` в TUI, чтобы просмотреть список рекомендуемых нами моделей. + + ```txt + /models + ``` + +Он работает как любой другой поставщик в OpenCode и его использование совершенно необязательно. + +--- + +## Каталог + +Рассмотрим некоторых провайдеров подробнее. Если вы хотите добавить провайдера в +список, смело открывайте пиар. + +:::примечание +Не видите здесь провайдера? Разместите пиар. +::: + +--- + +### 302.ИИ + +1. Перейдите в консоль 302.AI](https://302.ai/), создайте учетную запись и сгенерируйте ключ API. + +2. Запустите команду `/connect` и найдите **302.AI**. + + ```txt + /connect + ``` + +3. Введите свой ключ API 302.AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель. + + ```txt + /models + ``` + +--- + +### Амазонка + +Чтобы использовать Amazon Bedrock с OpenCode: + +1. Перейдите в **Каталог моделей** в консоли Amazon Bedrock и запросите + доступ к нужным моделям. + + :::кончик + Вам необходимо иметь доступ к нужной модели в Amazon Bedrock. + ::: + +2. **Настройте аутентификацию** одним из следующих способов: + + #### Переменные среды (быстрый старт) + + Установите одну из этих переменных среды при запуске открытого кода: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + Или добавьте их в свой профиль bash: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### Файл конфигурации (рекомендуется) + + Для конкретной или постоянной конфигурации проекта используйте `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **Доступные варианты:** + - `region` – регион AWS (например, `us-east-1`, `eu-west-1`). + - `profile` – именованный профиль AWS из `~/.aws/credentials`. + - `endpoint` — URL-адрес пользовательской конечной точки для конечных точек VPC (псевдоним для общей опции `baseURL`). + + :::кончик + Параметры файла конфигурации имеют приоритет над переменными среды. + ::: + + #### Дополнительно: конечные точки VPC + + Если вы используете конечные точки VPC для Bedrock: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::примечание + Параметр `endpoint` — это псевдоним общего параметра `baseURL`, использующий терминологию, специфичную для AWS. Если указаны и `endpoint`, и `baseURL`, `endpoint` имеет приоритет. + ::: + + #### Методы аутентификации + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: создайте пользователя IAM и сгенерируйте ключи доступа в консоли AWS. + - **`AWS_PROFILE`**: использовать именованные профили из `~/.aws/credentials`. Сначала настройте `aws configure --profile my-profile` или `aws sso login`. + - **`AWS_BEARER_TOKEN_BEDROCK`**: создание долгосрочных ключей API из консоли Amazon Bedrock. + - **`AWS_WEB_IDENTITY_TOKEN_FILE`/`AWS_ROLE_ARN`**: для EKS IRSA (роли IAM для учетных записей служб) или других сред Kubernetes с федерацией OIDC. Эти переменные среды автоматически вводятся Kubernetes при использовании аннотаций учетной записи службы. + + #### Приоритет аутентификации + + Amazon Bedrock использует следующий приоритет аутентификации: + 1. **Токен носителя** — переменная среды `AWS_BEARER_TOKEN_BEDROCK` или токен из команды `/connect`. + 2. **Цепочка учетных данных AWS** — профиль, ключи доступа, общие учетные данные, роли IAM, токены веб-идентификации (EKS IRSA), метаданные экземпляра. + + :::примечание + Когда токен-носитель установлен (через `/connect` или `AWS_BEARER_TOKEN_BEDROCK`), он имеет приоритет над всеми методами учетных данных AWS, включая настроенные профили. + ::: + +3. Запустите команду `/models`, чтобы выбрать нужную модель. + + ```txt + /models + ``` + +:::примечание +Для пользовательских профилей вывода используйте имя модели и поставщика в ключе и задайте для свойства `id` значение arn. Это обеспечивает правильное кэширование: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### антропный + +1. После регистрации введите команду `/connect` и выберите Anthropic. + + ```txt + /connect + ``` + +2. Здесь вы можете выбрать опцию **Claude Pro/Max**, и ваш браузер откроется. + и попросите вас пройти аутентификацию. + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. Теперь все модели Anthropic должны быть доступны при использовании команды `/models`. + + ```txt + /models + ``` + +:::информация +Использование вашей подписки Claude Pro/Max в OpenCode официально не поддерживается [Anthropic](https://anthropic.com). +::: + +##### Использование ключей API + +Вы также можете выбрать **Создать ключ API**, если у вас нет подписки Pro/Max. Он также откроет ваш браузер и попросит вас войти в Anthropic и предоставит вам код, который вы можете вставить в свой терминал. + +Или, если у вас уже есть ключ API, вы можете выбрать **Ввести ключ API вручную** и вставить его в свой терминал. + +--- + +### Azure OpenAI + +:::примечание +Если вы столкнулись с ошибками «Извините, но я не могу помочь с этим запросом», попробуйте изменить фильтр содержимого с **DefaultV2** на **Default** в своем ресурсе Azure. +::: + +1. Перейдите на [портал Azure](https://portal.azure.com/) и создайте ресурс **Azure OpenAI**. Вам понадобится: + - **Имя ресурса**: оно становится частью вашей конечной точки API (`https://RESOURCE_NAME.openai.azure.com/`). + - **Ключ API**: `KEY 1` или `KEY 2` из вашего ресурса. + +2. Перейдите в [Azure AI Foundry](https://ai.azure.com/) и разверните модель. + + :::примечание + Для правильной работы открытого кода имя развертывания должно совпадать с именем модели. + ::: + +3. Запустите команду `/connect` и найдите **Azure**. + + ```txt + /connect + ``` + +4. Введите свой ключ API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Задайте имя ресурса как переменную среды: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + Или добавьте его в свой профиль bash: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. Запустите команду `/models`, чтобы выбрать развернутую модель. + + ```txt + /models + ``` + +--- + +### Когнитивные службы Azure + +1. Перейдите на [портал Azure](https://portal.azure.com/) и создайте ресурс **Azure OpenAI**. Вам понадобится: + - **Имя ресурса**: оно становится частью вашей конечной точки API (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`). + - **Ключ API**: `KEY 1` или `KEY 2` из вашего ресурса. + +2. Перейдите в [Azure AI Foundry](https://ai.azure.com/) и разверните модель. + + :::примечание + Для правильной работы открытого кода имя развертывания должно совпадать с именем модели. + ::: + +3. Запустите команду `/connect` и найдите **Azure Cognitive Services**. + + ```txt + /connect + ``` + +4. Введите свой ключ API. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Задайте имя ресурса как переменную среды: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + Или добавьте его в свой профиль bash: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. Запустите команду `/models`, чтобы выбрать развернутую модель. + + ```txt + /models + ``` + +--- + +### Бассет-хаунд + +1. Перейдите в [Baseten](https://app.baseten.co/), создайте учетную запись и сгенерируйте ключ API. + +2. Запустите команду `/connect` и найдите **Baseten**. + + ```txt + /connect + ``` + +3. Введите свой ключ API Baseten. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель. + + ```txt + /models + ``` + +--- + +### Мозги + +1. Перейдите в [консоль Cerebras](https://inference.cerebras.ai/), создайте учетную запись и сгенерируйте ключ API. + +2. Запустите команду `/connect` и найдите **Cerebras**. + + ```txt + /connect + ``` + +3. Введите свой ключ API Cerebras. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать такую ​​модель, как _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### Cloudflare AI-шлюз + +Cloudflare AI Gateway позволяет вам получать доступ к моделям OpenAI, Anthropic, Workers AI и т. д. через единую конечную точку. Благодаря [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) вам не нужны отдельные ключи API для каждого провайдера. + +1. Перейдите на [панель управления Cloudflare](https://dash.cloudflare.com/), выберите **AI** > **AI Gateway** и создайте новый шлюз. + +2. Установите идентификатор своей учетной записи и идентификатор шлюза в качестве переменных среды. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. Запустите команду `/connect` и найдите **Cloudflare AI Gateway**. + + ```txt + /connect + ``` + +4. Введите свой токен API Cloudflare. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + Или установите его как переменную среды. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. Запустите команду `/models`, чтобы выбрать модель. + + ```txt + /models + ``` + + Вы также можете добавлять модели через конфигурацию открытого кода. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### Кора + +1. Перейдите в [консоль Cortecs](https://cortecs.ai/), создайте учетную запись и сгенерируйте ключ API. + +2. Запустите команду `/connect` и найдите **Cortecs**. + + ```txt + /connect + ``` + +3. Введите свой ключ API Cortecs. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать такую ​​модель, как _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### ДипСик + +1. Перейдите в [консоль DeepSeek](https://platform.deepseek.com/), создайте учетную запись и нажмите **Создать новый ключ API**. + +2. Запустите команду `/connect` и найдите **DeepSeek**. + + ```txt + /connect + ``` + +3. Введите свой ключ API DeepSeek. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель DeepSeek, например _DeepSeek Reasoner_. + + ```txt + /models + ``` + +--- + +### Глубокая инфра + +1. Перейдите на панель мониторинга Deep Infra](https://deepinfra.com/dash), создайте учетную запись и сгенерируйте ключ API. + +2. Запустите команду `/connect` и найдите **Deep Infra**. + + ```txt + /connect + ``` + +3. Введите свой ключ API Deep Infra. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель. + + ```txt + /models + ``` + +--- + +### Прошивка + +1. Перейдите на [панель встроенного ПО](https://app.firmware.ai/signup), создайте учетную запись и сгенерируйте ключ API. + +2. Запустите команду `/connect` и найдите **Прошивка**. + + ```txt + /connect + ``` + +3. Введите ключ API прошивки. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель. + + ```txt + /models + ``` + +--- + +### Фейерверк ИИ + +1. Перейдите в [консоль Fireworks AI](https://app.fireworks.ai/), создайте учетную запись и нажмите **Создать ключ API**. + +2. Запустите команду `/connect` и найдите **Fireworks AI**. + + ```txt + /connect + ``` + +3. Введите ключ API Fireworks AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать такую ​​модель, как _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### GitLab Дуэт + +GitLab Duo предоставляет агентский чат на базе искусственного интеллекта со встроенными возможностями вызова инструментов через прокси-сервер GitLab Anthropic. + +1. Запустите команду `/connect` и выберите GitLab. + + ```txt + /connect + ``` + +2. Выберите метод аутентификации: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### Использование OAuth (рекомендуется) + + Выберите **OAuth**, и ваш браузер откроется для авторизации. + + #### Использование токена личного доступа + 1. Перейдите в [Настройки пользователя GitLab > Токены доступа](https://gitlab.com/-/user_settings/personal_access_tokens). + 2. Нажмите **Добавить новый токен**. + 3. Имя: `OpenCode`, Области применения: `api` + 4. Скопируйте токен (начинается с `glpat-`) + 5. Введите его в терминал + +3. Запустите команду `/models`, чтобы просмотреть доступные модели. + + ```txt + /models + ``` + + Доступны три модели на основе Claude: + - **duo-chat-haiku-4-5** (по умолчанию) — быстрые ответы на быстрые задачи. + - **duo-chat-sonnet-4-5** — сбалансированная производительность для большинства рабочих процессов. + - **duo-chat-opus-4-5** — Наиболее способен к комплексному анализу. + +:::примечание +Вы также можете указать переменную среды «GITLAB_TOKEN», если не хотите. +для хранения токена в хранилище аутентификации открытого кода. +::: + +##### Самостоятельная GitLab + +:::примечание[примечание о соответствии] +OpenCode использует небольшую модель для некоторых задач ИИ, таких как создание заголовка сеанса. +По умолчанию он настроен на использование gpt-5-nano, размещенного на Zen. Чтобы заблокировать OpenCode +чтобы использовать только свой собственный экземпляр, размещенный на GitLab, добавьте следующее в свой +`opencode.json` файл. Также рекомендуется отключить совместное использование сеансов. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +Для самостоятельных экземпляров GitLab: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +Если в вашем экземпляре используется собственный AI-шлюз: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +Или добавьте в свой профиль bash: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::примечание +Ваш администратор GitLab должен включить следующее: + +1. [Платформа Duo Agent](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) для пользователя, группы или экземпляра +2. Флаги функций (через консоль Rails): + - ХХ0ГГ + - ХХ0ГГ + ::: + +##### OAuth для локальных экземпляров + +Чтобы Oauth работал на вашем локальном экземпляре, вам необходимо создать +новое приложение (Настройки → Приложения) с +URL обратного вызова `http://127.0.0.1:8080/callback` и следующие области: + +- API (Доступ к API от вашего имени) +- read_user (прочитать вашу личную информацию) +- read_repository (разрешает доступ к репозиторию только для чтения) + +Затем укажите идентификатор приложения как переменную среды: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +Дополнительная документация на домашней странице [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth). + +##### Конфигурация + +Настройте через `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### Инструменты API GitLab (необязательно, но настоятельно рекомендуется) + +Чтобы получить доступ к инструментам GitLab (мерж-реквесты, задачи, конвейеры, CI/CD и т. д.): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +Этот плагин предоставляет комплексные возможности управления репозиторием GitLab, включая проверки MR, отслеживание проблем, мониторинг конвейера и многое другое. + +--- + +### GitHub второй пилот + +Чтобы использовать подписку GitHub Copilot с открытым кодом: + +:::примечание +Некоторым моделям может потребоваться [Pro+ +подписка](https://github.com/features/copilot/plans) для использования. + +Некоторые модели необходимо включить вручную в настройках [GitHub Copilot](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. Запустите команду `/connect` и найдите GitHub Copilot. + + ```txt + /connect + ``` + +2. Перейдите на [github.com/login/device](https://github.com/login/device) и введите код. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. Теперь запустите команду `/models`, чтобы выбрать нужную модель. + + ```txt + /models + ``` + +--- + +### Google Вертекс ИИ + +Чтобы использовать Google Vertex AI с OpenCode: + +1. Перейдите в **Model Garden** в Google Cloud Console и проверьте + модели, доступные в вашем регионе. + + :::примечание + Вам необходим проект Google Cloud с включенным Vertex AI API. + ::: + +2. Установите необходимые переменные среды: + - `GOOGLE_CLOUD_PROJECT`: идентификатор вашего проекта Google Cloud. + - `VERTEX_LOCATION` (необязательно): регион для Vertex AI (по умолчанию `global`). + - Аутентификация (выберите одну): + - `GOOGLE_APPLICATION_CREDENTIALS`: путь к ключевому файлу JSON вашего сервисного аккаунта. + - Аутентификация с помощью интерфейса командной строки gcloud: `gcloud auth application-default login`. + + Установите их во время запуска открытого кода. + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + Или добавьте их в свой профиль bash. + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::кончик +Регион `global` повышает доступность и уменьшает количество ошибок без дополнительных затрат. Используйте региональные конечные точки (например, `us-central1`) для требований к местонахождению данных. [Подробнее](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. Запустите команду `/models`, чтобы выбрать нужную модель. + + ```txt + /models + ``` + +--- + +### Грок + +1. Перейдите в консоль Groq](https://console.groq.com/), нажмите **Создать ключ API** и скопируйте ключ. + +2. Запустите команду `/connect` и найдите Groq. + + ```txt + /connect + ``` + +3. Введите ключ API для провайдера. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать тот, который вам нужен. + + ```txt + /models + ``` + +--- + +### Обнимающее лицо + +[Поставщики Hugging Face Inference Provider](https://huggingface.co/docs/inference-providers) предоставляют доступ к открытым моделям, поддерживаемым более чем 17 поставщиками. + +1. Перейдите в [Настройки Hugging Face](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained), чтобы создать токен с разрешением совершать вызовы к поставщикам выводов. + +2. Запустите команду `/connect` и найдите **Обнимающее лицо**. + + ```txt + /connect + ``` + +3. Введите свой жетон «Обнимающее лицо». + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать такую ​​модель, как _Kimi-K2-Instruct_ или _GLM-4.6_. + + ```txt + /models + ``` + +--- + +### Геликон + +[Helicone](https://helicone.ai) — это платформа наблюдения LLM, которая обеспечивает ведение журнала, мониторинг и аналитику для ваших приложений искусственного интеллекта. Helicone AI Gateway автоматически направляет ваши запросы соответствующему поставщику на основе модели. + +1. Перейдите в [Helicone](https://helicone.ai), создайте учетную запись и сгенерируйте ключ API на своей панели управления. + +2. Запустите команду `/connect` и найдите **Helicone**. + + ```txt + /connect + ``` + +3. Введите свой ключ API Helicone. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель. + + ```txt + /models + ``` + +Дополнительные сведения о дополнительных провайдерах и расширенных функциях, таких как кэширование и ограничение скорости, см. в [Документация Helicone](https://docs.helicone.ai). + +#### Дополнительные конфигурации + +Если вы видите функцию или модель от Helicone, которая не настраивается автоматически через открытый код, вы всегда можете настроить ее самостоятельно. + +Вот [Справочник моделей Helicone](https://helicone.ai/models), он понадобится вам, чтобы получить идентификаторы моделей, которые вы хотите добавить. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### Пользовательские заголовки + +Helicone поддерживает пользовательские заголовки для таких функций, как кэширование, отслеживание пользователей и управление сеансами. Добавьте их в конфигурацию вашего провайдера, используя `options.headers`: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### Отслеживание сеансов + +Функция Helicone [Sessions](https://docs.helicone.ai/features/sessions) позволяет группировать связанные запросы LLM вместе. Используйте плагин [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session), чтобы автоматически регистрировать каждый диалог OpenCode как сеанс в Helicone. + +```bash +npm install -g opencode-helicone-session +``` + +Добавьте его в свою конфигурацию. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +Плагин вставляет в ваши запросы заголовки `Helicone-Session-Id` и `Helicone-Session-Name`. На странице «Сеансы» Helicone вы увидите каждый диалог OpenCode, указанный как отдельный сеанс. + +##### Общие разъемы Helicone + +| Заголовок | Описание | +| -------------------------- | ------------------------------------------------------------- | +| ХХ0ГГ | Включить кэширование ответов (`true`/`false`) | +| ХХ0ГГ | Отслеживание показателей по пользователю | +| ХХ0ГГ | Добавьте пользовательские свойства (например, `Helicone-Property-Environment`) | +| ХХ0ГГ | Связывание запросов с подсказками | + +См. [Справочник заголовков Helicone](https://docs.helicone.ai/helicone-headers/header-directory) для всех доступных заголовков. + +--- + +### вызов.cpp + +Вы можете настроить открытый код для использования локальных моделей с помощью [утилиты llama-server llama.cpp's](https://github.com/ggml-org/llama.cpp) + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +В этом примере: + +- `llama.cpp` — это идентификатор пользовательского поставщика. Это может быть любая строка, которую вы хотите. +- `npm` указывает пакет, который будет использоваться для этого поставщика. Здесь `@ai-sdk/openai-compatible` используется для любого API-интерфейса, совместимого с OpenAI. +- `name` — это отображаемое имя поставщика в пользовательском интерфейсе. +- `options.baseURL` — конечная точка локального сервера. +- `models` — это карта идентификаторов моделей с их конфигурациями. Название модели будет отображаться в списке выбора модели. + +--- + +### ИО.НЕТ + +IO.NET предлагает 17 моделей, оптимизированных для различных случаев использования: + +1. Перейдите в консоль IO.NET](https://ai.io.net/), создайте учетную запись и сгенерируйте ключ API. + +2. Запустите команду `/connect` и найдите **IO.NET**. + + ```txt + /connect + ``` + +3. Введите свой ключ API IO.NET. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель. + + ```txt + /models + ``` + +--- + +### ЛМ Студия + +Вы можете настроить открытый код для использования локальных моделей через LM Studio. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +В этом примере: + +- `lmstudio` — это идентификатор пользовательского поставщика. Это может быть любая строка, которую вы хотите. +- `npm` указывает пакет, который будет использоваться для этого поставщика. Здесь `@ai-sdk/openai-compatible` используется для любого API-интерфейса, совместимого с OpenAI. +- `name` — это отображаемое имя поставщика в пользовательском интерфейсе. +- `options.baseURL` — конечная точка локального сервера. +- `models` — это карта идентификаторов моделей с их конфигурациями. Название модели будет отображаться в списке выбора модели. + +--- + +### Лунный выстрел ИИ + +Чтобы использовать Кими К2 из Moonshot AI: + +1. Перейдите в [консоль Moonshot AI](https://platform.moonshot.ai/console), создайте учетную запись и нажмите **Создать ключ API**. + +2. Запустите команду `/connect` и найдите **Moonshot AI**. + + ```txt + /connect + ``` + +3. Введите свой API-ключ Moonshot. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать _Kimi K2_. + + ```txt + /models + ``` + +--- + +### МиниМакс + +1. Перейдите в [консоль API MiniMax](https://platform.minimax.io/login), создайте учетную запись и сгенерируйте ключ API. + +2. Запустите команду `/connect` и найдите **MiniMax**. + + ```txt + /connect + ``` + +3. Введите свой ключ API MiniMax. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель типа _M2.1_. + + ```txt + /models + ``` + +--- + +### Фабрика токенов Небиуса + +1. Перейдите в консоль Nebius Token Factory](https://tokenfactory.nebius.com/), создайте учетную запись и нажмите **Добавить ключ**. + +2. Запустите команду `/connect` и найдите **Nebius Token Factory**. + + ```txt + /connect + ``` + +3. Введите ключ API фабрики токенов Nebius. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать такую ​​модель, как _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Быть + +Вы можете настроить открытый код для использования локальных моделей через Ollama. + +:::кончик +Ollama может автоматически настроиться для OpenCode. Подробности см. в документации по интеграции Ollama](https://docs.ollama.com/integrations/opencode). +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +В этом примере: + +- `ollama` — это идентификатор пользовательского поставщика. Это может быть любая строка, которую вы хотите. +- `npm` указывает пакет, который будет использоваться для этого поставщика. Здесь `@ai-sdk/openai-compatible` используется для любого API-интерфейса, совместимого с OpenAI. +- `name` — это отображаемое имя поставщика в пользовательском интерфейсе. +- `options.baseURL` — конечная точка локального сервера. +- `models` — это карта идентификаторов моделей с их конфигурациями. Название модели будет отображаться в списке выбора модели. + +:::кончик +Если вызовы инструментов не работают, попробуйте увеличить `num_ctx` в Олламе. Начните с 16–32 тысяч. +::: + +--- + +### Оллама Облако + +Чтобы использовать Ollama Cloud с OpenCode: + +1. Перейдите на [https://ollama.com/](https://ollama.com/) и войдите в систему или создайте учетную запись. + +2. Перейдите в **Настройки** > **Ключи** и нажмите **Добавить ключ API**, чтобы создать новый ключ API. + +3. Скопируйте ключ API для использования в OpenCode. + +4. Запустите команду `/connect` и найдите **Ollama Cloud**. + + ```txt + /connect + ``` + +5. Введите свой ключ API Ollama Cloud. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **Важно**. Перед использованием облачных моделей в OpenCode необходимо получить информацию о модели локально: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. Запустите команду `/models`, чтобы выбрать модель облака Ollama. + + ```txt + /models + ``` + +--- + +### ОпенАИ + +Мы рекомендуем подписаться на [ChatGPT Plus или Pro](https://chatgpt.com/pricing). + +1. После регистрации выполните команду `/connect` и выберите OpenAI. + + ```txt + /connect + ``` + +2. Здесь вы можете выбрать опцию **ChatGPT Plus/Pro**, и ваш браузер откроется. + и попросите вас пройти аутентификацию. + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. Теперь все модели OpenAI должны быть доступны при использовании команды `/models`. + + ```txt + /models + ``` + +##### Использование ключей API + +Если у вас уже есть ключ API, вы можете выбрать **Ввести ключ API вручную** и вставить его в свой терминал. + +--- + +### OpenCode Дзен + +OpenCode Zen — это список протестированных и проверенных моделей, предоставленный командой OpenCode. [Подробнее](/docs/zen). + +1. Войдите в систему **OpenCode Zen** и нажмите **Создать ключ API**. + +2. Запустите команду `/connect` и найдите **OpenCode Zen**. + + ```txt + /connect + ``` + +3. Введите свой ключ API OpenCode. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать такую ​​модель, как _Qwen 3 Coder 480B_. + + ```txt + /models + ``` + +--- + +### OpenRouter + +1. Перейдите на панель управления OpenRouter](https://openrouter.ai/settings/keys), нажмите **Создать ключ API** и скопируйте ключ. + +2. Запустите команду `/connect` и найдите OpenRouter. + + ```txt + /connect + ``` + +3. Введите ключ API для провайдера. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Многие модели OpenRouter предварительно загружены по умолчанию. Запустите команду `/models`, чтобы выбрать нужную. + + ```txt + /models + ``` + + Вы также можете добавить дополнительные модели через конфигурацию открытого кода. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. Вы также можете настроить их через конфигурацию открытого кода. Вот пример указания провайдера + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP AI Ядро + +SAP AI Core предоставляет доступ к более чем 40 моделям от OpenAI, Anthropic, Google, Amazon, Meta, Mistral и AI21 через единую платформу. + +1. Перейдите в [SAP BTP Cockpit](https://account.hana.ondemand.com/), перейдите к экземпляру службы SAP AI Core и создайте ключ службы. + + :::кончик + Ключ службы — это объект JSON, содержащий `clientid`, `clientsecret`, `url` и `serviceurls.AI_API_URL`. Экземпляр AI Core можно найти в разделе **Сервисы** > **Экземпляры и подписки** в панели управления BTP. + ::: + +2. Запустите команду `/connect` и найдите **SAP AI Core**. + + ```txt + /connect + ``` + +3. Введите свой сервисный ключ в формате JSON. + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + Или установите переменную среды `AICORE_SERVICE_KEY`: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + Или добавьте его в свой профиль bash: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. При необходимости укажите идентификатор развертывания и группу ресурсов: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::примечание + Эти параметры являются необязательными и должны быть настроены в соответствии с настройками SAP AI Core. + ::: + +5. Запустите команду `/models`, чтобы выбрать одну из более чем 40 доступных моделей. + + ```txt + /models + ``` + +--- + +### Конечные точки OVHcloud AI + +1. Перейдите к [OVHcloud Panel](https://ovh.com/manager). Перейдите в раздел `Public Cloud`, `AI & Machine Learning` > `AI Endpoints` и на вкладке `API Keys` нажмите **Создать новый ключ API**. + +2. Запустите команду `/connect` и найдите **Конечные точки OVHcloud AI**. + + ```txt + /connect + ``` + +3. Введите ключ API конечных точек OVHcloud AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель типа _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Чешуйчатая дорога + +Чтобы использовать [Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/) с Opencode: + +1. Перейдите к [Настройки IAM консоли Scaleway](https://console.scaleway.com/iam/api-keys), чтобы сгенерировать новый ключ API. + +2. Запустите команду `/connect` и найдите **Scaleway**. + + ```txt + /connect + ``` + +3. Введите ключ API Scaleway. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель, например _devstral-2-123b-instruct-2512_ или _gpt-oss-120b_. + + ```txt + /models + ``` + +--- + +### Вместе ИИ + +1. Перейдите в [консоль Together AI](https://api.together.ai), создайте учетную запись и нажмите **Добавить ключ**. + +2. Запустите команду `/connect` и найдите **Together AI**. + + ```txt + /connect + ``` + +3. Введите ключ API Together AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать такую ​​модель, как _Kimi K2 Instruct_. + + ```txt + /models + ``` + +--- + +### Венеция ИИ + +1. Перейдите к [консоли Venice AI](https://venice.ai), создайте учетную запись и сгенерируйте ключ API. + +2. Запустите команду `/connect` и найдите **Венеция AI**. + + ```txt + /connect + ``` + +3. Введите свой ключ API Венеции AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель типа _Llama 3.3 70B_. + + ```txt + /models + ``` + +--- + +### AI-шлюз Vercel + +Vercel AI Gateway позволяет получать доступ к моделям OpenAI, Anthropic, Google, xAI и других источников через единую конечную точку. Модели предлагаются по прейскурантной цене без наценок. + +1. Перейдите на [панель мониторинга Vercel](https://vercel.com/), перейдите на вкладку **AI Gateway** и нажмите **Ключи API**, чтобы создать новый ключ API. + +2. Запустите команду `/connect` и найдите **Vercel AI Gateway**. + + ```txt + /connect + ``` + +3. Введите ключ API Vercel AI Gateway. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель. + + ```txt + /models + ``` + +Вы также можете настраивать модели через конфигурацию открытого кода. Ниже приведен пример указания порядка маршрутизации поставщика. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +Некоторые полезные параметры маршрутизации: + +| Вариант | Описание | +| ------------------- | ---------------------------------------------------- | +| ХХ0ГГ | Последовательность действий поставщика, которую стоит попробовать | +| ХХ0ГГ | Ограничить конкретными поставщиками | +| ХХ0ГГ | Используйте только поставщиков с нулевой политикой хранения данных. | + +--- + +### xAI + +1. Перейдите на [консоль xAI](https://console.x.ai/), создайте учетную запись и сгенерируйте ключ API. + +2. Запустите команду `/connect` и найдите **xAI**. + + ```txt + /connect + ``` + +3. Введите свой ключ API xAI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать такую ​​модель, как _Grok Beta_. + + ```txt + /models + ``` + +--- + +### З.АИ + +1. Перейдите в [консоль Z.AI API](https://z.ai/manage-apikey/apikey-list), создайте учетную запись и нажмите **Создать новый ключ API**. + +2. Запустите команду `/connect` и найдите **Z.AI**. + + ```txt + /connect + ``` + + Если вы подписаны на **План кодирования GLM**, выберите **План кодирования Z.AI**. + +3. Введите свой ключ API Z.AI. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Запустите команду `/models`, чтобы выбрать модель типа _GLM-4.7_. + + ```txt + /models + ``` + +--- + +### ДзенМукс + +1. Перейдите на [панель управления ZenMux](https://zenmux.ai/settings/keys), нажмите **Создать ключ API** и скопируйте ключ. + +2. Запустите команду `/connect` и найдите ZenMux. + + ```txt + /connect + ``` + +3. Введите ключ API для провайдера. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Многие модели ZenMux предварительно загружены по умолчанию. Запустите команду `/models`, чтобы выбрать нужную. + + ```txt + /models + ``` + + Вы также можете добавить дополнительные модели через конфигурацию открытого кода. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## Пользовательский поставщик + +Чтобы добавить любого **совместимого с OpenAI** поставщика, не указанного в команде `/connect`: + +:::кончик +Вы можете использовать любого OpenAI-совместимого провайдера с открытым кодом. Большинство современных поставщиков ИИ предлагают API-интерфейсы, совместимые с OpenAI. +::: + +1. Запустите команду `/connect` и прокрутите вниз до пункта **Другое**. + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. Введите уникальный идентификатор провайдера. + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::примечание + Выберите запоминающийся идентификатор, вы будете использовать его в своем файле конфигурации. + ::: + +3. Введите свой ключ API для провайдера. + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. Создайте или обновите файл `opencode.json` в каталоге вашего проекта: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + Вот варианты конфигурации: + - **npm**: используемый пакет AI SDK, `@ai-sdk/openai-compatible` для поставщиков, совместимых с OpenAI. + - **имя**: отображаемое имя в пользовательском интерфейсе. + - **модели**: Доступные модели. + - **options.baseURL**: URL-адрес конечной точки API. + - **options.apiKey**: при необходимости установите ключ API, если не используется аутентификация. + - **options.headers**: при необходимости можно установить собственные заголовки. + + Подробнее о дополнительных параметрах в примере ниже. + +5. Запустите команду `/models`, и ваш пользовательский поставщик и модели появятся в списке выбора. + +--- + +##### Пример + +Ниже приведен пример настройки параметров `apiKey`, `headers` и модели `limit`. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +Детали конфигурации: + +- **apiKey**: устанавливается с использованием синтаксиса переменной `env`, [подробнее ](/docs/config#env-vars). +- **заголовки**: пользовательские заголовки, отправляемые с каждым запросом. +- **limit.context**: Максимальное количество входных токенов, которые принимает модель. +- **limit.output**: Максимальное количество токенов, которые может сгенерировать модель. + +Поля `limit` позволяют OpenCode понять, сколько контекста у вас осталось. Стандартные поставщики автоматически извлекают их из models.dev. + +--- + +## Поиск неисправностей + +Если у вас возникли проблемы с настройкой провайдера, проверьте следующее: + +1. **Проверьте настройку аутентификации**: запустите `opencode auth list`, чтобы проверить, верны ли учетные данные. + для провайдера добавлены в ваш конфиг. + + Это не относится к таким поставщикам, как Amazon Bedrock, которые для аутентификации полагаются на переменные среды. + +2. Для пользовательских поставщиков проверьте конфигурацию открытого кода и: + - Убедитесь, что идентификатор провайдера, используемый в команде `/connect`, соответствует идентификатору в вашей конфигурации открытого кода. + - Для провайдера используется правильный пакет npm. Например, используйте `@ai-sdk/cerebras` для Cerebras. А для всех других поставщиков, совместимых с OpenAI, используйте `@ai-sdk/openai-compatible`. + - Убедитесь, что в поле `options.baseURL` используется правильная конечная точка API. diff --git a/packages/web/src/content/docs/ru/rules.mdx b/packages/web/src/content/docs/ru/rules.mdx new file mode 100644 index 000000000..0d42db2d3 --- /dev/null +++ b/packages/web/src/content/docs/ru/rules.mdx @@ -0,0 +1,180 @@ +--- +title: Правила +description: Установите пользовательские инструкции для открытого кода. +--- + +Вы можете предоставить собственные инструкции для открытия кода, создав файл `AGENTS.md`. Это похоже на правила Курсора. Он содержит инструкции, которые будут включены в контекст LLM для настройки его поведения для вашего конкретного проекта. + +--- + +## Инициализировать + +Чтобы создать новый файл `AGENTS.md`, вы можете запустить команду `/init` в открытом коде. + +:::кончик +Вам следует зафиксировать файл `AGENTS.md` вашего проекта в Git. +::: + +Это позволит отсканировать ваш проект и все его содержимое, чтобы понять, о чем этот проект, и сгенерировать с его помощью файл `AGENTS.md`. Это помогает opencode лучше ориентироваться в проекте. + +Если у вас есть существующий файл `AGENTS.md`, мы попытаемся добавить его. + +--- + +## Пример + +Вы также можете просто создать этот файл вручную. Вот пример того, что вы можете поместить в файл `AGENTS.md`. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +Мы добавляем сюда инструкции для конкретного проекта, и они будут доступны всей вашей команде. + +--- + +## Типы + +opencode также поддерживает чтение файла `AGENTS.md` из нескольких мест. И это служит разным целям. + +### Проект + +Поместите `AGENTS.md` в корень вашего проекта для правил, специфичных для проекта. Они применяются только тогда, когда вы работаете в этом каталоге или его подкаталогах. + +### Глобальный + +Вы также можете иметь глобальные правила в файле `~/.config/opencode/AGENTS.md`. Это применяется ко всем сеансам открытого кода. + +Поскольку это не передается в Git и не передается вашей команде, мы рекомендуем использовать его для указания любых личных правил, которым должен следовать LLM. + +### Совместимость кода Клода + +Для пользователей, переходящих с Claude Code, OpenCode поддерживает файловые соглашения Claude Code в качестве резерва: + +- **Правила проекта**: `CLAUDE.md` в каталоге вашего проекта (используется, если `AGENTS.md` не существует). +- **Глобальные правила**: `~/.claude/CLAUDE.md` (используется, если `~/.config/opencode/AGENTS.md` не существует). +- **Навыки**: `~/.claude/skills/` — подробности см. в [Навыки агента](/docs/skills/). + +Чтобы отключить совместимость Claude Code, установите одну из этих переменных среды: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## Приоритет + +Когда opencode запускается, он ищет файлы правил в следующем порядке: + +1. **Локальные файлы** путем перехода вверх из текущего каталога (`AGENTS.md`, `CLAUDE.md`) +2. **Глобальный файл** в `~/.config/opencode/AGENTS.md`. +3. **Файл кода Клауда** по адресу `~/.claude/CLAUDE.md` (если не отключено) + +Первый совпадающий файл побеждает в каждой категории. Например, если у вас есть и `AGENTS.md`, и `CLAUDE.md`, используется только `AGENTS.md`. Аналогично, `~/.config/opencode/AGENTS.md` имеет приоритет над `~/.claude/CLAUDE.md`. + +--- + +## Пользовательские инструкции + +Вы можете указать собственные файлы инструкций в `opencode.json` или в глобальном `~/.config/opencode/opencode.json`. Это позволит вам и вашей команде повторно использовать существующие правила вместо того, чтобы дублировать их на AGENTS.md. + +Пример: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Вы также можете использовать удаленные URL-адреса для загрузки инструкций из Интернета. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +Удаленные инструкции извлекаются с таймаутом в 5 секунд. + +Все файлы инструкций объединяются с вашими файлами `AGENTS.md`. + +--- + +## Ссылки на внешние файлы + +Хотя opencode не анализирует автоматически ссылки на файлы в `AGENTS.md`, аналогичной функциональности можно добиться двумя способами: + +### Использование opencode.json + +Рекомендуемый подход — использовать поле `instructions` в `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Ручные инструкции в AGENTS.md + +Вы можете научить открытый код читать внешние файлы, предоставив явные инструкции в файле `AGENTS.md`. Вот практический пример: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +Такой подход позволяет: + +- Создавайте модульные файлы правил многократного использования. +- Делитесь правилами между проектами с помощью символических ссылок или подмодулей git. +- Сохраняйте AGENTS.md кратким, ссылаясь на подробные инструкции. +- Убедитесь, что открытый код загружает файлы только тогда, когда это необходимо для конкретной задачи. + +:::кончик +Для монорепозиториев или проектов с общими стандартами использование `opencode.json` с шаблонами glob (например, `packages/*/AGENTS.md`) более удобно в обслуживании, чем инструкции вручную. +::: diff --git a/packages/web/src/content/docs/ru/sdk.mdx b/packages/web/src/content/docs/ru/sdk.mdx new file mode 100644 index 000000000..955dc6358 --- /dev/null +++ b/packages/web/src/content/docs/ru/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: Типобезопасный JS-клиент для сервера открытого кода. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +SDK JS/TS с открытым кодом предоставляет типобезопасный клиент для взаимодействия с сервером. +Используйте его для создания интеграции и программного управления открытым кодом. + +[Узнайте больше](/docs/server) о том, как работает сервер. Примеры можно найти в [projects](/docs/ecosystem#projects), созданном сообществом. + +--- + +## Установить + +Установите SDK из npm: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## Создать клиента + +Создайте экземпляр открытого кода: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +Это запускает и сервер, и клиент. + +#### Параметры + +| Вариант | Тип | Описание | По умолчанию | +| ------- | ----- | -------------------------------- | ------------ | +| ХХ0ГГ | ХХ0ГГ | Имя хоста сервера | `127.0.0.1` | +| ХХ0ГГ | ХХ0ГГ | Порт сервера | `4096` | +| ХХ0ГГ | ХХ0ГГ | Сигнал отмены для отмены | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Таймаут в мс для запуска сервера | `5000` | +| ХХ0ГГ | ХХ0ГГ | Объект конфигурации | `{}` | + +--- + +## Конфигурация + +Вы можете передать объект конфигурации для настройки поведения. Экземпляр по-прежнему получает ваш `opencode.json`, но вы можете переопределить или добавить встроенную конфигурацию: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## Только клиент + +Если у вас уже есть работающий экземпляр открытого кода, вы можете создать экземпляр клиента для подключения к нему: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### Параметры + +| Вариант | Тип | Описание | По умолчанию | +| ------- | ----- | ------------------------------------ | ------------ | +| ХХ0ГГ | ХХ0ГГ | URL-адрес сервера | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Пользовательская реализация выборки | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Метод анализа ответа | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Стиль возврата: `data` или `fields`. | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Выдавать ошибки вместо возврата | ХХ0ГГ | + +--- + +## Типы + +SDK включает определения TypeScript для всех типов API. Импортируйте их напрямую: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +Все типы генерируются на основе спецификации OpenAPI сервера и доступны в файле types. + +--- + +## Ошибки + +SDK может выдавать ошибки, которые вы можете отловить и обработать: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## API + +SDK предоставляет все серверные API через типобезопасный клиент. + +--- + +### Глобальный + +| Метод | Описание | Ответ | +| ----- | -------------------------------------------- | ----- | +| ХХ0ГГ | Проверьте работоспособность и версию сервера | ХХ0ГГ | + +--- + +#### Примеры + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### Приложение + +| Метод | Описание | Ответ | +| ----- | ----------------------------- | ------------------------------------------- | +| ХХ0ГГ | Написать запись в журнале | ХХ0ГГ | +| ХХ0ГГ | Список всех доступных агентов | Агент[] | + +--- + +#### Примеры + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### Проект + +| Метод | Описание | Ответ | +| ----- | ----------------------- | -------------------------------------------- | +| ХХ0ГГ | Список всех проектов | Проект[] | +| ХХ0ГГ | Получить текущий проект | Проект | + +--- + +#### Примеры + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### Путь + +| Метод | Описание | Ответ | +| ----- | --------------------- | ---------------------------------------- | +| ХХ0ГГ | Получить текущий путь | Путь | + +--- + +#### Примеры + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### Конфигурация + +| Метод | Описание | Ответ | +| ----- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| ХХ0ГГ | Получить информацию о конфигурации | Config | +| ХХ0ГГ | Список поставщиков и моделей по умолчанию | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +#### Примеры + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### Сессии + +| Метод | Описание | Примечания | +| ----- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ХХ0ГГ | Получение списка сеансов | Возвращает Session[] | +| ХХ0ГГ | Получить сеанс | Возвращает Session | +| ХХ0ГГ | Список дочерних сеансов | Возвращает Session[] | +| ХХ0ГГ | Создать сеанс | Возвращает Session | +| ХХ0ГГ | Удалить сеанс | Возвращает `boolean` | +| ХХ0ГГ | Обновить свойства сеанса | Возвращает Session | +| ХХ0ГГ | Проанализируйте приложение и создайте `AGENTS.md`. | Возвращает `boolean` | +| ХХ0ГГ | Прервать текущий сеанс | Возвращает `boolean` | +| ХХ0ГГ | Поделиться сеансом | Возвращает Session | +| ХХ0ГГ | Отменить общий доступ к сеансу | Возвращает Session | +| ХХ0ГГ | Подведение итогов сессии | Возвращает `boolean` | +| ХХ0ГГ | Список сообщений в сеансе | Возвращает `{ info: `Message`, parts: `Part[]`}[]` | +| ХХ0ГГ | Получить подробную информацию о сообщении | Возвращает `{ info: `Message`, parts: `Part[]`}` | +| ХХ0ГГ | Отправить оперативное сообщение | `body.noReply: true` возвращает UserMessage (только контекст). По умолчанию возвращается AssistantMessage с ответом AI. | +| ХХ0ГГ | Отправить команду в сеанс | Возвращает `{ info: `AssistantMessage`, parts: `Part[]`}` | +| ХХ0ГГ | Запустите команду оболочки | Возвращает AssistantMessage | +| ХХ0ГГ | Отменить сообщение | Возвращает Session | +| ХХ0ГГ | Восстановить восстановленные сообщения | Возвращает Session | +| ХХ0ГГ | Ответ на запрос разрешения | Возвращает `boolean` | + +--- + +#### Примеры + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### Файлы + +| Метод | Описание | Ответ | +| ----- | ------------------------------------ | --------------------------------------------------------------------------------------------- | +| ХХ0ГГ | Поиск текста в файлах | Массив объектов соответствия `path`, `lines`, `line_number`, `absolute_offset`, `submatches`. | +| ХХ0ГГ | Поиск файлов и каталогов по имени | `string[]` (пути) | +| ХХ0ГГ | Найдите символы рабочей области | Символ[] | +| ХХ0ГГ | Чтение файла | `{ type: "raw" \| "patch", content: string }` | +| ХХ0ГГ | Получить статус отслеживаемых файлов | Файл[] | + +`find.files` поддерживает несколько дополнительных полей запроса: + +- `type`: `"file"` или `"directory"` +- `directory`: переопределить корень проекта для поиска. +- `limit`: максимальное количество результатов (1–200) + +--- + +#### Примеры + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### ТУИ + +| Метод | Описание | Ответ | +| ----- | -------------------------------- | ----- | +| ХХ0ГГ | Добавить текст в приглашение | ХХ0ГГ | +| ХХ0ГГ | Открыть диалоговое окно справки | ХХ0ГГ | +| ХХ0ГГ | Откройте селектор сеансов | ХХ0ГГ | +| ХХ0ГГ | Откройте выбор темы | ХХ0ГГ | +| ХХ0ГГ | Откройте выбор модели | ХХ0ГГ | +| ХХ0ГГ | Отправить текущий запрос | ХХ0ГГ | +| ХХ0ГГ | Очистить подсказку | ХХ0ГГ | +| ХХ0ГГ | Выполнить команду | ХХ0ГГ | +| ХХ0ГГ | Показать всплывающее уведомление | ХХ0ГГ | + +--- + +#### Примеры + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### Авторизация + +| Метод | Описание | Ответ | +| ----- | -------------------------------------------- | ----- | +| ХХ0ГГ | Установите учетные данные для аутентификации | ХХ0ГГ | + +--- + +#### Примеры + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### События + +| Метод | Описание | Ответ | +| ----- | ------------------------------------ | ------------------------------------ | +| ХХ0ГГ | Поток событий, отправленных сервером | Поток событий, отправленных сервером | + +--- + +#### Примеры + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/ru/server.mdx b/packages/web/src/content/docs/ru/server.mdx new file mode 100644 index 000000000..0c3a5ebc2 --- /dev/null +++ b/packages/web/src/content/docs/ru/server.mdx @@ -0,0 +1,287 @@ +--- +title: Сервер +description: Взаимодействуйте с сервером открытого кода через HTTP. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +Команда `opencode serve` запускает автономный HTTP-сервер, который предоставляет конечную точку OpenAPI, которую может использовать клиент с открытым кодом. + +--- + +### Использование + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### Параметры + +| Флаг | Описание | По умолчанию | +| --------------- | ----------------------------------- | ---------------- | +| ХХ0ГГ | Порт для прослушивания | `4096` | +| ХХ0ГГ | Имя хоста для прослушивания | `127.0.0.1` | +| ХХ0ГГ | Включить обнаружение mDNS | ХХ0ГГ | +| ХХ0ГГ | Пользовательское доменное имя для службы mDNS | ХХ0ГГ | +| ХХ0ГГ | Дополнительные источники браузера, позволяющие | `[]` | + +`--cors` можно передать несколько раз: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### Аутентификация + +Установите `OPENCODE_SERVER_PASSWORD`, чтобы защитить сервер с помощью базовой аутентификации HTTP. Имя пользователя по умолчанию — `opencode` или установите `OPENCODE_SERVER_USERNAME`, чтобы переопределить его. Это относится как к `opencode serve`, так и к `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### Как это работает + +Когда вы запускаете `opencode`, он запускает TUI и сервер. Где находится TUI +клиент, который общается с сервером. Сервер предоставляет спецификацию OpenAPI 3.1. +конечная точка. Эта конечная точка также используется для создания файла [SDK](/docs/sdk). + +:::кончик +Используйте сервер открытого кода для программного взаимодействия с открытым кодом. +::: + +Эта архитектура позволяет открытому коду поддерживать несколько клиентов и позволяет программно взаимодействовать с открытым кодом. + +Вы можете запустить `opencode serve`, чтобы запустить автономный сервер. Если у вас есть +TUI с открытым кодом запущен, `opencode serve` запустит новый сервер. + +--- + +#### Подключиться к существующему серверу + +Когда вы запускаете TUI, он случайным образом назначает порт и имя хоста. Вместо этого вы можете передать `--hostname` и `--port` [flags](/docs/cli). Затем используйте это для подключения к его серверу. + +Конечную точку [`/tui`](#tui) можно использовать для управления TUI через сервер. Например, вы можете предварительно заполнить или запустить подсказку. Эта настройка используется плагинами OpenCode [IDE](/docs/ide). + +--- + +## Спецификация + +Сервер публикует спецификацию OpenAPI 3.1, которую можно просмотреть по адресу: + +``` +http://:/doc +``` + +Например, ХХ0ГГ. Используйте спецификацию для создания клиентов или проверки типов запросов и ответов. Или просмотрите его в обозревателе Swagger. + +--- + +## API + +Сервер открытого кода предоставляет следующие API. + +--- + +### Глобальный + +| Метод | Путь | Описание | Ответ | +| ------ | ---------------- | ------------------------------ | ------------------------------------ | +| ХХ0ГГ | ХХ0ГГ | Получить информацию о состоянии и версии сервера | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Получить глобальные события (поток SSE) | Трансляция событий | + +--- + +### Проект + +| Метод | Путь | Описание | Ответ | +| ------ | ------------------ | ----------------------- | --------------------------------------------- | +| ХХ0ГГ | ХХ0ГГ | Список всех проектов | Проект[] | +| ХХ0ГГ | ХХ0ГГ | Получить текущий проект | Проект | + +--- + +### Путь и система контроля версий + +| Метод | Путь | Описание | Ответ | +| ------ | ------- | ------------------------------------ | ------------------------------------------- | +| ХХ0ГГ | ХХ0ГГ | Получить текущий путь | Путь | +| ХХ0ГГ | ХХ0ГГ | Получить информацию VCS для текущего проекта | VcsInfo | + +--- + +### Пример + +| Метод | Путь | Описание | Ответ | +| ------ | ------------------- | ---------------------------- | --------- | +| ХХ0ГГ | ХХ0ГГ | Удалить текущий экземпляр | ХХ0ГГ | + +--- + +### Конфигурация + +| Метод | Путь | Описание | Ответ | +| ------- | ------------------- | --------------------------------- | ---------------------------------------------------------------------------------------- | +| ХХ0ГГ | ХХ0ГГ | Получить информацию о конфигурации | Config | +| ХХ0ГГ | ХХ0ГГ | Обновить конфигурацию | Config | +| ХХ0ГГ | ХХ0ГГ | Список поставщиков и моделей по умолчанию | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +### Поставщик + +| Метод | Путь | Описание | Ответ | +| ------ | -------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------- | +| ХХ0ГГ | ХХ0ГГ | Список всех поставщиков | `{ all: `Provider[]`, default: {...}, connected: string[] }` | +| ХХ0ГГ | ХХ0ГГ | Получить методы аутентификации поставщика | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| ХХ0ГГ | ХХ0ГГ | Авторизуйте провайдера с помощью OAuth | ProviderAuthAuthorization | +| ХХ0ГГ | ХХ0ГГ | Обработка обратного вызова OAuth для провайдера | ХХ0ГГ | + +--- + +### Сессии + +| Метод | Путь | Описание | Примечания | +| -------- | ---------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------- | +| ХХ0ГГ | ХХ0ГГ | Список всех сессий | Возвращает Session[] | +| ХХ0ГГ | ХХ0ГГ | Создать новый сеанс | тело: `{ parentID?, title? }`, возвращает Session | +| ХХ0ГГ | ХХ0ГГ | Получить статус сеанса для всех сеансов | Возвращает `{ [sessionID: string]: `SessionStatus` }` | +| ХХ0ГГ | ХХ0ГГ | Получить подробную информацию о сеансе | Возвращает Session | +| ХХ0ГГ | ХХ0ГГ | Удалить сеанс и все его данные | Возвращает `boolean` | +| ХХ0ГГ | ХХ0ГГ | Обновить свойства сеанса | тело: `{ title? }`, возвращает Session | +| ХХ0ГГ | ХХ0ГГ | Получить дочерние сеансы сеанса | Возвращает Session[] | +| ХХ0ГГ | ХХ0ГГ | Получить список дел для сеанса | Возвращает Todo[] | +| ХХ0ГГ | ХХ0ГГ | Проанализируйте приложение и создайте `AGENTS.md`. | тело: `{ messageID, providerID, modelID }`, возвращает `boolean` | +| ХХ0ГГ | ХХ0ГГ | Разветвить существующий сеанс по сообщению | тело: `{ messageID? }`, возвращает Session | +| ХХ0ГГ | ХХ0ГГ | Прервать текущий сеанс | Возвращает `boolean` | +| ХХ0ГГ | ХХ0ГГ | Поделиться сеансом | Возвращает Session | +| ХХ0ГГ | ХХ0ГГ | Отменить общий доступ к сеансу | Возвращает Session | +| ХХ0ГГ | ХХ0ГГ | Получить разницу для этой сессии | запрос: `messageID?`, возвращает FileDiff[] | +| ХХ0ГГ | ХХ0ГГ | Подведите итоги сессии | тело: `{ providerID, modelID }`, возвращает `boolean` | +| ХХ0ГГ | ХХ0ГГ | Отменить сообщение | тело: `{ messageID, partID? }`, возвращает `boolean` | +| ХХ0ГГ | ХХ0ГГ | Восстановить все восстановленные сообщения | Возвращает `boolean` | +| ХХ0ГГ | ХХ0ГГ | Ответ на запрос разрешения | тело: `{ response, remember? }`, возвращает `boolean` | + +--- + +### Сообщения + +| Метод | Путь | Описание | Примечания | +| ------ | --------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ХХ0ГГ | ХХ0ГГ | Список сообщений в сеансе | запрос: `limit?`, возвращает `{ info: `Message`, parts: `Part[]`}[]` | +| ХХ0ГГ | ХХ0ГГ | Отправьте сообщение и дождитесь ответа | тело: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, возвращает `{ info: `Message`, parts: `Part[]`}` | +| ХХ0ГГ | ХХ0ГГ | Получить подробную информацию о сообщении | Возвращает `{ info: `Message`, parts: `Part[]`}` | +| ХХ0ГГ | ХХ0ГГ | Отправить сообщение асинхронно (без ожидания) | тело: то же, что и `/session/:id/message`, возвращает `204 No Content`. | +| ХХ0ГГ | ХХ0ГГ | Выполнить команду косой черты | тело: `{ messageID?, agent?, model?, command, arguments }`, возвращает `{ info: `Message`, parts: `Part[]`}` | +| ХХ0ГГ | ХХ0ГГ | Запустите команду оболочки | тело: `{ agent, model?, command }`, возвращает `{ info: `Message`, parts: `Part[]`}` | + +--- + +### Команды + +| Метод | Путь | Описание | Ответ | +| ------ | ---------- | ----------------- | --------------------------------------------- | +| ХХ0ГГ | ХХ0ГГ | Список всех команд | Команда[] | + +--- + +### Файлы + +| Метод | Путь | Описание | Ответ | +| ------ | ------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| ХХ0ГГ | ХХ0ГГ | Поиск текста в файлах | Массив объектов соответствия `path`, `lines`, `line_number`, `absolute_offset`, `submatches`. | +| ХХ0ГГ | ХХ0ГГ | Поиск файлов и каталогов по имени | `string[]` (пути) | +| ХХ0ГГ | ХХ0ГГ | Найдите символы рабочей области | Символ[] | +| ХХ0ГГ | ХХ0ГГ | Список файлов и каталогов | FileNode[] | +| ХХ0ГГ | ХХ0ГГ | Чтение файла | FileContent | +| ХХ0ГГ | ХХ0ГГ | Получить статус отслеживаемых файлов | Файл[] | + +#### `/find/file` параметры запроса + +- `query` (обязательно) — строка поиска (нечеткое совпадение) +- `type` (необязательно) — ограничить результаты `"file"` или `"directory"`. +- `directory` (необязательно) — переопределить корень проекта для поиска. +- `limit` (необязательно) — максимальное количество результатов (1–200) +- `dirs` (необязательно) — устаревший флаг (`"false"` возвращает только файлы) + +--- + +### Инструменты (Экспериментальные) + +| Метод | Путь | Описание | Ответ | +| ------ | ------------------------------------------- | ---------------------------------------- | -------------------------------------------- | +| ХХ0ГГ | ХХ0ГГ | Список всех идентификаторов инструментов | ToolIDs | +| ХХ0ГГ | ХХ0ГГ | Список инструментов со схемами JSON для модели | ToolList | + +--- + +### LSP, форматтеры и MCP + +| Метод | Путь | Описание | Ответ | +| ------ | ------------ | -------------------------- | -------------------------------------------------------- | +| ХХ0ГГ | ХХ0ГГ | Получить статус LSP-сервера | LSPStatus[] | +| ХХ0ГГ | ХХ0ГГ | Получить статус форматтера | FormatterStatus[] | +| ХХ0ГГ | ХХ0ГГ | Получить статус сервера MCP | `{ [name: string]: `MCPStatus` }` | +| ХХ0ГГ | ХХ0ГГ | Динамическое добавление сервера MCP | тело: `{ name, config }`, возвращает объект состояния MCP | + +--- + +### Агенты + +| Метод | Путь | Описание | Ответ | +| ------ | -------- | ------------------------- | ------------------------------------------- | +| ХХ0ГГ | ХХ0ГГ | Список всех доступных агентов | Агент[] | + +--- + +### Ведение журнала + +| Метод | Путь | Описание | Ответ | +| ------ | ------ | ------------------------------------------------------------ | --------- | +| ХХ0ГГ | ХХ0ГГ | Напишите запись в журнале. Тело: `{ service, level, message, extra? }` | ХХ0ГГ | + +--- + +### ТУИ + +| Метод | Путь | Описание | Ответ | +| ------ | ----------------------- | ------------------------------------------- | ---------------------- | +| ХХ0ГГ | ХХ0ГГ | Добавить текст в приглашение | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Открыть диалоговое окно справки | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Откройте селектор сеансов | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Откройте выбор темы | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Откройте выбор модели | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Отправить текущий запрос | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Очистить подсказку | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Выполнить команду (`{ command }`) | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Показать тост (`{ title?, message, variant }`) | ХХ0ГГ | +| ХХ0ГГ | ХХ0ГГ | Дождитесь следующего запроса на управление | Объект запроса управления | +| ХХ0ГГ | ХХ0ГГ | Ответ на запрос управления (`{ body }`) | ХХ0ГГ | + +--- + +### Авторизация + +| Метод | Путь | Описание | Ответ | +| ------ | ----------- | --------------------------------------------------------------- | --------- | +| ХХ0ГГ | ХХ0ГГ | Установите учетные данные для аутентификации. Тело должно соответствовать схеме поставщика. | ХХ0ГГ | + +--- + +### События + +| Метод | Путь | Описание | Ответ | +| ------ | -------- | ----------------------------------------------------------------------------- | ------------------------- | +| ХХ0ГГ | ХХ0ГГ | Поток событий, отправленный сервером. Первое событие — `server.connected`, затем события шины. | Поток событий, отправленных сервером | + +--- + +### Документы + +| Метод | Путь | Описание | Ответ | +| ------ | ------ | ------------------------- | --------------------------- | +| ХХ0ГГ | ХХ0ГГ | Спецификация OpenAPI 3.1 | HTML-страница со спецификацией OpenAPI | diff --git a/packages/web/src/content/docs/ru/share.mdx b/packages/web/src/content/docs/ru/share.mdx new file mode 100644 index 000000000..3e52db0e4 --- /dev/null +++ b/packages/web/src/content/docs/ru/share.mdx @@ -0,0 +1,128 @@ +--- +title: Делиться +description: Поделитесь своими разговорами об OpenCode. +--- + +Функция общего доступа OpenCode позволяет вам создавать общедоступные ссылки на ваши беседы OpenCode, чтобы вы могли сотрудничать с товарищами по команде или получать помощь от других. + +:::примечание +Общие беседы общедоступны для всех, у кого есть ссылка. +::: + +--- + +## Как это работает + +Когда вы делитесь беседой, OpenCode: + +1. Создает уникальный общедоступный URL-адрес для вашего сеанса. +2. Синхронизирует историю ваших разговоров с нашими серверами +3. Делает беседу доступной по общей ссылке — `opncd.ai/s/`. + +--- + +## Совместное использование + +OpenCode поддерживает три режима общего доступа, которые контролируют общий доступ к разговорам: + +--- + +### Ручной (по умолчанию) + +По умолчанию OpenCode использует режим совместного использования вручную. Сессии не передаются автоматически, но вы можете поделиться ими вручную с помощью команды `/share`: + +``` +/share +``` + +Это создаст уникальный URL-адрес, который будет скопирован в буфер обмена. + +Чтобы явно установить ручной режим в вашем [файле конфигурации](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### Автоматическая публикация + +Вы можете включить автоматический общий доступ для всех новых разговоров, установив для параметра `share` значение `"auto"` в вашем [файле конфигурации](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +Если функция автоматического обмена включена, каждый новый разговор будет автоматически опубликован и будет создана ссылка. + +--- + +### Неполноценный + +Вы можете полностью отключить общий доступ, установив для параметра `share` значение `"disabled"` в вашем [файле конфигурации](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +Чтобы обеспечить соблюдение этого правила для всей вашей команды в конкретном проекте, добавьте его в `opencode.json` вашего проекта и зарегистрируйтесь в Git. + +--- + +## Отменить совместное использование + +Чтобы прекратить делиться беседой и удалить ее из общего доступа: + +``` +/unshare +``` + +Это приведет к удалению ссылки общего доступа и удалению данных, связанных с разговором. + +--- + +## Конфиденциальность + +Есть несколько вещей, которые следует учитывать при общении. + +--- + +### Хранение данных + +Общие разговоры остаются доступными до тех пор, пока вы явно не отмените общий доступ к ним. Этот +включает в себя: + +- Полная история разговоров +- Все сообщения и ответы +- Метаданные сеанса + +--- + +### Рекомендации + +- Делитесь только разговорами, которые не содержат конфиденциальной информации. +- Прежде чем поделиться, просмотрите содержимое разговора. +- Отмените общий доступ к разговорам после завершения сотрудничества. +- Избегайте обмена разговорами с проприетарным кодом или конфиденциальными данными. +- Для конфиденциальных проектов полностью отключите общий доступ. + +--- + +## Для предприятий + +Для корпоративных развертываний функция общего доступа может быть: + +- **Отключено** полностью из соображений безопасности. +- **Только** только для пользователей, прошедших аутентификацию посредством единого входа. +- **Автономное размещение** в вашей собственной инфраструктуре + +[Узнайте больше](/docs/enterprise) об использовании открытого кода в вашей организации. diff --git a/packages/web/src/content/docs/ru/skills.mdx b/packages/web/src/content/docs/ru/skills.mdx new file mode 100644 index 000000000..4e5cc63d0 --- /dev/null +++ b/packages/web/src/content/docs/ru/skills.mdx @@ -0,0 +1,222 @@ +--- +title: «Навыки агента» +description: «Определите повторно используемое поведение с помощью определений SKILL.md» +--- + +Навыки агента позволяют OpenCode обнаруживать многократно используемые инструкции из вашего репозитория или домашнего каталога. +Навыки загружаются по требованию с помощью встроенного инструмента `skill`: агенты видят доступные навыки и при необходимости могут загрузить весь контент. + +--- + +## Разместить файлы + +Создайте одну папку для каждого имени навыка и поместите в нее `SKILL.md`. +OpenCode выполняет поиск в следующих местах: + +- Конфигурация проекта: `.opencode/skills//SKILL.md` +- Глобальная конфигурация: `~/.config/opencode/skills//SKILL.md`. +- Совместимость с Project Claude: `.claude/skills//SKILL.md` +- Глобальная совместимость с Claude: `~/.claude/skills//SKILL.md` +- Совместимость с агентом проекта: `.agents/skills//SKILL.md` +- Совместимость с глобальным агентом: `~/.agents/skills//SKILL.md` + +--- + +## Понять открытие + +Для локальных путей проекта OpenCode переходит из вашего текущего рабочего каталога, пока не достигнет рабочего дерева git. +Он загружает все соответствующие `skills/*/SKILL.md` в `.opencode/` и все соответствующие `.claude/skills/*/SKILL.md` или `.agents/skills/*/SKILL.md` по пути. + +Глобальные определения также загружаются из `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` и `~/.agents/skills/*/SKILL.md`. + +--- + +## Напишите заголовок + +Каждый `SKILL.md` должен начинаться с заголовка YAML. +Распознаются только эти поля: + +- ХХ0ГГ (обязательно) +- ХХ0ГГ (обязательно) +- `license` (необязательно) +- `compatibility` (необязательно) +- `metadata` (необязательно, преобразование строк в строки) + +Неизвестные поля заголовка игнорируются. + +--- + +## Проверка имен + +`name` должен: + +- Длина от 1 до 64 символов. +- Используйте строчные буквы и цифры с одинарным дефисом. +- Не начинаться и не заканчиваться на `-`. +- Не содержать последовательных `--` +- Сопоставьте имя каталога, содержащее `SKILL.md`. + +Эквивалентное регулярное выражение: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## Соблюдайте правила длины + +`description` должно содержать от 1 до 1024 символов. +Держите его достаточно конкретным, чтобы агент мог сделать правильный выбор. + +--- + +## Используйте пример + +Создайте `.opencode/skills/git-release/SKILL.md` следующим образом: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## Распознать описание инструмента + +OpenCode перечисляет доступные навыки в описании инструмента `skill`. +Каждая запись включает название и описание навыка: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +Агент загружает навык, вызывая инструмент: + +``` +skill({ name: "git-release" }) +``` + +--- + +## Настройка разрешений + +Контролируйте, к каким навыкам агенты могут получить доступ, используя разрешения на основе шаблонов в `opencode.json`: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Разрешение | Поведение | +| ---------- | ----------------------------------------- | +| ХХ0ГГ | Навык загружается сразу | +| ХХ0ГГ | Навык скрыт от агента, доступ отклонен | +| ХХ0ГГ | Перед загрузкой пользователю запрашивается подтверждение | + +Шаблоны поддерживают подстановочные знаки: `internal-*` соответствует `internal-docs`, `internal-tools` и т. д. + +--- + +## Переопределить для каждого агента + +Предоставьте конкретным агентам разрешения, отличные от глобальных настроек по умолчанию. + +**Для пользовательских агентов** (в заголовке агента): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**Для встроенных агентов** (в формате `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## Отключить инструмент навыков + +Полностью отключить навыки для агентов, которым не следует их использовать: + +**Для индивидуальных агентов**: + +```yaml +--- +tools: + skill: false +--- +``` + +**Для встроенных агентов**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +Если этот параметр отключен, раздел `` полностью опускается. + +--- + +## Устранение неполадок с загрузкой + +Если навык не отображается: + +1. Убедитесь, что `SKILL.md` написано заглавными буквами. +2. Убедитесь, что заголовок включает `name` и `description`. +3. Убедитесь, что названия навыков уникальны во всех локациях. +4. Проверьте разрешения — навыки с `deny` скрыты от агентов. diff --git a/packages/web/src/content/docs/ru/themes.mdx b/packages/web/src/content/docs/ru/themes.mdx new file mode 100644 index 000000000..48aab3ef0 --- /dev/null +++ b/packages/web/src/content/docs/ru/themes.mdx @@ -0,0 +1,369 @@ +--- +title: Темы +description: Выберите встроенную тему или определите свою собственную. +--- + +С помощью OpenCode вы можете выбрать одну из нескольких встроенных тем, использовать тему, которая адаптируется к теме вашего терминала, или определить свою собственную тему. + +По умолчанию OpenCode использует нашу собственную тему `opencode`. + +--- + +## Требования к терминалу + +Чтобы темы корректно отображались в полной цветовой палитре, ваш терминал должен поддерживать **truecolor** (24-битный цвет). Большинство современных терминалов поддерживают это по умолчанию, но вам может потребоваться включить его: + +- **Проверьте поддержку**: запустите `echo $COLORTERM` — должен появиться `truecolor` или `24bit`. +- **Включить truecolor**: установите переменную среды `COLORTERM=truecolor` в профиле оболочки. +- **Совместимость терминала**: убедитесь, что ваш эмулятор терминала поддерживает 24-битный цвет (большинство современных терминалов, таких как iTerm2, Alacritty, Kitty, Windows Terminal и последние версии терминала GNOME, поддерживают). + +Без поддержки truecolor темы могут отображаться с пониженной точностью цветопередачи или вернуться к ближайшему приближению к 256 цветам. + +--- + +## Встроенные темы + +OpenCode поставляется с несколькими встроенными темами. + +| Имя | Описание | +| ---------------------- | ---------------------------------------------------------------------------- | +| ХХ0ГГ | Адаптируется к цвету фона вашего терминала | +| ХХ0ГГ | На основе темы [Tokyonight](https://github.com/folke/tokyonight.nvim) | +| ХХ0ГГ | На основе темы [Everforest](https://github.com/sainnhe/everforest) | +| ХХ0ГГ | На основе темной темы Ayu](https://github.com/ayu-theme). | +| ХХ0ГГ | На основе темы [Catppuccin](https://github.com/catppuccin) | +| ХХ0ГГ | На основе темы [Catppuccin](https://github.com/catppuccin) | +| ХХ0ГГ | На основе темы [Gruvbox](https://github.com/morhetz/gruvbox) | +| ХХ0ГГ | На основе темы [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | +| ХХ0ГГ | На основе [темы Nord](https://github.com/nordtheme/nord) | +| ХХ0ГГ | Зеленый цвет в хакерском стиле на черной теме | +| ХХ0ГГ | На основе темной темы Atom One](https://github.com/Th3Whit3Wolf/one-nvim). | + +И более того, мы постоянно добавляем новые темы. + +--- + +## Системная тема + +Тема `system` автоматически адаптируется к цветовой схеме вашего терминала. В отличие от традиционных тем, использующих фиксированные цвета, тема _system_: + +- **Создает шкалу серого**: создает пользовательскую шкалу серого на основе цвета фона вашего терминала, обеспечивая оптимальный контраст. +- **Использует цвета ANSI**: использует стандартные цвета ANSI (0–15) для подсветки синтаксиса и элементов пользовательского интерфейса, которые соответствуют цветовой палитре вашего терминала. +- **Сохраняет настройки терминала по умолчанию**: использует `none` для цветов текста и фона, чтобы сохранить естественный вид вашего терминала. + +Системная тема предназначена для пользователей, которые: + +- Хотите, чтобы OpenCode соответствовал внешнему виду их терминала +- Используйте пользовательские цветовые схемы терминала +- Предпочитайте единообразный вид для всех терминальных приложений. + +--- + +## Использование темы + +Вы можете выбрать тему, вызвав выбор темы с помощью команды `/theme`. Или вы можете указать это в файле [config](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Пользовательские темы + +OpenCode поддерживает гибкую систему тем на основе JSON, которая позволяет пользователям легко создавать и настраивать темы. + +--- + +### Иерархия + +Темы загружаются из нескольких каталогов в следующем порядке: более поздние каталоги переопределяют предыдущие: + +1. **Встроенные темы** – они встроены в двоичный файл. +2. **Каталог конфигурации пользователя** – определяется в `~/.config/opencode/themes/*.json` или `$XDG_CONFIG_HOME/opencode/themes/*.json`. +3. **Корневой каталог проекта** – определено в `/.opencode/themes/*.json`. +4. **Текущий рабочий каталог** – определено в `./.opencode/themes/*.json`. + +Если несколько каталогов содержат тему с одинаковым именем, будет использоваться тема из каталога с более высоким приоритетом. + +--- + +### Создание темы + +Чтобы создать собственную тему, создайте файл JSON в одном из каталогов темы. + +Для общепользовательских тем: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +И для тем, специфичных для проекта. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### Формат JSON + +В темах используется гибкий формат JSON с поддержкой: + +- **Шестнадцатеричные цвета**: `"#ffffff"` +- **Цвета ANSI**: `3` (0–255). +- **Ссылки на цвета**: `"primary"` или пользовательские определения. +- **Темный/светлый варианты**: `{"dark": "#000", "light": "#fff"}` +- **Нет цвета**: `"none"` — используется цвет терминала по умолчанию или прозрачный. + +--- + +### Определения цвета + +Раздел `defs` является необязательным и позволяет вам определять повторно используемые цвета, на которые можно ссылаться в теме. + +--- + +### Настройки терминала по умолчанию + +Специальное значение `"none"` можно использовать для любого цвета, чтобы наследовать цвет терминала по умолчанию. Это особенно полезно для создания тем, которые органично сочетаются с цветовой схемой вашего терминала: + +- `"text": "none"` — использует цвет переднего плана терминала по умолчанию. +- `"background": "none"` — использует цвет фона терминала по умолчанию. + +--- + +### Пример + +Вот пример пользовательской темы: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/ru/tools.mdx b/packages/web/src/content/docs/ru/tools.mdx new file mode 100644 index 000000000..239141251 --- /dev/null +++ b/packages/web/src/content/docs/ru/tools.mdx @@ -0,0 +1,379 @@ +--- +title: Инструменты +description: Управляйте инструментами, которые может использовать LLM. +--- + +Инструменты позволяют LLM выполнять действия в вашей кодовой базе. OpenCode поставляется с набором встроенных инструментов, но вы можете расширить его с помощью [пользовательских инструментов](/docs/custom-tools) или [MCP-серверов](/docs/mcp-servers). + +По умолчанию все инструменты **включены** и не требуют разрешения для запуска. Вы можете контролировать поведение инструмента через [permissions](/docs/permissions). + +--- + +## Настроить + +Используйте поле `permission` для управления поведением инструмента. Вы можете разрешить, запретить или потребовать одобрения для каждого инструмента. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +Вы также можете использовать подстановочные знаки для одновременного управления несколькими инструментами. Например, чтобы потребовать одобрения всех инструментов с сервера MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[Подробнее](/docs/permissions) о настройке разрешений. + +--- + +## Встроенный + +Вот все встроенные инструменты, доступные в OpenCode. + +--- + +### бить + +Выполняйте команды оболочки в среде вашего проекта. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +Этот инструмент позволяет LLM запускать команды терминала, такие как `npm install`, `git status` или любую другую команду оболочки. + +--- + +### редактировать + +Измените существующие файлы, используя точную замену строк. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Этот инструмент выполняет точное редактирование файлов, заменяя точные совпадения текста. Это основной способ изменения кода в LLM. + +--- + +### писать + +Создавайте новые файлы или перезаписывайте существующие. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Используйте это, чтобы позволить LLM создавать новые файлы. Он перезапишет существующие файлы, если они уже существуют. + +:::примечание +Инструмент `write` контролируется разрешением `edit`, которое распространяется на все модификации файлов (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### читать + +Прочитайте содержимое файла из вашей кодовой базы. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +Этот инструмент читает файлы и возвращает их содержимое. Он поддерживает чтение определенных диапазонов строк для больших файлов. + +--- + +### grep + +Поиск содержимого файла с помощью регулярных выражений. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Быстрый поиск контента по вашей кодовой базе. Поддерживает полный синтаксис регулярных выражений и фильтрацию шаблонов файлов. + +--- + +### шарик + +Найдите файлы по шаблону. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +Ищите файлы, используя шаблоны glob, например `**/*.js` или `src/**/*.ts`. Возвращает соответствующие пути к файлам, отсортированные по времени изменения. + +--- + +### список + +Список файлов и каталогов по заданному пути. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +Этот инструмент отображает содержимое каталога. Он принимает шаблоны glob для фильтрации результатов. + +--- + +### лсп (экспериментальный) + +Взаимодействуйте с настроенными серверами LSP, чтобы получить функции анализа кода, такие как определения, ссылки, информация о наведении и иерархия вызовов. + +:::примечание +Этот инструмент доступен только при `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (или `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +Поддерживаемые операции включают `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` и `outgoingCalls`. + +Чтобы настроить серверы LSP, доступные для вашего проекта, см. [LSP Servers](/docs/lsp). + +--- + +### пластырь + +Применяйте патчи к файлам. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Этот инструмент применяет файлы исправлений к вашей кодовой базе. Полезно для применения различий и патчей из различных источников. + +:::примечание +Инструмент `patch` контролируется разрешением `edit`, которое распространяется на все модификации файлов (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### навык + +Загрузите [skill](/docs/skills) (файл `SKILL.md`) и верните его содержимое в диалог. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todowrite + +Управляйте списками дел во время сеансов кодирования. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +Создает и обновляет списки задач для отслеживания прогресса во время сложных операций. LLM использует это для организации многоэтапных задач. + +:::примечание +По умолчанию этот инструмент отключен для субагентов, но вы можете включить его вручную. [Подробнее](/docs/agents/#permissions) +::: + +--- + +### todoread + +Прочтите существующие списки дел. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +Считывает текущее состояние списка дел. Используется LLM для отслеживания задач, ожидающих или завершенных. + +:::примечание +По умолчанию этот инструмент отключен для субагентов, но вы можете включить его вручную. [Подробнее](/docs/agents/#permissions) +::: + +--- + +### веб-загрузка + +Получить веб-контент. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +Позволяет LLM получать и читать веб-страницы. Полезно для поиска документации или исследования онлайн-ресурсов. + +--- + +### веб-поиск + +Найдите информацию в Интернете. + +:::примечание +Этот инструмент доступен только при использовании поставщика OpenCode или когда для переменной среды `OPENCODE_ENABLE_EXA` установлено любое истинное значение (например, `true` или `1`). + +Чтобы включить при запуске OpenCode: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Выполняет поиск в Интернете с помощью Exa AI для поиска соответствующей информации в Интернете. Полезно для исследования тем, поиска текущих событий или сбора информации, выходящей за рамки данных обучения. + +Ключ API не требуется — инструмент подключается напрямую к сервису MCP, размещенному на Exa AI, без аутентификации. + +:::кончик +Используйте `websearch`, когда вам нужно найти информацию (обнаружение), и `webfetch`, когда вам нужно получить контент с определенного URL-адреса (извлечение). +::: + +--- + +### вопрос + +Задавайте вопросы пользователю во время выполнения. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +Этот инструмент позволяет LLM задавать вопросы пользователю во время выполнения задачи. Это полезно для: + +- Сбор предпочтений или требований пользователей +- Уточнение двусмысленных инструкций +- Получение решений по вариантам реализации +- Предлагая выбор, в каком направлении двигаться + +Каждый вопрос включает заголовок, текст вопроса и список вариантов. Пользователи могут выбрать один из предложенных вариантов или ввести собственный ответ. Если вопросов несколько, пользователи могут перемещаться между ними, прежде чем отправлять все ответы. + +--- + +## Пользовательские инструменты + +Пользовательские инструменты позволяют вам определять собственные функции, которые может вызывать LLM. Они определены в вашем файле конфигурации и могут выполнять произвольный код. + +[Подробнее](/docs/custom-tools) о создании собственных инструментов. + +--- + +## MCP-серверы + +Серверы MCP (Model Context Protocol) позволяют интегрировать внешние инструменты и сервисы. Сюда входит доступ к базе данных, интеграция API и сторонние сервисы. + +[Подробнее](/docs/mcp-servers) о настройке серверов MCP. + +--- + +## Внутренности + +Внутренне такие инструменты, как `grep`, `glob` и `list`, используют [ripgrep](https://github.com/BurntSushi/ripgrep). По умолчанию ripgrep учитывает шаблоны `.gitignore`, что означает, что файлы и каталоги, перечисленные в вашем `.gitignore`, будут исключены из поиска и списков. + +--- + +### Игнорировать шаблоны + +Чтобы включить файлы, которые обычно игнорируются, создайте файл `.ignore` в корне вашего проекта. Этот файл может явно разрешать определенные пути. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +Например, этот файл `.ignore` позволяет ripgrep выполнять поиск в каталогах `node_modules/`, `dist/` и `build/`, даже если они указаны в `.gitignore`. diff --git a/packages/web/src/content/docs/ru/troubleshooting.mdx b/packages/web/src/content/docs/ru/troubleshooting.mdx new file mode 100644 index 000000000..df1cfab03 --- /dev/null +++ b/packages/web/src/content/docs/ru/troubleshooting.mdx @@ -0,0 +1,300 @@ +--- +title: Поиск неисправностей +description: Распространенные проблемы и способы их решения. +--- + +Чтобы устранить проблемы с OpenCode, начните с проверки журналов и локальных данных, которые он хранит на диске. + +--- + +## Журналы + +Лог-файлы записываются в: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: нажмите `WIN+R` и вставьте `%USERPROFILE%\.local\share\opencode\log`. + +Файлам журналов присваиваются имена с метками времени (например, `2025-01-09T123456.log`), и сохраняются 10 последних файлов журналов. + +Вы можете установить уровень журнала с помощью параметра командной строки `--log-level`, чтобы получить более подробную информацию об отладке. Например, `opencode --log-level DEBUG`. + +--- + +## Хранилище + +opencode хранит данные сеанса и другие данные приложения на диске по адресу: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: нажмите `WIN+R` и вставьте `%USERPROFILE%\.local\share\opencode`. + +Этот каталог содержит: + +- `auth.json` – данные аутентификации, такие как ключи API и токены OAuth. +- `log/` – журналы приложений. +- `project/` — данные, специфичные для проекта, такие как данные сеанса и сообщения. + - Если проект находится в репозитории Git, он хранится в `.//storage/`. + - Если это не репозиторий Git, он хранится в `./global/storage/`. + +--- + +## Настольное приложение + +OpenCode Desktop запускает локальный сервер OpenCode (сопутствующий модуль `opencode-cli`) в фоновом режиме. Большинство проблем вызвано неправильно работающим плагином, поврежденным кешем или неверными настройками сервера. + +### Быстрые проверки + +- Полностью закройте и перезапустите приложение. +- Если приложение отображает экран с ошибкой, нажмите **Перезапустить** и скопируйте сведения об ошибке. +- Только для macOS: меню `OpenCode` -> **Обновить веб-просмотр** (помогает, если пользовательский интерфейс пуст или завис). + +--- + +### Отключить плагины + +Если настольное приложение дает сбой при запуске, зависает или ведет себя странно, начните с отключения плагинов. + +#### Проверьте глобальную конфигурацию + +Откройте файл глобальной конфигурации и найдите ключ `plugin`. + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (или `~/.config/opencode/opencode.json`) +- **macOS/Linux** (более ранние версии): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: нажмите `WIN+R` и вставьте `%USERPROFILE%\.config\opencode\opencode.jsonc`. + +Если у вас настроены плагины, временно отключите их, удалив ключ или установив для него пустой массив: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### Проверьте каталоги плагинов + +OpenCode также может загружать локальные плагины с диска. Временно переместите их в сторону (или переименуйте папку) и перезапустите настольное приложение: + +- **Глобальные плагины** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: нажмите `WIN+R` и вставьте `%USERPROFILE%\.config\opencode\plugins`. +- **Плагины проекта** (только если вы используете конфигурацию для каждого проекта) + - ХХ0ГГ + +Если приложение снова начнет работать, повторно включите плагины по одному, чтобы определить, какой из них вызывает проблему. + +--- + +### Очистить кеш + +Если отключение плагинов не помогает (или установка плагина зависла), очистите кеш, чтобы OpenCode мог его пересобрать. + +1. Полностью закройте OpenCode Desktop. +2. Удалите каталог кэша: + +- **macOS**: Finder -> `Cmd+Shift+G` -> вставить `~/.cache/opencode`. +- **Linux**: удалите `~/.cache/opencode` (или запустите `rm -rf ~/.cache/opencode`). +- **Windows**: нажмите `WIN+R` и вставьте `%USERPROFILE%\.cache\opencode`. + +3. Перезапустите рабочий стол OpenCode. + +--- + +### Исправить проблемы с подключением к серверу + +OpenCode Desktop может либо запустить собственный локальный сервер (по умолчанию), либо подключиться к настроенному вами URL-адресу сервера. + +Если вы видите диалоговое окно **Ошибка подключения** (или приложение никогда не выходит за пределы заставки), проверьте URL-адрес пользовательского сервера. + +#### Очистите URL-адрес сервера по умолчанию для рабочего стола. + +На главном экране щелкните имя сервера (с точкой состояния), чтобы открыть окно выбора сервера. В разделе **Сервер по умолчанию** нажмите **Очистить**. + +#### Удалите `server.port`/`server.hostname` из вашей конфигурации. + +Если ваш `opencode.json(c)` содержит раздел `server`, временно удалите его и перезапустите настольное приложение. + +#### Проверьте переменные среды + +Если в вашей среде установлен `OPENCODE_PORT`, настольное приложение попытается использовать этот порт для локального сервера. + +- Отмените настройку `OPENCODE_PORT` (или выберите свободный порт) и перезапустите. + +--- + +### Linux: проблемы с Wayland/X11 + +В Linux некоторые настройки Wayland могут вызывать пустые окна или ошибки компоновщика. + +- Если вы используете Wayland, а приложение не работает или вылетает, попробуйте запустить с помощью `OC_ALLOW_WAYLAND=1`. +- Если это усугубляет ситуацию, удалите его и попробуйте вместо этого запустить сеанс X11. + +--- + +### Windows: среда выполнения WebView2. + +В Windows для OpenCode Desktop требуется Microsoft Edge **WebView2 Runtime**. Если приложение открывается в пустом окне или не запускается, установите/обновите WebView2 и повторите попытку. + +--- + +### Windows: общие проблемы с производительностью + +Если вы испытываете низкую производительность, проблемы с доступом к файлам или проблемы с терминалом в Windows, попробуйте использовать [WSL (подсистема Windows для Linux)](/docs/windows-wsl). WSL предоставляет среду Linux, которая более эффективно работает с функциями OpenCode. + +--- + +### Уведомления не отображаются + +OpenCode Desktop отображает системные уведомления только в следующих случаях: + +- уведомления для OpenCode включены в настройках вашей ОС, и +- окно приложения не в фокусе. + +--- + +### Сбросить хранилище настольных приложений (последнее средство) + +Если приложение не запускается и вы не можете очистить настройки из пользовательского интерфейса, сбросьте сохраненное состояние настольного приложения. + +1. Закройте рабочий стол OpenCode. +2. Найдите и удалите эти файлы (они находятся в каталоге данных приложения OpenCode Desktop): + +- `opencode.settings.dat` (URL-адрес сервера по умолчанию для рабочего стола) +- `opencode.global.dat` и `opencode.workspace.*.dat` (состояние пользовательского интерфейса, например, недавние серверы/проекты) + +Чтобы быстро найти каталог: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (затем найдите имена файлов, указанные выше) +- **Linux**: найдите в `~/.local/share` имена файлов, указанные выше. +- **Windows**: нажмите `WIN+R` -> `%APPDATA%` (затем найдите имена файлов, указанные выше). + +--- + +## Получение помощи + +Если у вас возникли проблемы с OpenCode: + +1. **Сообщайте о проблемах на GitHub** + + Лучший способ сообщить об ошибках или запросить новые функции — через наш репозиторий GitHub: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + Прежде чем создавать новую проблему, выполните поиск по существующим проблемам, чтобы узнать, не сообщалось ли уже о вашей проблеме. + +2. **Присоединяйтесь к нашему Discord** + + Для получения помощи в режиме реального времени и обсуждения в сообществе присоединяйтесь к нашему серверу Discord: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Общие проблемы + +Вот некоторые распространенные проблемы и способы их решения. + +--- + +### OpenCode не запускается + +1. Проверьте журналы на наличие сообщений об ошибках +2. Попробуйте запустить `--print-logs`, чтобы увидеть вывод в терминале. +3. Убедитесь, что у вас установлена ​​последняя версия `opencode upgrade`. + +--- + +### Проблемы аутентификации + +1. Попробуйте выполнить повторную аутентификацию с помощью команды `/connect` в TUI. +2. Убедитесь, что ваши ключи API действительны +3. Убедитесь, что ваша сеть разрешает подключения к API провайдера. + +--- + +### Модель недоступна + +1. Убедитесь, что вы прошли аутентификацию у провайдера +2. Проверьте правильность названия модели в вашей конфигурации. +3. Для некоторых моделей может потребоваться специальный доступ или подписка. + +Если вы столкнулись с `ProviderModelNotFoundError`, вы, скорее всего, ошибаетесь. +ссылка на модель где-то. +На модели следует ссылаться следующим образом: `/`. + +Примеры: + +- ХХ0ГГ +- ХХ0ГГ +- ХХ0ГГ + +Чтобы выяснить, к каким моделям у вас есть доступ, запустите `opencode models`. + +--- + +### Провидеринитеррор + +Если вы столкнулись с ошибкой ProviderInitError, скорее всего, у вас неверная или поврежденная конфигурация. + +Чтобы решить эту проблему: + +1. Сначала убедитесь, что ваш провайдер настроен правильно, следуя [руководству провайдеров](/docs/providers) +2. Если проблема не устранена, попробуйте очистить сохраненную конфигурацию: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + В Windows нажмите `WIN+R` и удалите: `%USERPROFILE%\.local\share\opencode`. + +3. Повторно выполните аутентификацию у своего провайдера, используя команду `/connect` в TUI. + +--- + +### AI_APICallError и проблемы с пакетом провайдера + +Если вы столкнулись с ошибками вызова API, это может быть связано с устаревшими пакетами провайдера. opencode динамически устанавливает пакеты провайдеров (OpenAI, Anthropic, Google и т. д.) по мере необходимости и кэширует их локально. + +Чтобы решить проблемы с пакетом поставщика: + +1. Очистите кеш пакетов провайдера: + + ```bash + rm -rf ~/.cache/opencode + ``` + + В Windows нажмите `WIN+R` и удалите: `%USERPROFILE%\.cache\opencode`. + +2. Перезапустите открытый код, чтобы переустановить последние пакеты поставщиков. + +Это заставит opencode загружать самые последние версии пакетов провайдеров, что часто решает проблемы совместимости с параметрами модели и изменениями API. + +--- + +### Копирование/вставка не работает в Linux + +Для работы функций копирования/вставки пользователям Linux необходимо установить одну из следующих утилит буфера обмена: + +**Для систем X11:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**Для систем Wayland:** + +```bash +apt install -y wl-clipboard +``` + +**Для безголовых сред:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode определит, используете ли вы Wayland и предпочитаете `wl-clipboard`, в противном случае он попытается найти инструменты буфера обмена в порядке: `xclip` и `xsel`. diff --git a/packages/web/src/content/docs/ru/tui.mdx b/packages/web/src/content/docs/ru/tui.mdx new file mode 100644 index 000000000..e08ab84e4 --- /dev/null +++ b/packages/web/src/content/docs/ru/tui.mdx @@ -0,0 +1,390 @@ +--- +title: ТУИ +description: Использование пользовательского интерфейса терминала OpenCode. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode предоставляет интерактивный интерфейс терминала или TUI для работы над вашими проектами с помощью LLM. + +Запуск OpenCode запускает TUI для текущего каталога. + +```bash +opencode +``` + +Или вы можете запустить его для определенного рабочего каталога. + +```bash +opencode /path/to/project +``` + +Как только вы окажетесь в TUI, вы можете запросить его с помощью сообщения. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## Ссылки на файлы + +Вы можете ссылаться на файлы в своих сообщениях, используя `@`. Это выполняет нечеткий поиск файлов в текущем рабочем каталоге. + +:::кончик +Вы также можете использовать `@` для ссылки на файлы в своих сообщениях. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +Содержимое файла добавляется в беседу автоматически. + +--- + +## Bash-команды + +Начните сообщение с `!`, чтобы запустить команду оболочки. + +```bash frame="none" +!ls -la +``` + +Вывод команды добавляется в диалог как результат работы инструмента. + +--- + +## Команды + +При использовании OpenCode TUI вы можете ввести `/`, а затем имя команды, чтобы быстро выполнить действия. Например: + +```bash frame="none" +/help +``` + +Большинство команд также имеют привязку клавиш с использованием `ctrl+x` в качестве ведущей клавиши, где `ctrl+x` — это ведущая клавиша по умолчанию. [Подробнее ](/docs/keybinds). + +Вот все доступные слэш-команды: + +--- + +### соединять + +Добавьте провайдера в OpenCode. Позволяет выбирать из доступных поставщиков и добавлять их ключи API. + +```bash frame="none" +/connect +``` + +--- + +### компактный + +Сжать текущий сеанс. _Псевдоним_: `/summarize` + +```bash frame="none" +/compact +``` + +**Привязка клавиш:** `ctrl+x c` + +--- + +### подробности + +Переключить детали выполнения инструмента. + +```bash frame="none" +/details +``` + +**Привязка клавиш:** `ctrl+x d` + +--- + +### редактор + +Открыть внешний редактор для составления сообщений. Использует редактор, установленный в переменной среды `EDITOR`. [Подробнее ](#editor-setup). + +```bash frame="none" +/editor +``` + +**Привязка клавиш:** `ctrl+x e` + +--- + +### Выход + +Выйдите из OpenCode. _Псевдонимы_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Привязка клавиш:** `ctrl+x q` + +--- + +### экспорт + +Экспортируйте текущий разговор в Markdown и откройте его в редакторе по умолчанию. Использует редактор, установленный в переменной среды `EDITOR`. [Подробнее ](#editor-setup). + +```bash frame="none" +/export +``` + +**Привязка клавиш:** `ctrl+x x` + +--- + +### помощь + +Показать диалоговое окно помощи. + +```bash frame="none" +/help +``` + +**Привязка клавиш:** `ctrl+x h` + +--- + +### инициализация + +Создайте или обновите файл `AGENTS.md`. [Подробнее ](/docs/rules). + +```bash frame="none" +/init +``` + +**Привязка клавиш:** `ctrl+x i` + +--- + +### модели + +Перечислите доступные модели. + +```bash frame="none" +/models +``` + +**Привязка клавиш:** `ctrl+x m` + +--- + +### новый + +Начать новый сеанс. _Псевдоним_: `/clear` + +```bash frame="none" +/new +``` + +**Привязка клавиш:** `ctrl+x n` + +--- + +### переделывать + +Повторить ранее отмененное сообщение. Доступно только после использования `/undo`. + +:::кончик +Любые изменения файлов также будут восстановлены. +::: + +Внутри это использует Git для управления изменениями файлов. Итак, ваш проект ** должен +быть репозиторием Git**. + +```bash frame="none" +/redo +``` + +**Привязка клавиш:** `ctrl+x r` + +--- + +### сессии + +Составляйте список и переключайтесь между сеансами. _Псевдонимы_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Привязка клавиш:** `ctrl+x l` + +--- + +### делиться + +Поделиться текущим сеансом. [Подробнее](/docs/share). + +```bash frame="none" +/share +``` + +**Привязка клавиш:** `ctrl+x s` + +--- + +### темы + +Список доступных тем. + +```bash frame="none" +/theme +``` + +**Привязка клавиш:** `ctrl+x t` + +--- + +### мышление + +Переключить видимость блоков мышления/рассуждения в разговоре. Если этот параметр включен, вы можете увидеть процесс рассуждения модели для моделей, поддерживающих расширенное мышление. + +:::примечание +Эта команда только контролирует, будут ли **отображаться** блоки мышления, но не включает и не отключает возможности модели по рассуждению. Чтобы переключить фактические возможности рассуждения, используйте `ctrl+t` для циклического переключения вариантов модели. +::: + +```bash frame="none" +/thinking +``` + +--- + +### отменить + +Отменить последнее сообщение в разговоре. Удаляет самое последнее сообщение пользователя, все последующие ответы и любые изменения файлов. + +:::кончик +Любые внесенные изменения в файле также будут отменены. +::: + +Внутри это использует Git для управления изменениями файлов. Итак, ваш проект ** должен +быть репозиторием Git**. + +```bash frame="none" +/undo +``` + +**Привязка клавиш:** `ctrl+x u` + +--- + +### отменить совместное использование + +Отменить общий доступ к текущему сеансу. [Подробнее](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## Настройка редактора + +Команды `/editor` и `/export` используют редактор, указанный в переменной среды `EDITOR`. + +ХХ0ГГ + ХХ0ГГ + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + + Чтобы сделать его постоянным, добавьте это в свой профиль оболочки; + `~/.bashrc`, `~/.zshrc` и т. д. + + ХХ0ГГ + + ХХ0ГГ + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + + Чтобы сделать его постоянным, используйте **Свойства системы** > **Среда. + Переменные**. + + ХХ0ГГ + + ХХ0ГГ + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + + Чтобы сделать его постоянным, добавьте его в свой профиль PowerShell. + + ХХ0ГГ +ХХ0ГГ + +Популярные варианты редактора включают в себя: + +- `code` — код Visual Studio +- `cursor` — Курсор +- `windsurf` - Виндсерфинг +- `nvim` - Редактор Neovim +- `vim` — редактор Vim +- `nano` — Нано-редактор +- `notepad` — Блокнот Windows +- `subl` – возвышенный текст + +:::примечание +Некоторые редакторы, такие как VS Code, необходимо запускать с флагом `--wait`. +::: + +Некоторым редакторам для работы в режиме блокировки необходимы аргументы командной строки. Флаг `--wait` блокирует процесс редактора до его закрытия. + +--- + +## Настроить + +Вы можете настроить поведение TUI через файл конфигурации OpenCode. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### Параметры + +- `scroll_acceleration` — включите ускорение прокрутки в стиле macOS для плавной и естественной прокрутки. Если этот параметр включен, скорость прокрутки увеличивается при быстрой прокрутке и остается точной при более медленных движениях. **Этот параметр имеет приоритет над `scroll_speed` и переопределяет его, если он включен.** +- `scroll_speed` — контролирует скорость прокрутки TUI при использовании команд прокрутки (минимум: `1`). По умолчанию `3`. **Примечание. Это игнорируется, если для `scroll_acceleration.enabled` установлено значение `true`.** + +--- + +## Кастомизация + +Вы можете настроить различные аспекты представления TUI, используя палитру команд (`ctrl+x h` или `/help`). Эти настройки сохраняются после перезапуска. + +--- + +#### Отображение имени пользователя + +Включите, будет ли ваше имя пользователя отображаться в сообщениях чата. Доступ к этому через: + +- Палитра команд: поиск «имя пользователя» или «скрыть имя пользователя». +- Настройка сохраняется автоматически и будет запоминаться во время сеансов TUI. diff --git a/packages/web/src/content/docs/ru/web.mdx b/packages/web/src/content/docs/ru/web.mdx new file mode 100644 index 000000000..d99abf883 --- /dev/null +++ b/packages/web/src/content/docs/ru/web.mdx @@ -0,0 +1,142 @@ +--- +title: Интернет +description: Использование OpenCode в вашем браузере. +--- + +OpenCode может работать как веб-приложение в вашем браузере, обеспечивая такой же мощный опыт кодирования AI без необходимости использования терминала. + +![OpenCode Web — новый сеанс](../../../assets/web/web-homepage-new-session.png) + +## Начиная + +Запустите веб-интерфейс, выполнив: + +```bash +opencode web +``` + +Это запустит локальный сервер `127.0.0.1` со случайным доступным портом и автоматически откроет OpenCode в браузере по умолчанию. + +:::осторожность +Если `OPENCODE_SERVER_PASSWORD` не установлен, сервер будет незащищен. Это подходит для локального использования, но его следует настроить для доступа к сети. +::: + +:::tip[Пользователи Windows] +Для получения наилучших результатов запустите `opencode web` из [WSL](/docs/windows-wsl), а не из PowerShell. Это обеспечивает правильный доступ к файловой системе и интеграцию терминала. +::: + +--- + +## Конфигурация + +Вы можете настроить веб-сервер с помощью флагов командной строки или в файле [config file](/docs/config). + +### Порт + +По умолчанию OpenCode выбирает доступный порт. Вы можете указать порт: + +```bash +opencode web --port 4096 +``` + +### Имя хоста + +По умолчанию сервер привязывается к `127.0.0.1` (только локальный хост). Чтобы сделать OpenCode доступным в вашей сети: + +```bash +opencode web --hostname 0.0.0.0 +``` + +При использовании `0.0.0.0` OpenCode будет отображать как локальные, так и сетевые адреса: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### обнаружение mDNS + +Включите mDNS, чтобы ваш сервер был доступен для обнаружения в локальной сети: + +```bash +opencode web --mdns +``` + +Это автоматически устанавливает имя хоста `0.0.0.0` и объявляет сервер как `opencode.local`. + +Вы можете настроить доменное имя mDNS для запуска нескольких экземпляров в одной сети: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### КОРС + +Чтобы разрешить дополнительные домены для CORS (полезно для пользовательских интерфейсов): + +```bash +opencode web --cors https://example.com +``` + +### Аутентификация + +Чтобы защитить доступ, установите пароль, используя переменную среды `OPENCODE_SERVER_PASSWORD`: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +Имя пользователя по умолчанию — `opencode`, но его можно изменить с помощью `OPENCODE_SERVER_USERNAME`. + +--- + +## Использование веб-интерфейса + +После запуска веб-интерфейс предоставляет доступ к вашим сеансам OpenCode. + +### Сессии + +Просматривайте свои сеансы и управляйте ими с главной страницы. Вы можете видеть активные сеансы и начинать новые. + +![OpenCode Web — активный сеанс](../../../assets/web/web-homepage-active-session.png) + +### Статус сервера + +Нажмите «Просмотреть серверы», чтобы просмотреть подключенные серверы и их статус. + +![OpenCode Web — см. Серверы](../../../assets/web/web-homepage-see-servers.png) + +--- + +## Подключение терминала + +Вы можете подключить TUI терминала к работающему веб-серверу: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +Это позволяет вам одновременно использовать веб-интерфейс и терминал, используя одни и те же сеансы и состояние. + +--- + +## Конфигурационный файл + +Вы также можете настроить параметры сервера в файле конфигурации `opencode.json`: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +Флаги командной строки имеют приоритет над настройками файла конфигурации. diff --git a/packages/web/src/content/docs/ru/windows-wsl.mdx b/packages/web/src/content/docs/ru/windows-wsl.mdx new file mode 100644 index 000000000..9043403e7 --- /dev/null +++ b/packages/web/src/content/docs/ru/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: Запускайте OpenCode в Windows через WSL. +--- + +import { Steps } from "@astrojs/starlight/components" + +OpenCode можно запускать напрямую в Windows, но для лучшего опыта мы рекомендуем [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install). WSL дает Linux-среду, которая отлично работает с возможностями OpenCode. + +:::tip[Почему WSL?] +WSL дает более высокую производительность файловой системы, полноценную поддержку терминала и совместимость с инструментами разработки, на которые опирается OpenCode. +::: + +--- + +## Настройка + + + +1. **Установите WSL** + + Если вы еще не сделали этого, установите WSL по [официальному руководству Microsoft](https://learn.microsoft.com/en-us/windows/wsl/install). + +2. **Установите OpenCode в WSL** + + После настройки WSL откройте терминал WSL и установите OpenCode одним из [способов установки](/docs/). + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **Запускайте OpenCode из WSL** + + Перейдите в каталог проекта (к файлам Windows можно обращаться через `/mnt/c/`, `/mnt/d/` и т.д.) и запустите OpenCode. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## Десктопное приложение + сервер в WSL + +Если вы предпочитаете OpenCode Desktop, но хотите запускать сервер в WSL: + +1. **Запустите сервер в WSL** с параметром `--hostname 0.0.0.0`, чтобы разрешить внешние подключения: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Подключите десктопное приложение** к `http://localhost:4096` + +:::note +Если в вашей конфигурации `localhost` не работает, используйте IP-адрес WSL (выполните в WSL: `hostname -I`) и подключайтесь по `http://:4096`. +::: + +:::caution +При использовании `--hostname 0.0.0.0` задайте `OPENCODE_SERVER_PASSWORD`, чтобы защитить сервер. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Веб-клиент + WSL + +Для лучшего веб-опыта в Windows: + +1. **Запускайте `opencode web` в терминале WSL**, а не в PowerShell: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Открывайте в браузере Windows** адрес `http://localhost:` (OpenCode выведет URL) + +Запуск `opencode web` из WSL обеспечивает корректный доступ к файловой системе и интеграцию с терминалом, при этом интерфейс остается доступным из браузера Windows. + +--- + +## Доступ к файлам Windows + +WSL может получать доступ ко всем вашим файлам Windows через каталог `/mnt/`: + +- `C:` drive → `/mnt/c/` +- `D:` drive → `/mnt/d/` +- И так далее + +Пример: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +Для максимально плавной работы стоит клонировать или скопировать репозиторий в файловую систему WSL (например, в `~/code/`) и запускать OpenCode оттуда. +::: + +--- + +## Советы + +- Даже для проектов на дисках Windows запускайте OpenCode в WSL, чтобы получить более плавный доступ к файлам +- Используйте OpenCode вместе с [расширением WSL для VS Code](https://code.visualstudio.com/docs/remote/wsl) для единого рабочего процесса +- Конфигурация и сессии OpenCode хранятся в среде WSL по пути `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/ru/zen.mdx b/packages/web/src/content/docs/ru/zen.mdx new file mode 100644 index 000000000..8623ae7bc --- /dev/null +++ b/packages/web/src/content/docs/ru/zen.mdx @@ -0,0 +1,254 @@ +--- +title: Дзен +description: Кураторский список моделей, предоставленный OpenCode. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen — это список протестированных и проверенных моделей, предоставленный командой OpenCode. + +:::примечание +OpenCode Zen в настоящее время находится в стадии бета-тестирования. +::: + +Zen работает как любой другой провайдер в OpenCode. Вы входите в OpenCode Zen и получаете +ваш ключ API. Это **совершенно необязательно**, и вам не обязательно использовать его для использования +Открытый код. + +--- + +## Фон + +Существует большое количество моделей, но лишь некоторые из них. +эти модели хорошо работают в качестве агентов кодирования. Кроме того, большинство провайдеров +настроен совсем по-другому; так что вы получите совсем другую производительность и качество. + +:::кончик +Мы протестировали избранную группу моделей и поставщиков, которые хорошо работают с OpenCode. +::: + +Поэтому, если вы используете модель через что-то вроде OpenRouter, вы никогда не сможете +уверен, что вы получаете лучшую версию модели, которую хотите. + +Чтобы это исправить, мы сделали пару вещей: + +1. Мы протестировали избранную группу моделей и поговорили с их командами о том, как + лучше всего запустить их. +2. Затем мы поработали с несколькими поставщиками услуг, чтобы убедиться, что они обслуживаются. + правильно. +3. Наконец, мы сравнили комбинацию модель/провайдер и пришли к выводу, что + со списком, который мы с удовольствием рекомендуем. + +OpenCode Zen — это шлюз искусственного интеллекта, который дает вам доступ к этим моделям. + +--- + +## Как это работает + +OpenCode Zen работает так же, как и любой другой поставщик OpenCode. + +1. Вы входите в систему **OpenCode Zen**, добавляете свой платежный аккаунт. + подробности и скопируйте свой ключ API. +2. Вы запускаете команду `/connect` в TUI, выбираете OpenCode Zen и вставляете свой ключ API. +3. Запустите `/models` в TUI, чтобы просмотреть список рекомендуемых нами моделей. + +С вас взимается плата за каждый запрос, и вы можете добавить кредиты на свой счет. + +--- + +## Конечные точки + +Вы также можете получить доступ к нашим моделям через следующие конечные точки API. + +| Модель | Идентификатор модели | Конечная точка | Пакет AI SDK | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | ХХ0ГГ | ХХ0ГГ | +| Кодекс GPT 5.2 | gpt-5.2-кодекс | ХХ0ГГ | ХХ0ГГ | +| GPT 5.1 | gpt-5.1 | ХХ0ГГ | ХХ0ГГ | +| Кодекс GPT 5.1 | gpt-5.1-кодекс | ХХ0ГГ | ХХ0ГГ | +| Кодекс GPT 5.1 Макс. | gpt-5.1-кодекс-макс | ХХ0ГГ | ХХ0ГГ | +| Кодекс GPT 5.1 Мини | gpt-5.1-кодекс-мини | ХХ0ГГ | ХХ0ГГ | +| GPT 5 | гпт-5 | ХХ0ГГ | ХХ0ГГ | +| Кодекс GPT 5 | gpt-5-кодекс | ХХ0ГГ | ХХ0ГГ | +| ГПТ 5 Нано | gpt-5-нано | ХХ0ГГ | ХХ0ГГ | +| Клод Сонет 4.5 | Клод-сонет-4-5 | ХХ0ГГ | ХХ0ГГ | +| Клод Сонет 4 | Клод-Сонет-4 | ХХ0ГГ | ХХ0ГГ | +| Клод Хайку 4.5 | Клод-Хайку-4-5 | ХХ0ГГ | ХХ0ГГ | +| Клод Хайку 3.5 | Клод-3-5-хайку | ХХ0ГГ | ХХ0ГГ | +| Закрыть работу 4.6 | плотная работа-4-6 | ХХ0ГГ | ХХ0ГГ | +| Закрыть работу 4.5 | плотная работа-4-5 | ХХ0ГГ | ХХ0ГГ | +| Закрыть работу 4.1 | плотная работа-4-1 | ХХ0ГГ | ХХ0ГГ | +| Близнецы 3 Про | Близнецы-3-про | ХХ0ГГ | ХХ0ГГ | +| Близнецы 3 Флэш | Близнецы-3-вспышка | ХХ0ГГ | ХХ0ГГ | +| МиниМакс М2.1 | минимакс-м2.1 | ХХ0ГГ | ХХ0ГГ | +| МиниМакс М2.1 Бесплатно | минимакс-м2.1-бесплатно | ХХ0ГГ | ХХ0ГГ | +| ГЛМ 4.7 | глм-4.7 | ХХ0ГГ | ХХ0ГГ | +| ГЛМ 4.7 Бесплатно | glm-4.7-бесплатно | ХХ0ГГ | ХХ0ГГ | +| ГЛМ 4.6 | глм-4.6 | ХХ0ГГ | ХХ0ГГ | +| Как К2.5 | ас-к2.5 | ХХ0ГГ | ХХ0ГГ | +| Кими K2.5 Бесплатно | кими-к2.5-бесплатно | ХХ0ГГ | ХХ0ГГ | +| Кими К2 думает | Кими-К2-думает | ХХ0ГГ | ХХ0ГГ | +| Как К2 | as-k2 | ХХ0ГГ | ХХ0ГГ | +| Qwen3 Кодер 480B | qwen3-кодер | ХХ0ГГ | ХХ0ГГ | +| Большой рассол | большой рассол | ХХ0ГГ | ХХ0ГГ | + +[модель id](/docs/config/#models) в вашей конфигурации OpenCode +использует формат `opencode/`. Например, для Кодекса GPT 5.2 вы должны +используйте `opencode/gpt-5.2-codex` в вашей конфигурации. + +--- + +### Модели + +Полный список доступных моделей и их метаданные можно получить по адресу: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## Цены + +Мы поддерживаем модель оплаты по мере использования. Ниже приведены цены **за 1 миллион токенов**. + +| Модель | Вход | Выход | Кэшированное чтение | Кэшированная запись | +| --------------------------------- | ------ | ------ | ----------- | ------------ | +| Большой рассол | Бесплатно | Бесплатно | Бесплатно | - | +| МиниМакс М2.1 Бесплатно | Бесплатно | Бесплатно | Бесплатно | - | +| МиниМакс М2.1 | $0.30 | $1.20 | $0.10 | - | +| ГЛМ 4.7 Бесплатно | Бесплатно | Бесплатно | Бесплатно | - | +| ГЛМ 4.7 | $0.60 | $2.20 | $0.10 | - | +| ГЛМ 4.6 | $0.60 | $2.20 | $0.10 | - | +| Кими K2.5 Бесплатно | Бесплатно | Бесплатно | Бесплатно | - | +| Как К2.5 | $0.60 | $3.00 | $0.08 | - | +| Кими К2 думает | $0.40 | $2.50 | - | - | +| Как К2 | $0.40 | $2.50 | - | - | +| Qwen3 Кодер 480B | $0.45 | $1.50 | - | - | +| Клод Сонет 4.5 (≤ 200 тыс. токенов) | $3.00 | $15.00 | $0.30 | $3.75 | +| Клод Сонет 4.5 (> 200 тыс. токенов) | $6.00 | $22.50 | $0.60 | $7.50 | +| Клод Сонет 4 (≤ 200 тыс. токенов) | $3.00 | $15.00 | $0.30 | $3.75 | +| Клод Сонет 4 (> 200 тыс. токенов) | $6.00 | $22.50 | $0.60 | $7.50 | +| Клод Хайку 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | +| Клод Хайку 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | +| Клод Опус 4.6 (≤ 200 тыс. токенов) | $5.00 | $25.00 | $0.50 | $6.25 | +| Клод Опус 4.6 (> 200 тыс. токенов) | $10.00 | $37.50 | $1.00 | $12.50 | +| Закрыть работу 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | +| Закрыть работу 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | +| Gemini 3 Pro (≤ 200 тыс. токенов) | $2.00 | $12.00 | $0.20 | - | +| Gemini 3 Pro (> 200 тыс. токенов) | $4.00 | $18.00 | $0.40 | - | +| Близнецы 3 Флэш | $0.50 | $3.00 | $0.05 | - | +| GPT 5.2 | $1.75 | $14.00 | $0.175 | - | +| Кодекс GPT 5.2 | $1.75 | $14.00 | $0.175 | - | +| GPT 5.1 | $1.07 | $8.50 | $0.107 | - | +| Кодекс GPT 5.1 | $1.07 | $8.50 | $0.107 | - | +| Кодекс GPT 5.1 Макс. | $1.25 | $10.00 | $0.125 | - | +| Кодекс GPT 5.1 Мини | $0.25 | $2.00 | $0.025 | - | +| GPT 5 | $1.07 | $8.50 | $0.107 | - | +| Кодекс GPT 5 | $1.07 | $8.50 | $0.107 | - | +| ГПТ 5 Нано | Бесплатно | Бесплатно | Бесплатно | - | + +Вы можете заметить _Claude Haiku 3.5_ в своей истории использования. Это [недорогая модель](/docs/config/#models), которая используется для создания заголовков ваших сеансов. + +:::примечание +Комиссии по кредитной карте учитываются по себестоимости (4,4% + 0,30 доллара США за транзакцию); мы не взимаем ничего сверх этого. +::: + +Бесплатные модели: + +- GLM 4.7 Free доступен на OpenCode в течение ограниченного времени. Команда использует это время для сбора отзывов и улучшения модели. +- Kimi K2.5 Free доступен на OpenCode в течение ограниченного времени. Команда использует это время для сбора отзывов и улучшения модели. +- MiniMax M2.1 Free доступен на OpenCode в течение ограниченного времени. Команда использует это время для сбора отзывов и улучшения модели. +- Big Pickle — это стелс-модель, которая доступна бесплатно на OpenCode в течение ограниченного времени. Команда использует это время для сбора отзывов и улучшения модели. + +Свяжитесь с нами, если у вас есть вопросы. + +--- + +### Автоматическая перезагрузка + +Если ваш баланс упадет ниже 5 долларов, Zen автоматически пополнит 20 долларов. + +Вы можете изменить сумму автопополнения. Вы также можете полностью отключить автоматическую перезагрузку. + +--- + +### Ежемесячные лимиты + +Вы также можете установить месячный лимит использования для всего рабочего пространства и для каждого +член вашей команды. + +Например, предположим, что вы установили ежемесячный лимит использования в размере 20 долларов США, Zen не будет использовать +более 20 долларов в месяц. Но если у вас включена автоматическая перезагрузка, Дзен может оказаться +взимать с вас более 20 долларов США, если ваш баланс опускается ниже 5 долларов США. + +--- + +## Конфиденциальность + +Все наши модели размещены в США. Наши поставщики придерживаются политики нулевого хранения и не используют ваши данные для обучения моделей, за следующими исключениями: + +- Big Pickle: во время бесплатного периода собранные данные могут быть использованы для улучшения модели. +- GLM 4.7 Бесплатная: в течение бесплатного периода собранные данные могут использоваться для улучшения модели. +- Kimi K2.5 Free: в течение бесплатного периода собранные данные могут использоваться для улучшения модели. +- MiniMax M2.1 Бесплатно: в течение бесплатного периода собранные данные могут использоваться для улучшения модели. +- API OpenAI: запросы хранятся в течение 30 дней в соответствии с [Политикой данных OpenAI](https://platform.openai.com/docs/guides/your-data). +- API-интерфейсы Anthropic: запросы хранятся в течение 30 дней в соответствии с [Политикой данных Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## Для команд + +Дзен также отлично подходит для команд. Вы можете приглашать товарищей по команде, назначать роли, курировать +модели, которые использует ваша команда, и многое другое. + +:::примечание +Рабочие пространства в настоящее время бесплатны для команд в рамках бета-тестирования. +::: + +Управление вашим рабочим пространством в настоящее время бесплатно для команд в рамках бета-тестирования. Мы будем +скоро поделимся более подробной информацией о ценах. + +--- + +### Роли + +Вы можете приглашать товарищей по команде в свое рабочее пространство и распределять роли: + +- **Администратор**: управляйте моделями, участниками, ключами API и выставлением счетов. +- **Участник**: Управляйте только своими собственными ключами API. + +Администраторы также могут установить ежемесячные лимиты расходов для каждого участника, чтобы держать расходы под контролем. + +--- + +### Доступ к модели + +Администраторы могут включать или отключать определенные модели для рабочей области. Запросы, сделанные к отключенной модели, вернут ошибку. + +Это полезно в случаях, когда вы хотите отключить использование модели, которая +собирает данные. + +--- + +### Принесите свой ключ + +Вы можете использовать свои собственные ключи API OpenAI или Anthropic, сохраняя при этом доступ к другим моделям в Zen. + +Когда вы используете свои собственные ключи, счета за токены взимаются непосредственно провайдером, а не Zen. + +Например, у вашей организации уже может быть ключ для OpenAI или Anthropic. +и вы хотите использовать его вместо того, который предоставляет Zen. + +--- + +## Цели + +Мы создали OpenCode Zen, чтобы: + +1. **Сравните** лучшие модели/поставщики агентов кодирования. +2. Получите доступ к вариантам **самого высокого качества**, не снижая производительность и не обращаясь к более дешевым поставщикам. +3. Не допускайте **падения цен**, продавая по себестоимости; поэтому единственная надбавка предназначена для покрытия наших сборов за обработку. +4. Не допускайте **привязки**, позволяя использовать его с любым другим агентом кодирования. И всегда позволяйте вам использовать любого другого провайдера с OpenCode. diff --git a/packages/web/src/content/docs/th/1-0.mdx b/packages/web/src/content/docs/th/1-0.mdx new file mode 100644 index 000000000..1d67da62d --- /dev/null +++ b/packages/web/src/content/docs/th/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: สำหรับสิ่งนี้ 1.0 +description: ใน OpenCode 1.0 +--- + +OpenCode 1.0 เป็นเนื้อหา TUI ทั้งหมด + +เราย้ายจาก TUI ใช้ go+bubbletea ที่มีปัญหาด้านประสิทธิภาพและความสามารถไปเป็นพวงกุญแจภายใน (OpenTUI) ที่เขียนด้วย zig+solidjs + +TUIล่าสุดทำงานเหมือนกับเก่าเพราะความเชื่อ Opencode เดียวกัน + +--- + +## สู่กรุงเดลต้า + +คุณอัปเดตอัตโนมัติเป็น 1.0 อีกครั้งและปรับปรุงอยู่ +รุ่นดังกล่าว OpenCode ผู้เล่นเก่าบางเฉียบจะคว้ารางวัลล่าสุดเสมอ + +อย่างต่อเนื่องไม่จำเป็นต้องจดบันทึก + +```bash +$ opencode upgrade 1.0.0 +``` + +ส่วนดาวน์เกรดกลับเป็น 0.x อีกต่อไป... + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## การเปลี่ยนแปลง UX + +การค้นพบที่ค้นพบโดยความเชื่อโดยแสดงเฉพาะรายละเอียดในส่วนที่แก้ไขและทุบตีเท่านั้น + +ขอคำสั่งซึ่งหมายถึงทุกอย่างไหลผ่านกด ctrl+p จะเรียกสิ่งนี้ถึงคำอธิบายที่อธิบายทุกอย่างที่คุณทำได้ + +จักรพรรดิ์อัจฉริยะ (สามารถมีได้) พร้อมข้อมูลข่าวสาร + +เราจะลบสิ่งที่เราเชื่อว่ามีใครใช้จริงออกเลยโปรดเปิดปัญหาแล้วเราจะเพิ่มกลับอย่างรวดเร็ว + +--- + +## ทำลายล้าง + +### เปลี่ยนชื่อแล้ว + +- Messages_revert -> Messages_undo +- switch_agent -> agent_cycle +- switch_agent_reverse -> agent_cycle_reverse +- switch_mode -> agent_cycle +- switch_mode_reverse -> agent_cycle_reverse + +### คีย์ถูกลบออก + +- Messages_layout_toggle +- สิ่ง_ถัดไป +- ข้อเสนอที่_เปอร์โตริโก +- file_diff_toggle +- file_search +- file_close +- file_list +- app_help +- โครงการ_init +- รายละเอียด_รายละเอียด +- สร้างสรรค์_บล็อก diff --git a/packages/web/src/content/docs/th/acp.mdx b/packages/web/src/content/docs/th/acp.mdx new file mode 100644 index 000000000..92638b9ab --- /dev/null +++ b/packages/web/src/content/docs/th/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACPสามารถช่วย +description: ใช้ OpenCode ในโปรแกรมแก้ไขที่ต้องการ ACP +--- + +OpenCode ที่แสดง [Agent Client Protocol](https://agentclientprotocol.com) หรือ (ACP) ซึ่งสามารถช่วยได้โดยตรงในการแก้ไขและ IDE ที่หน่วยความจำ + +:::tip +สำหรับรายชื่อและเครื่องมือที่รองรับ ACPรายงานที่[ACP รายงาน](https://zed.dev/blog/acp-progress-report#available-now) +::: + +ACP เป็นแบบเปิดมาตรฐานการสื่อสารระหว่างโปรแกรมแก้ไขโค้ดและตัวแทน AI + +--- + +## เม็กซิโก + +บางครั้งใช้ OpenCode ผ่าน ACP ไม่อนุญาตให้โปรแกรมแก้ไขของคุณให้รันคำสั่ง `opencode acp` + +สั่งเริ่ม OpenCode เนื่องจากต้องย่อยที่จำเป็นต้องมี ACP ซึ่งจะต้องแก้ไขโปรแกรมของคุณผ่าน JSON-RPC ผ่าน stdio + +นี่คือตัวอย่างโปรแกรมแก้ไขยอดนิยมที่รองรับ ACP + +--- + +### เซด + +อดทนต่อไป [Zed](https://zed.dev) (`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +สิ่งนั้นเปิดใช้สำหรับ `agent: new thread` ใน **Command Palette** + +คุณต้องผูกมัดอย่างหนักเพื่อแก้ไข `keymap.json` ของคุณ: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### เจ็ตเบรนส์ IDE + +ไปที่ [JetBrains IDE](https://www.jetbrains.com/) acp.json ของคุณตาม [เอกสาร](https://www.jetbrains.com/help/ai-assistant/acp.html): + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +นี่เป็นการเปิดให้ตัวแทน 'OpenCode' ในเนื้อหาของตัวแทน AI Chat + +--- + +### Avante.nvim + +ยังคงมี [Avante.nvim](https://github.com/yetone/avante.nvim) ของคุณ: + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +จะต้องส่งผ่านวันพรุ่งนี้: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +ลองใช้ OpenCode ACP ใน [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) ให้เพิ่มสิ่งต่อไปนี้ใน Neovim ของคุณ: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +คุณสามารถใช้ CodeCompanion เพื่อใช้ OpenCode ACP สำหรับแชท + +บางครั้งการส่งผ่านบางครั้ง (เช่น `OPENCODE_API_KEY`) ต้อง [ต้องอธิบายเหตุผล:https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) ในเอกสารประกอบ CodeCompanion.nvim สำหรับรายละเอียดทั้งหมด + +## เพื่อ + +OpenCode เป็นเวลานาน ACP และในการตรวจสอบคุณสมบัติทั้งหมด: + +:::note +คำสั่งสแลมในคำสั่งบางคำสั่งเช่น `/undo` และ `/redo` ยังไม่รองรับในขณะนี้ +::: + +- เครื่องมือใน (ไฟล์ไฟล์คำสั่งอื่นๆ) +- คำอธิบายและคำสั่งสแลช +- MCP แขกที่นี่คือข้อมูลเพิ่มเติมของ OpenCode ของคุณ +- กฎเฉพาะโครงการจาก `AGENTS.md` +- คนจัดรูปแบบและ linters เวียนนา +- ระบบตัวแทนและระบบ diff --git a/packages/web/src/content/docs/th/agents.mdx b/packages/web/src/content/docs/th/agents.mdx new file mode 100644 index 000000000..acd3d553b --- /dev/null +++ b/packages/web/src/content/docs/th/agents.mdx @@ -0,0 +1,747 @@ +--- +title: ตัวแทน +description: และตัวแทนพิเศษ +--- + +เจ้าหน้าที่คือผู้ช่วย AI ในช่องทางต่างๆ ของอินเทอร์เฟซและอินเทอร์เฟซของโฟลว์เฉพาะได้สามารถสร้างเครื่องมือที่รวบรวมข้อมูลด้วยโมดูลและอินเทอร์เฟซของอินเทอร์เฟซ... + +:::tip +ใช้แผนของตัวแทนเพื่อวิเคราะห์โค้ดและทบทวนเหตุผลในการทำการเปลี่ยนแปลงโค้ดใดๆ +::: + +การผสมผสานระหว่างตัวแทนระหว่างการประชุมหรือต้องการโดยระบุ `@` + +--- + +## ประเภท + +OpenCode มีเอเจนต์สองประเภทตัวแทนหลักและตัวแทนย่อย + +--- + +### ตัวแทนหลัก + +ตัวแทนหลักคือผู้ช่วยหลักที่คุณมักจะเกิดขึ้นด้วยโดยตรงในวนดูได้เฉพาะปุ่ม **Tab** หรือปุ่ม `switch_agent` ที่โน่ไว้เจ้าหน้าที่สามารถจัดการระบบของคุณได้โดยได้รับเครื่องมือที่มีคุณลักษณะหลักเช่น Build มีเครื่องมือทั้งหมดในส่วนของแผนถูกจำกัด + +:::tip +**Tab** บันทึกเรื่องราวระหว่างตัวแทนหลักดื่มด่ำได้ +::: + +OpenCode ของเอเจนต์หลักในตัวได้แก่ **Build** และ **Plan** ดี +ดูด้านล่าง + +--- + +### ตัวแทนย่อย + +ตัวแทนย่อยคือผู้ช่วยเฉพาะทางที่ตัวแทนหลักสามารถเรียกงานเฉพาะได้เฉพาะเรียกได้โดยตรงโดย **@ หมายถึง**ความหมายในข้อความของคุณ + +OpenCode ในการควบคุมเอเจนต์ย่อยในส่วนนี้ได้แก่ **ทั่วไป** และ **สำรวจ** ส่วนดูพื้นที่ + +--- + +## บิวท์อิน + +OpenCode สืบสวนเอเจนต์หลักในตัวและเอเจนต์ย่อยในอีกหนึ่ง + +--- + +### ใช้บิลด์ + +__ โหมด: `primary` + +สร้างเว็บหลัก **รองรับ** พร้อมด้วยเครื่องมือทั้งหมดที่มีเอเจนต์มาตรฐานเพื่อให้มีสิทธิ์การเข้าถึงไฟล์และคำสั่งระบบโดยสมบูรณ์ + +--- + +### ใช้แผน + +__ โหมด: `primary` + +ตัวแทนแบบจำกัดที่ความเชื่อถือและการควบคุมระบบของการที่แจ้งให้ทราบอย่างเป็นทางการและป้องกันการเปลี่ยนแปลงโดยเฉพาะอย่างยิ่ง +ตามคำอธิบายตามลำดับทั้งหมดของระบบเป็น `ask`: + +- `file edits`: เนื้อหา แพตช์ และเป็นที่ทั้งหมด +- `bash`: คำสั่งทุบตีทั้งหมด + +เอเจนต์นี้มีประโยชน์ต้องการให้ LLM ตรวจสอบโค้ดตรวจสอบการเปลี่ยนแปลงหรือสร้างแผนว่าจะทำดีเบสของคุณจริง + +--- + +### ใช้ทั่วไป + +__ โหมด: `subagent` + +ตัวแทนเพื่อค้นหาคำถามที่จำเป็นและต่อเนื่องหลายขั้นตอน อนุญาตให้เข้าถึงเครื่องมือต่างๆ (ยกเว้นการตรวจสอบ) และการปรับปรุงไฟล์ได้เมื่อจำเป็นต้องใช้สิ่งนี้เพื่อรันงานหลายหน่วยพร้อมกัน + +--- + +### ใช้สำรวจ + +__ โหมด: `subagent` + +เอเจนต์ความเร็วสูงและอ่านอย่างเดียวสำหรับฐานพื้นฐานโค้ดและตรวจดูไฟล์ได้ใช้สิ่งนี้เมื่อคุณต้องการค้นหาไฟล์อย่างรวดเร็วรูปแบบตามค้นหาโค้ดด้วยคำสำคัญหรือแบบสอบถามเกี่ยวกับโค้ดเบส + +--- + +### ใช้การบดอัด + +__ โหมด: `primary` + +เอเจนต์ระบบนั้นมีส่วนช่วยในการสรุปที่ยาวไปสู่บทสรุปที่เล็กลงโดยเฉพาะอย่างยิ่งเมื่อจำเป็นต้องมีและใน UI + +--- + +### ใช้ชื่อ + +__ โหมด: `primary` + +ตัวแทนของระบบซึ่งสร้างชื่อที่ออกแบบสั้น ๆ มันทำงานได้โดยไม่ต้องใช้ UI + +--- + +### ใช้สรุป + +__ โหมด: `primary` + +ตัวแทนระบบนั้นซึ่งสร้างสรุปการตรวจสอบและทำงานโดยไม่ต้องมี UI + +--- + +## เรื่องนั้น + +1. สำหรับตัวแทนหลักให้ใช้ปุ่ม **Tab** เพื่อวนดูตัวแทนที่มีความสำคัญ โปรดใช้การผูกปุ่ม `switch_agent` ที่โรงยิมไว้ได้ + +2. สามารถตัวแทนย่อยได้: + - ****โดยตัวแทนหลักโดยเฉพาะพิเศษตามคำอธิบาย + - เพิ่มเติมโดย **@ ต้องการ** ตัวแทนย่อยในข้อความของคุณเช่น + + ```txt frame="none" + @general help me search for this function + ``` + +3. **ปรับปรุงระหว่างการปรับปรุง**: เมื่อตัวแทนย่อยสร้างหลังคาและเรียนรู้ร่วมกันระหว่างการปรับปรุงหลักและหลังคาทั้งหมดได้ทั้งหมด: + - **\+Right** (หรือ `session_child_cycle` keybind ที่คุณรู้ไว้) ในวนผ่าน parent → child1 → child2 → ... → parent + - **\+Left** (หรือฟัง `session_child_cycle_reverse` keybind) เพื่อวนย้อนกลับผ่าน parent ← child1 ← child2 ← ... ← parent + + เรียนรู้การดำเนินการระหว่างการดำเนินการหลักและงานตัวแทนย่อยเฉพาะเจาะจง + +--- + +## เม็กซิโก + +ปรับแต่งเอเจนต์ในหรือสร้างเอเจนต์ได้ผ่านมาได้อย่างไม่น่าเชื่อตัวแทนได้สองวิธี: + +--- + +### JSON + +ไม่เชื่อตัวแทนในไฟล์ในกรุง `opencode.json` ของคุณ: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### มาร์กดาวน์ + +คุณอาจกำหนดเอเจนต์สำหรับไฟล์มาร์กดาวน์ได้หลายสีใน: + +- ทั่วโลก: `~/.config/opencode/agents/` +- ต่อโครงการ: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +ชื่อไฟล์มาร์กดาวน์พร้อมกับชื่อเอเจนต์เช่น `review.md` สร้างตัวแทน `review` + +--- + +## ต + +มาดูรายละเอียดเพิ่มเติมที่จุดนั้นกัน + +--- + +### คำอธิบาย + +ใช้ฟีเจอร์ `description` เพื่อให้คำอธิบายสีนี้ทำอะไรและแนะนำเมื่อใด + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +รายการไม่จำเป็น **จำเป็น** + +--- + +### นั่น + +เหตุผลของการสุ่มและการตอบกลับของ LLM ด้วย `temperature` + +ค่าที่ต่ำกว่านี้จะตอบสนองมีจุดมุ่งหมายและทราบถึงค่าที่จะช่วยลดการส่งผลและส่งผลถึง + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +อุณหภูมิจะเท่ากัน 0.0 ถึง 1.0: + +- **0.0-0.2**: สิ่งที่เราคาดการณ์และกำหนดไว้เป็นไปได้และวางแผนโค้ด +- **0.3-0.5**: ปฏิกิริยาที่สมดุลและเป็นผลให้เกิดงานพัฒนาทั่วไป +- **0.6-1.0**: คำตอบที่สร้างสรรค์และหลากหลายมากขึ้นซึ่งมีประโยชน์สำหรับการศึกษาและต่อไป + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +ข้อสังเกตอุณหภูมิ OpenCode โดยทั่วไปจะมีเฉพาะรุ่นเท่านั้นแล้ว 0 สำหรับรุ่นส่วนใหญ่ 0.55 สำหรับรุ่น Qwen + +--- + +### สูงสุด + +จำนวนส่วนประกอบของการวนซ้ำของเอเจนต์ที่เอเจนต์เป็นผลสืบเนื่องด้วยข้อความเท่านั้นวิธีการที่ต้องการควบคุมต้นทุนสามารถกำหนดได้ในแนวทางที่ตัวแทนได้ + +หากไม่ได้ตั้งค่านี้ เอเจนต์จะดำเนินต่อไปจนกว่าโมเดลจะจะหยุดหรือผู้ใช้ขัดจังหวะ + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +ไปถึงความโดดเด่นจะได้รับพร้อมท์พิเศษที่แนะนำให้เรียนรู้ด้วยการสรุปงานและงานที่เหลืออีกครั้ง + +:::caution +ช่อง `maxSteps` แบบเดิมเลิกใช้แล้วใช้ `steps` แทน +::: + +--- + +### ต่อไปนี้ + +ตั้งค่าเป็น `true` ไปถึงสมาชิก + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### พรอมมาน + +ระบุไฟล์พร้อมท์ระบบสำหรับเอเจนต์นี้ด้วย `prompt`ความละเอียดสูงพร้อมคำแนะนำเฉพาะสำหรับกรณีของตัวแทน + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +เกี่ยวเนื่องกับสิ่งนี้กับระบบไฟล์ที่อาจเป็นสาเหตุว่าทำไมจึงสามารถใช้ได้กับทั้ง OpenCode ส่วนกลางและเฉพาะโครงการ + +--- + +### อย่างอย่างนั้น + +ใช้ฟังก์ชัน `model` ในส่วนของโมเดลโมเดลสำหรับเอเจนต์นี้มีประโยชน์สำหรับการใช้โมเดลโมเลกุลซึ่งปรับให้เหมาะกับงานโครงสร้างเช่นโมดูลสำหรับโมดูลที่ตรวจสอบที่เก็บข้อมูลจำนวนมากสำหรับการดำเนินการ + +:::tip +ไม่ได้ระบุโมเดลตัวแทนหลักๆ [ โมเดลที่ build ทั่วโลก](/docs/config#models) ทำให้ตัวแทนย่อยในเมนูของตัวแทนหลักที่ทอดตัวแทนย่อยทั่วโลก +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +รหัสโมเดลในบางครั้ง OpenCode ของคุณใช้รูปแบบ `provider/model-id` เช่นต้องใช้ [OpenCode Zen](/docs/zen) แล้วก็ใช้ `opencode/gpt-5.1-codex` สำหรับ GPT 5.1 Codex + +--- + +### เครื่องมือ + +พื้นฐานว่าเครื่องมือนี้สามารถตรวจสอบประสิทธิภาพของเอเจนต์ด้วย `tools` วิจัยเปิดหรือตรวจสอบเครื่องมือเฉพาะเจาะจงเป็น `true` หรือ `false` + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +ความพยายามเฉพาะเอเจนต์จะเน้นไปที่ส่วนกลาง +::: + +จำเป็นต้องใช้ไวด์การ์ดเพื่อควบคุมเครื่องมือหลายรายการพร้อมกันได้ยืนยันว่าเครื่องมือทั้งหมดจากเซิร์ฟเวอร์ MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[เรียนรู้เพิ่มเติมเกี่ยวกับเครื่องมือ](/docs/tools) + +--- + +### สิทธิ์ + +หลักการที่ถูกต้องเพื่อประสิทธิภาพในการดำเนินการที่ตัวแทนหลายแห่งในปัจจุบันความสามารถในการสำหรับเครื่องมือ `edit`, `bash` และ `webfetch` ได้อย่างมีประสิทธิภาพเป็น: + +- `"ask"` — อนุมัติก่อนการเข้าถึงเครื่องมือ +- `"allow"` — ประสิทธิภาพการทำงานทั้งหมดเป็นเพียง... +- `"deny"` — มันเป็นเครื่องมือ + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +ทำให้คุณมีสิทธิ์ที่จะต่อตัวแทนได้ + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +คุณไม่จำเป็นต้องมีสิทธิ์ในตัวแทน Markdown + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +การตั้งค่าเริ่มต้นสำหรับคำสั่งทุบตีเฉพาะได้ + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +นี่อาจใช้รูปแบบ glob + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +และอีกครั้งใช้ `*` wildcard เพื่อให้สิทธิ์สำหรับคำสั่งทั้งหมดได้ +เมื่อกฎเริ่มขึ้นล่าสุดมีความสำคัญมากกว่าที่จะใส่ `*` ไวด์การ์ดขึ้นนำและกฎเฉพาะตามหลัง + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[เรียนรู้เพิ่มเติมเกี่ยวกับเรื่องนี้](/docs/permissions) + +--- + +### สิ่ง + +ต้นแบบโหมดของตัวแทนด้วย `mode` บันทึก `mode` บันทึกวิธีการกำหนดวิธีการใช้ตัวแทน + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +สวัสดี `mode` สามารถตั้งค่าเป็น `primary`, `subagent` หรือ `all` หากไม่ได้ระบุ `mode` ระบบระบบควบคุมเป็น `all` + +--- + +### ส่วนนั้น + +ซ่อนตัวแทนย่อยจากเมนูเติมข้อความอัตโนมัติ `@` ด้วย `hidden: true` มีประโยชน์สำหรับตัวแทนย่อยภายในจำเป็นต้องมีโปรแกรมโดยทางอื่นตัวแทนผ่านเครื่องมืองานเท่านั้น + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +ในที่สุดคุณจะพบในเมนูเติมข้อความอัตโนมัติเท่านั้นที่จำเป็นต้องมีเอเจนต์ที่เป็นได้ผ่านเครื่องมืองานหากต้องการ + +:::note +สามารถตัวแทน `mode: subagent` ได้ +::: + +--- + +### สิทธิ์งาน + +ต้นแบบตัวแทนย่อยที่ตัวแทนสามารถต้องใช้เครื่องมือผ่านงานด้วย `permission.task` ใช้รูปแบบ glob ส่วนใหญ่ที่ใหญ่ขึ้น + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +ตั้งเป็น `deny` แอดเจนต์ย่อยจะลบคำอธิบายเครื่องมืองานทั้งหมดนั่นคือโมเดลจะไม่พยายามทำอะไร + +:::tip +กฎเพื่อให้ชนะตามลำดับและ **กฎส่วนใหญ่ส่วนใหญ่จะสุดท้ายจะ** ในตัวอย่าง `*` (ปฏิเสธ) และ `orchestrator-*` (อาจจะ) แต่เนื่องจาก `orchestrator-*` มาหลัง `*` ผลลัพธ์ที่เป็น `allow` +::: + +:::tip +ไม่จำเป็นต้องให้ตัวแทนย่อยใดๆก็ได้โดยตรงผ่านเมนูเติมข้อความอัตโนมัติ `@` สำหรับความต้องการของงานของตัวแทนจะเพิกเฉย +::: + +--- + +### สี + +ปรับแต่งความต้องการของตัวแทนใน UI ด้วยตัวเลือก `color` เพื่อดูลักษณะเฉพาะของตัวแทนในการปฏิบัติตาม + +ใช้สีฐานสิบหกที่ถูกต้อง (เช่น `#FF5733`) หรือระบบควบคุม: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info` + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### ท็อปพี + +หลักการของปฏิกิริยาด้วยตัวเลือก `top_p` ทางเลือกแทนการควบคุมการสุ่ม + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +ค่าครองชีพ 0.0 ถึง 1.0 ค่าที่ต่ำกว่าจะเน้นไปที่ค่าที่มักจะเป็นเวลานาน + +--- + +### นั่น + +ข้อมูลอื่นๆ ที่คุณระบุในบางครั้งตัวแทนของคุณไปที่ **ส่งผ่านโดยตรง** ในส่วนของโครงสร้างข้อมูล คุณจะต้องดำเนินการและตรวจสอบเฉพาะของข้อมูลเท่านั้นได้ + +เช่น ด้วยรูปแบบการใช้เหตุผลของ OpenAI อ่านการควบคุมเพื่อให้เหตุผล: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +ตรวจสอบเพิ่มเติมในรุ่นและเฉพาะเจาะจงการสแกนเอกสารของคุณเพื่อดูภาพรวม + +:::tip +ต้องการ `opencode models` เพื่อดูรายการที่สมบูรณ์ +::: + +--- + +## สร้างตัวแทน + +การสร้างตัวแทนใหม่ได้อีกครั้งตามลำดับ: + +```bash +opencode agent create +``` + +คำสั่งแบบในเวลานี้: + +1. ถามว่าจะบันทึกตัวแทนได้ที่ไหนระดับโลกหรือเฉพาะโครงการ +2. คำอธิบายสิ่งที่ตัวแทนควรทำ +3. สร้างพรอมต์และตัวระบุชนิดของที่เหมาะสม +4. ให้คุณเลือกเครื่องมือที่ตัวแทนอย่างเป็นทางการ +5. ในที่สุดสร้างไฟล์มาร์กดาวน์ด้วยเอเจนต์ + +--- + +## กรณีการใช้งาน + +ต่อไปเป็นกรณีการใช้งานทั่วไปสำหรับตัวแทนต่างๆ + +- **ตัวแทนที่กำลังพัฒนา**: งานพัฒนาใหม่ล่าสุดโดยอาศัยเครื่องมือทั้งหมด +- **ตัวแทนแผน**: ผู้วิเคราะห์และวางแผนโดยไม่ทำการเปลี่ยนแปลง +- **ตัวแทนตรวจสอบ**: ตรวจสอบโค้ดพร้อมแบบอ่านเพียงอย่างเดียวพร้อมเครื่องมือเอกสารประกอบ +- **ตัวแทนแก้ไขข้อบกพร่อง**: ตรวจสอบโดยการตรวจสอบโดยการควบคุมตีและผู้อ่าน +- **ตัวแทนเอกสาร**: เนื้อหาเอกสารด้วยไฟล์จัดเก็บข้อมูลที่ระบบปฏิบัติตาม + +--- + +## แปลความหมายได้ + +ตัวแทนอธิบายว่าคุณอาจจะพบว่ามีประโยชน์ + +:::tip +คุณเป็นตัวแทนคุณต้องการแบ่งปันหรือไม่? [ส่งประชาสัมพันธ์](https://github.com/anomalyco/opencode) +::: + +--- + +### ตัวแทนเอกสาร + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### ผู้ตรวจสอบความปลอดภัย + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/th/cli.mdx b/packages/web/src/content/docs/th/cli.mdx new file mode 100644 index 000000000..a3c3a8ace --- /dev/null +++ b/packages/web/src/content/docs/th/cli.mdx @@ -0,0 +1,601 @@ +--- +title: CLI +description: OpenCode CLI รับสัญญาณและคำสั่ง +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode CLI โดยเฉพาะอย่างยิ่งจะเริ่มต้น [TUI](/docs/tui) ไม่ต้องทำงานโดยไม่มีข้อใดใดๆ + +```bash +opencode +``` + +การยอมรับคำสั่งตามเอกสารในนั้นด้วยเหตุนี้ทำให้คุณสามารถพบกับ OpenCode โดยทางโปรแกรมได้ + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui + +เริ่มเปิดให้ผู้ใช้เริ่มใช้ OpenCode + +```bash +opencode [project] +``` + +#### ยอด + +| ยอด | สั้น | คำอธิบาย | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | มาดูกันเป็นครั้งสุดท้าย | +| `--session` | `-s` | รหัสให้ดีเพื่อเหตุการณ์ | +| `--prompt` | | แจ้งการใช้งาน | +| `--model` | `-m` | รูปแบบการใช้งานรูปแบบ provider/model | +| `--agent` | | ตัวแทนการรับ | +| `--port` | | ท่าเรือที่จะฟัง | +| `--hostname` | | ชื่อที่จะฟัง | + +--- + +## คำสั่ง + +OpenCode CLI ยังมีคำสั่งอีกมากมาย + +--- + +### agent + +จัดการตัวแทนสำหรับ OpenCode + +```bash +opencode agent [command] +``` + +--- + +### attach + +สาเหตุว่าทำไมเซิร์ฟเวอร์แบ็กเอนด์ OpenCode ที่รันจริงๆ ซึ่งเริ่มต้นผ่านคำสั่ง `serve` หรือ `web` + +```bash +opencode attach [url] +``` + +วิธีการใช้ TUI กับแบ็กเอนด์ OpenCode ตัวอย่าง: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### ยอด + +| ยอด | สั้น | คำอธิบาย | +| ----------- | ----- | --------------------------------- | +| `--dir` | | ไดเร็กทอรีการทำงานเพื่อเริ่มต้น TUI ใน | +| `--session` | `-s` | รหัสให้ดีเพื่อเหตุการณ์ | + +--- + +#### create + +สร้างตัวแทนใหม่ด้วยคืนนี้ + +```bash +opencode agent create +``` + +คำสั่งนี้จะแนะนำคุณตลอดไปจนถึงเอเจนต์ใหม่พร้อมพร้อมท์ระบบและประสิทธิภาพของเครื่องมือ + +--- + +#### list + +รายชื่อตัวแทนทั้งหมดทั้งหมด + +```bash +opencode agent list +``` + +--- + +### auth + +ขอแจ้งให้ทราบข้อมูลและข้อมูลเข้าสู่ระบบสำหรับ... + +```bash +opencode auth [command] +``` + +--- + +#### login + +OpenCode มีประสิทธิภาพสูงโดยรายชื่อทั่วไปที่ [Models.dev](https://models.dev) ดังนั้นเหตุผลที่เป็นไปได้ API สำหรับความต้องการใดๆ จำเป็นต้องใช้ข้อมูลนี้ถูกที่ `~/.local/share/opencode/auth.json` + +```bash +opencode auth login +``` + +เมื่อ OpenCode เริ่มต้นระบบจะโหลดจากไฟล์ข้อมูลรับรองและไม่จำเป็นต้องคำนึงถึงสิ่งใด ๆ ที่จะพบไฟล์ของคุณหรือ `.env` ในโปรเจ็กต์ของคุณ + +--- + +#### list + +การแจ้งเตือนที่พิสูจน์ความถูกต้องทั้งหมดซึ่งจัดเป็นไฟล์ข้อมูลสามารถตรวจสอบได้ + +```bash +opencode auth list +``` + +หรือฮิลตันสั้น + +```bash +opencode auth ls +``` + +--- + +#### logout + +นำคุณออกจากระบบของมักจะพบข้อมูลจากไฟล์รับรองข้อมูล + +```bash +opencode auth logout +``` + +--- + +### github + +การจัดการเอเจนต์ GitHub สำหรับพื้นที่อัตโนมัติ + +```bash +opencode github [command] +``` + +--- + +#### install + +ตู้เสื้อผ้าเอเจนต์ GitHub ในที่เก็บของคุณ + +```bash +opencode github install +``` + +ไม่ว่าคุณจะเริ่มต้นโฟลว์ GitHub Actions และแนะนำคุณตลอดประวัติศาสตร์ [เรียนรู้เพิ่มเติม](/docs/github) + +--- + +#### run + +ต้องการตัวแทน GitHub อีกครั้งใน GitHub Actions + +```bash +opencode github run +``` + +##### ยอด + +| ยอด | คำอธิบาย | +| --------- | -------------------------------------- | +| `--event` | การจำลอง GitHub เพื่อขอรับตัวแทน | +| `--token` | ความเป็นส่วนตัวของ GitHub | + +--- + +### mcp + +เซิร์ฟเวอร์เซิร์ฟเวอร์ Model Context Protocol + +```bash +opencode mcp [command] +``` + +--- + +#### add + +เพลิดเพลินไปกับแขก MCP ในคืนนี้ของคุณ + +```bash +opencode mcp add +``` + +คำสั่งนี้จะแนะนำคุณในคืนนี้ MCP ความเชื่อหรือในตำนาน + +--- + +#### list + +เชิญแขก MCP ที่ RAM ทั้งหมดและดำรงอยู่ + +```bash +opencode mcp list +``` + +ต้องใช้หอพักระยะสั้น + +```bash +opencode mcp ls +``` + +--- + +#### auth + +ตัดสิทธิ์กับแขก MCP ที่ OAuth + +```bash +opencode mcp auth [name] +``` + +ไม่ต้องระบุชื่อเซิร์ฟเวอร์ คุณจะได้รับแจ้งจากเซิร์ฟเวอร์ที่รองรับ OAuth ที่พร้อมให้บริการ + +รับรองว่ารองรับ OAuth และสถานะยืนยันสิทธิ์ได้ + +```bash +opencode mcp auth list +``` + +ต้องใช้หอพักระยะสั้น + +```bash +opencode mcp auth ls +``` + +--- + +#### logout + +ข้อมูลรับรอง OAuth สำหรับผู้เข้าชม MCP + +```bash +opencode mcp logout [name] +``` + +--- + +#### debug + +โปรดตรวจสอบ OAuth สำหรับเซิร์ฟเวอร์ MCP + +```bash +opencode mcp debug +``` + +--- + +### models + +การทดลองแบบจำลองทั้งหมดทั้งหมดจากที่เก็บข้อมูลนี้ + +```bash +opencode models [provider] +``` + +คำสั่งนี้แสดงให้เห็นโมเดลทั้งหมดและเป็นที่เก็บข้อมูลของคุณ `provider/model` + +คุณสามารถใช้ชื่อรุ่นได้อย่างแม่นยำใน [ ฟังก์ชั่นของคุณ](/docs/config/) + +สามารถส่งรหัสมีหน้าที่เพื่อกรองโมเดลตามส่วนรายนั้นได้ + +```bash +opencode models anthropic +``` + +#### ยอด + +| ยอด | คำอธิบาย | +| ----------- | ------------------------------------------------------------ | +| `--refresh` | โครงสร้างแคชโมเดลจาก models.dev | +| `--verbose` | ใช้โมเดลนี้เพื่อตรวจสอบ (รวมข้อมูลเมตาเช่นต้นทุน) | + +ใช้แฟล็ก `--refresh` ในที่นี้รายการโมเดลที่แคชไว้ตรงนั้นมีประโยชน์เพิ่มโมเดลใหม่ให้กับระบบและขอดูโมเดลของข้อมูลใน OpenCode + +```bash +opencode models --refresh +``` + +--- + +### run + +ต้องการ opencode ภายนอกไม่มีการแจ้งโดยแจ้งแจ้งโดยตรง + +```bash +opencode run [message..] +``` + +มีประโยชน์สำหรับการทำงานร่วมกันของการทำงานอัตโนมัติหรือเมื่อต้องการให้ตอบสนองอย่างรวดเร็วเปิด TUI เป็นตัวอย่าง + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +ขอแนบไปกับฟีเจอร์นี้ `opencode serve` ทำงานอยู่อีกครั้งเวลาของแขก MCP การทำงานหลายอย่าง: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### ยอด + +| ยอด | สั้น | คำอธิบาย | +| ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | | คำสั่งให้รันใช้ข้อความสำหรับ args | +| `--continue` | `-c` | มาดูกันเป็นครั้งสุดท้าย | +| `--session` | `-s` | รหัสให้ดีเพื่อเหตุการณ์ | +| `--share` | | เซสชั่น | +| `--model` | `-m` | รูปแบบการใช้งานรูปแบบ provider/model | +| `--agent` | | ตัวแทนการรับ | +| `--file` | `-f` | แนบไปกับข้อความได้เลย | +| `--format` | | การรักษา: (จัดรูปแบบ) หรือ json ( อดทนดิบ JSON) | +| `--title` | | ชื่อเรื่องสำหรับการเฉลิมฉลอง (ใช้พร้อมท์ที่สามารถนำมาใช้กับค่าตัวยึด) | +| `--attach` | | แนบไปกับผู้โดยสาร opencode สำนักงานอยู่ (เช่น http://localhost:4096) | +| `--port` | | ท่าเรือสำหรับผู้โดยสารภายในเครื่อง (ตรวจสอบเป็นพอร์ตสุ่ม) | + +--- + +### serve + +เริ่มต้นเลานจ์ OpenCode ไม่เพียงแต่สำหรับนักท่องเที่ยวเท่านั้น API ภาพถ่าย [เอกสารรับรอง](/docs/server) เพื่อดู HTTP เต็มรูปแบบ + +```bash +opencode serve +``` + +ตัวควบคุมจะเริ่มต้นเซิร์ฟเวอร์ HTTP ให้ API เข้าถึงฟังก์ชันการทำงานของ opencode ได้อย่างมีประสิทธิภาพ TUI จัดเตรียม `OPENCODE_SERVER_PASSWORD` ประสิทธิภาพของฮาร์ดแวร์ฮาร์ดแวร์ความถูกต้องพื้นฐาน HTTP (ตัวควบคุมของฮาร์ดแวร์คือ `opencode`) + +#### ยอด + +| ยอด | คำอธิบาย | +| ------------ | ------------------------------------------ | +| `--port` | ท่าเรือที่จะฟัง | +| `--hostname` | ชื่อที่จะฟัง | +| `--mdns` | โปรดตรวจสอบ mDNS | +| `--cors` | จำเป็นต้องมีเพิ่มเติมเพื่อการทำงาน CORS | + +--- + +### session + +การจัดการ OpenCode + +```bash +opencode session [command] +``` + +--- + +#### list + +การแจ้งเตือน OpenCode ทั้งหมด + +```bash +opencode session list +``` + +##### ยอด + +| ยอด | สั้น | คำอธิบาย | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` | จำกัดการควบคุม N ใหม่ล่าสุด | +| `--format` | | ตารางตารางหรือ json (ตาราง) | + +--- + +### stats + +แสดงสถิติการเริ่มต้นและค่าใช้จ่ายสำหรับ OpenCode ของคุณ + +```bash +opencode stats +``` + +#### ยอด + +| ยอด | คำอธิบาย | +| ----------- | --------------------------------------------------------------------------- | +| `--days` | แสดงสถิติของ N วันในอดีต (ตลอดเวลา) | +| `--tools` | เครื่องมือที่มองเห็น (ทั้งหมด) | +| `--models` | แสดงรายละเอียดการใช้งานโมเดล (ซ่อนไว้ตามตัวอย่าง) เอกสารหมายเลขนั้น N หมายเลขบน | +| `--project` | กรองตามโครงการ (โครงการทั้งหมดที่มีอยู่: โครงการปัจจุบัน) | + +--- + +### export + +ส่งออกข้อมูลข่าวสารเป็น JSON + +```bash +opencode export [sessionID] +``` + +ไม่ระบุรหัสผู้ดูแลระบบ คุณจะได้รับแจ้งจากการปรับปรุงดังกล่าว + +--- + +### import + +นำเข้าข้อมูลที่ดีจากไฟล์ JSON หรือแชร์ OpenCode URL + +```bash +opencode import +``` + +ไม่เคยนำเข้าไฟล์ในเครื่องหรือแชร์ OpenCode URL + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### web + +เชิญแขก OpenCode อย่างเป็นทางการด้วยเว็บอินเตอร์เฟส + +```bash +opencode web +``` + +ตัวควบคุมจะเริ่มต้นเซิร์ฟเวอร์ HTTP และเปิดเว็บเองเพื่อเข้าถึง OpenCode ผ่านทางเว็บอินเตอร์เฟส จัดเตรียม `OPENCODE_SERVER_PASSWORD` สำหรับคำอธิบายคุณสมบัติความถูกต้องพื้นฐาน HTTP (ตัวยึดของฮาร์ดแวร์คือ `opencode`) + +#### ยอด + +| ยอด | คำอธิบาย | +| ------------ | ------------------------------------------ | +| `--port` | ท่าเรือที่จะฟัง | +| `--hostname` | ชื่อที่จะฟัง | +| `--mdns` | โปรดตรวจสอบ mDNS | +| `--cors` | จำเป็นต้องมีเพิ่มเติมเพื่อการทำงาน CORS | + +--- + +### acp + +เริ่มต้นเซิร์ฟเวอร์ ACP (Agent Client Protocol) + +```bash +opencode acp +``` + +สั่งนี้เริ่มต้นผู้โดยสาร ACP ที่สื่อสารผ่าน stdin/stdout nd-JSON + +#### ยอด + +| ยอด | คำอธิบาย | +| ------------ | --------------------- | +| `--cwd` | ไดเร็กทอรีการทำงาน | +| `--port` | ท่าเรือที่จะฟัง | +| `--hostname` | ชื่อที่จะฟัง | + +--- + +### uninstall + +ไม่ว่า OpenCode และลบไฟล์ทั้งหมดทั้งหมด + +```bash +opencode uninstall +``` + +#### ยอด + +| ยอด | สั้น | คำอธิบาย | +| --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` | เก็บไฟล์ไว้ที่นี่ | +| `--keep-data` | `-d` | บางครั้งเซสชั่นและสแน็ปช็อต | +| `--dry-run` | | แสดงสิ่งที่จะลบออกโดยไม่ต้องใช้ออก | +| `--force` | `-f` | ข้อความแจ้งข้อความ | + +--- + +### upgrade + +อัปเดต opencode เป็นครั้งสุดท้ายหรือเฉพาะเจาะจง + +```bash +opencode upgrade [target] +``` + +เราปรับปรุงเป็นระดับล่าสุด + +```bash +opencode upgrade +``` + +เพื่อพัฒนาเป็นฮอนด้าโดยเฉพาะ + +```bash +opencode upgrade v0.1.48 +``` + +#### ยอด + +| ยอด | สั้น | คำอธิบาย | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` | วิธีการติดตั้งที่ใช้curl, npm, pnpm, ขนมปัง, ชง | + +--- + +## ระดับโลก + +opencode CLI รับค่าสถานะสากลต่อไป + +| ยอด | สั้น | คำอธิบาย | +| -------------- | ----- | ------------------------------------ | +| `--help` | `-h` | แสดงความช่วยเหลือ | +| `--version` | `-v` | หมายเลขการพิมพ์ | +| `--print-logs` | | พิมพ์บันทึกไปยัง stderr | +| `--log-level` | | ระดับการเรียนรู้ (DEBUG, INFO, WARN, ERROR) | + +--- + +## อีกครั้งหนึ่ง + +OpenCode สามารถทำได้ตามที่กล่าวมาข้างต้น + +| ส่วนนั้น | พิมพ์ | คำอธิบาย | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | บูลิน | แชร์การแจ้งเตือน | +| `OPENCODE_GIT_BASH_PATH` | เชือก | เข้าสู่ Git Bash ได้บน Windows | +| `OPENCODE_CONFIG` | เชือก | ไปยังไฟล์ฟิลม์ | +| `OPENCODE_CONFIG_DIR` | เชือก | เพื่อเป็นไดเร็กทอรีคุณสามารถดู | +| `OPENCODE_CONFIG_CONTENT` | เชือก | เนื้อหาเหมือนกับ json แบบอินไลน์ | +| `OPENCODE_DISABLE_AUTOUPDATE` | บูลิน | ตรวจสอบระบบควบคุมอัตโนมัติ | +| `OPENCODE_DISABLE_PRUNE` | บูลิน | การควบคุมการกำจัดข้อมูลเก่า | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | บูลิน | เพื่อเป็นชื่อระบบควบคุมอัตโนมัติ | +| `OPENCODE_PERMISSION` | เชือก | มีสิทธิ์ json แบบอินไลน์ | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | บูลิน | การติดตามผลเริ่มต้น | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | บูลิน | ค่ำคืนนี้อาหารค่ำ LSP อัตโนมัติ | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | บูลิน | รูปแบบการทดลอง | +| `OPENCODE_DISABLE_AUTOCOMPACT` | บูลิน | เพื่อการกระชับระบบอัตโนมัติ | +| `OPENCODE_DISABLE_CLAUDE_CODE` | บูลิน | การควบคุมดูแลจาก `.claude` (พร้อมท์ + ทักษะ) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | บูลิน | การควบคุมดูแล `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | บูลิน | ต่อมา `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | บูลิน | ปิดใช้การดึงโมเดลจากแหล่งที่มาของข้อมูล | +| `OPENCODE_FAKE_VCS` | เชือก | ประธานาธิบดี VCS ปลอมเพื่อการทดสอบ | +| `OPENCODE_DISABLE_FILETIME_CHECK` | บูลิน | ตรวจสอบเวลาไฟล์เพื่อตรวจสอบ | +| `OPENCODE_CLIENT` | เชือก | คนที่ระบุลูกค้า (ส่วนคือ `cli`) | +| `OPENCODE_ENABLE_EXA` | บูลิน | นอกจากนี้เรายังมีเว็บ Exa | +| `OPENCODE_SERVER_PASSWORD` | เชือก | เอกสารสิทธิ์พื้นฐานสำหรับ `serve`/@@1@@ | +| `OPENCODE_SERVER_USERNAME` | เชือก | เมนบอร์ดระบบควบคุมคุณสมบัติความถูกต้องพื้นฐาน ( `opencode`) | +| `OPENCODE_MODELS_URL` | เชือก | ขอขอบคุณ URL สำหรับข้อมูลดึงข้อมูลโมเดล | + +--- + +### ส่วนนั้น + +อาจเป็นไปได้ว่าคุณสมบัติการทดลองนี้สามารถปรับเปลี่ยนหรือถูกลบออกได้ + +| ส่วนนั้น | พิมพ์ | คำอธิบาย | +| ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | บูลิน | ในที่สุดเราก็ทดลองทั้งหมด | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | บูลิน | การแจ้งเตือนการแจ้งเตือน | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | บูลิน | ยังไงก็ตามการเลือกที่จะเลือกใน TUI | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | ตัวเลข | การหมดเวลาเริ่มต้นสำหรับคำสั่ง bash ในหน่วย ms | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | ตัวเลข | เหตุผลที่สูงสุดสำหรับตอบกลับ LLM | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | บูลิน | เพื่อให้ตัวดูไฟล์สำหรับ dir ทั้งหมด | +| `OPENCODE_EXPERIMENTAL_OXFMT` | บูลิน | เพื่อให้เป็นไปตามแมตเตอร์ oxfmt | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | บูลิน | สามารถใช้เครื่องมือทดลอง LSP | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | บูลิน | ไม่ใช่ตัวดูไฟล์ | +| `OPENCODE_EXPERIMENTAL_EXA` | บูลิน | คุณสมบัติ Exa ทดลอง | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | บูลิน | ตรวจสอบประเภท LSP แบบทดลอง | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | บูลิน | สามารถใช้มาร์กดาวน์รุ่นทดลองได้ | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | บูลิน | เพื่อเป็นโหมด | diff --git a/packages/web/src/content/docs/th/commands.mdx b/packages/web/src/content/docs/th/commands.mdx new file mode 100644 index 000000000..eacd35934 --- /dev/null +++ b/packages/web/src/content/docs/th/commands.mdx @@ -0,0 +1,323 @@ +--- +title: คำสั่ง +description: คำสั่งสร้างคำสั่งอีกครั้งที่ซ้ำกัน +--- + +คำสั่งดังกล่าวระบุพรอมต์จำเป็นต้องร้องขอเมื่อคำสั่งนั้นถูกดำเนินการใน TUI + +```bash frame="none" +/my-command +``` + +คำสั่งแบบกำหนดเองเป็นส่วนเพิ่มเติมจากคำสั่งในตัว เช่น `/init`, `/undo`, `/redo`, `/share`, `/help` [เรียนรู้เพิ่มเติม](/docs/tui#คำสั่ง) + +--- + +## สร้างไฟล์คำสั่ง + +สร้างไฟล์มาร์กดาวน์ในไดเร็กทอรี `commands/` เพื่อกำหนดคำสั่งทำตาม + +สร้าง `.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +frontmatter กำหนดคุณสมบัติคำสั่งเนื้อหาโดยละเอียด + +ใช้คำสั่งโดยพิมพ์ `/` คำสั่งคำสั่ง + +```bash frame="none" +"/test" +``` + +--- + +## เม็กซิโก + +คำสั่งนี้จะผ่าน OpenCode หรือโดยการดำเนินการไฟล์มาร์กดาวน์ในไดเร็กทอรี `commands/` + +--- + +### JSON + +ใช้ส่วน `command` ใน OpenCode ของคุณ [config](/docs/config): + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +รันคำสั่งนี้ใน TUI: + +```bash frame="none" +/test +``` + +--- + +### มาร์กดาวน์ + +หากต้องการกำหนดคำสั่งของไฟล์มาร์กดาวน์ได้คุณจะต้องดำเนินการใน: + +- ทั่วโลก: `~/.config/opencode/commands/` +- ต่อโครงการ: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +ชื่อไฟล์มาร์กดาวน์ในชื่อคำสั่งเช่น `test.md` ให้ +คุณวิ่ง: + +```bash frame="none" +/test +``` + +--- + +## เรามีพร้อมท์ + +พร้อมรองรับคำสั่งรองรับตามตำแหน่งและพิเศษหลายรายการ + +--- + +### บทความโทรทัศน์ + +ส่งผ่านข้อเขียนไปยังคำสั่งของวงดนตรี `$ARGUMENTS` + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +รันคำสั่งพร้อมอาร์กิวเมนต์: + +```bash frame="none" +/component Button +``` + +และ `$ARGUMENTS` จะเป็นอย่างไร `Button` + +เราสามารถเข้าถึงแต่ละจุดได้ตามความต้องการตามหลัก: + +- `$1` - ​​​​อาร์กิวเมนต์แรก +- `$2` - ​​​​อาร์กิวเมนต์ที่สอง +- `$3` - ​​​​อาร์กิวเมนต์ที่สาม +- นั่น... + +เช่น: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +รันคำสั่ง: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +คุณจะรู้สึกได้ถึงความสูง: + +- `$1` กับ `config.json` +- `$2` กับ `src` +- `$3` กับ `{ "key": "value" }` + +--- + +### ส่วนเชล + +ใช้ _!`command`_เพื่อที่จะฉีดประสิทธิภาพสูง [bash command](/docs/tui#bash-commands) ติดตั้งพรอมต์ของคุณ + +เพื่อเป็นคำสั่งสร้างความพยายามเพื่อวิเคราะห์การทดสอบของการทดสอบ: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +หรือตรวจสอบการเปลี่ยนแปลงล่าสุด: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +คำสั่งไดเร็กทอรีรากของโปรเจ็กต์การปฏิบัติตามคำสั่งพร้อมท์ + +--- + +### อ้างถึงไฟล์ + +รวมไฟล์ในคำสั่งของคุณ `@` ในชื่อไฟล์ + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +เนื้อหาไฟล์จะถูกรวมไว้ด้วยการประกาศอย่างเป็นทางการ + +--- + +## ต + +มาดูรายละเอียดเพิ่มเติมกัน + +--- + +### เทม + +`template` กำหนดพรอมต์ที่จะเป็นไปได้ LLM จะดำเนินการคำสั่ง + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +รายการไม่จำเป็น **จำเป็น** + +--- + +### คำอธิบาย + +ใช้ตัวเลือก `description` เพื่อให้คำอธิบายโดยย่อเกี่ยวกับสิ่งที่คำสั่งทำ + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +คำอธิบายที่เป็นคำอธิบายใน TUI คุณต้องการเขียนคำสั่ง + +--- + +### ตัวแทน + +ใช้ `agent` เพื่อระบุทางเลือกว่า [ตัวแทน](/docs/agents) ใดควรดำเนินการคำสั่งนี้ +นี่คือ [ตัวแทนย่อย](/docs/agents/#subagents) คำสั่งจะไม่จำเป็นต้องทำการย่อยตัวแทนย่อยตาม... +เหตุผลที่ทำให้สิ่งนี้เป็นไปได้ `subtask` เป็น `false` + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +ขึ้นอยู่กับ ** ตัวเลือก** หากไม่ได้ระบุเหตุผลว่าเป็นเอเจนต์ปัจจุบันของคุณ + +--- + +### งานย่อย + +ใช้ `subtask` บูลีนเพื่อไม่จำเป็นต้องทำอะไรเลย [subagent](/docs/agents/#subagents) +เพราะเหตุใดจะช่วยให้คำสั่งไม่ทำให้ระบบหลักของคุณเสียหาย และจะ **บังคับ** เอเจนต์ให้ความเห็นตัวแทนย่อย +โปรดดู `mode` เพื่อดูการตั้งค่าเป็น `primary` ในคืนนี้ [agent](/docs/agents) แขก + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +ส่วนนี้ **ทางเลือก** + +--- + +### อย่างอย่างนั้น + +ใช้ `model` ไปจนถึงโมเดลเริ่มต้นสำหรับคำสั่งนี้ + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +ส่วนนี้ **ทางเลือก** + +--- + +## บิวท์อิน + +opencode มีคำสั่งในคำสั่งหลายเช่น `/init`, `/undo`, `/redo`, `/share`, `/help`; [เรียนรู้เพิ่มเติม](/docs/tui#คำสั่ง) + +:::note +คำสั่งนี้สามารถดำเนินการได้ในขั้นตอนนี้ +::: + +บันทึกคำสั่งด้วยชื่อเดียวกันคำสั่งย้ำคำสั่งใน diff --git a/packages/web/src/content/docs/th/config.mdx b/packages/web/src/content/docs/th/config.mdx new file mode 100644 index 000000000..273b40ee8 --- /dev/null +++ b/packages/web/src/content/docs/th/config.mdx @@ -0,0 +1,685 @@ +--- +title: การกำหนดค่า +description: การใช้การกำหนดค่า OpenCode JSON +--- + +คุณสามารถกำหนดค่า OpenCode ได้โดยใช้ไฟล์กำหนดค่า JSON + +--- + +## รูปแบบ + +OpenCode รองรับทั้งรูปแบบ **JSON** และ **JSONC** (JSON พร้อมความคิดเห็น) + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## สถานที่ + +คุณสามารถวางการกำหนดค่าของคุณในสถานที่ต่าง ๆ สองสามแห่งและมี +ลำดับความสำคัญที่แตกต่างกัน + +:::note +ไฟล์การกำหนดค่า **ถูกรวมเข้าด้วยกัน** โดยไม่มีการแทนที่ +::: + +ไฟล์การกำหนดค่าจะถูกรวมเข้าด้วยกัน โดยไม่มีการแทนที่ การตั้งค่าจากตำแหน่งการกำหนดค่าต่อไปนี้จะรวมกัน การกำหนดค่าในภายหลังจะแทนที่การกำหนดค่าก่อนหน้าสำหรับคีย์ที่ขัดแย้งกันเท่านั้น การตั้งค่าที่ไม่ขัดแย้งจากการกำหนดค่าทั้งหมดจะยังคงอยู่ + +ตัวอย่างเช่น หากการกำหนดค่าส่วนกลางของคุณตั้งค่า `theme: "opencode"` และ `autoupdate: true` และการกำหนดค่าโปรเจ็กต์ของคุณตั้งค่า `model: "anthropic/claude-sonnet-4-5"` การกำหนดค่าสุดท้ายจะรวมการตั้งค่าทั้งสามรายการไว้ด้วย + +--- + +### ลำดับความสำคัญ + +แหล่งที่มาของการกำหนดค่าถูกโหลดตามลำดับนี้ (แหล่งที่มาภายหลังจะแทนที่แหล่งที่มาก่อนหน้า): + +1. **การกำหนดค่าระยะไกล** (จาก `.well-known/opencode`) - ค่าเริ่มต้นขององค์กร +2. **การกำหนดค่าสากล** (`~/.config/opencode/opencode.json`) - การตั้งค่าของผู้ใช้ +3. **การกำหนดค่าแบบกำหนดเอง** (`OPENCODE_CONFIG` env var) - การแทนที่แบบกำหนดเอง +4. **การกำหนดค่าโครงการ** (`opencode.json` ในโครงการ) - การตั้งค่าเฉพาะโครงการ +5. **`.opencode` ไดเรกทอรี** - ตัวแทน คำสั่ง ปลั๊กอิน +6. **การกำหนดค่าแบบอินไลน์** (`OPENCODE_CONFIG_CONTENT` env var) - การแทนที่รันไทม์ + +ซึ่งหมายความว่าการกำหนดค่าโปรเจ็กต์สามารถแทนที่ค่าเริ่มต้นส่วนกลางได้ และการกำหนดค่าส่วนกลางสามารถแทนที่ค่าเริ่มต้นขององค์กรระยะไกลได้ + +:::note +ไดเรกทอรี `.opencode` และ `~/.config/opencode` ใช้ **ชื่อพหูพจน์** สำหรับไดเรกทอรีย่อย: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/` และ `themes/` ชื่อเอกพจน์ (เช่น `agent/`) ยังรองรับความเข้ากันได้แบบย้อนหลังด้วย +::: + +--- + +### ระยะไกล + +องค์กรสามารถจัดเตรียมการกำหนดค่าเริ่มต้นผ่านทางจุดสิ้นสุด `.well-known/opencode` สิ่งนี้จะถูกดึงออกมาโดยอัตโนมัติเมื่อคุณตรวจสอบสิทธิ์กับผู้ให้บริการที่รองรับ + +โหลดการกำหนดค่าระยะไกลก่อน โดยทำหน้าที่เป็นเลเยอร์พื้นฐาน แหล่งการกำหนดค่าอื่นๆ ทั้งหมด (ส่วนกลาง โปรเจ็กต์) สามารถแทนที่ค่าเริ่มต้นเหล่านี้ได้ + +ตัวอย่างเช่น หากองค์กรของคุณมีเซิร์ฟเวอร์ MCP ที่ถูกปิดใช้งานตามค่าเริ่มต้น: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +คุณสามารถเปิดใช้งานเซิร์ฟเวอร์เฉพาะในการกำหนดค่าภายในเครื่องของคุณได้: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### ทั่วโลก + +วางการกำหนดค่า OpenCode ส่วนกลางของคุณใน `~/.config/opencode/opencode.json` ใช้การกำหนดค่าส่วนกลางสำหรับการตั้งค่าทั้งผู้ใช้ เช่น ธีม ผู้ให้บริการ หรือปุ่มลัด + +การกำหนดค่าส่วนกลางจะแทนที่ค่าเริ่มต้นขององค์กรระยะไกล + +--- + +### ต่อโครงการ + +เพิ่ม `opencode.json` ในรูทโปรเจ็กต์ของคุณ การกำหนดค่าโปรเจ็กต์มีความสำคัญสูงสุดในบรรดาไฟล์กำหนดค่ามาตรฐาน โดยจะแทนที่การกำหนดค่าทั้งส่วนกลางและระยะไกล + +:::tip +วางการกำหนดค่าเฉพาะโปรเจ็กต์ไว้ที่รากของโปรเจ็กต์ของคุณ +::: + +เมื่อ OpenCode เริ่มต้นระบบ จะค้นหาไฟล์กำหนดค่าในไดเร็กทอรีปัจจุบันหรือข้ามไปยังไดเร็กทอรี Git ที่ใกล้ที่สุด + +นอกจากนี้ยังปลอดภัยที่จะตรวจสอบใน Git และใช้สคีมาเดียวกันกับสคีมาระดับโลก + +--- + +### เส้นทางที่กำหนดเอง + +ระบุเส้นทางไฟล์กำหนดค่าที่กำหนดเองโดยใช้ตัวแปรสภาพแวดล้อม `OPENCODE_CONFIG` + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +มีการโหลดการกำหนดค่าแบบกำหนดเองระหว่างการกำหนดค่าส่วนกลางและโครงการตามลำดับความสำคัญ + +--- + +### ไดเรกทอรีที่กำหนดเอง + +ระบุไดเร็กทอรีการกำหนดค่าที่กำหนดเองโดยใช้ `OPENCODE_CONFIG_DIR` +ตัวแปรสภาพแวดล้อม ไดเร็กทอรีนี้จะถูกค้นหาตัวแทน, คำสั่ง, +โหมดและปลั๊กอินเหมือนกับไดเร็กทอรี `.opencode` มาตรฐานและควร +เป็นไปตามโครงสร้างเดียวกัน + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +ไดเร็กทอรีที่กำหนดเองถูกโหลดหลังจากไดเร็กทอรี config ส่วนกลางและ `.opencode` ดังนั้นจึง **สามารถแทนที่** การตั้งค่าได้ + +--- + +## สคีมา + +ไฟล์กำหนดค่ามีสคีมาที่กำหนดไว้ใน [**`opencode.ai/config.json`**](https://opencode.ai/config.json) + +ผู้แก้ไขของคุณควรสามารถตรวจสอบและเติมข้อความอัตโนมัติตามสคีมาได้ + +--- + +### TUI + +คุณสามารถกำหนดการตั้งค่าเฉพาะ TUI ผ่านตัวเลือก `tui` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +ตัวเลือกที่มี: + +- `scroll_acceleration.enabled` - ​​เปิดใช้งานการเร่งความเร็วการเลื่อนแบบ macOS **มีลำดับความสำคัญมากกว่า `scroll_speed`.** +- `scroll_speed` - ​​ตัวคูณความเร็วการเลื่อนแบบกำหนดเอง (ค่าเริ่มต้น: `3` ขั้นต่ำ: `1`) ไม่สนใจหาก `scroll_acceleration.enabled` คือ `true` +- `diff_style` - ​​ควบคุมการเรนเดอร์ต่าง `"auto"` ปรับให้เข้ากับความกว้างของเทอร์มินัล `"stacked"` จะแสดงคอลัมน์เดียวเสมอ + +[เรียนรู้เพิ่มเติมเกี่ยวกับการใช้ TUI ที่นี่](/docs/tui) + +--- + +### เซิร์ฟเวอร์ + +คุณสามารถกำหนดการตั้งค่าเซิร์ฟเวอร์สำหรับคำสั่ง `opencode serve` และ `opencode web` ผ่านตัวเลือก `server` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +ตัวเลือกที่มี: + +- `port` - ​​พอร์ตสำหรับฟัง +- `hostname` - ​​ชื่อโฮสต์ที่จะฟัง เมื่อเปิดใช้งาน `mdns` และไม่ได้ตั้งชื่อโฮสต์ ค่าเริ่มต้นจะเป็น `0.0.0.0` +- `mdns` - ​​เปิดใช้งานการค้นหาบริการ mDNS ซึ่งช่วยให้อุปกรณ์อื่นๆ บนเครือข่ายค้นพบเซิร์ฟเวอร์ OpenCode ของคุณได้ +- `mdnsDomain` - ​​ชื่อโดเมนที่กำหนดเองสำหรับบริการ mDNS ค่าเริ่มต้นเป็น `opencode.local` มีประโยชน์สำหรับการเรียกใช้หลายอินสแตนซ์บนเครือข่ายเดียวกัน +- `cors` - ​​ต้นกำเนิดเพิ่มเติมเพื่ออนุญาต CORS เมื่อใช้เซิร์ฟเวอร์ HTTP จากไคลเอนต์ที่ใช้เบราว์เซอร์ ค่าจะต้องเป็นต้นกำเนิดแบบเต็ม (สคีมา + โฮสต์ + พอร์ตเสริม) เช่น `https://app.example.com` + +[เรียนรู้เพิ่มเติมเกี่ยวกับเซิร์ฟเวอร์ที่นี่](/docs/server) + +--- + +### เครื่องมือ + +คุณสามารถจัดการเครื่องมือที่ LLM สามารถใช้ได้ผ่านตัวเลือก `tools` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[เรียนรู้เพิ่มเติมเกี่ยวกับเครื่องมือที่นี่](/docs/tools) + +--- + +### โมเดล + +คุณสามารถกำหนดค่าผู้ให้บริการและรุ่นที่คุณต้องการใช้ในการกำหนดค่า OpenCode ของคุณได้ผ่านตัวเลือก `provider`, `model` และ `small_model` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +ตัวเลือก `small_model` จะกำหนดค่าโมเดลแยกต่างหากสำหรับงานที่ไม่ซับซ้อน เช่น การสร้างชื่อเรื่อง ตามค่าเริ่มต้น OpenCode จะพยายามใช้โมเดลที่ถูกกว่าหากมีให้บริการจากผู้ให้บริการของคุณ ไม่เช่นนั้นโมเดลจะกลับไปเป็นโมเดลหลักของคุณ + +ตัวเลือกผู้ให้บริการอาจรวมถึง `timeout` และ `setCacheKey`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - ​​คำขอหมดเวลาเป็นมิลลิวินาที (ค่าเริ่มต้น: 300000) ตั้งค่าเป็น `false` เพื่อปิดใช้งาน +- `setCacheKey` - ​​ตรวจสอบให้แน่ใจว่าได้ตั้งค่าคีย์แคชสำหรับผู้ให้บริการที่กำหนดเสมอ + +คุณยังสามารถกำหนดค่า [รุ่นท้องถิ่น](/docs/models#local) ได้ [เรียนรู้เพิ่มเติม](/docs/models) + +--- + +#### ตัวเลือกเฉพาะของผู้ให้บริการ + +ผู้ให้บริการบางรายรองรับตัวเลือกการกำหนดค่าเพิ่มเติมนอกเหนือจากการตั้งค่า `timeout` และ `apiKey` ทั่วไป + +##### อเมซอน ข้อเท็จจริง + +Amazon Bedrock รองรับ AWS-การกำหนดค่าเฉพาะ: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - ​​AWS ภูมิภาคสำหรับ Bedrock (ค่าเริ่มต้นเป็น `AWS_REGION` env var หรือ `us-east-1`) +- `profile` - ​​AWS ตั้งชื่อโปรไฟล์จาก `~/.aws/credentials` (ค่าเริ่มต้นเป็น `AWS_PROFILE` env var) +- `endpoint` - ​​จุดสิ้นสุดที่กำหนดเอง URL สำหรับจุดสิ้นสุด VPC นี่เป็นนามแฝงสำหรับตัวเลือก `baseURL` ทั่วไปโดยใช้คำศัพท์เฉพาะ AWS หากระบุทั้งสองรายการ `endpoint` จะมีความสำคัญกว่า + +:::note +โทเค็นผู้ถือ (`AWS_BEARER_TOKEN_BEDROCK` หรือ `/connect`) มีความสำคัญมากกว่าการตรวจสอบสิทธิ์ตามโปรไฟล์ ดู [ลำดับความสำคัญในการรับรองความถูกต้อง](/docs/providers#การรับรองความถูกต้อง-เหนือกว่า) สำหรับรายละเอียด +::: + +[เรียนรู้เพิ่มเติมเกี่ยวกับการกำหนดค่า Amazon Bedrock](/docs/providers#amazon-bedrock) + +--- + +### ธีมส์ + +คุณสามารถกำหนดค่าธีมที่คุณต้องการใช้ในการกำหนดค่า OpenCode ของคุณได้ผ่านตัวเลือก `theme` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[เรียนรู้เพิ่มเติมที่นี่](/docs/themes) + +--- + +### ตัวแทน + +คุณสามารถกำหนดค่าตัวแทนเฉพาะสำหรับงานเฉพาะผ่านตัวเลือก `agent` + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +คุณยังสามารถกำหนดตัวแทนโดยใช้ไฟล์มาร์กดาวน์ใน `~/.config/opencode/agents/` หรือ `.opencode/agents/` [เรียนรู้เพิ่มเติมที่นี่](/docs/agents) + +--- + +### ตัวแทนเริ่มต้น + +คุณสามารถตั้งค่าตัวแทนเริ่มต้นได้โดยใช้ตัวเลือก `default_agent` ซึ่งจะกำหนดว่าเอเจนต์ใดที่จะใช้เมื่อไม่มีการระบุอย่างชัดเจน + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +ตัวแทนเริ่มต้นจะต้องเป็นตัวแทนหลัก (ไม่ใช่ตัวแทนย่อย) ซึ่งอาจเป็นตัวแทนในตัว เช่น `"build"` หรือ `"plan"` หรือ [ตัวแทนที่กำหนดเอง](/docs/agents) ที่คุณกำหนดไว้ หากไม่มีตัวแทนที่ระบุหรือเป็นตัวแทนย่อย OpenCode จะถอยกลับไปที่ `"build"` พร้อมคำเตือน + +การตั้งค่านี้ใช้กับอินเทอร์เฟซทั้งหมด: TUI, CLI (`opencode run`) แอปเดสก์ท็อป และ GitHub Action + +--- + +### การแบ่งปัน + +คุณสามารถกำหนดค่าคุณสมบัติ [แบ่งปัน](/docs/share) ได้ผ่านทางตัวเลือก `share` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +ใช้เวลา: + +- `"manual"` - ​​อนุญาตให้แชร์ด้วยตนเองผ่านคำสั่ง (ค่าเริ่มต้น) +- `"auto"` - ​​แบ่งปันการสนทนาใหม่โดยอัตโนมัติ +- `"disabled"` - ​​ปิดการใช้งานการแชร์ทั้งหมด + +ตามค่าเริ่มต้น การแชร์จะถูกตั้งค่าเป็นโหมดกำหนดเอง ซึ่งคุณต้องแชร์การสนทนาอย่างชัดเจนโดยใช้คำสั่ง `/share` + +--- + +### คำสั่ง + +คุณสามารถกำหนดค่าคำสั่งที่กำหนดเองสำหรับงานซ้ำๆ ได้ผ่านตัวเลือก `command` + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +คุณยังสามารถกำหนดคำสั่งโดยใช้ไฟล์มาร์กดาวน์ใน `~/.config/opencode/commands/` หรือ `.opencode/commands/` [เรียนรู้เพิ่มเติมที่นี่](/docs/commands) + +--- + +### ปุ่มลัด + +คุณสามารถปรับแต่งปุ่มลัดของคุณได้ผ่านตัวเลือก `keybinds` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[เรียนรู้เพิ่มเติมที่นี่](/docs/keybinds) + +--- + +### อัปเดตอัตโนมัติ + +OpenCode จะดาวน์โหลดการอัปเดตใหม่โดยอัตโนมัติเมื่อเริ่มต้นระบบ คุณสามารถปิดการใช้งานนี้ได้โดยใช้ตัวเลือก `autoupdate` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +หากคุณไม่ต้องการการอัปเดตแต่ต้องการรับการแจ้งเตือนเมื่อมีเวอร์ชันใหม่ ให้ตั้งค่า `autoupdate` เป็น `"notify"` +โปรดสังเกตว่าสิ่งนี้ใช้ได้เฉพาะเมื่อไม่ได้ติดตั้งโดยใช้ตัวจัดการแพ็คเกจเช่น Homebrew + +--- + +### ฟอร์แมตเตอร์ + +คุณสามารถกำหนดค่าตัวจัดรูปแบบโค้ดผ่านตัวเลือก `formatter` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[เรียนรู้เพิ่มเติมเกี่ยวกับฟอร์แมตเตอร์ที่นี่](/docs/formatters) + +--- + +### สิทธิ์ + +ตามค่าเริ่มต้น opencode **อนุญาตการดำเนินการทั้งหมด** โดยไม่ต้องมีการอนุมัติอย่างชัดเจน คุณสามารถเปลี่ยนสิ่งนี้ได้โดยใช้ตัวเลือก `permission` + +ตัวอย่างเช่น เพื่อให้แน่ใจว่าเครื่องมือ `edit` และ `bash` ต้องได้รับการอนุมัติจากผู้ใช้: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[เรียนรู้เพิ่มเติมเกี่ยวกับการอนุญาตที่นี่](/docs/permissions) + +--- + +### การบดอัด + +คุณสามารถควบคุมลักษณะการทำงานของการบีบอัดบริบทได้โดยใช้ตัวเลือก `compaction` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - ​​กระชับเซสชันโดยอัตโนมัติเมื่อบริบทเต็ม (ค่าเริ่มต้น: `true`) +- `prune` - ​​ลบเอาท์พุตเครื่องมือเก่าเพื่อบันทึกโทเค็น (ค่าเริ่มต้น: `true`) + +--- + +### ผู้เฝ้าดู + +คุณสามารถกำหนดค่ารูปแบบการละเว้นตัวเฝ้าดูไฟล์ได้ผ่านตัวเลือก `watcher` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +รูปแบบเป็นไปตามไวยากรณ์ glob ใช้ตัวเลือกนี้เพื่อยกเว้นไดเร็กทอรีที่มีเสียงดังจากการดูไฟล์ + +--- + +### MCP เซิร์ฟเวอร์ + +คุณสามารถกำหนดค่าเซิร์ฟเวอร์ MCP ที่คุณต้องการใช้ผ่านตัวเลือก `mcp` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[เรียนรู้เพิ่มเติมที่นี่](/docs/mcp-servers) + +--- + +### ปลั๊กอิน + +[ปลั๊กอิน](/docs/plugins) ขยาย OpenCode ด้วยเครื่องมือที่กำหนดเอง hooks และการผสานรวม + +วางไฟล์ปลั๊กอินใน `.opencode/plugins/` หรือ `~/.config/opencode/plugins/` คุณยังสามารถโหลดปลั๊กอินจาก npm ผ่านตัวเลือก `plugin` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[เรียนรู้เพิ่มเติมที่นี่](/docs/plugins) + +--- + +### คำแนะนำ + +คุณสามารถกำหนดค่าคำแนะนำสำหรับรุ่นที่คุณใช้ผ่านตัวเลือก `instructions` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +สิ่งนี้จะนำอาร์เรย์ของเส้นทางและรูปแบบ glob ไปยังไฟล์คำสั่ง [เรียนรู้เพิ่มเติม +เกี่ยวกับกฎที่นี่](/docs/rules) + +--- + +### ผู้ให้บริการที่พิการ + +คุณสามารถปิดการใช้งานผู้ให้บริการที่โหลดโดยอัตโนมัติผ่านตัวเลือก `disabled_providers` สิ่งนี้มีประโยชน์เมื่อคุณต้องการป้องกันไม่ให้โหลดผู้ให้บริการบางรายแม้ว่าจะมีข้อมูลประจำตัวอยู่ก็ตาม + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +`disabled_providers` มีลำดับความสำคัญมากกว่า `enabled_providers` +::: + +ตัวเลือก `disabled_providers` ยอมรับอาร์เรย์ของรหัสผู้ให้บริการ เมื่อผู้ให้บริการถูกปิดใช้งาน: + +- มันจะไม่ถูกโหลดแม้ว่าจะมีการตั้งค่าตัวแปรสภาพแวดล้อมก็ตาม +- มันจะไม่ถูกโหลดแม้ว่าจะมีการกำหนดค่าคีย์ API ผ่านคำสั่ง `/connect` +- รุ่นของผู้ให้บริการจะไม่ปรากฏในรายการการเลือกรุ่น + +--- + +### ผู้ให้บริการที่เปิดใช้งาน + +คุณสามารถระบุรายชื่อผู้ให้บริการที่อนุญาตได้ผ่านตัวเลือก `enabled_providers` เมื่อตั้งค่าแล้ว เฉพาะผู้ให้บริการที่ระบุเท่านั้นที่จะเปิดใช้งาน และผู้ให้บริการอื่นๆ ทั้งหมดจะถูกละเว้น + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +สิ่งนี้มีประโยชน์เมื่อคุณต้องการจำกัด OpenCode ให้ใช้เฉพาะผู้ให้บริการบางราย แทนที่จะปิดการใช้งานทีละราย + +:::note +`disabled_providers` มีลำดับความสำคัญมากกว่า `enabled_providers` +::: + +หากผู้ให้บริการปรากฏทั้ง `enabled_providers` และ `disabled_providers` `disabled_providers` จะมีลำดับความสำคัญสำหรับความเข้ากันได้แบบย้อนหลัง + +--- + +### การทดลอง + +ปุ่ม `experimental` มีตัวเลือกที่อยู่ระหว่างการพัฒนา + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::caution +ตัวเลือกการทดลองไม่เสถียร อาจมีการเปลี่ยนแปลงหรือลบออกโดยไม่ต้องแจ้งให้ทราบล่วงหน้า +::: + +--- + +## ตัวแปร + +คุณสามารถใช้การทดแทนตัวแปรในไฟล์กำหนดค่าของคุณเพื่ออ้างอิงตัวแปรสภาพแวดล้อมและเนื้อหาไฟล์ได้ + +--- + +### ตัวแปร Env + +ใช้ `{env:VARIABLE_NAME}` เพื่อทดแทนตัวแปรสภาพแวดล้อม: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +หากไม่ได้ตั้งค่าตัวแปรสภาพแวดล้อม ตัวแปรนั้นจะถูกแทนที่ด้วยสตริงว่าง + +--- + +### ไฟล์ + +ใช้ `{file:path/to/file}` เพื่อทดแทนเนื้อหาของไฟล์: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +เส้นทางไฟล์อาจเป็น: + +- สัมพันธ์กับไดเร็กทอรีไฟล์ปรับแต่ง +- หรือเส้นทางที่แน่นอนเริ่มต้นด้วย `/` หรือ `~` + +สิ่งเหล่านี้มีประโยชน์สำหรับ: + +- เก็บข้อมูลที่ละเอียดอ่อนเช่นคีย์ API ไว้ในไฟล์แยกกัน +- รวมไฟล์คำสั่งขนาดใหญ่โดยไม่ทำให้การกำหนดค่าของคุณเกะกะ +- การแชร์ข้อมูลโค้ดการกำหนดค่าทั่วไปในไฟล์กำหนดค่าหลายไฟล์ diff --git a/packages/web/src/content/docs/th/custom-tools.mdx b/packages/web/src/content/docs/th/custom-tools.mdx new file mode 100644 index 000000000..28cd229cf --- /dev/null +++ b/packages/web/src/content/docs/th/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: เครื่องมือที่กำหนดเอง +description: สร้างเครื่องมือที่ LLM สามารถเรียกใช้ใน opencode +--- + +เครื่องมือแบบกำหนดเองคือฟังก์ชันที่คุณสร้างขึ้นซึ่ง LLM สามารถเรียกใช้ระหว่างการสนทนาได้ โดยทำงานร่วมกับ [เครื่องมือในตัว](/docs/tools) ของ opencode เช่น `read`, `write` และ `bash` + +--- + +## การสร้างเครื่องมือ + +เครื่องมือถูกกำหนดให้เป็นไฟล์ **TypeScript** หรือ **JavaScript** อย่างไรก็ตาม คำจำกัดความของเครื่องมือสามารถเรียกใช้สคริปต์ที่เขียนใน **ภาษาใดก็ได้** — TypeScript หรือ JavaScript ใช้สำหรับคำจำกัดความของเครื่องมือเท่านั้น + +--- + +### ที่ตั้ง + +สามารถกำหนดได้: + +- ภายในเครื่องโดยวางไว้ในไดเรกทอรี `.opencode/tools/` ของโครงการของคุณ +- หรือทั่วโลกโดยวางไว้ที่ `~/.config/opencode/tools/` + +--- + +### โครงสร้าง + +วิธีที่ง่ายที่สุดในการสร้างเครื่องมือคือการใช้ตัวช่วย `tool()` ซึ่งให้ความปลอดภัยและการตรวจสอบประเภท + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +**ชื่อไฟล์** จะกลายเป็น **ชื่อเครื่องมือ** ข้างต้นจะสร้างเครื่องมือ `database` + +--- + +#### เครื่องมือหลายอย่างต่อไฟล์ + +คุณยังสามารถส่งออกเครื่องมือหลายรายการจากไฟล์เดียวได้ การส่งออกแต่ละครั้งจะกลายเป็น **เครื่องมือแยกต่างหาก** โดยมีชื่อ **`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +สิ่งนี้จะสร้างเครื่องมือสองอย่าง: `math_add` และ `math_multiply` + +--- + +### ข้อโต้แย้ง + +คุณสามารถใช้ `tool.schema` ซึ่งก็คือ [Zod](https://zod.dev) เพื่อกำหนดประเภทอาร์กิวเมนต์ + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +คุณยังสามารถนำเข้า [Zod](https://zod.dev) ได้โดยตรงและส่งคืนออบเจ็กต์ธรรมดา: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### บริบท + +เครื่องมือได้รับบริบทเกี่ยวกับเซสชันปัจจุบัน: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +ใช้ `context.directory` สำหรับไดเร็กทอรีการทำงานของเซสชัน +ใช้ `context.worktree` สำหรับรูท git worktree + +--- + +## ตัวอย่าง + +### เขียนเครื่องมือใน Python + +คุณสามารถเขียนเครื่องมือของคุณเป็นภาษาใดก็ได้ที่คุณต้องการ นี่คือตัวอย่างที่บวกตัวเลขสองตัวโดยใช้ Python + +ขั้นแรก สร้างเครื่องมือเป็นสคริปต์ Python: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +จากนั้นสร้างคำจำกัดความของเครื่องมือที่เรียกใช้: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +ที่นี่เราใช้ยูทิลิตี้ [`Bun.$`](https://bun.com/docs/runtime/shell) เพื่อรันสคริปต์ Python diff --git a/packages/web/src/content/docs/th/ecosystem.mdx b/packages/web/src/content/docs/th/ecosystem.mdx new file mode 100644 index 000000000..ff1b108d6 --- /dev/null +++ b/packages/web/src/content/docs/th/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: ระบบนิเวศ +description: โปรเจ็กต์และการผสานรวมที่สร้างด้วย OpenCode +--- + +ชุดโครงการชุมชนที่สร้างขึ้นบน OpenCode + +:::note +ต้องการเพิ่มโครงการที่เกี่ยวข้องกับ OpenCode ของคุณลงในรายการนี้หรือไม่ ส่งพีอาร์. +::: + +คุณยังสามารถลองดู [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) และ [opencode.cafe](https://opencode.cafe) ซึ่งเป็นชุมชนที่รวบรวมระบบนิเวศและชุมชนไว้ด้วยกัน + +--- + +## ปลั๊กอิน + +| ชื่อ | คำอธิบาย | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [opencode-เดย์โทนา](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | เรียกใช้เซสชัน OpenCode โดยอัตโนมัติในแซนด์บ็อกซ์ Daytona ที่แยกออกมาพร้อม git sync และการแสดงตัวอย่างแบบสด | +| [opencode-helicone-เซสชัน](https://github.com/H2Shami/opencode-helicone-session) | แทรกส่วนหัวเซสชัน Helicone โดยอัตโนมัติสำหรับการจัดกลุ่มคำขอ | +| [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | ฉีดประเภท TypeScript/Svelte ลงในไฟล์ที่อ่านโดยอัตโนมัติด้วยเครื่องมือค้นหา | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | ใช้การสมัครสมาชิก ChatGPT Plus/Pro แทนเครดิต API | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | ใช้แผน Gemini ที่มีอยู่ของคุณแทนการเรียกเก็บเงิน API | +| [opencode-ต้านแรงโน้มถ่วง-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | ใช้โมเดลฟรีของ Antigravity แทนการเรียกเก็บเงิน API | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | การแยกคอนเทนเนอร์ Devcontainer แบบหลายสาขาพร้อมโคลนแบบตื้นและพอร์ตที่กำหนดอัตโนมัติ | +| [opencode-google-ต้านแรงโน้มถ่วง-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | ปลั๊กอิน Google Antigravity OAuth พร้อมรองรับ Google Search และการจัดการ API ที่แข็งแกร่งยิ่งขึ้น | +| [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | ปรับการใช้โทเค็นให้เหมาะสมโดยการตัดเอาท์พุตของเครื่องมือที่ล้าสมัย | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | เพิ่มการสนับสนุนการค้นหาเว็บแบบเนทีฟสำหรับผู้ให้บริการที่รองรับด้วยรูปแบบที่มีเหตุผลของ Google | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | ช่วยให้ตัวแทน AI สามารถเรียกใช้กระบวนการเบื้องหลังใน PTY และส่งข้อมูลเชิงโต้ตอบให้พวกเขาได้ | +| [opencode-shell-กลยุทธ์](https://github.com/JRedeker/opencode-shell-strategy) | คำแนะนำสำหรับคำสั่งเชลล์แบบไม่โต้ตอบ - ป้องกันการแฮงค์จากการดำเนินการที่ขึ้นอยู่กับ TTY | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | ติดตามการใช้งาน OpenCode ด้วย Wakatime | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | ทำความสะอาดตารางมาร์กดาวน์ที่ผลิตโดย LLM | +| [opencode-morph-ใช้อย่างรวดเร็ว](https://github.com/JRedeker/opencode-morph-fast-apply) | การแก้ไขโค้ดเร็วขึ้น 10 เท่าด้วย Morph Fast Apply API และเครื่องหมายแก้ไขแบบ Lazy | +| [โอ้ ฉัน-opencode](https://github.com/code-yeongyu/oh-my-opencode) | ตัวแทนเบื้องหลัง, เครื่องมือ LSP/AST/MCP ที่สร้างไว้ล่วงหน้า, ตัวแทนที่ได้รับการดูแลจัดการ, เข้ากันได้กับ Claude Code | +| [ผู้แจ้ง opencode](https://github.com/panta82/opencode-notificator) | การแจ้งเตือนบนเดสก์ท็อปและเสียงเตือนสำหรับเซสชัน OpenCode | +| [opencode-แจ้ง](https://github.com/mohak34/opencode-notifier) | การแจ้งเตือนบนเดสก์ท็อปและเสียงเตือนสำหรับการอนุญาต การดำเนินการเสร็จสิ้น และเหตุการณ์ข้อผิดพลาด | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | การตั้งชื่อเซสชัน Zellij อัตโนมัติที่ขับเคลื่อนด้วย AI ตามบริบทของ OpenCode | +| [opencode-เก่ง](https://github.com/zenobi-us/opencode-skillful) | อนุญาตให้ตัวแทน OpenCode โหลดแบบ Lazy Load ตามความต้องการพร้อมการค้นพบทักษะและการแทรก | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | หน่วยความจำถาวรตลอดเซสชันโดยใช้ Supermemory | +| [@ผู้วางแผน/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | การตรวจสอบแผนเชิงโต้ตอบพร้อมคำอธิบายประกอบแบบภาพและการแชร์ส่วนตัว/offline | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | ขยาย opencode /commands ไปสู่ระบบการประสานที่มีประสิทธิภาพพร้อมการควบคุมโฟลว์แบบละเอียด | +| [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | กำหนดเวลางานที่เกิดซ้ำโดยใช้ launchd (Mac) หรือ systemd (Linux) ด้วยไวยากรณ์ cron | +| [ไมโครโค้ด](https://github.com/vtemian/micode) | ระดมความคิดอย่างมีโครงสร้าง → วางแผน → นำเวิร์กโฟลว์ไปใช้ด้วยความต่อเนื่องของเซสชัน | +| [ตุลาคม](https://github.com/vtemian/octto) | UI เบราว์เซอร์แบบโต้ตอบสำหรับการระดมความคิด AI ด้วยแบบฟอร์มคำถามหลายข้อ | +| [opencode-พื้นหลัง-ตัวแทน](https://github.com/kdcokenny/opencode-background-agents) | เอเจนต์พื้นหลังสไตล์ Claude Code พร้อมการมอบหมายแบบอะซิงก์และการคงอยู่ของบริบท | +| [opencode-แจ้งเตือน](https://github.com/kdcokenny/opencode-notify) | การแจ้งเตือนระบบปฏิบัติการดั้งเดิมสำหรับ OpenCode – ทราบเมื่องานเสร็จสมบูรณ์ | +| [opencode-พื้นที่ทำงาน](https://github.com/kdcokenny/opencode-workspace) | ชุดสายรัดประสานหลายเอเจนต์ที่ให้มา – ส่วนประกอบ 16 ชิ้น ติดตั้งเพียงครั้งเดียว | +| [opencode-เวิร์กทรี](https://github.com/kdcokenny/opencode-worktree) | เวิร์กทรีคอมไพล์ไร้แรงเสียดทานสำหรับ OpenCode | + +--- + +## โครงการ + +| ชื่อ | คำอธิบาย | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [คิมากิ](https://github.com/remorses/kimaki) | บอท Discord เพื่อควบคุมเซสชัน OpenCode สร้างขึ้นบน SDK | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | ปลั๊กอิน Neovim สำหรับข้อความแจ้งที่ทราบโดยบรรณาธิการ ซึ่งสร้างขึ้นบน API | +| [พอร์ทัล](https://github.com/hosenur/portal) | UI เว็บบนมือถือเป็นครั้งแรกสำหรับ OpenCode บน Tailscale/VPN | +| [เทมเพลตปลั๊กอิน opencode](https://github.com/zenobi-us/opencode-plugin-template/) | เทมเพลตสำหรับสร้างปลั๊กอิน OpenCode | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | ส่วนหน้า Neovim สำหรับ opencode - เอเจนต์การเข้ารหัส AI ที่ใช้เทอร์มินัล | +| [ai-sdk-ผู้ให้บริการ-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | ผู้ให้บริการ Vercel AI SDK สำหรับการใช้งาน OpenCode ผ่าน @opencode-ai/sdk | +| [เปิดห้อง](https://github.com/btriapitsyn/openchamber) | แอพเว็บ / เดสก์ท็อปและส่วนขยายรหัส VS สำหรับ OpenCode | +| [OpenCode-ออบซิเดียน](https://github.com/mtymek/opencode-obsidian) | ปลั๊กอิน Obsidian ที่ฝัง OpenCode ไว้ใน UI ของ Obsidian | +| [โอเพ่นเวิร์ค](https://github.com/different-ai/openwork) | ทางเลือกโอเพ่นซอร์สแทน Claude Cowork ซึ่งขับเคลื่อนโดย OpenCode | +| [ocx](https://github.com/kdcokenny/ocx) | ตัวจัดการส่วนขยาย OpenCode พร้อมโปรไฟล์แบบพกพาและแยกส่วน | +| [โค้ดโนแมด](https://github.com/NeuralNomadsAI/CodeNomad) | แอปเดสก์ท็อป เว็บ มือถือ และไคลเอ็นต์ระยะไกลสำหรับ OpenCode | + +--- + +## ตัวแทน + +| ชื่อ | คำอธิบาย | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [ตัวแทน](https://github.com/Cluster444/agentic) | เอเจนต์ AI แบบแยกส่วนและคำสั่งสำหรับการพัฒนาแบบมีโครงสร้าง | +| [opencode-ตัวแทน](https://github.com/darrenhinde/opencode-agents) | กำหนดค่า พรอมต์ เอเจนต์ และปลั๊กอินสำหรับเวิร์กโฟลว์ที่ได้รับการปรับปรุง | diff --git a/packages/web/src/content/docs/th/enterprise.mdx b/packages/web/src/content/docs/th/enterprise.mdx new file mode 100644 index 000000000..4ac0c6f27 --- /dev/null +++ b/packages/web/src/content/docs/th/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: องค์กร +description: การใช้ OpenCode อย่างปลอดภัยในองค์กรของคุณ +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise เหมาะสำหรับองค์กรที่ต้องการให้แน่ใจว่าโค้ดและข้อมูลของตนไม่หลุดออกจากโครงสร้างพื้นฐาน ซึ่งสามารถทำได้โดยใช้การกำหนดค่าแบบรวมศูนย์ที่ทำงานร่วมกับ SSO และเกตเวย์ AI ภายในของคุณ + +:::note +OpenCode จะไม่เก็บโค้ดหรือข้อมูลบริบทใดๆ ของคุณ +::: + +ในการเริ่มต้นใช้งาน OpenCode Enterprise: + +1. ทดลองใช้งานภายในกับทีมของคุณ +2. **ติดต่อเรา** เพื่อหารือเกี่ยวกับตัวเลือกด้านราคาและการใช้งาน + +--- + +## การทดลอง + +OpenCode เป็นโอเพ่นซอร์สและไม่ได้จัดเก็บโค้ดหรือข้อมูลบริบทใดๆ ของคุณ ดังนั้นนักพัฒนาของคุณสามารถ [เริ่มต้น](/docs/) และดำเนินการทดลองใช้งานได้อย่างง่ายดาย + +--- + +### การจัดการข้อมูล + +**OpenCode จะไม่จัดเก็บโค้ดหรือข้อมูลบริบทของคุณ** การประมวลผลทั้งหมดเกิดขึ้นภายในเครื่องหรือผ่านการเรียก API โดยตรงไปยังผู้ให้บริการ AI ของคุณ + +ซึ่งหมายความว่าตราบใดที่คุณใช้ผู้ให้บริการที่คุณเชื่อถือหรือผู้ให้บริการภายใน +เกตเวย์ AI คุณสามารถใช้ OpenCode ได้อย่างปลอดภัย + +ข้อแม้เดียวที่นี่คือคุณสมบัติเสริม `/share` + +--- + +#### การแบ่งปันการสนทนา + +หากผู้ใช้เปิดใช้งานคุณสมบัติ `/share` การสนทนาและข้อมูลที่เกี่ยวข้องกับการสนทนาจะถูกส่งไปยังบริการที่เราใช้เพื่อโฮสต์เพจแชร์เหล่านี้ที่ opencode.ai + +ขณะนี้ข้อมูลให้บริการผ่านเครือข่าย Edge ของ CDN ของเรา และถูกแคชไว้ที่ Edge ใกล้ผู้ใช้ของคุณ + +เราขอแนะนำให้คุณปิดการใช้งานนี้สำหรับการทดลองใช้ของคุณ + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[เรียนรู้เพิ่มเติมเกี่ยวกับการแชร์](/docs/share) + +--- + +### ความเป็นเจ้าของรหัส + +**คุณเป็นเจ้าของโค้ดทั้งหมดที่สร้างโดย OpenCode** ไม่มีข้อจำกัดด้านใบอนุญาตหรือการอ้างสิทธิ์ความเป็นเจ้าของ + +--- + +## ราคา + +เราใช้แบบจำลองต่อที่นั่งสำหรับ OpenCode Enterprise หากคุณมีเกตเวย์ LLM ของคุณเอง เราจะไม่เรียกเก็บเงินสำหรับโทเค็นที่ใช้ สำหรับรายละเอียดเพิ่มเติมเกี่ยวกับตัวเลือกราคาและการใช้งาน **ติดต่อเรา** + +--- + +## การปรับใช้ + +เมื่อคุณทดลองใช้งานเสร็จแล้วและพร้อมที่จะใช้ OpenCode ที่ +องค์กรของคุณ คุณสามารถ **ติดต่อเรา** เพื่อหารือเกี่ยวกับ +ตัวเลือกการกำหนดราคาและการใช้งาน + +--- + +### การกำหนดค่าส่วนกลาง + +เราสามารถตั้งค่า OpenCode เพื่อใช้การกำหนดค่าส่วนกลางเพียงรายการเดียวสำหรับทั้งองค์กรของคุณได้ + +การกำหนดค่าแบบรวมศูนย์นี้สามารถทำงานร่วมกับผู้ให้บริการ SSO ของคุณได้ และรับรองว่าผู้ใช้ทุกคนจะเข้าถึงเฉพาะเกตเวย์ AI ภายในของคุณเท่านั้น + +--- + +### SSO บูรณาการ + +ด้วยการกำหนดค่าส่วนกลาง OpenCode สามารถทำงานร่วมกับผู้ให้บริการ SSO ขององค์กรของคุณเพื่อตรวจสอบสิทธิ์ได้ + +ซึ่งช่วยให้ OpenCode รับข้อมูลรับรองสำหรับเกตเวย์ AI ภายในของคุณผ่านระบบการจัดการข้อมูลประจำตัวที่คุณมีอยู่ + +--- + +### เกตเวย์ AI ภายใน + +ด้วยการกำหนดค่าส่วนกลาง คุณสามารถกำหนดค่า OpenCode ให้ใช้เกตเวย์ AI ภายในของคุณเท่านั้น + +คุณยังสามารถปิดการใช้งานผู้ให้บริการ AI อื่นๆ ทั้งหมดได้ เพื่อให้มั่นใจว่าคำขอทั้งหมดจะผ่านโครงสร้างพื้นฐานที่ได้รับอนุมัติขององค์กรของคุณ + +--- + +### โฮสติ้งด้วยตนเอง + +ในขณะที่เราแนะนำให้ปิดการใช้งานหน้าแบ่งปันเพื่อให้แน่ใจว่าข้อมูลของคุณจะไม่หายไป +องค์กรของคุณ เราก็สามารถช่วยคุณโฮสต์พวกเขาเองบนโครงสร้างพื้นฐานของคุณได้ + +ขณะนี้อยู่ในแผนงานของเรา หากคุณสนใจ **แจ้งให้เราทราบ** + +--- + +## FAQ + +
+What is OpenCode Enterprise? + +OpenCode Enterprise เหมาะสำหรับองค์กรที่ต้องการให้แน่ใจว่าโค้ดและข้อมูลของตนไม่หลุดออกจากโครงสร้างพื้นฐาน ซึ่งสามารถทำได้โดยใช้การกำหนดค่าแบบรวมศูนย์ที่ทำงานร่วมกับ SSO และเกตเวย์ AI ภายในของคุณ + +
+ +
+How do I get started with OpenCode Enterprise? + +เพียงเริ่มต้นด้วยการทดลองใช้ภายในกับทีมของคุณ ตามค่าเริ่มต้น OpenCode จะไม่จัดเก็บโค้ดหรือข้อมูลบริบทของคุณ ทำให้ง่ายต่อการเริ่มต้น + +จากนั้น **ติดต่อเรา** เพื่อหารือเกี่ยวกับตัวเลือกด้านราคาและการใช้งาน + +
+ +
+How does enterprise pricing work? + +เราเสนอราคาสำหรับองค์กรต่อที่นั่ง หากคุณมีเกตเวย์ LLM ของคุณเอง เราจะไม่เรียกเก็บเงินสำหรับโทเค็นที่ใช้ สำหรับรายละเอียดเพิ่มเติม **ติดต่อเรา** เพื่อขอใบเสนอราคาที่กำหนดเองตามความต้องการขององค์กรของคุณ + +
+ +
+Is my data secure with OpenCode Enterprise? + +ใช่. OpenCode จะไม่เก็บโค้ดหรือข้อมูลบริบทของคุณ การประมวลผลทั้งหมดเกิดขึ้นภายในเครื่องหรือผ่านการโทรศัพท์ API โดยตรงไปยังผู้ให้บริการ AI ของคุณ ด้วยการกำหนดค่าส่วนกลางและการบูรณาการ SSO ข้อมูลของคุณยังคงปลอดภัยภายในโครงสร้างพื้นฐานขององค์กรของคุณ + +
+ +
+Can we use our own private NPM registry? + +OpenCode รองรับการลงทะเบียน npm ส่วนตัวผ่านการรองรับไฟล์ `.npmrc` ดั้งเดิมของ Bun หากองค์กรของคุณใช้รีจิสทรีส่วนตัว เช่น JFrog Artifactory, Nexus หรือที่คล้ายกัน โปรดตรวจสอบให้แน่ใจว่านักพัฒนาได้รับการตรวจสอบสิทธิ์ก่อนเรียกใช้ OpenCode + +วิธีตั้งค่าการตรวจสอบสิทธิ์กับรีจิสทรีส่วนตัวของคุณ: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +สิ่งนี้จะสร้าง `~/.npmrc` พร้อมรายละเอียดการตรวจสอบสิทธิ์ OpenCode จะอัตโนมัติ +หยิบสิ่งนี้ขึ้นมา + +:::caution +คุณต้องเข้าสู่ระบบรีจิสทรีส่วนตัวก่อนที่จะเรียกใช้ OpenCode +::: + +หรือคุณสามารถกำหนดค่าไฟล์ `.npmrc` ด้วยตนเองได้: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +นักพัฒนาจะต้องลงชื่อเข้าใช้รีจิสทรีส่วนตัวก่อนที่จะเรียกใช้ OpenCode เพื่อให้แน่ใจว่าสามารถติดตั้งแพ็คเกจจากรีจิสทรีขององค์กรของคุณได้ + +
diff --git a/packages/web/src/content/docs/th/formatters.mdx b/packages/web/src/content/docs/th/formatters.mdx new file mode 100644 index 000000000..e0abc0294 --- /dev/null +++ b/packages/web/src/content/docs/th/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: ฟอร์แมตเตอร์ +description: OpenCode ใช้ตัวจัดรูปแบบเฉพาะภาษา +--- + +OpenCode จะจัดรูปแบบไฟล์โดยอัตโนมัติหลังจากที่เขียนหรือแก้ไขโดยใช้ตัวจัดรูปแบบเฉพาะภาษา เพื่อให้แน่ใจว่าโค้ดที่สร้างขึ้นเป็นไปตามสไตล์โค้ดของโปรเจ็กต์ของคุณ + +--- + +## บิวท์อิน + +OpenCode มาพร้อมกับฟอร์แมตเตอร์ในตัวหลายตัวสำหรับภาษาและเฟรมเวิร์กยอดนิยม ด้านล่างนี้คือรายการฟอร์แมตเตอร์ นามสกุลไฟล์ที่รองรับ และคำสั่งหรือตัวเลือกการกำหนดค่าที่ต้องการ + +| ฟอร์แมตเตอร์ | ส่วนขยาย | ความต้องการ | +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| กอฟท์ | .ไป | `gofmt` คำสั่งใช้ได้ | +| ผสม | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` คำสั่งใช้ได้ | +| สวยกว่า | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml และ [เพิ่มเติม](https://prettier.io/docs/en/index.html) | `prettier` การพึ่งพาใน `package.json` | +| ชีวนิเวศน์ | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml และ [เพิ่มเติม](https://biomejs.dev/) | `biome.json(c)` ไฟล์ปรับแต่ง | +| ซิกซิก | .ซิก, .ซอน | `zig` คำสั่งใช้ได้ | +| เสียงดังกราวรูปแบบ | .c, .cpp, .h, .hpp, .ino และ [เพิ่มเติม](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` ไฟล์ปรับแต่ง | +| เคทลินท์ | .kt, .kts | `ktlint` คำสั่งใช้ได้ | +| สร้อย | .py, .pyi | คำสั่ง `ruff` ใช้ได้กับ config | +| สนิม | .อาร์เอส | `rustfmt` คำสั่งใช้ได้ | +| สินค้าfmt | .อาร์เอส | `cargo fmt` คำสั่งใช้ได้ | +| ยูวี | .py, .pyi | `uv` คำสั่งใช้ได้ | +| รูโบคอป | .rb, .rake, .gemspec, .ru | `rubocop` คำสั่งใช้ได้ | +| มาตรฐานrb | .rb, .rake, .gemspec, .ru | `standardrb` คำสั่งใช้ได้ | +| htmlเสริมสวย | .erb, .html.erb | `htmlbeautifier` คำสั่งใช้ได้ | +| อากาศ | .ร | `air` คำสั่งใช้ได้ | +| โผ | .โผ | `dart` คำสั่งใช้ได้ | +| ocamlformat | .มล., .มลิ | มีคำสั่ง `ocamlformat` และไฟล์ปรับแต่ง `.ocamlformat` | +| ภูมิประเทศ | .tf, .tfvars | `terraform` คำสั่งใช้ได้ | +| เปล่งประกาย | .แวววาว | `gleam` คำสั่งใช้ได้ | +| ห้าม | .ห้าม | `nixfmt` คำสั่งใช้ได้ | +| สับเปลี่ยน | .sh, .ทุบตี | `shfmt` คำสั่งใช้ได้ | +| ไพน์ | .php | `laravel/pint` การพึ่งพาใน `composer.json` | +| oxfmt (ทดลอง) | .js, .jsx, .ts, .tsx | `oxfmt` การพึ่งพาใน `package.json` และ [แฟล็กตัวแปร env ทดลอง](/docs/cli/#experimental) | +| ออร์โมลู | .hs | `ormolu` คำสั่งใช้ได้ | + +ดังนั้นหากโปรเจ็กต์ของคุณมี `prettier` ใน `package.json` OpenCode จะใช้มันโดยอัตโนมัติ + +--- + +## มันทำงานอย่างไร + +เมื่อ OpenCode เขียนหรือแก้ไขไฟล์ มันจะ: + +1. ตรวจสอบนามสกุลไฟล์กับฟอร์แมตเตอร์ที่เปิดใช้งานทั้งหมด +2. รันคำสั่งฟอร์แมตเตอร์ที่เหมาะสมบนไฟล์ +3. ใช้การเปลี่ยนแปลงการจัดรูปแบบโดยอัตโนมัติ + +กระบวนการนี้เกิดขึ้นในเบื้องหลัง ทำให้มั่นใจได้ว่าสไตล์โค้ดของคุณจะถูกรักษาไว้โดยไม่มีขั้นตอนที่ต้องทำเอง + +--- + +## กำหนดค่า + +คุณสามารถปรับแต่งฟอร์แมตเตอร์ได้ผ่านทางส่วน `formatter` ในการกำหนดค่า OpenCode ของคุณ + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +การกำหนดค่าฟอร์แมตเตอร์แต่ละรายการรองรับสิ่งต่อไปนี้: + +| คุณสมบัติ | พิมพ์ | คำอธิบาย | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` | บูลีน | ตั้งค่านี้เป็น `true` เพื่อปิดใช้งานฟอร์แมตเตอร์ | +| `command` | สตริง[] | คำสั่งให้เรียกใช้การจัดรูปแบบ | +| `environment` | วัตถุ | ตัวแปรสภาพแวดล้อมที่จะตั้งค่าเมื่อรันฟอร์แมตเตอร์ | +| `extensions` | สตริง[] | นามสกุลไฟล์ที่ฟอร์แมตเตอร์นี้ควรรองรับ | + +ลองดูตัวอย่างบางส่วน + +--- + +### ปิดการใช้งานฟอร์แมตเตอร์ + +หากต้องการปิดการใช้งาน **ทั้งหมด** ฟอร์แมตเตอร์ทั่วโลก ให้ตั้งค่า `formatter` เป็น `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +หากต้องการปิดใช้งานฟอร์แมตเตอร์ **เฉพาะ** ให้ตั้งค่า `disabled` เป็น `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### ตัวจัดรูปแบบที่กำหนดเอง + +คุณสามารถแทนที่ฟอร์แมตเตอร์ที่มีอยู่แล้วภายในหรือเพิ่มฟอร์แมตใหม่ได้โดยการระบุคำสั่ง ตัวแปรสภาพแวดล้อม และนามสกุลไฟล์: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +ตัวยึดตำแหน่ง **`$FILE`** ในคำสั่งจะถูกแทนที่ด้วยเส้นทางไปยังไฟล์ที่กำลังจัดรูปแบบ diff --git a/packages/web/src/content/docs/th/github.mdx b/packages/web/src/content/docs/th/github.mdx new file mode 100644 index 000000000..5c98b7fa3 --- /dev/null +++ b/packages/web/src/content/docs/th/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: ใช้ OpenCode ในปัญหา GitHub และคำขอแบบดึง +--- + +OpenCode ผสานรวมกับเวิร์กโฟลว์ GitHub ของคุณ พูดถึง `/opencode` หรือ `/oc` ในความคิดเห็นของคุณ แล้ว OpenCode จะดำเนินการงานภายใน GitHub Actions runner ของคุณ + +--- + +## คุณสมบัติ + +- **ปัญหาการคัดแยก**: ขอให้ OpenCode ตรวจสอบปัญหาและอธิบายให้คุณทราบ +- **แก้ไขและนำไปใช้**: ขอให้ OpenCode แก้ไขปัญหาหรือใช้ฟีเจอร์ และมันจะทำงานในสาขาใหม่และส่ง PR พร้อมการเปลี่ยนแปลงทั้งหมด +- **ปลอดภัย**: OpenCode ทำงานภายในรันเนอร์ของ GitHub ของคุณ + +--- + +## การติดตั้ง + +รันคำสั่งต่อไปนี้ในโปรเจ็กต์ที่อยู่ใน repo GitHub: + +```bash +opencode github install +``` + +ขั้นตอนนี้จะแนะนำคุณตลอดขั้นตอนการติดตั้งแอป GitHub การสร้างเวิร์กโฟลว์ และการตั้งค่าความลับ + +--- + +### การตั้งค่าด้วยตนเอง + +หรือคุณสามารถตั้งค่าได้ด้วยตนเอง + +1. **ติดตั้งแอป GitHub** + + ไปที่ [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent) ตรวจสอบให้แน่ใจว่าได้ติดตั้งบนที่เก็บเป้าหมายแล้ว + +2. **เพิ่มขั้นตอนการทำงาน** + + เพิ่มไฟล์เวิร์กโฟลว์ต่อไปนี้ไปที่ `.github/workflows/opencode.yml` ใน repo ของคุณ ตรวจสอบให้แน่ใจว่าได้ตั้งค่า `model` ที่เหมาะสมและคีย์ API ที่จำเป็นใน `env` + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **เก็บคีย์ API เป็นความลับ** + + ในองค์กรหรือโครงการ **การตั้งค่า** ให้ขยาย **ความลับและตัวแปร** ทางด้านซ้าย แล้วเลือก **การดำเนินการ** และเพิ่มคีย์ API ที่จำเป็น + +--- + +## การกำหนดค่า + +- `model`: โมเดลที่จะใช้กับ OpenCode ใช้รูปแบบของ `provider/model` นี่คือ **จำเป็น** +- `agent`: ตัวแทนที่จะใช้ จะต้องเป็นตัวแทนหลัก ย้อนกลับไปที่ `default_agent` จาก config หรือ `"build"` หากไม่พบ +- `share`: ไม่ว่าจะแชร์เซสชัน OpenCode หรือไม่ ค่าเริ่มต้นเป็น **จริง** สำหรับที่เก็บข้อมูลสาธารณะ +- `prompt`: ตัวเลือกที่กำหนดเองพร้อมท์เพื่อแทนที่การทำงานเริ่มต้น ใช้สิ่งนี้เพื่อปรับแต่งวิธีที่ OpenCode ประมวลผลคำขอ +- `token`: โทเค็นการเข้าถึง GitHub เสริมสำหรับการดำเนินการ เช่น การสร้างความคิดเห็น การยอมรับการเปลี่ยนแปลง และการเปิดคำขอดึง ตามค่าเริ่มต้น OpenCode จะใช้โทเค็นการเข้าถึงการติดตั้งจากแอป OpenCode GitHub ดังนั้นคอมมิต แสดงความคิดเห็น และคำขอดึงข้อมูลจะปรากฏว่ามาจากแอป + + หรือคุณสามารถใช้ [ในตัว `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) ของ GitHub Action runner ได้โดยไม่ต้องติดตั้งแอป OpenCode GitHub เพียงตรวจสอบให้แน่ใจว่าได้ให้สิทธิ์ที่จำเป็นในขั้นตอนการทำงานของคุณ: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + คุณยังสามารถใช้ [โทเค็นการเข้าถึงส่วนบุคคล](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) ได้หากต้องการ + +--- + +## กิจกรรมที่รองรับ + +OpenCode สามารถทริกเกอร์ได้โดยเหตุการณ์ GitHub ต่อไปนี้: + +| ประเภทเหตุการณ์ | กระตุ้นโดย | รายละเอียด | +| ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | แสดงความคิดเห็นในประเด็นหรือประชาสัมพันธ์ | พูดถึง `/opencode` หรือ `/oc` ในความคิดเห็นของคุณ OpenCode อ่านบริบทและสามารถสร้างสาขา เปิด PR หรือตอบกลับได้ | +| `pull_request_review_comment` | แสดงความคิดเห็นเกี่ยวกับบรรทัดรหัสเฉพาะในการประชาสัมพันธ์ | พูดถึง `/opencode` หรือ `/oc` ในขณะที่ตรวจสอบโค้ด OpenCode รับเส้นทางไฟล์ หมายเลขบรรทัด และบริบทที่แตกต่าง | +| `issues` | ปัญหาเปิดหรือแก้ไข | ทริกเกอร์ OpenCode โดยอัตโนมัติเมื่อมีการสร้างหรือแก้ไขปัญหา ต้องป้อนข้อมูล `prompt` | +| `pull_request` | PR เปิดหรืออัปเดตแล้ว | ทริกเกอร์ OpenCode โดยอัตโนมัติเมื่อมีการเปิด ซิงโครไนซ์ หรือเปิด PR อีกครั้ง มีประโยชน์สำหรับการตรวจสอบอัตโนมัติ | +| `schedule` | กำหนดการตาม Cron | เรียกใช้ OpenCode ตามกำหนดเวลา ต้องป้อนข้อมูล `prompt` เอาต์พุตไปที่บันทึกและ PR (ไม่มีปัญหาในการแสดงความคิดเห็น) | +| `workflow_dispatch` | ทริกเกอร์ด้วยตนเองจาก GitHub UI | ทริกเกอร์ OpenCode ตามความต้องการผ่านแท็บการดำเนินการ ต้องป้อนข้อมูล `prompt` เอาต์พุตไปที่บันทึกและ PR | + +### ตัวอย่างกำหนดการ + +เรียกใช้ OpenCode ตามกำหนดเวลาเพื่อทำงานอัตโนมัติ: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +สำหรับกิจกรรมที่กำหนดเวลาไว้ อินพุต `prompt` เป็นสิ่งที่จำเป็น** เนื่องจากไม่มีความคิดเห็นที่จะดึงคำแนะนำออกมา เวิร์กโฟลว์ตามกำหนดการทำงานโดยไม่มีบริบทผู้ใช้ในการตรวจสอบสิทธิ์ ดังนั้นเวิร์กโฟลว์จะต้องให้สิทธิ์ `contents: write` และ `pull-requests: write` หากคุณคาดหวังให้ OpenCode สร้างสาขาหรือ PR + +--- + +### ตัวอย่างคำขอดึง + +ตรวจสอบ PR โดยอัตโนมัติเมื่อมีการเปิดหรืออัปเดต: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +สำหรับกิจกรรม `pull_request` หากไม่มีการระบุ `prompt` OpenCode จะใช้ค่าเริ่มต้นในการตรวจสอบคำขอดึง + +--- + +### ตัวอย่าง Triage ปัญหา + +คัดแยกปัญหาใหม่โดยอัตโนมัติ ตัวอย่างนี้กรองไปยังบัญชีที่มีอายุมากกว่า 30 วันเพื่อลดสแปม: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +สำหรับเหตุการณ์ `issues` อินพุต `prompt` นั้น **จำเป็น** เนื่องจากไม่มีความคิดเห็นที่จะดึงคำแนะนำออกมา + +--- + +## ข้อความแจ้งที่กำหนดเอง + +แทนที่ข้อความแจ้งเริ่มต้นเพื่อปรับแต่งการทำงานของ OpenCode สำหรับเวิร์กโฟลว์ของคุณ + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +สิ่งนี้มีประโยชน์สำหรับการบังคับใช้เกณฑ์การตรวจสอบเฉพาะ มาตรฐานการเขียนโค้ด หรือประเด็นมุ่งเน้นที่เกี่ยวข้องกับโครงการของคุณ + +--- + +## ตัวอย่าง + +นี่คือตัวอย่างบางส่วนของวิธีที่คุณสามารถใช้ OpenCode ใน GitHub + +- **อธิบายปัญหา** + + เพิ่มความคิดเห็นนี้ในปัญหา GitHub + + ``` + /opencode explain this issue + ``` + + OpenCode จะอ่านกระทู้ทั้งหมด รวมถึงความคิดเห็นทั้งหมด และตอบกลับพร้อมคำอธิบายที่ชัดเจน + +- **แก้ไขปัญหา** + + ในปัญหา GitHub ให้พูดว่า: + + ``` + /opencode fix this + ``` + + และ OpenCode จะสร้างสาขาใหม่ ดำเนินการเปลี่ยนแปลง และเปิด PR ที่มีการเปลี่ยนแปลง + +- **ตรวจสอบ PR และทำการเปลี่ยนแปลง** + + แสดงความคิดเห็นต่อไปนี้ใน GitHub PR + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + OpenCode จะดำเนินการเปลี่ยนแปลงที่ร้องขอและส่งมอบให้กับ PR เดียวกัน + +- **ตรวจสอบบรรทัดรหัสเฉพาะ** + + แสดงความคิดเห็นโดยตรงบนบรรทัดโค้ดในแท็บ "ไฟล์" ของ PR OpenCode จะตรวจจับไฟล์ หมายเลขบรรทัด และบริบทต่างโดยอัตโนมัติเพื่อให้การตอบสนองที่แม่นยำ + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + เมื่อแสดงความคิดเห็นในบรรทัดใดบรรทัดหนึ่ง OpenCode จะได้รับ: + - กำลังตรวจสอบไฟล์ที่แน่นอน + - บรรทัดโค้ดเฉพาะ + - บริบทที่แตกต่างโดยรอบ + - ข้อมูลหมายเลขบรรทัด + + ซึ่งช่วยให้สามารถร้องขอที่ตรงเป้าหมายมากขึ้นโดยไม่จำเป็นต้องระบุเส้นทางไฟล์หรือหมายเลขบรรทัดด้วยตนเอง diff --git a/packages/web/src/content/docs/th/gitlab.mdx b/packages/web/src/content/docs/th/gitlab.mdx new file mode 100644 index 000000000..48d89ef5c --- /dev/null +++ b/packages/web/src/content/docs/th/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: ใช้ OpenCode ในปัญหา GitLab และรวมคำขอ +--- + +OpenCode ทำงานร่วมกับเวิร์กโฟลว์ GitLab ของคุณผ่านไปป์ไลน์ GitLab CI/CD หรือกับ GitLab Duo + +ในทั้งสองกรณี OpenCode จะทำงานบน GitLab runners ของคุณ + +--- + +## GitLab CI + +OpenCode ทำงานในไปป์ไลน์ GitLab ปกติ คุณสามารถสร้างมันลงในไปป์ไลน์เป็น [องค์ประกอบ CI](https://docs.gitlab.com/ee/ci/components/) + +ที่นี่เรากำลังใช้คอมโพเนนต์ CI/CD ที่สร้างโดยชุมชนสำหรับ OpenCode — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode) + +--- + +### คุณสมบัติ + +- **ใช้การกำหนดค่าแบบกำหนดเองต่องาน**: กำหนดค่า OpenCode ด้วยไดเร็กทอรีการกำหนดค่าแบบกำหนดเอง เช่น `./config/#custom-directory` เพื่อเปิดหรือปิดฟังก์ชันการทำงานต่อการเรียกใช้ OpenCode +- **การตั้งค่าขั้นต่ำ**: องค์ประกอบ CI จะตั้งค่า OpenCode ในเบื้องหลัง คุณเพียงแค่ต้องสร้างการกำหนดค่า OpenCode และข้อความแจ้งเริ่มต้นเท่านั้น +- **ยืดหยุ่น**: ส่วนประกอบ CI รองรับอินพุตหลายอินพุตเพื่อปรับแต่งลักษณะการทำงาน + +--- + +### ตั้งค่า + +1. จัดเก็บการรับรองความถูกต้อง OpenCode ของคุณ JSON เป็นประเภทไฟล์ CI ตัวแปรสภาพแวดล้อมภายใต้ **การตั้งค่า** > **CI/CD** > **ตัวแปร** ตรวจสอบให้แน่ใจว่าได้ทำเครื่องหมายว่าเป็น "ปิดบังและซ่อนไว้" +2. เพิ่มสิ่งต่อไปนี้ในไฟล์ `.gitlab-ci.yml` ของคุณ + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +หากต้องการข้อมูลเพิ่มเติมและกรณีการใช้งาน [ตรวจสอบเอกสาร](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode) สำหรับส่วนประกอบนี้ + +--- + +## GitLab ดูโอ + +OpenCode ทำงานร่วมกับเวิร์กโฟลว์ GitLab ของคุณ +พูดถึง `@opencode` ในความคิดเห็น แล้ว OpenCode จะดำเนินการงานภายในไปป์ไลน์ GitLab CI ของคุณ + +--- + +### คุณสมบัติ + +- **ปัญหาการคัดแยก**: ขอให้ OpenCode ตรวจสอบปัญหาและอธิบายให้คุณทราบ +- **แก้ไขและนำไปใช้**: ขอให้ OpenCode แก้ไขปัญหาหรือใช้ฟีเจอร์ + มันจะสร้างสาขาใหม่และขอรวมการเปลี่ยนแปลง +- **ปลอดภัย**: OpenCode ทำงานบนนักวิ่ง GitLab ของคุณ + +--- + +### ตั้งค่า + +OpenCode ทำงานในไปป์ไลน์ GitLab CI/CD ของคุณ นี่คือสิ่งที่คุณจะต้องตั้งค่า: + +:::tip +ตรวจสอบ [**เอกสาร GitLab**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) เพื่อดูคำแนะนำล่าสุด +::: + +1. กำหนดค่าสภาพแวดล้อม GitLab ของคุณ +2. ตั้งค่า CI/CD +3. รับผู้ให้บริการโมเดล AI API คีย์ +4. สร้างบัญชีบริการ +5. กำหนดค่าตัวแปร CI/CD +6. สร้างไฟล์กำหนดค่าโฟลว์ ต่อไปนี้เป็นตัวอย่าง: + +
+ + Flow configuration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +คุณสามารถดูคำแนะนำโดยละเอียดได้ที่ [GitLab CLI agent docs](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) + +--- + +### ตัวอย่าง + +นี่คือตัวอย่างบางส่วนของวิธีที่คุณสามารถใช้ OpenCode ใน GitLab + +:::tip +คุณสามารถกำหนดค่าให้ใช้วลีทริกเกอร์ที่แตกต่างจาก `@opencode` +::: + +- **อธิบายปัญหา** + + เพิ่มความคิดเห็นนี้ในปัญหา GitLab + + ``` + @opencode explain this issue + ``` + + OpenCode จะอ่านปัญหาและตอบกลับพร้อมคำอธิบายที่ชัดเจน + +- **แก้ไขปัญหา** + + ในปัญหา GitLab ให้พูดว่า: + + ``` + @opencode fix this + ``` + + OpenCode จะสร้างสาขาใหม่ ดำเนินการเปลี่ยนแปลง และเปิดคำขอรวมที่มีการเปลี่ยนแปลง + +- **ตรวจสอบคำขอรวม** + + แสดงความคิดเห็นต่อไปนี้ในคำขอรวม GitLab + + ``` + @opencode review this merge request + ``` + + OpenCode จะตรวจสอบคำขอรวมและให้ข้อเสนอแนะ diff --git a/packages/web/src/content/docs/th/ide.mdx b/packages/web/src/content/docs/th/ide.mdx new file mode 100644 index 000000000..e82ca8320 --- /dev/null +++ b/packages/web/src/content/docs/th/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: ส่วนขยาย OpenCode สำหรับ VS Code, Cursor และ IDE อื่นๆ +--- + +OpenCode ทำงานร่วมกับ VS Code, Cursor หรือ IDE ใดๆ ที่รองรับเทอร์มินัล เพียงเรียกใช้ `opencode` ในเทอร์มินัลเพื่อเริ่มต้น + +--- + +## การใช้งาน + +- **เปิดใช้ด่วน**: ใช้ `Cmd+Esc` (Mac) หรือ `Ctrl+Esc` (Windows/Linux) เพื่อเปิด OpenCode ในมุมมองเทอร์มินัลแบบแยก หรือเน้นเซสชันเทอร์มินัลที่มีอยู่หากมีการทำงานอยู่แล้ว +- **เซสชันใหม่**: ใช้ `Cmd+Shift+Esc` (Mac) หรือ `Ctrl+Shift+Esc` (Windows/Linux) เพื่อเริ่มเซสชันเทอร์มินัล OpenCode ใหม่ แม้ว่าเซสชันหนึ่งจะเปิดอยู่แล้วก็ตาม คุณยังสามารถคลิกปุ่ม OpenCode ใน UI ได้ด้วย +- **การรับรู้บริบท**: แชร์การเลือกหรือแท็บปัจจุบันของคุณโดยอัตโนมัติด้วย OpenCode +- **ทางลัดการอ้างอิงไฟล์**: ใช้ `Cmd+Option+K` (Mac) หรือ `Alt+Ctrl+K` (Linux/Windows) เพื่อแทรกการอ้างอิงไฟล์ ตัวอย่างเช่น `@File#L37-42` + +--- + +## การติดตั้ง + +วิธีติดตั้ง OpenCode บน VS Code และทางแยกยอดนิยม เช่น Cursor, Windsurf, VSCodium: + +1. เปิดรหัส VS +2. เปิดเทอร์มินัลรวม +3. เรียกใช้ `opencode` - ​​ส่วนขยายจะติดตั้งโดยอัตโนมัติ + +ในทางกลับกัน หากคุณต้องการใช้ IDE ของคุณเองเมื่อคุณเรียกใช้ `/editor` หรือ `/export` จาก TUI คุณจะต้องตั้งค่า `export EDITOR="code --wait"` [เรียนรู้เพิ่มเติม](/docs/tui/#editor-setup) + +--- + +### ติดตั้งด้วยตนเอง + +ค้นหา **OpenCode** ใน Extension Marketplace แล้วคลิก **ติดตั้ง** + +--- + +### การแก้ไขปัญหา + +หากส่วนขยายไม่สามารถติดตั้งได้โดยอัตโนมัติ: + +- ตรวจสอบให้แน่ใจว่าคุณใช้งาน `opencode` ในเทอร์มินัลรวม +- ยืนยันว่า CLI สำหรับ IDE ของคุณได้รับการติดตั้งแล้ว: + - สำหรับรหัส VS: `code` คำสั่ง + - สำหรับเคอร์เซอร์: `cursor` คำสั่ง + - สำหรับวินด์เซิร์ฟ: `windsurf` คำสั่ง + - สำหรับ VSCodium: `codium` คำสั่ง + - ถ้าไม่เช่นนั้น ให้รัน `Cmd+Shift+P` (Mac) หรือ `Ctrl+Shift+P` (Windows/Linux) และค้นหา "Shell Command: Install 'code' command in PATH" (หรือเทียบเท่ากับ IDE ของคุณ) +- ตรวจสอบให้แน่ใจว่ารหัส VS มีสิทธิ์ในการติดตั้งส่วนขยาย diff --git a/packages/web/src/content/docs/th/index.mdx b/packages/web/src/content/docs/th/index.mdx new file mode 100644 index 000000000..92e71b7e0 --- /dev/null +++ b/packages/web/src/content/docs/th/index.mdx @@ -0,0 +1,359 @@ +--- +title: บทนำ +description: เริ่มต้นใช้งาน OpenCode +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) คือเอเจนต์การเข้ารหัส AI แบบโอเพ่นซอร์ส มีให้บริการในรูปแบบอินเทอร์เฟซบนเทอร์มินัล แอปเดสก์ท็อป หรือส่วนขยาย IDE + +![OpenCode TUI พร้อมธีม opencode](../../../assets/lander/screenshot.png) + +มาเริ่มกันเลย + +--- + +#### ข้อกำหนดเบื้องต้น + +หากต้องการใช้ OpenCode ในเทอร์มินัล คุณจะต้องมี: + +1. เทอร์มินัลอีมูเลเตอร์ที่ทันสมัยเช่น: + - [WezTerm](https://wezterm.org) ข้ามแพลตฟอร์ม + - [Alacritty](https://alacritty.org) ข้ามแพลตฟอร์ม + - [โกสต์ตี้](https://ghostty.org), ลินุกซ์ และ macOS + - [คิตตี้](https://sw.kovidgoyal.net/kitty/), Linux และ macOS + +2. ปุ่ม API สำหรับผู้ให้บริการ LLM ที่คุณต้องการใช้ + +--- + +## ติดตั้ง + +วิธีที่ง่ายที่สุดในการติดตั้ง OpenCode คือการใช้สคริปต์การติดตั้ง + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +คุณยังสามารถติดตั้งได้ด้วยคำสั่งต่อไปนี้: + +- **การใช้ Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **การใช้ Homebrew บน macOS และ Linux** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > เราขอแนะนำให้ใช้การแตะ OpenCode เพื่อเผยแพร่ข้อมูลล่าสุด สูตร `brew install opencode` อย่างเป็นทางการได้รับการดูแลโดยทีมงาน Homebrew และมีการอัปเดตไม่บ่อยนัก + +- **การใช้ Paru บน Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### หน้าต่าง + +:::tip[แนะนำ: ใช้ WSL] +เพื่อประสบการณ์ที่ดีที่สุดบน Windows เราขอแนะนำให้ใช้ [ระบบย่อย Windows สำหรับ Linux (WSL)](/docs/windows-wsl) ให้ประสิทธิภาพที่ดีขึ้นและความเข้ากันได้เต็มรูปแบบกับคุณสมบัติของ OpenCode +::: + +- **ใช้ช็อคโกแลต** + + ```bash + choco install opencode + ``` + +- **การใช้สกู๊ป** + + ```bash + scoop install opencode + ``` + +- **การใช้ NPM** + + ```bash + npm install -g opencode-ai + ``` + +- ** การใช้ Mise ** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **การใช้นักเทียบท่า** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +ขณะนี้การสนับสนุนสำหรับการติดตั้ง OpenCode บน Windows โดยใช้ Bun อยู่ระหว่างดำเนินการ + +คุณยังสามารถคว้าไบนารี่ได้จาก [เผยแพร่](https://github.com/anomalyco/opencode/releases) + +--- + +## กำหนดค่า + +ด้วย OpenCode คุณสามารถใช้ผู้ให้บริการ LLM ใดก็ได้โดยกำหนดค่าคีย์ API + +หากคุณยังใหม่ต่อการใช้ผู้ให้บริการ LLM เราขอแนะนำให้ใช้ [OpenCode Zen](/docs/zen) +เป็นรายการโมเดลที่ได้รับการดูแลจัดการซึ่งได้รับการทดสอบและตรวจสอบโดย OpenCode +ทีม. + +1. เรียกใช้คำสั่ง `/connect` ใน TUI เลือก opencode และไปที่ [opencode.ai/auth](https://opencode.ai/auth) + + ```txt + /connect + ``` + +2. ลงชื่อเข้าใช้ เพิ่มรายละเอียดการเรียกเก็บเงินของคุณ และคัดลอกรหัส API ของคุณ + +3. วางคีย์ API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +หรือคุณสามารถเลือกหนึ่งในผู้ให้บริการรายอื่นได้ [เรียนรู้เพิ่มเติม](/docs/providers#ไดเรกทอรี) + +--- + +## เริ่มต้น + +เมื่อคุณได้กำหนดค่าผู้ให้บริการแล้ว คุณสามารถนำทางไปยังโปรเจ็กต์นั้นได้ +คุณอยากทำงานต่อ + +```bash +cd /path/to/project +``` + +และเรียกใช้ OpenCode + +```bash +opencode +``` + +จากนั้น เริ่มต้น OpenCode สำหรับโปรเจ็กต์โดยการรันคำสั่งต่อไปนี้ + +```bash frame="none" +/init +``` + +นี่จะได้รับ OpenCode เพื่อวิเคราะห์โครงการของคุณและสร้างไฟล์ `AGENTS.md` +รากของโครงการ + +:::tip +คุณควรคอมมิตไฟล์ `AGENTS.md` ของโปรเจ็กต์ของคุณไปที่ Git +::: + +ซึ่งจะช่วยให้ OpenCode เข้าใจโครงสร้างโปรเจ็กต์และรูปแบบการเขียนโค้ด +ใช้แล้ว. + +--- + +## การใช้งาน + +ตอนนี้คุณพร้อมที่จะใช้ OpenCode เพื่อทำงานในโครงการของคุณแล้ว อย่าลังเลที่จะถามมัน +อะไรก็ตาม! + +หากคุณยังใหม่ต่อการใช้เอเจนต์การเข้ารหัส AI ต่อไปนี้คือตัวอย่างบางส่วนที่อาจเป็นไปได้ +ช่วย. + +--- + +### ถามคำถาม + +คุณสามารถขอให้ OpenCode อธิบาย codebase ให้คุณได้ + +:::tip +ใช้ปุ่ม `@` เพื่อค้นหาไฟล์ในโครงการอย่างคลุมเครือ +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +สิ่งนี้มีประโยชน์หากมีส่วนหนึ่งของโค้ดเบสที่คุณไม่ได้ดำเนินการ + +--- + +### เพิ่มคุณสมบัติ + +คุณสามารถขอให้ OpenCode เพิ่มคุณสมบัติใหม่ให้กับโครงการของคุณได้ แม้ว่าเราจะแนะนำให้ขอให้สร้างแผนก่อนก็ตาม + +1. **สร้างแผน** + + OpenCode มีโหมด _Plan_ ที่ปิดการใช้งานความสามารถในการเปลี่ยนแปลงและ + แนะนำ _how_ ว่าจะใช้งานฟีเจอร์นี้แทน + + เปลี่ยนไปใช้ปุ่ม **Tab** คุณจะเห็นตัวบ่งชี้นี้ที่มุมขวาล่าง + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + ตอนนี้เรามาอธิบายสิ่งที่เราต้องการให้ทำ + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + คุณต้องการให้รายละเอียด OpenCode เพียงพอเพื่อทำความเข้าใจสิ่งที่คุณต้องการ มันช่วยได้ + เพื่อพูดคุยเหมือนคุณกำลังพูดคุยกับนักพัฒนารุ่นน้องในทีมของคุณ + + :::tip + ให้บริบทและตัวอย่างมากมายแก่ OpenCode เพื่อช่วยให้เข้าใจสิ่งที่คุณ + ต้องการ. + ::: + +2. **ทบทวนแผน** + + เมื่อมีแผนแล้ว คุณสามารถให้ข้อเสนอแนะหรือเพิ่มรายละเอียดเพิ่มเติมได้ + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::tip + ลากและวางรูปภาพลงในเทอร์มินัลเพื่อเพิ่มลงในพรอมต์ + ::: + + OpenCode สามารถสแกนรูปภาพที่คุณให้มาและเพิ่มลงในข้อความแจ้งได้ คุณสามารถ + ทำได้โดยลากและวางรูปภาพลงในเทอร์มินัล + +3. **สร้างฟีเจอร์** + + เมื่อคุณรู้สึกพอใจกับแผนแล้ว ให้เปลี่ยนกลับเป็น _Build mode_ ภายใน + กดปุ่ม **Tab** อีกครั้ง + + ```bash frame="none" + + ``` + + และขอให้ทำการเปลี่ยนแปลง + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### ทำการเปลี่ยนแปลง + +หากต้องการการเปลี่ยนแปลงที่ตรงไปตรงมามากขึ้น คุณสามารถขอให้ OpenCode สร้างมันโดยตรงได้ +โดยไม่ต้องทบทวนแผนก่อน + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +คุณต้องการให้แน่ใจว่าคุณให้รายละเอียดในปริมาณที่เหมาะสมเพื่อให้ OpenCode ดำเนินการได้ถูกต้อง +การเปลี่ยนแปลง + +--- + +### เลิกทำการเปลี่ยนแปลง + +สมมติว่าคุณขอให้ OpenCode ทำการเปลี่ยนแปลงบางอย่าง + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +แต่คุณก็รู้ว่ามันไม่ใช่สิ่งที่คุณต้องการ คุณ **สามารถยกเลิก** การเปลี่ยนแปลงได้ +โดยใช้คำสั่ง `/undo` + +```bash frame="none" +/undo +``` + +OpenCode จะคืนค่าการเปลี่ยนแปลงที่คุณทำและแสดงข้อความต้นฉบับของคุณ +อีกครั้ง. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +จากที่นี่ คุณสามารถปรับแต่งข้อความแจ้งและขอให้ OpenCode ลองอีกครั้ง + +:::tip +คุณสามารถเรียกใช้ `/undo` ได้หลายครั้งเพื่อเลิกทำการเปลี่ยนแปลงหลายรายการ +::: + +หรือคุณสามารถ **สามารถทำซ้ำ** การเปลี่ยนแปลงโดยใช้คำสั่ง `/redo` + +```bash frame="none" +/redo +``` + +--- + +## แบ่งปัน + +การสนทนาที่คุณมีกับ OpenCode สามารถ [แชร์กับคุณได้ +ทีมงาน](/docs/share) + +```bash frame="none" +/share +``` + +การดำเนินการนี้จะสร้างลิงก์ไปยังการสนทนาปัจจุบันและคัดลอกไปยังคลิปบอร์ดของคุณ + +:::note +การสนทนาจะไม่ถูกแชร์โดยค่าเริ่มต้น +::: + +นี่คือ [ตัวอย่างการสนทนา](https://opencode.ai/s/4XP1fce5) กับ OpenCode + +--- + +## ปรับแต่ง + +แค่นั้นแหละ! ตอนนี้คุณเป็นมืออาชีพในการใช้ OpenCode แล้ว + +หากต้องการทำให้เป็นของคุณเอง เราขอแนะนำให้ [เลือกธีม](/docs/themes), [ปรับแต่งปุ่มลัด](/docs/keybinds), [กำหนดค่าตัวจัดรูปแบบโค้ด](/docs/formatters), [สร้างคำสั่งที่กำหนดเอง](/docs/commands) หรือลองใช้ [การกำหนดค่า OpenCode](/docs/config) diff --git a/packages/web/src/content/docs/th/keybinds.mdx b/packages/web/src/content/docs/th/keybinds.mdx new file mode 100644 index 000000000..b84873e58 --- /dev/null +++ b/packages/web/src/content/docs/th/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: ปุ่มลัด +description: ปรับแต่งปุ่มลัดของคุณ +--- + +OpenCode มีรายการปุ่มลัดที่คุณปรับแต่งได้ผ่านการกำหนดค่า OpenCode + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## กุญแจผู้นำ + +OpenCode ใช้คีย์ `leader` สำหรับการเชื่อมโยงคีย์ส่วนใหญ่ วิธีนี้จะหลีกเลี่ยงความขัดแย้งในเทอร์มินัลของคุณ + +ตามค่าเริ่มต้น `ctrl+x` จะเป็นปุ่มผู้นำ และการดำเนินการส่วนใหญ่ต้องการให้คุณกดปุ่มผู้นำก่อน จากนั้นจึงกดทางลัด ตัวอย่างเช่น หากต้องการเริ่มเซสชันใหม่ คุณต้องกด `ctrl+x` ก่อน จากนั้นจึงกด `n` + +คุณไม่จำเป็นต้องใช้คีย์ผู้นำสำหรับการผูกคีย์ แต่เราขอแนะนำให้ทำเช่นนั้น + +--- + +## ปิดการใช้งานการผูกปุ่ม + +คุณสามารถปิดการใช้งานการผูกปุ่มได้โดยการเพิ่มคีย์ลงในการกำหนดค่าของคุณด้วยค่า "none" + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## ทางลัดพร้อมท์เดสก์ท็อป + +การป้อนข้อมูลพร้อมท์ของแอป OpenCode บนเดสก์ท็อปรองรับทางลัด Readline/Emacs-style ทั่วไปสำหรับการแก้ไขข้อความ สิ่งเหล่านี้มีอยู่แล้วภายในและปัจจุบันไม่สามารถกำหนดค่าผ่าน `opencode.json` ได้ + +| ทางลัด | การกระทำ | +| -------- | ---------------------------------------- | +| `ctrl+a` | ย้ายไปที่จุดเริ่มต้นของบรรทัดปัจจุบัน | +| `ctrl+e` | ย้ายไปที่จุดสิ้นสุดของบรรทัดปัจจุบัน | +| `ctrl+b` | เลื่อนเคอร์เซอร์กลับไปหนึ่งอักขระ | +| `ctrl+f` | เลื่อนเคอร์เซอร์ไปข้างหน้าหนึ่งอักขระ | +| `alt+b` | เลื่อนเคอร์เซอร์กลับไปหนึ่งคำ | +| `alt+f` | เลื่อนเคอร์เซอร์ไปข้างหน้าหนึ่งคำ | +| `ctrl+d` | ลบอักขระใต้เคอร์เซอร์ | +| `ctrl+k` | ฆ่าให้จบแถว | +| `ctrl+u` | ฆ่าที่จุดเริ่มต้นของบรรทัด | +| `ctrl+w` | ฆ่าคำก่อนหน้า | +| `alt+d` | ฆ่าคำถัดไป | +| `ctrl+t` | ย้ายอักขระ | +| `ctrl+g` | ยกเลิกป๊อปโอเวอร์ / ยกเลิกการตอบกลับที่ทำงานอยู่ | + +--- + +## Shift+Enter + +เทอร์มินัลบางตัวไม่ส่งคีย์ตัวปรับแต่งพร้อม Enter เป็นค่าเริ่มต้น คุณอาจต้องกำหนดค่าเทอร์มินัลของคุณให้ส่ง `Shift+Enter` เป็นลำดับหลีก + +### เทอร์มินัลวินโดวส์ + +เปิด `settings.json` ของคุณที่: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +เพิ่มสิ่งนี้ลงในอาร์เรย์ `actions` ระดับรูท: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +เพิ่มสิ่งนี้ลงในอาร์เรย์ `keybindings` ระดับรูท: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +บันทึกไฟล์และรีสตาร์ท Windows Terminal หรือเปิดแท็บใหม่ diff --git a/packages/web/src/content/docs/th/lsp.mdx b/packages/web/src/content/docs/th/lsp.mdx new file mode 100644 index 000000000..4ad79384a --- /dev/null +++ b/packages/web/src/content/docs/th/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: LSP เซิร์ฟเวอร์ +description: OpenCode ทำงานร่วมกับเซิร์ฟเวอร์ LSP ของคุณ +--- + +OpenCode ทำงานร่วมกับ Language Server Protocol (LSP) เพื่อช่วยให้ LLM โต้ตอบกับโค้ดเบสของคุณ ใช้การวินิจฉัยเพื่อให้ข้อเสนอแนะไปยัง LLM + +--- + +## บิวท์อิน + +OpenCode มาพร้อมกับเซิร์ฟเวอร์ LSP ในตัวหลายตัวสำหรับภาษายอดนิยม: + +| LSP เซิร์ฟเวอร์ | ส่วนขยาย | ความต้องการ | +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +| โหราศาสตร์ | .แอสโตร | ติดตั้งอัตโนมัติสำหรับโปรเจ็กต์ Astro | +| ทุบตี | .sh, .ทุบตี, .zsh, .ksh | ติดตั้ง bash-Language-Server โดยอัตโนมัติ | +| เสียงดังกราว | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | ติดตั้งอัตโนมัติสำหรับโครงการ C/C++ | +| ซีชาร์ป | .ซีเอส | `.NET SDK` ติดตั้งแล้ว | +| clojure-lsp | .clj, .cljs, .cljc, .edn | `clojure-lsp` คำสั่งใช้ได้ | +| โผ | .โผ | `dart` คำสั่งใช้ได้ | +| เดโน | .ts, .tsx, .js, .jsx, .mjs | มีคำสั่ง `deno` (ตรวจจับอัตโนมัติ deno.json/deno.jsonc) | +| น้ำอมฤต-ls | .ex, .exs | `elixir` คำสั่งใช้ได้ | +| เอสลินท์ | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` การพึ่งพาในโครงการ | +| เอฟชาร์ป | .fs, .fsi, .fsx, .fsscript | `.NET SDK` ติดตั้งแล้ว | +| เปล่งประกาย | .แวววาว | `gleam` คำสั่งใช้ได้ | +| โกปลส์ | .ไป | `go` คำสั่งใช้ได้ | +| สวัสดี | .hs, .lhs | `haskell-language-server-wrapper` คำสั่งใช้ได้ | +| jdtls | .java | `Java SDK (version 21+)` ติดตั้งแล้ว | +| kotlin-ls | .kt, .kts | ติดตั้งอัตโนมัติสำหรับโปรเจ็กต์ Kotlin | +| lua-ls | .lua | ติดตั้งอัตโนมัติสำหรับโปรเจ็กต์ Lua | +| ห้าม | .ห้าม | `nixd` คำสั่งใช้ได้ | +| ocaml-lsp | .มล., .มลิ | `ocamllsp` คำสั่งใช้ได้ | +| ออกซ์ลินท์ | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | `oxlint` การพึ่งพาในโครงการ | +| php intelephense.php | .php | ติดตั้งอัตโนมัติสำหรับโครงการ PHP | +| ปริซึม | .ปริซึม | `prisma` คำสั่งใช้ได้ | +| ไพไรท์ | .py, .pyi | `pyright` ติดตั้งการพึ่งพาแล้ว | +| ทับทิม-lsp (rubocop) | .rb, .rake, .gemspec, .ru | มีคำสั่ง `ruby` และ `gem` | +| สนิม | .อาร์เอส | `rust-analyzer` คำสั่งใช้ได้ | +| ซอร์สคิท-lsp | .สวิฟท์, .objc, .objcpp | ติดตั้ง `swift` (`xcode` บน macOS) | +| เก๋ไก๋ | .svelte | ติดตั้งอัตโนมัติสำหรับโครงการ Svelte | +| ภูมิประเทศ | .tf, .tfvars | ติดตั้งอัตโนมัติจากรุ่น GitHub | +| คนตัวเล็ก | .พิมพ์, .พิมพ์ | ติดตั้งอัตโนมัติจากรุ่น GitHub | +| ตัวพิมพ์ดีด | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` การพึ่งพาในโครงการ | +| วิว | .vue | ติดตั้งอัตโนมัติสำหรับโปรเจ็กต์ Vue | +| yaml-ls | .yaml, .yml | ติดตั้งเซิร์ฟเวอร์ภาษา Red Hat yaml โดยอัตโนมัติ | +| zls | .ซิก, .ซอน | `zig` คำสั่งใช้ได้ | + +เซิร์ฟเวอร์ LSP จะถูกเปิดใช้งานโดยอัตโนมัติเมื่อตรวจพบนามสกุลไฟล์ใดนามสกุลหนึ่งข้างต้นและเป็นไปตามข้อกำหนด + +:::note +คุณสามารถปิดใช้งานการดาวน์โหลดเซิร์ฟเวอร์ LSP อัตโนมัติได้โดยตั้งค่าตัวแปรสภาพแวดล้อม `OPENCODE_DISABLE_LSP_DOWNLOAD` เป็น `true` +::: + +--- + +## มันทำงานอย่างไร + +เมื่อ opencode เปิดไฟล์ มันจะ: + +1. ตรวจสอบนามสกุลไฟล์กับเซิร์ฟเวอร์ LSP ที่เปิดใช้งานทั้งหมด +2. เริ่มเซิร์ฟเวอร์ LSP ที่เหมาะสมหากยังไม่ได้ทำงาน + +--- + +## กำหนดค่า + +You can customize LSP servers through the `lsp` section in your opencode config. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +เซิร์ฟเวอร์ LSP แต่ละเซิร์ฟเวอร์รองรับสิ่งต่อไปนี้: + +| คุณสมบัติ | พิมพ์ | คำอธิบาย | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` | บูลีน | ตั้งค่านี้เป็น `true` เพื่อปิดการใช้งานเซิร์ฟเวอร์ LSP | +| `command` | สตริง[] | คำสั่งเพื่อเริ่มต้นเซิร์ฟเวอร์ LSP | +| `extensions` | สตริง[] | นามสกุลไฟล์ที่เซิร์ฟเวอร์ LSP นี้ควรจัดการ | +| `env` | วัตถุ | ตัวแปรสภาพแวดล้อมที่จะตั้งค่าเมื่อเริ่มต้นเซิร์ฟเวอร์ | +| `initialization` | วัตถุ | ตัวเลือกการเริ่มต้นที่จะส่งไปยังเซิร์ฟเวอร์ LSP | + +ลองดูตัวอย่างบางส่วน + +--- + +### ตัวแปรสภาพแวดล้อม + +ใช้คุณสมบัติ `env` เพื่อตั้งค่าตัวแปรสภาพแวดล้อมเมื่อเริ่มต้นเซิร์ฟเวอร์ LSP: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### ตัวเลือกการเริ่มต้น + +ใช้คุณสมบัติ `initialization` เพื่อส่งตัวเลือกการเริ่มต้นไปยังเซิร์ฟเวอร์ LSP นี่คือการตั้งค่าเฉพาะเซิร์ฟเวอร์ที่ส่งระหว่างคำขอ LSP `initialize`: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +ตัวเลือกการเริ่มต้นจะแตกต่างกันไปตามเซิร์ฟเวอร์ LSP ตรวจสอบเอกสารประกอบของเซิร์ฟเวอร์ LSP ของคุณเพื่อดูตัวเลือกที่มี +::: + +--- + +### ปิดการใช้งานเซิร์ฟเวอร์ LSP + +หากต้องการปิดการใช้งานเซิร์ฟเวอร์ **ทั้งหมด** LSP ทั่วโลก ให้ตั้งค่า `lsp` เป็น `false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +หากต้องการปิดการใช้งานเซิร์ฟเวอร์ **เฉพาะ** LSP ให้ตั้งค่า `disabled` เป็น `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### เซิร์ฟเวอร์ LSP แบบกำหนดเอง + +คุณสามารถเพิ่มเซิร์ฟเวอร์ LSP แบบกำหนดเองได้โดยระบุคำสั่งและนามสกุลไฟล์: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## ข้อมูลเพิ่มเติม + +### PHP อินเทเลฟินส์ + +PHP Intelephense นำเสนอคุณสมบัติระดับพรีเมียมผ่านรหัสลิขสิทธิ์ คุณสามารถระบุรหัสสัญญาอนุญาตได้โดยการวาง (เท่านั้น) รหัสในไฟล์ข้อความที่: + +- บน macOS/Linux: `$HOME/intelephense/licence.txt` +- บนวินโดวส์: `%USERPROFILE%/intelephense/licence.txt` + +ไฟล์ควรมีเฉพาะรหัสลิขสิทธิ์โดยไม่มีเนื้อหาเพิ่มเติม diff --git a/packages/web/src/content/docs/th/mcp-servers.mdx b/packages/web/src/content/docs/th/mcp-servers.mdx new file mode 100644 index 000000000..43ac571b8 --- /dev/null +++ b/packages/web/src/content/docs/th/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: MCP เซิร์ฟเวอร์ +description: เพิ่มเครื่องมือ MCP ในพื้นที่และระยะไกล +--- + +คุณสามารถเพิ่มเครื่องมือภายนอกให้กับ OpenCode ได้โดยใช้ _Model Context Protocol_ หรือ MCP OpenCode รองรับทั้งเซิร์ฟเวอร์ภายในและเซิร์ฟเวอร์ระยะไกล + +เมื่อเพิ่มแล้ว เครื่องมือ MCP จะพร้อมใช้งานโดยอัตโนมัติสำหรับ LLM ควบคู่ไปกับเครื่องมือในตัว + +--- + +#### คำเตือน + +เมื่อคุณใช้เซิร์ฟเวอร์ MCP เซิร์ฟเวอร์ดังกล่าวจะเพิ่มบริบท สิ่งนี้สามารถเพิ่มขึ้นได้อย่างรวดเร็วหากคุณมีเครื่องมือมากมาย ดังนั้นเราขอแนะนำให้ระมัดระวังเซิร์ฟเวอร์ MCP ที่คุณใช้ + +:::tip +เซิร์ฟเวอร์ MCP เพิ่มในบริบทของคุณ ดังนั้นคุณจึงต้องระวังด้วยว่าเซิร์ฟเวอร์ใดที่คุณเปิดใช้งาน +::: + +เซิร์ฟเวอร์ MCP บางตัว เช่น เซิร์ฟเวอร์ GitHub MCP มีแนวโน้มที่จะเพิ่มโทเค็นจำนวนมากและอาจเกินขีดจำกัดบริบทได้อย่างง่ายดาย + +--- + +## เปิดใช้งาน + +คุณสามารถกำหนดเซิร์ฟเวอร์ MCP ได้ใน [OpenCode Config](https://opencode.ai/docs/config/) ภายใต้ `mcp` เพิ่ม MCP แต่ละรายการด้วยชื่อที่ไม่ซ้ำใคร คุณสามารถอ้างอิงถึง MCP ด้วยชื่อได้เมื่อแจ้ง LLM + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +คุณยังสามารถปิดการใช้งานเซิร์ฟเวอร์ได้โดยการตั้งค่า `enabled` เป็น `false` สิ่งนี้มีประโยชน์หากคุณต้องการปิดการใช้งานเซิร์ฟเวอร์ชั่วคราวโดยไม่ต้องลบออกจากการกำหนดค่าของคุณ + +--- + +### การเอาชนะค่าเริ่มต้นระยะไกล + +องค์กรสามารถจัดเตรียมเซิร์ฟเวอร์ MCP เริ่มต้นผ่านทางจุดสิ้นสุด `.well-known/opencode` เซิร์ฟเวอร์เหล่านี้อาจถูกปิดใช้งานตามค่าเริ่มต้น ทำให้ผู้ใช้สามารถเลือกใช้เซิร์ฟเวอร์ที่ต้องการได้ + +หากต้องการเปิดใช้งานเซิร์ฟเวอร์เฉพาะจากการกำหนดค่าระยะไกลขององค์กรของคุณ ให้เพิ่มเซิร์ฟเวอร์ดังกล่าวลงในการกำหนดค่าภายในเครื่องของคุณด้วย `enabled: true`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +ค่าการกำหนดค่าในเครื่องของคุณจะแทนที่ค่าเริ่มต้นระยะไกล ดู [config ลำดับความสำคัญ](/docs/config#precedence-order) สำหรับรายละเอียดเพิ่มเติม + +--- + +## ท้องถิ่น + +เพิ่มเซิร์ฟเวอร์ท้องถิ่น MCP โดยใช้ `type` ไปยัง `"local"` ภายในวัตถุ MCP + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +คำสั่งคือวิธีที่เซิร์ฟเวอร์ MCP ท้องถิ่นเริ่มทำงาน คุณยังสามารถส่งผ่านรายการตัวแปรสภาพแวดล้อมได้เช่นกัน + +ตัวอย่างเช่น นี่คือวิธีที่คุณสามารถเพิ่มการทดสอบเซิร์ฟเวอร์ [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP เซิร์ฟเวอร์ + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +และหากต้องการใช้งาน ฉันสามารถเพิ่ม `use the mcp_everything tool` ในข้อความแจ้งของฉันได้ + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### ตัวเลือก + +นี่คือตัวเลือกทั้งหมดสำหรับการกำหนดค่าเซิร์ฟเวอร์ MCP ภายในเครื่อง + +| ตัวเลือก | พิมพ์ | ที่จำเป็น | คำอธิบาย | +| ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | สตริง | ย | ประเภทของการเชื่อมต่อเซิร์ฟเวอร์ MCP ต้องเป็น `"local"` | +| `command` | อาร์เรย์ | ย | คำสั่งและอาร์กิวเมนต์เพื่อรันเซิร์ฟเวอร์ MCP | +| `environment` | วัตถุ | | ตัวแปรสภาพแวดล้อมที่จะตั้งค่าเมื่อรันเซิร์ฟเวอร์ | +| `enabled` | บูลีน | | เปิดหรือปิดใช้งานเซิร์ฟเวอร์ MCP เมื่อเริ่มต้นระบบ | +| `timeout` | ตัวเลข | | หมดเวลาเป็น ms สำหรับการดึงเครื่องมือจากเซิร์ฟเวอร์ MCP ค่าเริ่มต้นคือ 5,000 (5 วินาที) | + +--- + +## ระยะไกล + +เพิ่มเซิร์ฟเวอร์ระยะไกล MCP โดยตั้งค่า `type` เป็น `"remote"` + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` คือ URL ของเซิร์ฟเวอร์ MCP ระยะไกล และด้วยตัวเลือก `headers` คุณสามารถส่งผ่านรายการส่วนหัวได้ + +--- + +#### ตัวเลือก + +| ตัวเลือก | พิมพ์ | ที่จำเป็น | คำอธิบาย | +| --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` | สตริง | ย | ประเภทของการเชื่อมต่อเซิร์ฟเวอร์ MCP ต้องเป็น `"remote"` | +| `url` | สตริง | ย | URL ของเซิร์ฟเวอร์ MCP ระยะไกล | +| `enabled` | บูลีน | | เปิดหรือปิดใช้งานเซิร์ฟเวอร์ MCP เมื่อเริ่มต้นระบบ | +| `headers` | วัตถุ | | ส่วนหัวที่จะส่งพร้อมกับคำขอ | +| `oauth` | วัตถุ | | การกำหนดค่าการตรวจสอบสิทธิ์ OAuth ดูส่วน [OAuth](#oauth) ด้านล่าง | +| `timeout` | ตัวเลข | | หมดเวลาเป็น ms สำหรับการดึงเครื่องมือจากเซิร์ฟเวอร์ MCP ค่าเริ่มต้นคือ 5,000 (5 วินาที) | + +--- + +## OAuth + +OpenCode จะจัดการการตรวจสอบสิทธิ์ OAuth สำหรับเซิร์ฟเวอร์ MCP ระยะไกลโดยอัตโนมัติ เมื่อเซิร์ฟเวอร์ต้องการการรับรองความถูกต้อง OpenCode จะ: + +1. ตรวจหาการตอบสนอง 401 และเริ่มโฟลว์ OAuth +2. ใช้ **การลงทะเบียนไคลเอ็นต์แบบไดนามิก (RFC 7591)** หากเซิร์ฟเวอร์รองรับ +3. จัดเก็บโทเค็นอย่างปลอดภัยสำหรับคำขอในอนาคต + +--- + +### อัตโนมัติ + +สำหรับเซิร์ฟเวอร์ MCP ที่เปิดใช้งาน OAuth ส่วนใหญ่ ไม่จำเป็นต้องมีการกำหนดค่าพิเศษ เพียงกำหนดค่าเซิร์ฟเวอร์ระยะไกล: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +หากเซิร์ฟเวอร์ต้องมีการตรวจสอบสิทธิ์ OpenCode จะแจ้งให้คุณตรวจสอบความถูกต้องเมื่อคุณพยายามใช้งานครั้งแรก หากไม่เป็นเช่นนั้น คุณสามารถ[ทริกเกอร์โฟลว์ด้วยตนเอง](#การตรวจสอบสิทธิ์) ด้วย `opencode mcp auth ` + +--- + +### ลงทะเบียนล่วงหน้า + +หากคุณมีข้อมูลประจำตัวไคลเอ็นต์จากผู้ให้บริการเซิร์ฟเวอร์ MCP คุณสามารถกำหนดค่าได้: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### กำลังตรวจสอบสิทธิ์ + +คุณสามารถทริกเกอร์การตรวจสอบสิทธิ์หรือจัดการข้อมูลประจำตัวได้ด้วยตนเอง + +ตรวจสอบสิทธิ์กับเซิร์ฟเวอร์ MCP เฉพาะ: + +```bash +opencode mcp auth my-oauth-server +``` + +แสดงรายการเซิร์ฟเวอร์ MCP ทั้งหมดและสถานะการตรวจสอบสิทธิ์: + +```bash +opencode mcp list +``` + +ลบข้อมูลรับรองที่เก็บไว้: + +```bash +opencode mcp logout my-oauth-server +``` + +คำสั่ง `mcp auth` จะเปิดเบราว์เซอร์ของคุณเพื่อขออนุญาต หลังจากที่คุณอนุญาตแล้ว OpenCode จะจัดเก็บโทเค็นอย่างปลอดภัยใน `~/.local/share/opencode/mcp-auth.json` + +--- + +#### ปิดการใช้งาน OAuth + +หากคุณต้องการปิดการใช้งาน OAuth อัตโนมัติสำหรับเซิร์ฟเวอร์ (เช่น สำหรับเซิร์ฟเวอร์ที่ใช้คีย์ API แทน) ให้ตั้งค่า `oauth` เป็น `false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### ตัวเลือก OAuth + +| ตัวเลือก | พิมพ์ | คำอธิบาย | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` | วัตถุ \ | เท็จ | ออบเจ็กต์การกำหนดค่า OAuth หรือ `false` เพื่อปิดใช้การตรวจจับอัตโนมัติของ OAuth | +| `clientId` | สตริง | รหัสไคลเอ็นต์ OAuth หากไม่ได้ระบุไว้ จะพยายามลงทะเบียนไคลเอ็นต์แบบไดนามิก | +| `clientSecret` | สตริง | ข้อมูลลับไคลเอ็นต์ OAuth หากเซิร์ฟเวอร์การให้สิทธิ์กำหนดไว้ | +| `scope` | สตริง | ขอบเขต OAuth ที่จะขอระหว่างการให้สิทธิ์ | + +#### การดีบัก + +หากเซิร์ฟเวอร์ MCP ระยะไกลไม่สามารถตรวจสอบสิทธิ์ได้ คุณสามารถวินิจฉัยปัญหาด้วย: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +คำสั่ง `mcp debug` แสดงสถานะการตรวจสอบสิทธิ์ปัจจุบัน ทดสอบการเชื่อมต่อ HTTP และพยายามใช้ขั้นตอนการค้นหา OAuth + +--- + +## จัดการ + +MCP ของคุณพร้อมใช้งานในฐานะเครื่องมือใน OpenCode ควบคู่ไปกับเครื่องมือในตัว คุณจึงสามารถจัดการผ่านการกำหนดค่า OpenCode ได้เหมือนกับเครื่องมืออื่นๆ + +--- + +### ทั่วโลก + +ซึ่งหมายความว่าคุณสามารถเปิดหรือปิดใช้งานได้ทั่วโลก + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +นอกจากนี้เรายังสามารถใช้รูปแบบ glob เพื่อปิดใช้งาน MCP ที่ตรงกันทั้งหมดได้ + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +ที่นี่เราใช้รูปแบบ glob `my-mcp*` เพื่อปิดการใช้งาน MCP ทั้งหมด + +--- + +### ต่อตัวแทน + +หากคุณมีเซิร์ฟเวอร์ MCP จำนวนมาก คุณอาจต้องการเปิดใช้งานเซิร์ฟเวอร์เหล่านี้ต่อตัวแทนเท่านั้น และปิดใช้งานเซิร์ฟเวอร์เหล่านั้นทั่วโลก เมื่อต้องการทำสิ่งนี้: + +1. ปิดการใช้งานเป็นเครื่องมือทั่วโลก +2. ใน [agent config](/docs/agents#tools) ให้เปิดใช้งานเซิร์ฟเวอร์ MCP เป็นเครื่องมือ + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### รูปแบบลูกโลก + +รูปแบบ glob ใช้รูปแบบ globbing regex แบบง่าย: + +- `*` ตรงกับอักขระใดๆ ตั้งแต่ศูนย์ขึ้นไป (เช่น `"my-mcp*"` ตรงกับ `my-mcp_search`, `my-mcp_list` ฯลฯ) +- `?` ตรงกับอักขระหนึ่งตัวเท่านั้น +- อักขระอื่นๆ ทั้งหมดตรงกันอย่างแท้จริง + +:::note +MCP เครื่องมือเซิร์ฟเวอร์ได้รับการลงทะเบียนด้วยชื่อเซิร์ฟเวอร์เป็นคำนำหน้า ดังนั้นหากต้องการปิดการใช้งานเครื่องมือทั้งหมดสำหรับเซิร์ฟเวอร์ เพียงใช้: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## ตัวอย่าง + +ด้านล่างนี้เป็นตัวอย่างของเซิร์ฟเวอร์ MCP ทั่วไปบางส่วน คุณสามารถส่ง PR ได้ถ้าคุณต้องการจัดทำเอกสารเซิร์ฟเวอร์อื่น + +--- + +### ยาม + +เพิ่ม [เซิร์ฟเวอร์ Sentry MCP](https://mcp.sentry.dev) เพื่อโต้ตอบกับโครงการและปัญหา Sentry ของคุณ + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +หลังจากเพิ่มการกำหนดค่าแล้ว ให้ตรวจสอบสิทธิ์กับ Sentry: + +```bash +opencode mcp auth sentry +``` + +ซึ่งจะเป็นการเปิดหน้าต่างเบราว์เซอร์เพื่อดำเนินการโฟลว์ OAuth ให้เสร็จสมบูรณ์ และเชื่อมต่อ OpenCode กับบัญชี Sentry ของคุณ + +เมื่อตรวจสอบสิทธิ์แล้ว คุณจะใช้เครื่องมือ Sentry ในข้อความแจ้งเพื่อค้นหาปัญหา โปรเจ็กต์ และข้อมูลข้อผิดพลาดได้ + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### บริบท7 + +เพิ่ม [Context7 MCP server](https://github.com/upstash/context7) เพื่อค้นหาในเอกสาร + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +หากคุณได้ลงทะเบียนสำหรับบัญชีฟรี คุณสามารถใช้รหัส API ของคุณและรับขีดจำกัดอัตราที่สูงขึ้น + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +ที่นี่เราสมมติว่าคุณมีชุดตัวแปรสภาพแวดล้อม `CONTEXT7_API_KEY` + +เพิ่ม `use context7` ในข้อความแจ้งของคุณเพื่อใช้เซิร์ฟเวอร์ Context7 MCP + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +หรือคุณสามารถเพิ่มสิ่งนี้ลงใน [AGENTS.md](/docs/rules/) ของคุณได้ + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep โดย Vercel + +เพิ่มเซิร์ฟเวอร์ [Grep by Vercel](https://grep.app) MCP เพื่อค้นหาผ่านข้อมูลโค้ดบน GitHub + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +เนื่องจากเราตั้งชื่อเซิร์ฟเวอร์ MCP `gh_grep` คุณสามารถเพิ่ม `use the gh_grep tool` ในข้อความแจ้งของคุณเพื่อให้ตัวแทนใช้งานได้ + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +หรือคุณสามารถเพิ่มสิ่งนี้ลงใน [AGENTS.md](/docs/rules/) ของคุณได้ + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/th/models.mdx b/packages/web/src/content/docs/th/models.mdx new file mode 100644 index 000000000..5f0856c0d --- /dev/null +++ b/packages/web/src/content/docs/th/models.mdx @@ -0,0 +1,223 @@ +--- +title: โมเดล +description: การกำหนดค่าผู้ให้บริการและรุ่น LLM +--- + +OpenCode ใช้ [AI SDK](https://ai-sdk.dev/) และ [Models.dev](https://models.dev) เพื่อรองรับผู้ให้บริการ **75+ LLM** และรองรับการใช้งานโมเดลท้องถิ่น + +--- + +## ผู้ให้บริการ + +ผู้ให้บริการที่ได้รับความนิยมส่วนใหญ่จะถูกโหลดไว้ล่วงหน้าตามค่าเริ่มต้น หากคุณได้เพิ่มข้อมูลรับรองสำหรับผู้ให้บริการผ่านคำสั่ง `/connect` ข้อมูลเหล่านั้นจะพร้อมใช้งานเมื่อคุณเริ่ม OpenCode + +เรียนรู้เพิ่มเติมเกี่ยวกับ [ผู้ให้บริการ](/docs/providers) + +--- + +## เลือกรุ่น + +เมื่อคุณกำหนดค่าผู้ให้บริการแล้ว คุณสามารถเลือกรุ่นที่ต้องการได้โดยพิมพ์: + +```bash frame="none" +/models +``` + +--- + +## รุ่นที่แนะนำ + +มีโมเดลออกมามากมาย โดยมีโมเดลใหม่ๆ ออกมาทุกสัปดาห์ + +:::tip +พิจารณาใช้รุ่นใดรุ่นหนึ่งที่เราแนะนำ +::: + +อย่างไรก็ตาม มีเพียงไม่กี่ตัวเท่านั้นที่เก่งทั้งการสร้างโค้ดและการเรียกใช้เครื่องมือ + +ต่อไปนี้เป็นโมเดลหลายรุ่นที่ทำงานได้ดีกับ OpenCode โดยไม่เรียงลำดับเป็นพิเศษ (นี่ไม่ใช่รายการที่ครอบคลุมและไม่จำเป็นต้องเป็นข้อมูลล่าสุด): + +- GPT 5.2 +- GPT 5.1 โคเด็กซ์ +- คลอดด์บทประพันธ์ 4.5 +- คล็อด ซอนเน็ต 4.5 +- มินิแม็กซ์ M2.1 +- เจมินี่ 3 โปร + +--- + +## ตั้งค่าเริ่มต้น + +หากต้องการตั้งค่าสิ่งใดสิ่งหนึ่งเป็นโมเดลเริ่มต้น คุณสามารถตั้งค่าคีย์ `model` ในของคุณ +การกำหนดค่า OpenCode + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +ID แบบเต็มคือ `provider_id/model_id` ตัวอย่างเช่น หากคุณใช้ [OpenCode Zen](/docs/zen) คุณจะใช้ `opencode/gpt-5.1-codex` สำหรับ GPT 5.1 Codex + +หากคุณได้กำหนดค่า [ผู้ให้บริการที่กำหนดเอง](/docs/providers#กำหนดเอง) `provider_id` จะเป็นคีย์จากส่วน `provider` ของการกำหนดค่าของคุณ และ `model_id` จะเป็นคีย์จาก `provider.models` + +--- + +## กำหนดค่าโมเดล + +คุณสามารถกำหนดค่าตัวเลือกของโมเดลได้ทั่วโลกผ่านการกำหนดค่า + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +ที่นี่เรากำลังกำหนดการตั้งค่าส่วนกลางสำหรับโมเดลในตัวสองรุ่น: `gpt-5` เมื่อเข้าถึงผ่านผู้ให้บริการ `openai` และ `claude-sonnet-4-20250514` เมื่อเข้าถึงผ่านผู้ให้บริการ `anthropic` +สามารถดูผู้ให้บริการและชื่อรุ่นในตัวได้ที่ [Models.dev](https://models.dev) + +คุณยังสามารถกำหนดค่าตัวเลือกเหล่านี้สำหรับตัวแทนใดๆ ที่คุณใช้อยู่ได้ การกำหนดค่าตัวแทนจะแทนที่ตัวเลือกส่วนกลางใดๆ ที่นี่ [เรียนรู้เพิ่มเติม](/docs/agents/#เพิ่มเติม) + +คุณยังสามารถกำหนดตัวแปรแบบกำหนดเองที่ขยายตัวแปรในตัวได้ ตัวแปรช่วยให้คุณกำหนดการตั้งค่าที่แตกต่างกันสำหรับรุ่นเดียวกันโดยไม่ต้องสร้างรายการที่ซ้ำกัน: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## หลากหลาย + +หลายรุ่นรองรับหลายรุ่นด้วยการกำหนดค่าที่แตกต่างกัน OpenCode มาพร้อมกับตัวแปรเริ่มต้นในตัวสำหรับผู้ให้บริการยอดนิยม + +### ตัวแปรในตัว + +OpenCode มาพร้อมกับตัวแปรเริ่มต้นสำหรับผู้ให้บริการหลายราย: + +**มานุษยวิทยา**: + +- `high` - ​​งบประมาณการคิดสูง (ค่าเริ่มต้น) +- `max` - ​​งบประมาณการคิดสูงสุด + +**โอเพนเอไอ**: + +แตกต่างกันไปตามรุ่น แต่โดยประมาณ: + +- `none` - ​​ไม่มีเหตุผล +- `minimal` - ​​ความพยายามในการให้เหตุผลน้อยที่สุด +- `low` - ​​ความพยายามในการให้เหตุผลต่ำ +- `medium` - ​​ความพยายามในการให้เหตุผลปานกลาง +- `high` - ​​ความพยายามในการให้เหตุผลสูง +- `xhigh` - ​​ความพยายามในการให้เหตุผลสูงเป็นพิเศษ + +**Google**: + +- `low` - ​​ลดความพยายาม/token งบประมาณ +- `high` - ​​ความพยายามที่สูงขึ้น/token งบประมาณ + +:::tip +รายการนี้ไม่ครอบคลุม ผู้ให้บริการรายอื่นหลายรายก็มีค่าเริ่มต้นในตัวเช่นกัน +::: + +### ตัวแปรที่กำหนดเอง + +คุณสามารถแทนที่ตัวแปรที่มีอยู่หรือเพิ่มตัวแปรของคุณเองได้: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### ตัวแปรของวงจร + +ใช้ปุ่มลัด `variant_cycle` เพื่อสลับระหว่างตัวแปรต่างๆ อย่างรวดเร็ว [เรียนรู้เพิ่มเติม](/docs/keybinds) + +--- + +## กำลังโหลดโมเดล + +เมื่อ OpenCode เริ่มทำงาน ระบบจะตรวจสอบรุ่นตามลำดับความสำคัญต่อไปนี้: + +1. การตั้งค่าสถานะบรรทัดคำสั่ง `--model` หรือ `-m` รูปแบบจะเหมือนกับในไฟล์ปรับแต่ง: `provider_id/model_id` + +2. รายการโมเดลในการกำหนดค่า OpenCode + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + รูปแบบที่นี่คือ `provider/model` + +3. รุ่นที่ใช้ล่าสุด. + +4. รุ่นแรกที่ใช้ลำดับความสำคัญภายใน diff --git a/packages/web/src/content/docs/th/modes.mdx b/packages/web/src/content/docs/th/modes.mdx new file mode 100644 index 000000000..623c9d156 --- /dev/null +++ b/packages/web/src/content/docs/th/modes.mdx @@ -0,0 +1,331 @@ +--- +title: โหมด +description: โหมดที่แตกต่างกันสำหรับกรณีการใช้งานที่แตกต่างกัน +--- + +:::caution +ขณะนี้โหมดได้รับการกำหนดค่าผ่านตัวเลือก `agent` ในการกำหนดค่า opencode ที่ +ตัวเลือก `mode` เลิกใช้แล้ว [เรียนรู้เพิ่มเติม](/docs/agents) +::: + +โหมดใน opencode ช่วยให้คุณปรับแต่งพฤติกรรม เครื่องมือ และพร้อมท์สำหรับกรณีการใช้งานที่แตกต่างกันได้ + +มาพร้อมกับโหมดในตัวสองโหมด: **สร้าง** และ **วางแผน** คุณสามารถปรับแต่งได้ +สิ่งเหล่านี้หรือกำหนดค่าของคุณเองผ่านการกำหนดค่า opencode + +คุณสามารถสลับระหว่างโหมดระหว่างเซสชันหรือกำหนดค่าในไฟล์กำหนดค่าของคุณ + +--- + +## บิวท์อิน + +opencode มาพร้อมกับโหมดในตัวสองโหมด + +--- + +### สร้าง + +Build เป็นโหมด **ค่าเริ่มต้น** โดยที่เครื่องมือทั้งหมดเปิดใช้งานอยู่ นี่คือโหมดมาตรฐานสำหรับงานพัฒนาที่คุณต้องการสิทธิ์เข้าถึงการทำงานของไฟล์และคำสั่งระบบโดยสมบูรณ์ + +--- + +### วางแผน + +โหมดจำกัดที่ออกแบบมาเพื่อการวางแผนและการวิเคราะห์ ในโหมดแผน เครื่องมือต่อไปนี้จะถูกปิดใช้งานตามค่าเริ่มต้น: + +- `write` - ​​ไม่สามารถสร้างไฟล์ใหม่ได้ +- `edit` - ​​ไม่สามารถแก้ไขไฟล์ที่มีอยู่ได้ ยกเว้นไฟล์ที่อยู่ใน `.opencode/plans/*.md` เพื่อดูรายละเอียดแผนงาน +- `patch` - ​​ไม่สามารถใช้แพตช์ได้ +- `bash` - ​​ไม่สามารถรันคำสั่งเชลล์ได้ + +โหมดนี้มีประโยชน์เมื่อคุณต้องการให้ AI วิเคราะห์โค้ด แนะนำการเปลี่ยนแปลง หรือสร้างแผนโดยไม่ต้องทำการแก้ไขโค้ดเบสของคุณจริง ๆ + +--- + +## การสลับ + +คุณสามารถสลับระหว่างโหมดระหว่างเซสชันได้โดยใช้ปุ่ม _Tab_ หรือการเชื่อมโยงคีย์ `switch_mode` ที่คุณกำหนดค่าไว้ + +ดูเพิ่มเติมที่: [Formatters](/docs/formatters) สำหรับข้อมูลเกี่ยวกับการกำหนดค่าการจัดรูปแบบโค้ด + +--- + +## กำหนดค่า + +คุณสามารถปรับแต่งโหมดในตัวหรือสร้างโหมดของคุณเองผ่านการกำหนดค่าได้ โหมดสามารถกำหนดค่าได้สองวิธี: + +### JSON การกำหนดค่า + +กำหนดค่าโหมดในไฟล์กำหนดค่า `opencode.json` ของคุณ: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### การกำหนดค่ามาร์กดาวน์ + +คุณยังสามารถกำหนดโหมดโดยใช้ไฟล์มาร์กดาวน์ได้ วางไว้ใน: + +- ทั่วโลก: `~/.config/opencode/modes/` +- โครงการ: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +ชื่อไฟล์มาร์กดาวน์จะกลายเป็นชื่อโหมด (เช่น `review.md` สร้างโหมด `review`) + +มาดูรายละเอียดตัวเลือกการกำหนดค่าเหล่านี้กัน + +--- + +### แบบอย่าง + +ใช้การกำหนดค่า `model` เพื่อแทนที่โมเดลเริ่มต้นสำหรับโหมดนี้ มีประโยชน์สำหรับการใช้โมเดลที่แตกต่างกันซึ่งปรับให้เหมาะกับงานที่แตกต่างกัน ตัวอย่างเช่น โมเดลสำหรับการวางแผนที่เร็วขึ้น โมเดลที่มีความสามารถมากขึ้นสำหรับการนำไปปฏิบัติ + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### อุณหภูมิ + +ควบคุมการสุ่มและความคิดสร้างสรรค์ของการตอบสนองของ AI ด้วยการกำหนดค่า `temperature` ค่าที่ต่ำกว่าจะทำให้คำตอบมีจุดมุ่งหมายและกำหนดได้มากขึ้น ในขณะที่ค่าที่สูงกว่าจะเพิ่มความคิดสร้างสรรค์และความแปรปรวน + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +โดยทั่วไปค่าอุณหภูมิจะอยู่ในช่วงตั้งแต่ 0.0 ถึง 1.0: + +- **0.0-0.2**: การตอบสนองที่มุ่งเน้นและกำหนดไว้อย่างมาก เหมาะสำหรับการวิเคราะห์และวางแผนโค้ด +- **0.3-0.5**: การตอบสนองที่สมดุลและความคิดสร้างสรรค์บางส่วน เหมาะสำหรับงานพัฒนาทั่วไป +- **0.6-1.0**: คำตอบที่สร้างสรรค์และหลากหลายยิ่งขึ้น ซึ่งมีประโยชน์สำหรับการระดมความคิดและการสำรวจ + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +หากไม่มีการระบุอุณหภูมิ opencode จะใช้ค่าเริ่มต้นเฉพาะรุ่น (โดยทั่วไปจะเป็น 0 สำหรับรุ่นส่วนใหญ่ และ 0.55 สำหรับรุ่น Qwen) + +--- + +### พรอมต์ + +ระบุไฟล์พรอมต์ระบบที่กำหนดเองสำหรับโหมดนี้ด้วยการกำหนดค่า `prompt` ไฟล์พร้อมท์ควรมีคำแนะนำเฉพาะสำหรับวัตถุประสงค์ของโหมด + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +เส้นทางนี้สัมพันธ์กับตำแหน่งของไฟล์กำหนดค่า ดังนั้นสิ่งนี้จึงใช้ได้กับ +ทั้งการกำหนดค่า opencode ส่วนกลางและการกำหนดค่าเฉพาะโครงการ + +--- + +### เครื่องมือ + +ควบคุมว่าเครื่องมือใดบ้างที่พร้อมใช้งานในโหมดนี้ด้วยการกำหนดค่า `tools` คุณสามารถเปิดหรือปิดใช้งานเครื่องมือเฉพาะได้โดยตั้งค่าเป็น `true` หรือ `false` + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +หากไม่มีการระบุเครื่องมือ เครื่องมือทั้งหมดจะถูกเปิดใช้งานตามค่าเริ่มต้น + +--- + +#### เครื่องมือที่มีอยู่ + +นี่คือเครื่องมือทั้งหมดที่สามารถควบคุมได้ผ่านการกำหนดค่าโหมด + +| เครื่องมือ | คำอธิบาย | +| ----------- | ----------------------- | +| `bash` | ดำเนินการคำสั่งเชลล์ | +| `edit` | แก้ไขไฟล์ที่มีอยู่ | +| `write` | สร้างไฟล์ใหม่ | +| `read` | อ่านเนื้อหาไฟล์ | +| `grep` | ค้นหาเนื้อหาไฟล์ | +| `glob` | ค้นหาไฟล์ตามรูปแบบ | +| `list` | แสดงรายการเนื้อหาไดเร็กทอรี | +| `patch` | ใช้แพทช์กับไฟล์ | +| `todowrite` | จัดการรายการสิ่งที่ต้องทำ | +| `todoread` | อ่านรายการสิ่งที่ต้องทำ | +| `webfetch` | ดึงเนื้อหาเว็บ | + +--- + +## โหมดกำหนดเอง + +คุณสามารถสร้างโหมดที่คุณกำหนดเองได้โดยเพิ่มเข้าไปในการกำหนดค่า นี่คือตัวอย่างที่ใช้ทั้งสองวิธี: + +### ใช้การกำหนดค่า JSON + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### การใช้ไฟล์มาร์กดาวน์ + +สร้างไฟล์โหมดใน `.opencode/modes/` สำหรับโหมดเฉพาะโครงการหรือ `~/.config/opencode/modes/` สำหรับโหมดทั่วโลก: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### กรณีการใช้งาน + +ต่อไปนี้เป็นกรณีการใช้งานทั่วไปสำหรับโหมดต่างๆ + +- **โหมดสร้าง**: งานพัฒนาเต็มรูปแบบโดยเปิดใช้งานเครื่องมือทั้งหมด +- **โหมดแผน**: วิเคราะห์และวางแผนโดยไม่ทำการเปลี่ยนแปลง +- **โหมดการตรวจสอบ**: การตรวจสอบโค้ดพร้อมการเข้าถึงแบบอ่านอย่างเดียวพร้อมเครื่องมือเอกสารประกอบ +- **โหมดแก้ไขข้อบกพร่อง**: มุ่งเน้นไปที่การตรวจสอบโดยเปิดใช้งานเครื่องมือทุบตีและอ่าน +- **โหมดเอกสาร**: การเขียนเอกสารด้วยการทำงานของไฟล์ แต่ไม่มีคำสั่งระบบ + +คุณอาจพบว่ารุ่นต่างๆ นั้นดีสำหรับกรณีการใช้งานที่แตกต่างกัน diff --git a/packages/web/src/content/docs/th/network.mdx b/packages/web/src/content/docs/th/network.mdx new file mode 100644 index 000000000..4a7144161 --- /dev/null +++ b/packages/web/src/content/docs/th/network.mdx @@ -0,0 +1,57 @@ +--- +title: เครือข่าย +description: กำหนดค่าพร็อกซีและใบรับรองที่กำหนดเอง +--- + +OpenCode รองรับตัวแปรสภาพแวดล้อมพร็อกซีมาตรฐานและใบรับรองที่กำหนดเองสำหรับสภาพแวดล้อมเครือข่ายองค์กร + +--- + +## หนังสือมอบฉันทะ + +OpenCode เคารพตัวแปรสภาพแวดล้อมพร็อกซีมาตรฐาน + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::caution +TUI สื่อสารกับเซิร์ฟเวอร์ HTTP ในพื้นที่ คุณต้องข้ามพร็อกซีสำหรับการเชื่อมต่อนี้เพื่อป้องกันการกำหนดเส้นทางวนซ้ำ +::: + +คุณสามารถกำหนดค่าพอร์ตของเซิร์ฟเวอร์และชื่อโฮสต์ได้โดยใช้ [CLI flags](/docs/cli#run) + +--- + +### ตรวจสอบสิทธิ์ + +หากพร็อกซีของคุณต้องการการรับรองความถูกต้องขั้นพื้นฐาน ให้ใส่ข้อมูลรับรองใน URL + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::caution +หลีกเลี่ยงรหัสผ่านฮาร์ดโค้ด ใช้ตัวแปรสภาพแวดล้อมหรือที่จัดเก็บข้อมูลรับรองที่ปลอดภัย +::: + +สำหรับพร็อกซีที่ต้องการการรับรองความถูกต้องขั้นสูง เช่น NTLM หรือ Kerberos ให้พิจารณาใช้เกตเวย์ LLM ที่รองรับวิธีการตรวจสอบความถูกต้องของคุณ + +--- + +## ใบรับรองที่กำหนดเอง + +หากองค์กรของคุณใช้ CA แบบกำหนดเองสำหรับการเชื่อมต่อ HTTPS ให้กำหนดค่า OpenCode ให้เชื่อถือ + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +ซึ่งใช้ได้กับทั้งการเชื่อมต่อพร็อกซีและการเข้าถึง API โดยตรง diff --git a/packages/web/src/content/docs/th/permissions.mdx b/packages/web/src/content/docs/th/permissions.mdx new file mode 100644 index 000000000..7ca31a5dc --- /dev/null +++ b/packages/web/src/content/docs/th/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: สิทธิ์ +description: ควบคุมการดำเนินการที่ต้องได้รับการอนุมัติจึงจะรันได้ +--- + +OpenCode ใช้การกำหนดค่า `permission` เพื่อตัดสินใจว่าการดำเนินการที่กำหนดควรทำงานโดยอัตโนมัติ แจ้งให้คุณทราบ หรือถูกบล็อก + +ตั้งแต่ `v1.1.1` การกำหนดค่าบูลีนแบบเดิม `tools` เลิกใช้แล้วและได้รวมเข้ากับ `permission` แล้ว การกำหนดค่า `tools` แบบเก่ายังคงรองรับความเข้ากันได้แบบย้อนหลัง + +--- + +## การดำเนินการ + +กฎการอนุญาตแต่ละข้อจะแก้ไขเป็นข้อใดข้อหนึ่งต่อไปนี้ + +- `"allow"` — ทำงานโดยไม่ได้รับการอนุมัติ +- `"ask"` — พร้อมท์สำหรับการอนุมัติ +- `"deny"` — บล็อกการกระทำ + +--- + +## การกำหนดค่า + +คุณสามารถตั้งค่าการอนุญาตทั่วโลก (ด้วย `*`) และแทนที่เครื่องมือเฉพาะ + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +คุณยังสามารถตั้งค่าการอนุญาตทั้งหมดพร้อมกันได้: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## กฎแบบละเอียด (ไวยากรณ์ของวัตถุ) + +สำหรับการอนุญาตส่วนใหญ่ คุณสามารถใช้ออบเจ็กต์เพื่อปรับใช้การดำเนินการต่างๆ ตามอินพุตของเครื่องมือได้ + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +กฎจะได้รับการประเมินโดยการจับคู่รูปแบบ โดย **กฎการจับคู่สุดท้ายจะชนะ** รูปแบบทั่วไปคือการใส่กฎ catch-all `"*"` ก่อน และใส่กฎที่เฉพาะเจาะจงมากขึ้นหลังจากนั้น + +### สัญลักษณ์แทน + +รูปแบบการอนุญาตใช้การจับคู่ไวด์การ์ดแบบง่าย: + +- `*` จับคู่อักขระใดๆ ตั้งแต่ศูนย์ขึ้นไป +- `?` ตรงกับอักขระหนึ่งตัวเท่านั้น +- อักขระอื่นๆ ทั้งหมดตรงกันอย่างแท้จริง + +### การขยายโฮมไดเร็กทอรี + +คุณสามารถใช้ `~` หรือ `$HOME` ที่จุดเริ่มต้นของรูปแบบเพื่ออ้างอิงโฮมไดเร็กตอรี่ของคุณ สิ่งนี้มีประโยชน์อย่างยิ่งสำหรับกฎของ [`external_directory`](#external-directories) + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### ไดเรกทอรีภายนอก + +ใช้ `external_directory` เพื่ออนุญาตการเรียกใช้เครื่องมือที่สัมผัสเส้นทางนอกไดเร็กทอรีการทำงานที่ OpenCode เริ่มทำงาน สิ่งนี้ใช้ได้กับเครื่องมือใดๆ ที่ใช้เส้นทางเป็นอินพุต (เช่น `read`, `edit`, `list`, `glob`, `grep` และคำสั่ง `bash` จำนวนมาก) + +การขยายบ้าน (เช่น `~/...`) ส่งผลต่อวิธีการเขียนรูปแบบเท่านั้น ไม่ได้ทำให้เส้นทางภายนอกเป็นส่วนหนึ่งของพื้นที่ทำงานปัจจุบัน ดังนั้นเส้นทางภายนอกไดเรกทอรีการทำงานยังต้องได้รับอนุญาตผ่าน `external_directory` + +ตัวอย่างเช่น อนุญาตให้เข้าถึงทุกสิ่งภายใต้ `~/projects/personal/`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +ไดเร็กทอรีใดๆ ที่ได้รับอนุญาตที่นี่จะสืบทอดค่าเริ่มต้นเดียวกันกับพื้นที่ทำงานปัจจุบัน เนื่องจาก [`read` มีค่าเริ่มต้นเป็น `allow`](#defaults) การอ่านจึงได้รับอนุญาตสำหรับรายการภายใต้ `external_directory` เว้นแต่จะถูกแทนที่ เพิ่มกฎที่ชัดเจนเมื่อควรจำกัดเครื่องมือในเส้นทางเหล่านี้ เช่น การบล็อกการแก้ไขในขณะที่ยังคงอ่านอยู่: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +ให้รายการมุ่งเน้นไปที่เส้นทางที่เชื่อถือได้ และเลเยอร์อนุญาตหรือปฏิเสธกฎเพิ่มเติมตามที่จำเป็นสำหรับเครื่องมืออื่นๆ (เช่น `bash`) + +--- + +## สิทธิ์ที่มีอยู่ + +สิทธิ์ของ OpenCode จะกำหนดไว้ตามชื่อเครื่องมือ พร้อมด้วยเจ้าหน้าที่รักษาความปลอดภัยอีก 2-3 คน: + +- `read` — อ่านไฟล์ (ตรงกับเส้นทางของไฟล์) +- `edit` — การแก้ไขไฟล์ทั้งหมด (ครอบคลุมถึง `edit`, `write`, `patch`, `multiedit`) +- `glob` — ไฟล์ globbing (ตรงกับรูปแบบ glob) +- `grep` — การค้นหาเนื้อหา (ตรงกับรูปแบบ regex) +- `list` — แสดงรายการไฟล์ในไดเร็กทอรี (ตรงกับเส้นทางไดเร็กทอรี) +- `bash` — การรันคำสั่งเชลล์ (ตรงกับคำสั่งที่แยกวิเคราะห์เช่น `git status --porcelain`) +- `task` — การเปิดตัวตัวแทนย่อย (ตรงกับประเภทตัวแทนย่อย) +- `skill` — กำลังโหลดทักษะ (ตรงกับชื่อทักษะ) +- `lsp` — กำลังเรียกใช้คำสั่ง LSP (ปัจจุบันยังไม่ละเอียด) +- `todoread`, `todowrite` — กำลังอ่าน/updating รายการสิ่งที่ต้องทำ +- `webfetch` — กำลังดึง URL (ตรงกับ URL) +- `websearch`, `codesearch` — การค้นหาเว็บ/code (ตรงกับข้อความค้นหา) +- `external_directory` — ทริกเกอร์เมื่อเครื่องมือแตะเส้นทางนอกไดเร็กทอรีการทำงานของโปรเจ็กต์ +- `doom_loop` — ทริกเกอร์เมื่อมีการเรียกใช้เครื่องมือเดียวกันซ้ำ 3 ครั้งโดยมีอินพุตเหมือนกัน + +--- + +## ค่าเริ่มต้น + +หากคุณไม่ได้ระบุสิ่งใด OpenCode จะเริ่มต้นจากค่าเริ่มต้นที่อนุญาต: + +- การอนุญาตส่วนใหญ่มีค่าเริ่มต้นเป็น `"allow"` +- `doom_loop` และ `external_directory` มีค่าเริ่มต้นเป็น `"ask"` +- `read` คือ `"allow"` แต่ไฟล์ `.env` ถูกปฏิเสธโดยค่าเริ่มต้น: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## สิ่งที่ "ถาม" ทำ + +เมื่อ OpenCode แจ้งให้อนุมัติ UI จะเสนอผลลัพธ์สามประการ: + +- `once` — อนุมัติเพียงคำขอนี้ +- `always` — อนุมัติคำขอในอนาคตที่ตรงกับรูปแบบที่แนะนำ (สำหรับส่วนที่เหลือของเซสชัน OpenCode ปัจจุบัน) +- `reject` — ปฏิเสธคำขอ + +ชุดรูปแบบที่ `always` จะอนุมัตินั้นมาจากเครื่องมือ (เช่น โดยทั่วไปการอนุมัติทุบตีจะกำหนดไวท์ลิสต์คำนำหน้าคำสั่งที่ปลอดภัย เช่น `git status*`) + +--- + +## ตัวแทน + +คุณสามารถแทนที่สิทธิ์ต่อตัวแทนได้ สิทธิ์ของตัวแทนจะผสานเข้ากับการกำหนดค่าส่วนกลาง และกฎของตัวแทนจะมีความสำคัญกว่า [เรียนรู้เพิ่มเติม](/docs/agents#permissions) เกี่ยวกับการอนุญาตของตัวแทน + +:::note +โปรดดูส่วน [กฎแบบละเอียด (ไวยากรณ์ของวัตถุ)](#granular-rules-object-syntax) ด้านบนเพื่อดูตัวอย่างการจับคู่รูปแบบโดยละเอียดเพิ่มเติม +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +คุณยังสามารถกำหนดค่าการอนุญาตตัวแทนใน Markdown ได้: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tip +ใช้การจับคู่รูปแบบสำหรับคำสั่งที่มีอาร์กิวเมนต์ `"grep *"` อนุญาต `grep pattern file.txt` ในขณะที่ `"grep"` คนเดียวจะบล็อกได้ คำสั่งเช่น `git status` ใช้งานได้กับพฤติกรรมเริ่มต้น แต่ต้องได้รับอนุญาตอย่างชัดเจน (เช่น `"git status *"`) เมื่ออาร์กิวเมนต์ถูกส่งผ่าน +::: diff --git a/packages/web/src/content/docs/th/plugins.mdx b/packages/web/src/content/docs/th/plugins.mdx new file mode 100644 index 000000000..af300d057 --- /dev/null +++ b/packages/web/src/content/docs/th/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: ปลั๊กอิน +description: เขียนปลั๊กอินของคุณเองเพื่อขยาย OpenCode +--- + +ปลั๊กอินช่วยให้คุณสามารถขยาย OpenCode ได้โดยเชื่อมโยงกับเหตุการณ์ต่างๆ และปรับแต่งลักษณะการทำงาน คุณสามารถสร้างปลั๊กอินเพื่อเพิ่มคุณสมบัติใหม่ บูรณาการกับบริการภายนอก หรือแก้ไขการทำงานเริ่มต้นของ OpenCode + +ตัวอย่างเช่น ลองดู [ปลั๊กอิน](/docs/ecosystem#ปลั๊กอิน) ที่สร้างโดยชุมชน + +--- + +## ใช้ปลั๊กอิน + +มีสองวิธีในการโหลดปลั๊กอิน + +--- + +### จากไฟล์ในเครื่อง + +วางไฟล์ JavaScript หรือ TypeScript ในไดเร็กทอรีปลั๊กอิน + +- `.opencode/plugins/` - ​​ปลั๊กอินระดับโครงการ +- `~/.config/opencode/plugins/` - ​​ปลั๊กอินทั่วโลก + +ไฟล์ในไดเร็กทอรีเหล่านี้จะถูกโหลดโดยอัตโนมัติเมื่อเริ่มต้นระบบ + +--- + +### ตั้งแต่เวลา 13.00 น + +ระบุแพ็คเกจ npm ในไฟล์ปรับแต่งของคุณ + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +รองรับแพ็คเกจ npm ทั้งแบบปกติและแบบกำหนดขอบเขต + +เรียกดูปลั๊กอินที่มีอยู่ใน [ระบบนิเวศ](/docs/ecosystem#plugins) + +--- + +### วิธีการติดตั้งปลั๊กอิน + +**ปลั๊กอิน npm** ได้รับการติดตั้งโดยอัตโนมัติโดยใช้ Bun เมื่อเริ่มต้น แพ็คเกจและการขึ้นต่อกันถูกแคชไว้ใน `~/.cache/opencode/node_modules/` + +**ปลั๊กอินท้องถิ่น** โหลดโดยตรงจากไดเร็กทอรีปลั๊กอิน หากต้องการใช้แพ็คเกจภายนอก คุณต้องสร้าง `package.json` ภายในไดเร็กทอรีการกำหนดค่าของคุณ (ดู [การพึ่งพา](#dependencies)) หรือเผยแพร่ปลั๊กอินไปที่ npm และ [เพิ่มลงในการกำหนดค่าของคุณ](/docs/config#plugins) + +--- + +### โหลดออเดอร์ + +ปลั๊กอินถูกโหลดจากทุกแหล่งและ hooks ทั้งหมดทำงานตามลำดับ ลำดับการโหลดคือ: + +1. การกำหนดค่าส่วนกลาง (`~/.config/opencode/opencode.json`) +2. การกำหนดค่าโครงการ (`opencode.json`) +3. ไดเร็กทอรีปลั๊กอินสากล (`~/.config/opencode/plugins/`) +4. ไดเรกทอรีปลั๊กอินโครงการ (`.opencode/plugins/`) + +แพ็กเกจ npm ที่ซ้ำกันซึ่งมีชื่อและเวอร์ชันเดียวกันจะถูกโหลดหนึ่งครั้ง อย่างไรก็ตาม ทั้งปลั๊กอินในเครื่องและปลั๊กอิน npm ที่มีชื่อคล้ายกันจะโหลดแยกกัน + +--- + +## สร้างปลั๊กอิน + +ปลั๊กอินคือ **JavaScript/TypeScript module** ที่ส่งออกปลั๊กอินอย่างน้อยหนึ่งรายการ +ฟังก์ชั่น แต่ละฟังก์ชันได้รับวัตถุบริบทและส่งกลับวัตถุ hooks + +--- + +### การพึ่งพาอาศัยกัน + +ปลั๊กอินท้องถิ่นและเครื่องมือแบบกำหนดเองสามารถใช้แพ็คเกจ npm ภายนอกได้ เพิ่ม `package.json` ลงในไดเร็กทอรี config ของคุณด้วยการอ้างอิงที่คุณต้องการ + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode รัน `bun install` เมื่อเริ่มต้นเพื่อติดตั้งสิ่งเหล่านี้ ปลั๊กอินและเครื่องมือของคุณสามารถนำเข้าได้ + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### โครงสร้างพื้นฐาน + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +ฟังก์ชั่นปลั๊กอินได้รับ: + +- `project`: ข้อมูลโครงการปัจจุบัน +- `directory`: ไดเร็กทอรีการทำงานปัจจุบัน +- `worktree`: เส้นทางเวิร์กทรีคอมไพล์ +- `client`: ไคลเอนต์ opencode SDK สำหรับการโต้ตอบกับ AI +- `$`: [shell API](https://bun.com/docs/runtime/shell) ของ Bun สำหรับการดำเนินการคำสั่ง + +--- + +### รองรับ TypeScript + +สำหรับปลั๊กอิน TypeScript คุณสามารถนำเข้าประเภทจากแพ็คเกจปลั๊กอินได้: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### กิจกรรม + +ปลั๊กอินสามารถสมัครรับกิจกรรมได้ดังที่แสดงด้านล่างในส่วนตัวอย่าง นี่คือรายการกิจกรรมต่างๆ ที่มี + +#### เหตุการณ์คำสั่ง + +- `command.executed` + +#### ไฟล์เหตุการณ์ + +- `file.edited` +- `file.watcher.updated` + +#### เหตุการณ์การติดตั้ง + +- `installation.updated` + +#### LSP กิจกรรม + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### เหตุการณ์ข้อความ + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### เหตุการณ์การอนุญาต + +- `permission.asked` +- `permission.replied` + +#### เหตุการณ์เซิร์ฟเวอร์ + +- `server.connected` + +#### กิจกรรมเซสชั่น + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### เหตุการณ์ที่ต้องทำ + +- `todo.updated` + +#### กิจกรรมของเชลล์ + +- `shell.env` + +#### เหตุการณ์เครื่องมือ + +- `tool.execute.after` +- `tool.execute.before` + +#### TUI กิจกรรม + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## ตัวอย่าง + +นี่คือตัวอย่างบางส่วนของปลั๊กอินที่คุณสามารถใช้เพื่อขยาย opencode + +--- + +### ส่งการแจ้งเตือน + +ส่งการแจ้งเตือนเมื่อมีเหตุการณ์บางอย่างเกิดขึ้น: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +เรากำลังใช้ `osascript` เพื่อเรียกใช้ AppleScript บน macOS ที่นี่เราใช้มันเพื่อส่งการแจ้งเตือน + +:::note +หากคุณใช้แอปเดสก์ท็อป OpenCode แอปสามารถส่งการแจ้งเตือนของระบบโดยอัตโนมัติเมื่อมีการตอบกลับพร้อมหรือเมื่อเซสชันเกิดข้อผิดพลาด +::: + +--- + +### การป้องกัน .env + +ป้องกันไม่ให้ opencode อ่านไฟล์ `.env`: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### ฉีดตัวแปรสภาพแวดล้อม + +แทรกตัวแปรสภาพแวดล้อมลงในการดำเนินการเชลล์ทั้งหมด (เครื่องมือ AI และเทอร์มินัลผู้ใช้): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### เครื่องมือที่กำหนดเอง + +ปลั๊กอินยังสามารถเพิ่มเครื่องมือที่กำหนดเองให้กับ opencode: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +ตัวช่วย `tool` สร้างเครื่องมือแบบกำหนดเองที่สามารถเรียกใช้ opencode ได้ ใช้ฟังก์ชัน Zod schema และส่งกลับคำจำกัดความของเครื่องมือด้วย: + +- `description`: เครื่องมือนี้ทำอะไร +- `args`: Zod schema สำหรับข้อโต้แย้งของเครื่องมือ +- `execute`: ฟังก์ชั่นที่ทำงานเมื่อมีการเรียกใช้เครื่องมือ + +เครื่องมือที่คุณกำหนดเองจะพร้อมใช้งานสำหรับ opencode ควบคู่ไปกับเครื่องมือในตัว + +--- + +### การบันทึก + +ใช้ `client.app.log()` แทน `console.log` สำหรับการบันทึกแบบมีโครงสร้าง: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +ระดับ: `debug`, `info`, `warn`, `error` ดู[SDKเอกสารประกอบ](https://opencode.ai/docs/sdk)สำหรับรายละเอียด + +--- + +### ตะขอบดอัด + +ปรับแต่งบริบทที่รวมไว้เมื่อมีการกระชับเซสชัน: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +`experimental.session.compacting` hook เริ่มทำงานก่อนที่ LLM จะสร้างข้อมูลสรุปต่อเนื่อง ใช้เพื่อแทรกบริบทเฉพาะโดเมนที่พรอมต์การบีบอัดข้อมูลเริ่มต้นอาจพลาดไป + +คุณยังสามารถแทนที่พรอมต์การกระชับข้อมูลทั้งหมดได้โดยตั้งค่า `output.prompt`: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +เมื่อตั้งค่า `output.prompt` มันจะแทนที่พร้อมท์การกระชับค่าเริ่มต้นโดยสมบูรณ์ อาร์เรย์ `output.context` จะถูกละเว้นในกรณีนี้ diff --git a/packages/web/src/content/docs/th/providers.mdx b/packages/web/src/content/docs/th/providers.mdx new file mode 100644 index 000000000..4034978b2 --- /dev/null +++ b/packages/web/src/content/docs/th/providers.mdx @@ -0,0 +1,1889 @@ +--- +title: ผู้ให้บริการ +description: ใช้ผู้ให้บริการ LLM ใน OpenCode +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode ใช้ [AI SDK](https://ai-sdk.dev/) และ [Models.dev](https://models.dev) เพื่อรองรับผู้ให้บริการ **75+ LLM** และรองรับการใช้งานโมเดลท้องถิ่น + +หากต้องการเพิ่มผู้ให้บริการ คุณต้อง: + +1. เพิ่มคีย์ API สำหรับผู้ให้บริการโดยใช้คำสั่ง `/connect` +2. กำหนดค่าผู้ให้บริการในการกำหนดค่า OpenCode ของคุณ + +--- + +### ข้อมูลรับรอง + +เมื่อคุณเพิ่มคีย์ API ของผู้ให้บริการด้วยคำสั่ง `/connect` คีย์เหล่านั้นจะถูกเก็บไว้ +ใน `~/.local/share/opencode/auth.json`. + +--- + +### การกำหนดค่า + +คุณสามารถปรับแต่งผู้ให้บริการได้ผ่านทางส่วน `provider` ใน OpenCode ของคุณ +กำหนดค่า + +--- + +#### ฐาน URL + +คุณสามารถปรับแต่งฐาน URL สำหรับผู้ให้บริการรายใดก็ได้โดยตั้งค่าตัวเลือก `baseURL` สิ่งนี้มีประโยชน์เมื่อใช้บริการพร็อกซีหรือจุดสิ้นสุดแบบกำหนดเอง + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## โอเพ่นโค้ดเซน + +OpenCode Zen คือรายชื่อโมเดลที่จัดทำโดยทีมงาน OpenCode ที่ได้รับ +ทดสอบและตรวจสอบแล้วว่าทำงานได้ดีกับ OpenCode [เรียนรู้เพิ่มเติม](/docs/zen) + +:::tip +หากคุณยังใหม่ เราขอแนะนำให้เริ่มต้นด้วย OpenCode Zen +::: + +1. เรียกใช้คำสั่ง `/connect` ใน TUI เลือก opencode และไปที่ [opencode.ai/auth](https://opencode.ai/auth) + + ```txt + /connect + ``` + +2. ลงชื่อเข้าใช้ เพิ่มรายละเอียดการเรียกเก็บเงินของคุณ และคัดลอกรหัส API ของคุณ + +3. วางคีย์ API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. เรียกใช้ `/models` ใน TUI เพื่อดูรายการรุ่นที่เราแนะนำ + + ```txt + /models + ``` + +มันทำงานเหมือนกับผู้ให้บริการรายอื่นใน OpenCode และเป็นทางเลือกในการใช้งานโดยสมบูรณ์ + +--- + +## ไดเรกทอรี + +มาดูรายละเอียดผู้ให้บริการบางรายกัน หากคุณต้องการเพิ่มผู้ให้บริการให้กับ +รายการอย่าลังเลที่จะเปิดประชาสัมพันธ์ + +:::note +ไม่เห็นผู้ให้บริการที่นี่ใช่ไหม ส่งพีอาร์. +::: + +--- + +### 302.เอไอ + +1. ไปที่ [คอนโซล 302.AI](https://302.ai/) สร้างบัญชี และสร้างคีย์ API + +2. เรียกใช้คำสั่ง `/connect` และค้นหา **302.AI** + + ```txt + /connect + ``` + +3. ป้อนคีย์ 302.AI API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกรุ่น + + ```txt + /models + ``` + +--- + +### อเมซอน ข้อเท็จจริง + +วิธีใช้ Amazon Bedrock กับ OpenCode: + +1. ไปที่ **แค็ตตาล็อกโมเดล** ในคอนโซล Amazon Bedrock และขอ + เข้าถึงโมเดลที่คุณต้องการ + + :::tip + คุณต้องมีสิทธิ์เข้าถึงโมเดลที่คุณต้องการใน Amazon Bedrock + ::: + +2. **กำหนดค่าการตรวจสอบสิทธิ์** โดยใช้วิธีใดวิธีหนึ่งต่อไปนี้: + + #### ตัวแปรสภาพแวดล้อม (เริ่มต้นอย่างรวดเร็ว) + + ตั้งค่าหนึ่งในตัวแปรสภาพแวดล้อมเหล่านี้ขณะเรียกใช้ opencode: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + หรือเพิ่มลงในโปรไฟล์ทุบตีของคุณ: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### ไฟล์การกำหนดค่า (แนะนำ) + + สำหรับการกำหนดค่าเฉพาะโครงการหรือแบบถาวร ให้ใช้ `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **ตัวเลือกที่มี:** + - `region` - ​​AWS ภูมิภาค (เช่น `us-east-1`, `eu-west-1`) + - `profile` - ​​AWS ตั้งชื่อโปรไฟล์จาก `~/.aws/credentials` + - `endpoint` - ​​จุดสิ้นสุดที่กำหนดเอง URL สำหรับ VPC จุดสิ้นสุด (นามแฝงสำหรับตัวเลือก `baseURL` ทั่วไป) + + :::tip + ตัวเลือกไฟล์การกำหนดค่ามีความสำคัญเหนือกว่าตัวแปรสภาพแวดล้อม + ::: + + #### ขั้นสูง: VPC จุดสิ้นสุด + + หากคุณใช้จุดสิ้นสุด VPC สำหรับ Bedrock: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::note + ตัวเลือก `endpoint` เป็นนามแฝงสำหรับตัวเลือก `baseURL` ทั่วไป โดยใช้คำศัพท์เฉพาะ AWS หากมีการระบุทั้ง `endpoint` และ `baseURL` `endpoint` จะมีความสำคัญเหนือกว่า + ::: + + #### วิธีการรับรองความถูกต้อง + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: สร้างผู้ใช้ IAM และสร้างคีย์การเข้าถึงในคอนโซล AWS + - **`AWS_PROFILE`**: ใช้โปรไฟล์ที่มีชื่อจาก `~/.aws/credentials` ขั้นแรกให้กำหนดค่าด้วย `aws configure --profile my-profile` หรือ `aws sso login` + - **`AWS_BEARER_TOKEN_BEDROCK`**: สร้างคีย์ API ระยะยาวจากคอนโซล Amazon Bedrock + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: สำหรับ EKS IRSA (IAM บทบาทสำหรับบัญชีบริการ) หรือสภาพแวดล้อม Kubernetes อื่นๆ ที่มีการเชื่อมโยง OIDC Kubernetes แทรกตัวแปรสภาพแวดล้อมเหล่านี้โดยอัตโนมัติเมื่อใช้คำอธิบายประกอบของบัญชีบริการ + + #### ลำดับความสำคัญของการรับรองความถูกต้อง + + Amazon Bedrock ใช้ลำดับความสำคัญในการรับรองความถูกต้องต่อไปนี้: + 1. **Bearer Token** - `AWS_BEARER_TOKEN_BEDROCK` ตัวแปรสภาพแวดล้อมหรือโทเค็นจากคำสั่ง `/connect` + 2. **AWS Credential Chain** - โปรไฟล์, คีย์การเข้าถึง, ข้อมูลประจำตัวที่แชร์, บทบาท IAM, โทเค็นข้อมูลประจำตัวของเว็บ (EKS IRSA), ข้อมูลเมตาของอินสแตนซ์ + + :::note + เมื่อตั้งค่าโทเค็นผู้ถือ (ผ่าน `/connect` หรือ `AWS_BEARER_TOKEN_BEDROCK`) โทเค็นนั้นจะมีความสำคัญเหนือกว่าวิธีการข้อมูลประจำตัว AWS ทั้งหมด รวมถึงโปรไฟล์ที่กำหนดค่าไว้ + ::: + +3. รันคำสั่ง `/models` เพื่อเลือกรุ่นที่ต้องการ + + ```txt + /models + ``` + +:::note +สำหรับโปรไฟล์การอนุมานแบบกำหนดเอง ให้ใช้ชื่อรุ่นและผู้ให้บริการในคีย์และตั้งค่าคุณสมบัติ `id` เป็น arn สิ่งนี้ทำให้มั่นใจได้ว่าแคชถูกต้อง: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### มานุษยวิทยา + +1. เมื่อคุณสมัครแล้ว ให้รันคำสั่ง `/connect` และเลือก Anthropic + + ```txt + /connect + ``` + +2. ที่นี่คุณสามารถเลือกตัวเลือก **Claude Pro/Max** และมันจะเปิดเบราว์เซอร์ของคุณ + และขอให้คุณตรวจสอบสิทธิ์ + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. ตอนนี้โมเดล Anthropic ทั้งหมดควรจะพร้อมใช้งานเมื่อคุณใช้คำสั่ง `/models` + + ```txt + /models + ``` + +:::info +การใช้การสมัครสมาชิก Claude Pro/Max ใน OpenCode ไม่ได้รับการสนับสนุนอย่างเป็นทางการจาก [Anthropic](https://anthropic.com) +::: + +##### ใช้ปุ่ม API + +คุณยังสามารถเลือก **สร้าง API คีย์** หากคุณไม่มีการสมัครสมาชิก Pro/Max นอกจากนี้ยังจะเปิดเบราว์เซอร์ของคุณและขอให้คุณเข้าสู่ระบบ Anthropic และให้รหัสที่คุณสามารถวางในเทอร์มินัลของคุณ + +หรือหากคุณมีคีย์ API อยู่แล้ว คุณสามารถเลือก **ป้อนคีย์ API ด้วยตนเอง** และวางลงในเทอร์มินัลของคุณ + +--- + +### อาซัวร์ โอเพ่นเอไอ + +:::note +หากคุณพบข้อผิดพลาด "ฉันขอโทษ แต่ฉันไม่สามารถช่วยเหลือคำขอนั้นได้" ให้ลองเปลี่ยนตัวกรองเนื้อหาจาก **DefaultV2** เป็น **Default** ในทรัพยากร Azure ของคุณ +::: + +1. ไปที่ [พอร์ทัล Azure](https://portal.azure.com/) และสร้างทรัพยากร **Azure OpenAI** คุณจะต้องการ: + - **ชื่อทรัพยากร**: นี่จะกลายเป็นส่วนหนึ่งของจุดสิ้นสุด API ของคุณ (`https://RESOURCE_NAME.openai.azure.com/`) + - **API key**: `KEY 1` หรือ `KEY 2` จากทรัพยากรของคุณ + +2. ไปที่ [Azure AI Foundry](https://ai.azure.com/) และปรับใช้โมเดล + + :::note + ชื่อการปรับใช้จะต้องตรงกับชื่อรุ่นเพื่อให้ opencode ทำงานได้อย่างถูกต้อง + ::: + +3. เรียกใช้คำสั่ง `/connect` และค้นหา **Azure** + + ```txt + /connect + ``` + +4. ป้อน API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. ตั้งชื่อทรัพยากรของคุณเป็นตัวแปรสภาพแวดล้อม: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + หรือเพิ่มลงในโปรไฟล์ทุบตีของคุณ: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. รันคำสั่ง `/models` เพื่อเลือกโมเดลที่ปรับใช้ของคุณ + + ```txt + /models + ``` + +--- + +### บริการความรู้ความเข้าใจ Azure + +1. ไปที่ [พอร์ทัล Azure](https://portal.azure.com/) และสร้างทรัพยากร **Azure OpenAI** คุณจะต้องการ: + - **ชื่อทรัพยากร**: นี่จะกลายเป็นส่วนหนึ่งของจุดสิ้นสุด API ของคุณ (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) + - **API key**: `KEY 1` หรือ `KEY 2` จากทรัพยากรของคุณ + +2. ไปที่ [Azure AI Foundry](https://ai.azure.com/) และปรับใช้โมเดล + + :::note + ชื่อการปรับใช้จะต้องตรงกับชื่อรุ่นเพื่อให้ opencode ทำงานได้อย่างถูกต้อง + ::: + +3. เรียกใช้คำสั่ง `/connect` และค้นหา **Azure Cognitive Services** + + ```txt + /connect + ``` + +4. ป้อน API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. ตั้งชื่อทรัพยากรของคุณเป็นตัวแปรสภาพแวดล้อม: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + หรือเพิ่มลงในโปรไฟล์ทุบตีของคุณ: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. รันคำสั่ง `/models` เพื่อเลือกโมเดลที่ปรับใช้ของคุณ + + ```txt + /models + ``` + +--- + +### บาสเตน + +1. ไปที่ [Baseten](https://app.baseten.co/) สร้างบัญชี และสร้างคีย์ API + +2. รันคำสั่ง `/connect` และค้นหา **Baseten** + + ```txt + /connect + ``` + +3. ป้อนคีย์ Baseten API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกรุ่น + + ```txt + /models + ``` + +--- + +### สมอง + +1. ไปที่ [คอนโซล Cerebras](https://inference.cerebras.ai/) สร้างบัญชี และสร้างคีย์ API + +2. เรียกใช้คำสั่ง `/connect` และค้นหา **Cerebras** + + ```txt + /connect + ``` + +3. ป้อนคีย์ Cerebras API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกรุ่นเช่น _Qwen 3 Coder 480B_ + + ```txt + /models + ``` + +--- + +### เกตเวย์ AI ของ Cloudflare + +Cloudflare AI Gateway ช่วยให้คุณเข้าถึงโมเดลจาก OpenAI, Anthropic, Workers AI และอื่นๆ อีกมากมายผ่านตำแหน่งข้อมูลแบบรวม ด้วย [การเรียกเก็บเงินแบบรวม](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) คุณไม่จำเป็นต้องใช้คีย์ API แยกต่างหากสำหรับผู้ให้บริการแต่ละราย + +1. ไปที่ [แดชบอร์ด Cloudflare](https://dash.cloudflare.com/) ไปที่ **AI** > **เกตเวย์ AI** และสร้างเกตเวย์ใหม่ + +2. ตั้งค่ารหัสบัญชีและรหัสเกตเวย์ของคุณเป็นตัวแปรสภาพแวดล้อม + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. รันคำสั่ง `/connect` และค้นหา **Cloudflare AI Gateway** + + ```txt + /connect + ``` + +4. ป้อนโทเค็น Cloudflare API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + หรือตั้งเป็นตัวแปรสภาพแวดล้อม + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. รันคำสั่ง `/models` เพื่อเลือกรุ่น + + ```txt + /models + ``` + + คุณยังสามารถเพิ่มโมเดลผ่านการกำหนดค่า opencode ของคุณได้ + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### คอร์เทคส์ + +1. ไปที่ [คอนโซล Cortecs](https://cortecs.ai/) สร้างบัญชี และสร้างคีย์ API + +2. เรียกใช้คำสั่ง `/connect` และค้นหา **Cortecs** + + ```txt + /connect + ``` + +3. ป้อนคีย์ Cortecs API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกโมเดลเช่น _Kimi K2 Instruct_ + + ```txt + /models + ``` + +--- + +### ดีปซีค + +1. ไปที่ [คอนโซล DeepSeek](https://platform.deepseek.com/) สร้างบัญชี แล้วคลิก **สร้างคีย์ API ใหม่** + +2. รันคำสั่ง `/connect` และค้นหา **DeepSeek** + + ```txt + /connect + ``` + +3. ป้อนคีย์ DeepSeek API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกโมเดล DeepSeek เช่น _DeepSeek Reasoner_ + + ```txt + /models + ``` + +--- + +### อินฟราเรดลึก + +1. ไปที่ [แดชบอร์ด Deep Infra](https://deepinfra.com/dash) สร้างบัญชี และสร้างคีย์ API + +2. เรียกใช้คำสั่ง `/connect` และค้นหา **Deep Infra** + + ```txt + /connect + ``` + +3. ป้อนคีย์ Deep Infra API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกรุ่น + + ```txt + /models + ``` + +--- + +### เฟิร์มแวร์ + +1. ไปที่ [แดชบอร์ดเฟิร์มแวร์](https://app.firmware.ai/signup) สร้างบัญชี และสร้างคีย์ API + +2. เรียกใช้คำสั่ง `/connect` และค้นหา **เฟิร์มแวร์** + + ```txt + /connect + ``` + +3. ป้อนคีย์เฟิร์มแวร์ API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกรุ่น + + ```txt + /models + ``` + +--- + +### ดอกไม้ไฟเอไอ + +1. ไปที่ [คอนโซล AI ดอกไม้ไฟ](https://app.fireworks.ai/) สร้างบัญชี แล้วคลิก **สร้าง API คีย์** + +2. รันคำสั่ง `/connect` และค้นหา **Fireworks AI** + + ```txt + /connect + ``` + +3. ป้อนคีย์ดอกไม้ไฟ AI API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกโมเดลเช่น _Kimi K2 Instruct_ + + ```txt + /models + ``` + +--- + +### GitLab ดูโอ + +GitLab Duo ให้การแชทแบบเอเจนต์ที่ขับเคลื่อนด้วย AI พร้อมความสามารถในการเรียกใช้เครื่องมือแบบเนทีฟผ่านพร็อกซี Anthropic ของ GitLab + +1. รันคำสั่ง `/connect` และเลือก GitLab + + ```txt + /connect + ``` + +2. เลือกวิธีการรับรองความถูกต้องของคุณ: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### การใช้ OAuth (แนะนำ) + + เลือก **OAuth** และเบราว์เซอร์ของคุณจะเปิดขึ้นเพื่อรับสิทธิ์ + + #### การใช้โทเค็นการเข้าถึงส่วนบุคคล + 1. ไปที่ [การตั้งค่าผู้ใช้ GitLab > โทเค็นการเข้าถึง](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. คลิก **เพิ่มโทเค็นใหม่** + 3. ชื่อ: `OpenCode`, ขอบเขต: `api` + 4. คัดลอกโทเค็น (เริ่มต้นด้วย `glpat-`) + 5. ป้อนลงในเทอร์มินัล + +3. รันคำสั่ง `/models` เพื่อดูรุ่นที่มีจำหน่าย + + ```txt + /models + ``` + + มีโมเดลที่ใช้ Claude สามรุ่นให้เลือก: + - **duo-chat-haiku-4-5** (ค่าเริ่มต้น) - ตอบสนองรวดเร็วสำหรับงานด่วน + - **duo-chat-sonnet-4-5** - ประสิทธิภาพที่สมดุลสำหรับขั้นตอนการทำงานส่วนใหญ่ + - **duo-chat-opus-4-5** - มีความสามารถมากที่สุดสำหรับการวิเคราะห์ที่ซับซ้อน + +:::note +คุณยังสามารถระบุตัวแปรสภาพแวดล้อม 'GITLAB_TOKEN' ได้หากคุณไม่ต้องการ +เพื่อจัดเก็บโทเค็นในที่เก็บข้อมูลการรับรองความถูกต้องของ opencode +::: + +##### GitLab ที่โฮสต์เอง + +:::note[บันทึกการปฏิบัติตาม] +OpenCode ใช้โมเดลขนาดเล็กสำหรับงาน AI บางอย่าง เช่น การสร้างชื่อเซสชัน +มีการกำหนดค่าให้ใช้ gpt-5-nano ตามค่าเริ่มต้น ซึ่งโฮสต์โดย Zen เพื่อล็อค OpenCode +หากต้องการใช้เฉพาะอินสแตนซ์ที่โฮสต์บน GitLab ของคุณเอง ให้เพิ่มสิ่งต่อไปนี้ในของคุณ +`opencode.json` ไฟล์. ขอแนะนำให้ปิดใช้งานการแชร์เซสชันด้วย + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +สำหรับอินสแตนซ์ GitLab ที่โฮสต์เอง: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +หากอินสแตนซ์ของคุณใช้งาน AI Gateway แบบกำหนดเอง: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +หรือเพิ่มในโปรไฟล์ทุบตีของคุณ: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +ผู้ดูแลระบบ GitLab ของคุณต้องเปิดใช้งานสิ่งต่อไปนี้: + +1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) สำหรับผู้ใช้ กลุ่ม หรืออินสแตนซ์ +2. แฟล็กคุณลักษณะ (ผ่านคอนโซล Rails): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### OAuth สำหรับอินสแตนซ์ที่โฮสต์เอง + +คุณต้องสร้างเพื่อให้ Oauth ทำงานกับอินสแตนซ์ที่โฮสต์เองได้ +แอพพลิเคชั่นใหม่ (Settings → Applications) ด้วย +โทรกลับ URL `http://127.0.0.1:8080/callback` และขอบเขตต่อไปนี้: + +- api (เข้าถึง API ในนามของคุณ) +- read_user (อ่านข้อมูลส่วนตัวของคุณ) +- read_repository (อนุญาตให้เข้าถึงที่เก็บแบบอ่านอย่างเดียว) + +จากนั้นเปิดเผย ID แอปพลิเคชันเป็นตัวแปรสภาพแวดล้อม: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +เอกสารประกอบเพิ่มเติมเกี่ยวกับหน้าแรกของ [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth) + +##### การกำหนดค่า + +ปรับแต่งผ่าน `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API Tools (เป็นทางเลือก แต่แนะนำเป็นอย่างยิ่ง) + +วิธีเข้าถึงเครื่องมือ GitLab (รวมคำขอ ปัญหา ไปป์ไลน์ CI/CD ฯลฯ): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +ปลั๊กอินนี้มอบความสามารถในการจัดการพื้นที่เก็บข้อมูล GitLab ที่ครอบคลุม รวมถึงการตรวจสอบ MR การติดตามปัญหา การตรวจสอบไปป์ไลน์ และอื่นๆ + +--- + +### นักบิน GitHub + +วิธีใช้การสมัครสมาชิก GitHub Copilot ด้วย opencode: + +:::note +บางรุ่นอาจต้องมี [Pro+ +สมัครสมาชิก](https://github.com/features/copilot/plans) เพื่อใช้งาน + +บางรุ่นจำเป็นต้องเปิดใช้งานด้วยตนเองใน [การตั้งค่า GitHub Copilot](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use) +::: + +1. รันคำสั่ง `/connect` และค้นหา GitHub Copilot + + ```txt + /connect + ``` + +2. ไปที่ [github.com/login/device](https://github.com/login/device) และป้อนรหัส + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. ตอนนี้รันคำสั่ง `/models` เพื่อเลือกรุ่นที่คุณต้องการ + + ```txt + /models + ``` + +--- + +### กูเกิล เวอร์เท็กซ์ เอไอ + +วิธีใช้ Google Vertex AI กับ OpenCode: + +1. ไปที่ **Model Garden** ใน Google Cloud Console แล้วตรวจสอบ + รุ่นที่มีในภูมิภาคของคุณ + + :::note + คุณต้องมีโปรเจ็กต์ Google Cloud ที่เปิดใช้งาน Vertex AI API + ::: + +2. ตั้งค่าตัวแปรสภาพแวดล้อมที่ต้องการ: + - `GOOGLE_CLOUD_PROJECT`: รหัสโครงการ Google Cloud ของคุณ + - `VERTEX_LOCATION` (เป็นทางเลือก): ภูมิภาคสำหรับ Vertex AI (ค่าเริ่มต้นคือ `global`) + - การรับรองความถูกต้อง (เลือกหนึ่งรายการ): + - `GOOGLE_APPLICATION_CREDENTIALS`: เส้นทางไปยังบัญชีบริการของคุณ JSON ไฟล์คีย์ + - ตรวจสอบสิทธิ์โดยใช้ gcloud CLI: `gcloud auth application-default login` + + ตั้งค่าในขณะที่เรียกใช้ opencode + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + หรือเพิ่มลงในโปรไฟล์ทุบตีของคุณ + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::tip +ภูมิภาค `global` ปรับปรุงความพร้อมใช้งานและลดข้อผิดพลาดโดยไม่มีค่าใช้จ่ายเพิ่มเติม ใช้ตำแหน่งข้อมูลระดับภูมิภาค (เช่น `us-central1`) สำหรับข้อกำหนดด้านถิ่นที่อยู่ของข้อมูล [เรียนรู้เพิ่มเติม](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. รันคำสั่ง `/models` เพื่อเลือกรุ่นที่ต้องการ + + ```txt + /models + ``` + +--- + +### กร็อก + +1. ไปที่ [คอนโซล Groq](https://console.groq.com/) คลิก **สร้าง API คีย์** และคัดลอกคีย์ + +2. เรียกใช้คำสั่ง `/connect` และค้นหา Groq + + ```txt + /connect + ``` + +3. ป้อนคีย์ API สำหรับผู้ให้บริการ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกคำสั่งที่คุณต้องการ + + ```txt + /models + ``` + +--- + +### กอดหน้า + +[ผู้ให้บริการการอนุมานใบหน้าแบบกอด](https://huggingface.co/docs/inference-providers) ช่วยให้สามารถเข้าถึงโมเดลแบบเปิดที่รองรับโดยผู้ให้บริการมากกว่า 17 ราย + +1. ไปที่ [การตั้งค่าการกอดใบหน้า](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) เพื่อสร้างโทเค็นที่มีสิทธิ์ในการโทรไปยังผู้ให้บริการการอนุมาน + +2. เรียกใช้คำสั่ง `/connect` และค้นหา **Hugging Face** + + ```txt + /connect + ``` + +3. ป้อนโทเค็น Hugging Face ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกโมเดล เช่น _Kimi-K2-Instruct_ หรือ _GLM-4.6_ + + ```txt + /models + ``` + +--- + +### เฮลิโคน + +[Helicone](https://helicone.ai) เป็นแพลตฟอร์มการติดตาม LLM ที่ให้การบันทึก การตรวจสอบ และการวิเคราะห์สำหรับแอปพลิเคชัน AI ของคุณ Helicone AI Gateway กำหนดเส้นทางคำขอของคุณไปยังผู้ให้บริการที่เหมาะสมโดยอัตโนมัติตามรุ่น + +1. ไปที่ [Helicone](https://helicone.ai) สร้างบัญชี และสร้างคีย์ API จากแดชบอร์ดของคุณ + +2. รันคำสั่ง `/connect` และค้นหา **Helicone** + + ```txt + /connect + ``` + +3. ป้อนคีย์ Helicone API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกรุ่น + + ```txt + /models + ``` + +หากต้องการทราบผู้ให้บริการเพิ่มเติมและฟีเจอร์ขั้นสูง เช่น การแคชและการจำกัดอัตรา โปรดตรวจสอบ [เอกสารประกอบของ Helicone](https://docs.helicone.ai) + +#### การกำหนดค่าเพิ่มเติม + +ในกรณีที่คุณเห็นคุณสมบัติหรือรุ่นจาก Helicone ที่ไม่ได้กำหนดค่าโดยอัตโนมัติผ่าน opencode คุณสามารถกำหนดค่าด้วยตนเองได้ตลอดเวลา + +นี่คือ [Helicone's Model Directory](https://helicone.ai/models) คุณจะต้องใช้สิ่งนี้เพื่อรับ ID ของโมเดลที่คุณต้องการเพิ่ม + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### ส่วนหัวที่กำหนดเอง + +Helicone รองรับส่วนหัวแบบกำหนดเองสำหรับฟีเจอร์ต่างๆ เช่น การแคช การติดตามผู้ใช้ และการจัดการเซสชัน เพิ่มลงในการกำหนดค่าผู้ให้บริการของคุณโดยใช้ `options.headers`: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### การติดตามเซสชัน + +คุณลักษณะ [เซสชัน](https://docs.helicone.ai/features/sessions) ของ Helicone ช่วยให้คุณสามารถจัดกลุ่มคำขอ LLM ที่เกี่ยวข้องเข้าด้วยกันได้ ใช้ปลั๊กอิน [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) เพื่อบันทึกการสนทนา OpenCode แต่ละรายการเป็นเซสชันใน Helicone โดยอัตโนมัติ + +```bash +npm install -g opencode-helicone-session +``` + +เพิ่มลงในการกำหนดค่าของคุณ + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +ปลั๊กอินจะแทรกส่วนหัว `Helicone-Session-Id` และ `Helicone-Session-Name` ลงในคำขอของคุณ ในหน้าเซสชันของ Helicone คุณจะเห็นการสนทนา OpenCode แต่ละรายการแยกเป็นเซสชันแยกกัน + +##### ส่วนหัวของ Helicone ทั่วไป + +| ส่วนหัว | คำอธิบาย | +| -------------------------- | ------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | เปิดใช้งานการแคชการตอบกลับ (`true`/@@1@@) | +| `Helicone-User-Id` | ติดตามตัวชี้วัดตามผู้ใช้ | +| `Helicone-Property-[Name]` | เพิ่มคุณสมบัติที่กำหนดเอง (เช่น `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | เชื่อมโยงคำขอกับเวอร์ชันพร้อมท์ | + +ดู [Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory) สำหรับส่วนหัวที่มีอยู่ทั้งหมด + +--- + +### llama.cpp + +คุณสามารถกำหนดค่า opencode เพื่อใช้โมเดลท้องถิ่นผ่านยูทิลิตี้ [llama.cpp's](https://github.com/ggml-org/llama.cpp) llama-server + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +ในตัวอย่างนี้: + +- `llama.cpp` คือ ID ผู้ให้บริการที่กำหนดเอง นี่อาจเป็นสตริงใดก็ได้ที่คุณต้องการ +- `npm` ระบุแพ็คเกจที่จะใช้สำหรับผู้ให้บริการรายนี้ ในที่นี้ `@ai-sdk/openai-compatible` ใช้สำหรับ API ที่เข้ากันได้กับ OpenAI +- `name` คือชื่อที่แสดงของผู้ให้บริการใน UI +- `options.baseURL` เป็นจุดสิ้นสุดสำหรับเซิร์ฟเวอร์ภายในเครื่อง +- `models` คือแมปของ ID โมเดลกับการกำหนดค่า ชื่อรุ่นจะปรากฏในรายการเลือกรุ่น + +--- + +### ไอโอ.NET + +IO.NET มี 17 โมเดลที่ได้รับการปรับให้เหมาะกับการใช้งานที่หลากหลาย: + +1. ไปที่ [IO.NET console](https://ai.io.net/) สร้างบัญชี และสร้างคีย์ API + +2. รันคำสั่ง `/connect` และค้นหา **IO.NET** + + ```txt + /connect + ``` + +3. ป้อนคีย์ IO.NET API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกรุ่น + + ```txt + /models + ``` + +--- + +### แอลเอ็ม สตูดิโอ + +คุณสามารถกำหนดค่า opencode เพื่อใช้โมเดลท้องถิ่นผ่าน LM Studio + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +ในตัวอย่างนี้: + +- `lmstudio` คือ ID ผู้ให้บริการที่กำหนดเอง นี่อาจเป็นสตริงใดก็ได้ที่คุณต้องการ +- `npm` ระบุแพ็คเกจที่จะใช้สำหรับผู้ให้บริการรายนี้ ในที่นี้ `@ai-sdk/openai-compatible` ใช้สำหรับ API ที่เข้ากันได้กับ OpenAI +- `name` คือชื่อที่แสดงของผู้ให้บริการใน UI +- `options.baseURL` เป็นจุดสิ้นสุดสำหรับเซิร์ฟเวอร์ภายในเครื่อง +- `models` คือแมปของ ID โมเดลกับการกำหนดค่า ชื่อรุ่นจะปรากฏในรายการเลือกรุ่น + +--- + +### มูนช็อตเอไอ + +วิธีใช้ Kimi K2 จาก Moonshot AI: + +1. ไปที่ [Moonshot AI console](https://platform.moonshot.ai/console) สร้างบัญชี แล้วคลิก **สร้าง API คีย์** + +2. รันคำสั่ง `/connect` และค้นหา **Moonshot AI** + + ```txt + /connect + ``` + +3. ป้อนคีย์ Moonshot API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือก _Kimi K2_ + + ```txt + /models + ``` + +--- + +### มินิแม็กซ์ + +1. ไปที่ [MiniMax API Console](https://platform.minimax.io/login) สร้างบัญชี และสร้างคีย์ API + +2. เรียกใช้คำสั่ง `/connect` และค้นหา **MiniMax** + + ```txt + /connect + ``` + +3. ป้อนคีย์ MiniMax API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกรุ่นเช่น _M2.1_ + + ```txt + /models + ``` + +--- + +### โรงงานโทเค็นเนบิอุส + +1. ไปที่ [คอนโซล Nebius Token Factory](https://tokenfactory.nebius.com/) สร้างบัญชี แล้วคลิก **เพิ่มรหัส** + +2. รันคำสั่ง `/connect` และค้นหา **Nebius Token Factory** + + ```txt + /connect + ``` + +3. ป้อนคีย์ Nebius Token Factory API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกโมเดลเช่น _Kimi K2 Instruct_ + + ```txt + /models + ``` + +--- + +### โอลามา + +คุณสามารถกำหนดค่า opencode เพื่อใช้โมเดลท้องถิ่นผ่าน Ollama + +:::tip +Ollama สามารถกำหนดค่าตัวเองสำหรับ OpenCode ได้โดยอัตโนมัติ ดู [เอกสารการบูรณาการ Ollama](https://docs.ollama.com/integrations/opencode) เพื่อดูรายละเอียด +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +ในตัวอย่างนี้: + +- `ollama` คือ ID ผู้ให้บริการที่กำหนดเอง นี่อาจเป็นสตริงใดก็ได้ที่คุณต้องการ +- `npm` ระบุแพ็คเกจที่จะใช้สำหรับผู้ให้บริการรายนี้ ในที่นี้ `@ai-sdk/openai-compatible` ใช้สำหรับ API ที่เข้ากันได้กับ OpenAI +- `name` คือชื่อที่แสดงของผู้ให้บริการใน UI +- `options.baseURL` เป็นจุดสิ้นสุดสำหรับเซิร์ฟเวอร์ภายในเครื่อง +- `models` คือแมปของ ID โมเดลกับการกำหนดค่า ชื่อรุ่นจะปรากฏในรายการเลือกรุ่น + +:::tip +หากการเรียกใช้เครื่องมือไม่ทำงาน ให้ลองเพิ่ม `num_ctx` ใน Ollama เริ่มต้นประมาณ 16,000 - 32,000 +::: + +--- + +### โอลามา คลาวด์ + +วิธีใช้ Ollama Cloud กับ OpenCode: + +1. ไปที่ [https://ollama.com/](https://ollama.com/) แล้วลงชื่อเข้าใช้หรือสร้างบัญชี + +2. ไปที่ **การตั้งค่า** > **คีย์** แล้วคลิก **เพิ่ม API คีย์** เพื่อสร้างคีย์ API ใหม่ + +3. คัดลอกคีย์ API เพื่อใช้ใน OpenCode + +4. เรียกใช้คำสั่ง `/connect` และค้นหา **Ollama Cloud** + + ```txt + /connect + ``` + +5. ป้อนคีย์ Ollama Cloud API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **สำคัญ**: ก่อนที่จะใช้โมเดลคลาวด์ใน OpenCode คุณต้องดึงข้อมูลโมเดลในเครื่อง: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. รันคำสั่ง `/models` เพื่อเลือกโมเดล Ollama Cloud ของคุณ + + ```txt + /models + ``` + +--- + +### OpenAI + +เราขอแนะนำให้สมัคร [ChatGPT Plus หรือ Pro](https://chatgpt.com/pricing) + +1. เมื่อคุณสมัครแล้ว ให้รันคำสั่ง `/connect` และเลือก OpenAI + + ```txt + /connect + ``` + +2. ที่นี่คุณสามารถเลือกตัวเลือก **ChatGPT Plus/Pro** จากนั้นเบราว์เซอร์จะเปิดขึ้นมา + และขอให้คุณตรวจสอบสิทธิ์ + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. ตอนนี้โมเดล OpenAI ทั้งหมดควรจะพร้อมใช้งานเมื่อคุณใช้คำสั่ง `/models` + + ```txt + /models + ``` + +##### ใช้ปุ่ม API + +หากคุณมีคีย์ API อยู่แล้ว คุณสามารถเลือก **ป้อนคีย์ API ด้วยตนเอง** และวางลงในเทอร์มินัลของคุณ + +--- + +### โอเพ่นโค้ดเซน + +OpenCode Zen คือรายการโมเดลที่ได้รับการทดสอบและตรวจสอบแล้วโดยทีมงาน OpenCode [เรียนรู้เพิ่มเติม](/docs/zen) + +1. ลงชื่อเข้าใช้ **OpenCode Zen** และคลิก **สร้าง API คีย์** + +2. เรียกใช้คำสั่ง `/connect` และค้นหา **OpenCode Zen** + + ```txt + /connect + ``` + +3. ป้อนคีย์ OpenCode API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกรุ่นเช่น _Qwen 3 Coder 480B_ + + ```txt + /models + ``` + +--- + +### เปิดเราเตอร์ + +1. ไปที่ [แดชบอร์ด OpenRouter](https://openrouter.ai/settings/keys) คลิก **สร้าง API คีย์** และคัดลอกคีย์ + +2. เรียกใช้คำสั่ง `/connect` และค้นหา OpenRouter + + ```txt + /connect + ``` + +3. ป้อนคีย์ API สำหรับผู้ให้บริการ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. OpenRouter หลายรุ่นถูกโหลดไว้ล่วงหน้าตามค่าเริ่มต้น ให้รันคำสั่ง `/models` เพื่อเลือกรุ่นที่คุณต้องการ + + ```txt + /models + ``` + + คุณยังสามารถเพิ่มโมเดลเพิ่มเติมผ่านการกำหนดค่า opencode ของคุณ + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. คุณยังสามารถปรับแต่งได้ผ่านการกำหนดค่า opencode ของคุณ นี่คือตัวอย่างการระบุผู้ให้บริการ + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP เอไอคอร์ + +SAP AI Core ให้การเข้าถึงโมเดลมากกว่า 40 โมเดลจาก OpenAI, Anthropic, Google, Amazon, Meta, Mistral และ AI21 ผ่านแพลตฟอร์มแบบครบวงจร + +1. ไปที่ห้องนักบิน [SAP BTP](https://account.hana.ondemand.com/) นำทางไปยังอินสแตนซ์บริการ SAP AI Core ของคุณ และสร้างรหัสบริการ + + :::tip + รหัสบริการคือวัตถุ JSON ที่ประกอบด้วย `clientid`, `clientsecret`, `url` และ `serviceurls.AI_API_URL` คุณสามารถค้นหาอินสแตนซ์ AI Core ของคุณได้ภายใต้ **บริการ** > **อินสแตนซ์และการสมัครสมาชิก** ในห้องควบคุม BTP + ::: + +2. รันคำสั่ง `/connect` และค้นหา **SAP AI Core** + + ```txt + /connect + ``` + +3. ป้อนรหัสบริการของคุณ JSON + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + หรือตั้งค่าตัวแปรสภาพแวดล้อม `AICORE_SERVICE_KEY`: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + หรือเพิ่มลงในโปรไฟล์ทุบตีของคุณ: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. ตั้งค่า ID การนำไปใช้งานและกลุ่มทรัพยากรเพิ่มเติม: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::note + การตั้งค่าเหล่านี้เป็นทางเลือกและควรกำหนดค่าตามการตั้งค่า SAP AI Core ของคุณ + ::: + +5. รันคำสั่ง `/models` เพื่อเลือกจากรุ่นที่มีให้เลือกมากกว่า 40 รุ่น + + ```txt + /models + ``` + +--- + +### ตำแหน่งข้อมูล AI ของ OVHcloud + +1. ไปที่ [แผง OVHcloud](https://ovh.com/manager) ไปที่ส่วน `Public Cloud` `AI & Machine Learning` > `AI Endpoints` และในแท็บ `API Keys` คลิก **สร้างคีย์ API ใหม่** + +2. รันคำสั่ง `/connect` และค้นหา **OVHcloud AI Endpoints** + + ```txt + /connect + ``` + +3. ป้อนคีย์ OVHcloud AI Endpoints API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกโมเดลเช่น _gpt-oss-120b_ + + ```txt + /models + ``` + +--- + +### สเกลเวย์ + +วิธีใช้ [Scaleway Generative API](https://www.scaleway.com/en/docs/generative-apis/) กับ Opencode: + +1. ไปที่ [การตั้งค่า Scaleway Console IAM](https://console.scaleway.com/iam/api-keys) เพื่อสร้างคีย์ API ใหม่ + +2. รันคำสั่ง `/connect` และค้นหา **Scaleway** + + ```txt + /connect + ``` + +3. ป้อนคีย์ Scaleway API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกโมเดล เช่น _devstral-2-123b-instruct-2512_ หรือ _gpt-oss-120b_ + + ```txt + /models + ``` + +--- + +### ร่วมกันเอไอ + +1. ไปที่ [Together AI console](https://api.together.ai) สร้างบัญชี แล้วคลิก **เพิ่มรหัส** + +2. เรียกใช้คำสั่ง `/connect` และค้นหา **Together AI** + + ```txt + /connect + ``` + +3. ป้อนคีย์ Together AI API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกโมเดลเช่น _Kimi K2 Instruct_ + + ```txt + /models + ``` + +--- + +### เวนิส เอไอ + +1. ไปที่ [คอนโซล AI ของเวนิส](https://venice.ai) สร้างบัญชี และสร้างคีย์ API + +2. รันคำสั่ง `/connect` และค้นหา **Venice AI** + + ```txt + /connect + ``` + +3. ป้อนคีย์ Venice AI API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกโมเดลเช่น _Llama 3.3 70B_ + + ```txt + /models + ``` + +--- + +### เกตเวย์ AI ของ Vercel + +Vercel AI Gateway ช่วยให้คุณเข้าถึงโมเดลจาก OpenAI, Anthropic, Google, xAI และอื่นๆ อีกมากมายผ่านจุดสิ้นสุดแบบรวม โมเดลมีจำหน่ายในราคาปลีกโดยไม่มีส่วนเพิ่ม + +1. ไปที่ [แดชบอร์ด Vercel](https://vercel.com/) ไปที่แท็บ **เกตเวย์ AI** และคลิก **API คีย์** เพื่อสร้างคีย์ API ใหม่ + +2. รันคำสั่ง `/connect` และค้นหา **Vercel AI Gateway** + + ```txt + /connect + ``` + +3. ป้อนคีย์ Vercel AI Gateway API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกรุ่น + + ```txt + /models + ``` + +คุณยังสามารถปรับแต่งโมเดลผ่านการกำหนดค่า opencode ของคุณได้อีกด้วย นี่คือตัวอย่างการระบุลำดับการกำหนดเส้นทางของผู้ให้บริการ + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +ตัวเลือกการกำหนดเส้นทางที่มีประโยชน์: + +| ตัวเลือก | คำอธิบาย | +| ------------------- | ---------------------------------------------------- | +| `order` | ลำดับผู้ให้บริการที่จะลอง | +| `only` | จำกัดเฉพาะผู้ให้บริการบางราย | +| `zeroDataRetention` | ใช้ผู้ให้บริการที่ไม่มีนโยบายการเก็บรักษาข้อมูลเท่านั้น | + +--- + +### xAI + +1. ไปที่ [xAI console](https://console.x.ai/) สร้างบัญชี และสร้างคีย์ API + +2. รันคำสั่ง `/connect` และค้นหา **xAI** + + ```txt + /connect + ``` + +3. ป้อนคีย์ xAI API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกโมเดลเช่น _Grok Beta_ + + ```txt + /models + ``` + +--- + +### ซี.เอ.ไอ + +1. ไปที่ [Z.AI API console](https://z.ai/manage-apikey/apikey-list) สร้างบัญชี และคลิก **สร้างคีย์ API ใหม่** + +2. รันคำสั่ง `/connect` และค้นหา **Z.AI** + + ```txt + /connect + ``` + + หากคุณสมัครสมาชิก **GLM Coding Plan** ให้เลือก **Z.AI Coding Plan** + +3. ป้อนคีย์ Z.AI API ของคุณ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. รันคำสั่ง `/models` เพื่อเลือกโมเดลเช่น _GLM-4.7_ + + ```txt + /models + ``` + +--- + +### ZenMux + +1. ไปที่ [แดชบอร์ด ZenMux](https://zenmux.ai/settings/keys) คลิก **สร้าง API คีย์** และคัดลอกคีย์ + +2. รันคำสั่ง `/connect` และค้นหา ZenMux + + ```txt + /connect + ``` + +3. ป้อนคีย์ API สำหรับผู้ให้บริการ + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. ZenMux หลายรุ่นถูกโหลดไว้ล่วงหน้าตามค่าเริ่มต้น รันคำสั่ง `/models` เพื่อเลือกรุ่นที่คุณต้องการ + + ```txt + /models + ``` + + คุณยังสามารถเพิ่มโมเดลเพิ่มเติมผ่านการกำหนดค่า opencode ของคุณ + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## ผู้ให้บริการที่กำหนดเอง + +หากต้องการเพิ่มผู้ให้บริการ **รองรับ OpenAI** ที่ไม่อยู่ในคำสั่ง `/connect`: + +:::tip +คุณสามารถใช้ผู้ให้บริการที่เข้ากันได้กับ OpenAI ด้วย opencode ผู้ให้บริการ AI สมัยใหม่ส่วนใหญ่เสนอ API ที่เข้ากันได้กับ OpenAI +::: + +1. เรียกใช้คำสั่ง `/connect` และเลื่อนลงไปที่ **อื่นๆ** + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. ป้อนรหัสเฉพาะสำหรับผู้ให้บริการ + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note + เลือก ID ที่น่าจดจำ คุณจะใช้รหัสนี้ในไฟล์กำหนดค่าของคุณ + ::: + +3. ป้อนรหัส API ของคุณสำหรับผู้ให้บริการ + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. สร้างหรืออัปเดตไฟล์ `opencode.json` ในไดเรกทอรีโครงการของคุณ: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + นี่คือตัวเลือกการกำหนดค่า: + - **npm**: แพ็คเกจ AI SDK ที่จะใช้ `@ai-sdk/openai-compatible` สำหรับผู้ให้บริการที่เข้ากันได้กับ OpenAI + - **ชื่อ**: ชื่อที่แสดงใน UI + - **รุ่น**: รุ่นที่มีจำหน่าย + - **options.baseURL**: API ปลายทาง URL + - **options.apiKey**: ตั้งค่าคีย์ API หรือไม่ก็ได้ หากไม่ได้ใช้การตรวจสอบสิทธิ์ + - **options.headers**: ตั้งค่าส่วนหัวที่กำหนดเองหรือไม่ก็ได้ + + ข้อมูลเพิ่มเติมเกี่ยวกับตัวเลือกขั้นสูงในตัวอย่างด้านล่าง + +5. รันคำสั่ง `/models` จากนั้นผู้ให้บริการและโมเดลที่คุณกำหนดเองจะปรากฏในรายการตัวเลือก + +--- + +##### ตัวอย่าง + +นี่คือตัวอย่างการตั้งค่าตัวเลือก `apiKey`, `headers` และโมเดล `limit` + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +รายละเอียดการกำหนดค่า: + +- **apiKey**: ตั้งค่าโดยใช้ไวยากรณ์ของตัวแปร `env` [เรียนรู้เพิ่มเติม](/docs/config#env-vars) +- **ส่วนหัว**: ส่วนหัวที่กำหนดเองส่งไปพร้อมกับคำขอแต่ละรายการ +- **limit.context**: โทเค็นอินพุตสูงสุดที่โมเดลยอมรับ +- **limit.output**: โทเค็นสูงสุดที่โมเดลสามารถสร้างได้ + +ช่อง `limit` ช่วยให้ OpenCode เข้าใจบริบทที่คุณเหลืออยู่ ผู้ให้บริการมาตรฐานจะดึงข้อมูลเหล่านี้จาก models.dev โดยอัตโนมัติ + +--- + +## การแก้ไขปัญหา + +หากคุณประสบปัญหาในการกำหนดค่าผู้ให้บริการ ให้ตรวจสอบสิ่งต่อไปนี้: + +1. **ตรวจสอบการตั้งค่าการรับรองความถูกต้อง**: เรียกใช้ `opencode auth list` เพื่อดูว่ามีข้อมูลรับรองหรือไม่ + สำหรับผู้ให้บริการจะถูกเพิ่มในการกำหนดค่าของคุณ + + สิ่งนี้ใช้ไม่ได้กับผู้ให้บริการอย่าง Amazon Bedrock ที่ต้องอาศัยตัวแปรสภาพแวดล้อมสำหรับการตรวจสอบสิทธิ์ + +2. สำหรับผู้ให้บริการแบบกำหนดเอง ให้ตรวจสอบการกำหนดค่า opencode และ: + - ตรวจสอบให้แน่ใจว่า ID ผู้ให้บริการที่ใช้ในคำสั่ง `/connect` ตรงกับ ID ในการกำหนดค่า opencode ของคุณ + - มีการใช้แพ็คเกจ npm ที่ถูกต้องสำหรับผู้ให้บริการ ตัวอย่างเช่น ใช้ `@ai-sdk/cerebras` สำหรับ Cerebras และสำหรับผู้ให้บริการรายอื่นที่เข้ากันได้กับ OpenAI ให้ใช้ `@ai-sdk/openai-compatible` + - ตรวจสอบว่ามีการใช้จุดสิ้นสุด API ที่ถูกต้องในช่อง `options.baseURL` diff --git a/packages/web/src/content/docs/th/rules.mdx b/packages/web/src/content/docs/th/rules.mdx new file mode 100644 index 000000000..ba521a405 --- /dev/null +++ b/packages/web/src/content/docs/th/rules.mdx @@ -0,0 +1,180 @@ +--- +title: กฎ +description: ตั้งค่าคำแนะนำที่กำหนดเองสำหรับ opencode +--- + +คุณสามารถให้คำแนะนำที่กำหนดเองแก่ opencode ได้โดยการสร้างไฟล์ `AGENTS.md` ซึ่งคล้ายกับกฎของเคอร์เซอร์ ประกอบด้วยคำแนะนำที่จะรวมอยู่ในบริบทของ LLM เพื่อปรับแต่งลักษณะการทำงานสำหรับโครงการเฉพาะของคุณ + +--- + +## เริ่มต้น + +หากต้องการสร้างไฟล์ `AGENTS.md` ใหม่ คุณสามารถเรียกใช้คำสั่ง `/init` ใน opencode + +:::tip +คุณควรคอมมิตไฟล์ `AGENTS.md` ของโปรเจ็กต์ของคุณไปที่ Git +::: + +การดำเนินการนี้จะสแกนโปรเจ็กต์ของคุณและเนื้อหาทั้งหมดเพื่อทำความเข้าใจว่าโปรเจ็กต์เกี่ยวกับอะไร และสร้างไฟล์ `AGENTS.md` ด้วย สิ่งนี้ช่วยให้ opencode นำทางโครงการได้ดีขึ้น + +หากคุณมีไฟล์ `AGENTS.md` อยู่แล้ว ระบบจะพยายามเพิ่มไฟล์ดังกล่าว + +--- + +## ตัวอย่าง + +คุณสามารถสร้างไฟล์นี้ด้วยตนเองได้ นี่คือตัวอย่างบางสิ่งที่คุณสามารถใส่ลงในไฟล์ `AGENTS.md` + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +เรากำลังเพิ่มคำแนะนำเฉพาะโครงการที่นี่ และจะมีการแชร์กับทีมของคุณ + +--- + +## ประเภท + +opencode ยังรองรับการอ่านไฟล์ `AGENTS.md` จากหลาย ๆ ที่ และสิ่งนี้มีจุดประสงค์ที่แตกต่างกัน + +### โครงการ + +วาง `AGENTS.md` ในรูทโปรเจ็กต์ของคุณสำหรับกฎเฉพาะโปรเจ็กต์ สิ่งเหล่านี้ใช้เฉพาะเมื่อคุณทำงานในไดเร็กทอรีนี้หรือไดเร็กทอรีย่อยเท่านั้น + +### ทั่วโลก + +คุณยังสามารถมีกฎสากลในไฟล์ `~/.config/opencode/AGENTS.md` สิ่งนี้จะนำไปใช้กับเซสชัน opencode ทั้งหมด + +เนื่องจากสิ่งนี้ไม่ได้ผูกมัดกับ Git หรือแชร์กับทีมของคุณ เราขอแนะนำให้ใช้สิ่งนี้เพื่อระบุกฎส่วนบุคคลที่ LLM ควรปฏิบัติตาม + +### ความเข้ากันได้ของรหัส Claude + +สำหรับผู้ใช้ที่ย้ายจาก Claude Code นั้น OpenCode รองรับรูปแบบไฟล์ของ Claude Code เป็นทางเลือก: + +- **กฎของโครงการ**: `CLAUDE.md` ในไดเรกทอรีโครงการของคุณ (ใช้หากไม่มี `AGENTS.md`) +- **กฎสากล**: `~/.claude/CLAUDE.md` (ใช้หากไม่มี `~/.config/opencode/AGENTS.md`) +- **ทักษะ**: `~/.claude/skills/` — ดูรายละเอียด [ทักษะตัวแทน](/docs/skills/) + +หากต้องการปิดใช้งานความเข้ากันได้ของ Claude Code ให้ตั้งค่าหนึ่งในตัวแปรสภาพแวดล้อมเหล่านี้: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## ลำดับความสำคัญ + +เมื่อ opencode เริ่มต้นขึ้น มันจะค้นหาไฟล์กฎตามลำดับนี้: + +1. **ไฟล์ในเครื่อง** โดยการสำรวจจากไดเรกทอรีปัจจุบัน (`AGENTS.md`, `CLAUDE.md`) +2. **ไฟล์ทั่วโลก** ที่ `~/.config/opencode/AGENTS.md` +3. **ไฟล์ Claude Code** ที่ `~/.claude/CLAUDE.md` (ยกเว้นปิดการใช้งาน) + +ไฟล์ที่ตรงกันไฟล์แรกจะชนะในแต่ละหมวดหมู่ ตัวอย่างเช่น หากคุณมีทั้ง `AGENTS.md` และ `CLAUDE.md` ระบบจะใช้เฉพาะ `AGENTS.md` ในทำนองเดียวกัน `~/.config/opencode/AGENTS.md` จะมีความสำคัญมากกว่า `~/.claude/CLAUDE.md` + +--- + +## คำแนะนำที่กำหนดเอง + +คุณสามารถระบุไฟล์คำแนะนำที่กำหนดเองได้ใน `opencode.json` หรือ `~/.config/opencode/opencode.json` ทั่วโลก สิ่งนี้ช่วยให้คุณและทีมของคุณสามารถนำกฎที่มีอยู่กลับมาใช้ใหม่ได้ แทนที่จะต้องทำซ้ำกฎเหล่านั้นกับ AGENTS.md + +ตัวอย่าง: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +คุณยังสามารถใช้ URL ระยะไกลเพื่อโหลดคำแนะนำจากเว็บได้ + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +คำแนะนำระยะไกลจะถูกดึงออกมาโดยหมดเวลา 5 วินาที + +ไฟล์คำสั่งทั้งหมดจะรวมกับไฟล์ `AGENTS.md` ของคุณ + +--- + +## การอ้างอิงไฟล์ภายนอก + +แม้ว่า opencode จะไม่แยกวิเคราะห์การอ้างอิงไฟล์ใน `AGENTS.md` โดยอัตโนมัติ แต่คุณสามารถใช้ฟังก์ชันที่คล้ายกันได้สองวิธี: + +### ใช้ opencode.json + +แนวทางที่แนะนำคือการใช้ฟิลด์ `instructions` ใน `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### คำแนะนำแบบแมนนวลใน AGENTS.md + +คุณสามารถสอนให้ opencode อ่านไฟล์ภายนอกได้โดยการให้คำแนะนำที่ชัดเจนใน `AGENTS.md` ของคุณ นี่เป็นตัวอย่างที่เป็นประโยชน์: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +แนวทางนี้ช่วยให้คุณ: + +- สร้างไฟล์กฎแบบโมดูลาร์ที่สามารถนำมาใช้ซ้ำได้ +- แชร์กฎระหว่างโปรเจ็กต์ผ่าน symlink หรือโมดูลย่อย git +- เขียน AGENTS.md ให้กระชับโดยอ้างอิงหลักเกณฑ์โดยละเอียด +- ตรวจสอบให้แน่ใจว่า opencode จะโหลดไฟล์เมื่อจำเป็นสำหรับงานเฉพาะเท่านั้น + +:::tip +สำหรับ monorepos หรือโปรเจ็กต์ที่มีมาตรฐานร่วมกัน การใช้ `opencode.json` ที่มีรูปแบบ glob (เช่น `packages/*/AGENTS.md`) จะสามารถบำรุงรักษาได้ดีกว่าคำสั่งแบบแมนนวล +::: diff --git a/packages/web/src/content/docs/th/sdk.mdx b/packages/web/src/content/docs/th/sdk.mdx new file mode 100644 index 000000000..b01cbded3 --- /dev/null +++ b/packages/web/src/content/docs/th/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: SDK +description: ไคลเอนต์ JS ประเภทที่ปลอดภัยสำหรับเซิร์ฟเวอร์ opencode +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +opencode JS/TS SDK จัดเตรียมไคลเอ็นต์ประเภทที่ปลอดภัยสำหรับการโต้ตอบกับเซิร์ฟเวอร์ +ใช้เพื่อสร้างการบูรณาการและควบคุม opencode โดยทางโปรแกรม + +[เรียนรู้เพิ่มเติม](/docs/server) เกี่ยวกับวิธีการทำงานของเซิร์ฟเวอร์ ตัวอย่างเช่น ลองดู [โครงการ](/docs/ecosystem#โครงการ) ที่สร้างโดยชุมชน + +--- + +## ติดตั้ง + +ติดตั้ง SDK จาก npm: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## สร้างไคลเอนต์ + +สร้างอินสแตนซ์ของ opencode: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +สิ่งนี้จะเริ่มต้นทั้งเซิร์ฟเวอร์และไคลเอนต์ + +#### ตัวเลือก + +| ตัวเลือก | พิมพ์ | คำอธิบาย | ค่าเริ่มต้น | +| ---------- | ------------- | ------------------------------------------- | ----------- | +| `hostname` | `string` | ชื่อโฮสต์ของเซิร์ฟเวอร์ | `127.0.0.1` | +| `port` | `number` | พอร์ตเซิร์ฟเวอร์ | `4096` | +| `signal` | `AbortSignal` | ยกเลิกสัญญาณสำหรับการยกเลิก | `undefined` | +| `timeout` | `number` | หมดเวลาเป็น ms สำหรับการเริ่มต้นเซิร์ฟเวอร์ | `5000` | +| `config` | `Config` | วัตถุการกำหนดค่า | `{}` | + +--- + +## การกำหนดค่า + +คุณสามารถส่งผ่านออบเจ็กต์การกำหนดค่าเพื่อปรับแต่งลักษณะการทำงานได้ อินสแตนซ์ยังคงรับ `opencode.json` ของคุณ แต่คุณสามารถแทนที่หรือเพิ่มการกำหนดค่าแบบอินไลน์ได้: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## ลูกค้าเท่านั้น + +หากคุณมีอินสแตนซ์ opencode ที่ทำงานอยู่แล้ว คุณสามารถสร้างอินสแตนซ์ไคลเอ็นต์เพื่อเชื่อมต่อได้: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### ตัวเลือก + +| ตัวเลือก | พิมพ์ | คำอธิบาย | ค่าเริ่มต้น | +| --------------- | ---------- | ---------------------------------------- | ----------------------- | +| `baseUrl` | `string` | URL ของเซิร์ฟเวอร์ | `http://localhost:4096` | +| `fetch` | `function` | การใช้งานการดึงข้อมูลแบบกำหนดเอง | `globalThis.fetch` | +| `parseAs` | `string` | วิธีการแยกวิเคราะห์การตอบสนอง | `auto` | +| `responseStyle` | `string` | รูปแบบการคืนสินค้า: `data` หรือ `fields` | `fields` | +| `throwOnError` | `boolean` | โยนข้อผิดพลาดแทนการส่งคืน | `false` | + +--- + +## ประเภท + +SDK มีคำจำกัดความ TypeScript สำหรับ API ประเภททั้งหมด นำเข้าโดยตรง: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +ทุกประเภทสร้างขึ้นจากข้อกำหนด OpenAPI ของเซิร์ฟเวอร์และมีอยู่ใน ไฟล์ประเภท + +--- + +## ข้อผิดพลาด + +SDK อาจทำให้เกิดข้อผิดพลาดที่คุณสามารถจับและจัดการได้: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## API + +SDK เปิดเผย API ของเซิร์ฟเวอร์ทั้งหมดผ่านไคลเอ็นต์ประเภทที่ปลอดภัย + +--- + +### ทั่วโลก + +| วิธี | คำอธิบาย | การตอบสนอง | +| ----------------- | ------------------------------------ | ------------------------------------ | +| `global.health()` | ตรวจสอบสภาพและเวอร์ชันของเซิร์ฟเวอร์ | `{ healthy: true, version: string }` | + +--- + +#### ตัวอย่าง + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### แอป + +| วิธี | คำอธิบาย | การตอบสนอง | +| -------------- | ----------------------------- | -------------------------------------------- | +| `app.log()` | เขียนรายการบันทึก | `boolean` | +| `app.agents()` | รายชื่อตัวแทนที่มีอยู่ทั้งหมด | ตัวแทน[] | + +--- + +#### ตัวอย่าง + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### โครงการ + +| วิธี | คำอธิบาย | การตอบสนอง | +| ------------------- | ------------------------ | --------------------------------------------- | +| `project.list()` | แสดงรายการโครงการทั้งหมด | Project[] | +| `project.current()` | รับโครงการปัจจุบัน | Project | + +--- + +#### ตัวอย่าง + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### เส้นทาง + +| วิธี | คำอธิบาย | การตอบสนอง | +| ------------ | ------------------ | ---------------------------------------- | +| `path.get()` | รับเส้นทางปัจจุบัน | Path | + +--- + +#### ตัวอย่าง + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### การกำหนดค่า + +| วิธี | คำอธิบาย | การตอบสนอง | +| -------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------- | +| `config.get()` | รับข้อมูลการกำหนดค่า | กำหนดค่า | +| `config.providers()` | ผู้ให้บริการรายชื่อและโมเดลเริ่มต้น | `{ providers: `ผู้ให้บริการ[]`, default: { [key: string]: string } }` | + +--- + +#### ตัวอย่าง + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### เซสชัน + +| วิธี | คำอธิบาย | หมายเหตุ | +| ---------------------------------------------------------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` | แสดงรายการเซสชัน | ส่งคืน เซสชัน[] | +| `session.get({ path })` | รับเซสชัน | ส่งคืน เซสชัน | +| `session.children({ path })` | แสดงรายการเซสชันย่อย | ส่งคืน เซสชัน[] | +| `session.create({ body })` | สร้างเซสชัน | ส่งคืน เซสชัน | +| `session.delete({ path })` | ลบเซสชัน | ส่งคืน `boolean` | +| `session.update({ path, body })` | อัปเดตคุณสมบัติเซสชัน | ส่งคืน เซสชัน | +| `session.init({ path, body })` | วิเคราะห์แอปและสร้าง `AGENTS.md` | ส่งคืน `boolean` | +| `session.abort({ path })` | ยกเลิกเซสชันที่ทำงานอยู่ | ส่งคืน `boolean` | +| `session.share({ path })` | แบ่งปันเซสชั่น | ส่งคืน เซสชัน | +| `session.unshare({ path })` | เลิกแชร์เซสชัน | ส่งคืน เซสชัน | +| `session.summarize({ path, body })` | สรุปเซสชัน | ส่งคืน `boolean` | +| `session.messages({ path })` | แสดงรายการข้อความในเซสชัน | ส่งคืน `{ info: `ข้อความ`, parts: `ส่วน[]`}[]` | +| `session.message({ path })` | รับรายละเอียดข้อความ | ส่งคืน `{ info: `ข้อความ`, parts: `ส่วน[]`}` | +| `session.prompt({ path, body })` | ส่งข้อความแจ้ง | `body.noReply: true` ส่งคืน UserMessage (บริบทเท่านั้น) ค่าเริ่มต้นส่งคืน AssistantMessage พร้อมการตอบสนองของ AI | +| `session.command({ path, body })` | ส่งคำสั่งไปยังเซสชั่น | ส่งคืน `{ info: `AssistantMessage`, parts: `ส่วน[]`}` | +| `session.shell({ path, body })` | รันคำสั่งเชลล์ | ส่งคืน AssistantMessage | +| `session.revert({ path, body })` | คืนค่าข้อความ | ส่งคืน เซสชัน | +| `session.unrevert({ path })` | คืนค่าข้อความที่เปลี่ยนกลับ | ส่งคืน เซสชัน | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | ตอบสนองต่อการร้องขอการอนุญาต | ส่งคืน `boolean` | + +--- + +#### ตัวอย่าง + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### ไฟล์ + +| วิธี | คำอธิบาย | การตอบสนอง | +| ------------------------- | ------------------------------ | ----------------------------------------------------------------------------------------- | +| `find.text({ query })` | ค้นหาข้อความในไฟล์ | อาร์เรย์ของวัตถุที่ตรงกับ `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `find.files({ query })` | ค้นหาไฟล์และไดเร็กทอรีตามชื่อ | `string[]` (paths) | +| `find.symbols({ query })` | ค้นหาสัญลักษณ์พื้นที่ทำงาน | Symbol[] | +| `file.read({ query })` | อ่านไฟล์ | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | รับสถานะสำหรับไฟล์ที่ถูกติดตาม | File[] | + +`find.files` รองรับช่องค้นหาเพิ่มเติมบางช่อง: + +- `type`: `"file"` หรือ `"directory"` +- `directory`: แทนที่รูทโปรเจ็กต์สำหรับการค้นหา +- `limit`: ผลลัพธ์สูงสุด (1–200) + +--- + +#### ตัวอย่าง + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +| วิธี | คำอธิบาย | การตอบสนอง | +| ------------------------------ | ------------------------------ | ---------- | +| `tui.appendPrompt({ body })` | เพิ่มข้อความต่อท้ายข้อความแจ้ง | `boolean` | +| `tui.openHelp()` | เปิดกล่องโต้ตอบความช่วยเหลือ | `boolean` | +| `tui.openSessions()` | เปิดตัวเลือกเซสชัน | `boolean` | +| `tui.openThemes()` | เปิดตัวเลือกธีม | `boolean` | +| `tui.openModels()` | เปิดตัวเลือกรุ่น | `boolean` | +| `tui.submitPrompt()` | ส่งข้อความแจ้งปัจจุบัน | `boolean` | +| `tui.clearPrompt()` | ล้างข้อความแจ้ง | `boolean` | +| `tui.executeCommand({ body })` | ดำเนินการคำสั่ง | `boolean` | +| `tui.showToast({ body })` | แสดงการแจ้งเตือนขนมปังปิ้ง | `boolean` | + +--- + +#### ตัวอย่าง + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### การรับรองความถูกต้อง + +| วิธี | คำอธิบาย | การตอบสนอง | +| ------------------- | ----------------------------------------- | ---------- | +| `auth.set({ ... })` | ตั้งค่าข้อมูลประจำตัวการรับรองความถูกต้อง | `boolean` | + +--- + +#### ตัวอย่าง + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### กิจกรรม + +| วิธี | คำอธิบาย | การตอบสนอง | +| ------------------- | ------------------------------- | ------------------------------- | +| `event.subscribe()` | สตรีมเหตุการณ์ที่เซิร์ฟเวอร์ส่ง | สตรีมเหตุการณ์ที่เซิร์ฟเวอร์ส่ง | + +--- + +#### ตัวอย่าง + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/th/server.mdx b/packages/web/src/content/docs/th/server.mdx new file mode 100644 index 000000000..c83851c6a --- /dev/null +++ b/packages/web/src/content/docs/th/server.mdx @@ -0,0 +1,287 @@ +--- +title: เซิร์ฟเวอร์ +description: โต้ตอบกับเซิร์ฟเวอร์ opencode ผ่าน HTTP +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +คำสั่ง `opencode serve` รันเซิร์ฟเวอร์ HTTP ที่ไม่มีหัวซึ่งเปิดเผยตำแหน่งข้อมูล OpenAPI ที่ไคลเอนต์ opencode สามารถใช้ได้ + +--- + +### การใช้งาน + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### ตัวเลือก + +| ธง | คำอธิบาย | ค่าเริ่มต้น | +| --------------- | ---------------------------------------- | ---------------- | +| `--port` | พอร์ตที่จะฟัง | `4096` | +| `--hostname` | ชื่อโฮสต์ที่จะฟัง | `127.0.0.1` | +| `--mdns` | เปิดใช้งานการค้นพบ mDNS | `false` | +| `--mdns-domain` | ชื่อโดเมนที่กำหนดเองสำหรับบริการ mDNS | `opencode.local` | +| `--cors` | ต้นกำเนิดเบราว์เซอร์เพิ่มเติมที่จะอนุญาต | `[]` | + +`--cors` สามารถส่งผ่านได้หลายครั้ง: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### การรับรองความถูกต้อง + +ตั้งค่า `OPENCODE_SERVER_PASSWORD` เพื่อปกป้องเซิร์ฟเวอร์ด้วย HTTP การตรวจสอบสิทธิ์ขั้นพื้นฐาน ชื่อผู้ใช้มีค่าเริ่มต้นเป็น `opencode` หรือตั้งค่า `OPENCODE_SERVER_USERNAME` เพื่อแทนที่ชื่อผู้ใช้ สิ่งนี้ใช้ได้กับทั้ง `opencode serve` และ `opencode web` + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### มันทำงานอย่างไร + +เมื่อคุณรัน `opencode` มันจะเริ่มต้น TUI และเซิร์ฟเวอร์ โดยที่ TUI คือ +ลูกค้าที่พูดคุยกับเซิร์ฟเวอร์ เซิร์ฟเวอร์เปิดเผยข้อมูลจำเพาะของ OpenAPI 3.1 +จุดสิ้นสุด ตำแหน่งข้อมูลนี้ยังใช้เพื่อสร้าง [SDK](/docs/sdk) + +:::tip +ใช้เซิร์ฟเวอร์ opencode เพื่อโต้ตอบกับ opencode โดยทางโปรแกรม +::: + +สถาปัตยกรรมนี้ช่วยให้ opencode รองรับไคลเอนต์หลายตัว และช่วยให้คุณสามารถโต้ตอบกับ opencode โดยทางโปรแกรมได้ + +คุณสามารถเรียกใช้ `opencode serve` เพื่อเริ่มเซิร์ฟเวอร์แบบสแตนด์อโลน ถ้าคุณมี +opencode TUI ทำงาน `opencode serve` จะเริ่มเซิร์ฟเวอร์ใหม่ + +--- + +#### เชื่อมต่อกับเซิร์ฟเวอร์ที่มีอยู่ + +เมื่อคุณเริ่ม TUI มันจะสุ่มกำหนดพอร์ตและชื่อโฮสต์ คุณสามารถผ่าน `--hostname` และ `--port` [ธง](/docs/cli) แทนได้ จากนั้นใช้สิ่งนี้เพื่อเชื่อมต่อกับเซิร์ฟเวอร์ + +ตำแหน่งข้อมูล [`/tui`](#tui) สามารถใช้เพื่อขับเคลื่อน TUI ผ่านเซิร์ฟเวอร์ ตัวอย่างเช่น คุณสามารถกรอกข้อมูลล่วงหน้าหรือเรียกใช้พร้อมท์ได้ การตั้งค่านี้ถูกใช้โดยปลั๊กอิน OpenCode [IDE](/docs/ide) + +--- + +## ข้อมูลจำเพาะ + +เซิร์ฟเวอร์เผยแพร่ข้อมูลจำเพาะ OpenAPI 3.1 ที่สามารถดูได้ที่: + +``` +http://:/doc +``` + +ตัวอย่างเช่น `http://localhost:4096/doc` ใช้ข้อมูลจำเพาะเพื่อสร้างไคลเอ็นต์หรือตรวจสอบคำขอและประเภทการตอบกลับ หรือดูใน Swagger explorer + +--- + +## API + +เซิร์ฟเวอร์ opencode เปิดเผย API ต่อไปนี้ + +--- + +### ทั่วโลก + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ----- | ---------------- | --------------------------------- | ------------------------------------ | +| `GET` | `/global/health` | รับสถานะและเวอร์ชันของเซิร์ฟเวอร์ | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | รับกิจกรรมระดับโลก (SSE สตรีม) | สตรีมกิจกรรม | + +--- + +### โครงการ + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ----- | ------------------ | ------------------------ | --------------------------------------------- | +| `GET` | `/project` | แสดงรายการโครงการทั้งหมด | Project[] | +| `GET` | `/project/current` | รับโครงการปัจจุบัน | Project | + +--- + +### เส้นทาง & VCS + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ----- | ------- | ----------------------------------- | ------------------------------------------- | +| `GET` | `/path` | รับเส้นทางปัจจุบัน | Path | +| `GET` | `/vcs` | รับข้อมูล VCS สำหรับโครงการปัจจุบัน | VcsInfo | + +--- + +### ตัวอย่าง + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ------ | ------------------- | ---------------------- | ---------- | +| `POST` | `/instance/dispose` | กำจัดอินสแตนซ์ปัจจุบัน | `boolean` | + +--- + +### การกำหนดค่า + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ------- | ------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------- | +| `GET` | `/config` | รับข้อมูลการกำหนดค่า | กำหนดค่า | +| `PATCH` | `/config` | อัปเดตการกำหนดค่า | กำหนดค่า | +| `GET` | `/config/providers` | ผู้ให้บริการรายชื่อและโมเดลเริ่มต้น | `{ providers: `ผู้ให้บริการ[]`, default: { [key: string]: string } }` | + +--- + +### ผู้ให้บริการ + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ------ | -------------------------------- | ------------------------------------------- | --------------------------------------------------------------------------------------- | +| `GET` | `/provider` | รายชื่อผู้ให้บริการทั้งหมด | `{ all: `ผู้ให้บริการ[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | รับวิธีการตรวจสอบความถูกต้องของผู้ให้บริการ | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | ให้สิทธิ์ผู้ให้บริการโดยใช้ OAuth | การอนุญาตของผู้ให้บริการ | +| `POST` | `/provider/{id}/oauth/callback` | จัดการการโทรกลับ OAuth สำหรับผู้ให้บริการ | `boolean` | + +--- + +### เซสชัน + +| วิธี | เส้นทาง | คำอธิบาย | หมายเหตุ | +| -------- | ---------------------------------------- | ---------------------------------- | -------------------------------------------------------------------------------- | +| `GET` | `/session` | แสดงรายการเซสชันทั้งหมด | ส่งคืน เซสชัน[] | +| `POST` | `/session` | สร้างเซสชันใหม่ | body: `{ parentID?, title? }` ส่งคืน เซสชัน | +| `GET` | `/session/status` | รับสถานะเซสชันสำหรับเซสชันทั้งหมด | ส่งคืน `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | รับรายละเอียดเซสชั่น | ส่งคืน เซสชัน | +| `DELETE` | `/session/:id` | ลบเซสชันและข้อมูลทั้งหมด | ส่งคืน `boolean` | +| `PATCH` | `/session/:id` | อัปเดตคุณสมบัติเซสชัน | body: `{ title? }` ส่งคืน เซสชัน | +| `GET` | `/session/:id/children` | รับเซสชันย่อยของเซสชัน | ส่งคืน เซสชัน[] | +| `GET` | `/session/:id/todo` | รับรายการสิ่งที่ต้องทำสำหรับเซสชัน | ส่งคืน สิ่งที่ต้องทำ[] | +| `POST` | `/session/:id/init` | วิเคราะห์แอปและสร้าง `AGENTS.md` | เนื้อความ: `{ messageID, providerID, modelID }` ส่งคืน `boolean` | +| `POST` | `/session/:id/fork` | แยกเซสชันที่มีอยู่ไปที่ข้อความ | body: `{ messageID? }` ส่งคืน เซสชัน | +| `POST` | `/session/:id/abort` | ยกเลิกเซสชันที่ทำงานอยู่ | ส่งคืน `boolean` | +| `POST` | `/session/:id/share` | แบ่งปันเซสชั่น | ส่งคืน เซสชัน | +| `DELETE` | `/session/:id/share` | ยกเลิกการแชร์เซสชัน | ส่งคืน เซสชัน | +| `GET` | `/session/:id/diff` | รับความแตกต่างสำหรับเซสชั่นนี้ | ข้อความค้นหา: `messageID?` ส่งคืน FileDiff[] | +| `POST` | `/session/:id/summarize` | สรุปเซสชัน | เนื้อความ: `{ providerID, modelID }` ส่งคืน `boolean` | +| `POST` | `/session/:id/revert` | คืนค่าข้อความ | เนื้อความ: `{ messageID, partID? }` ส่งคืน `boolean` | +| `POST` | `/session/:id/unrevert` | กู้คืนข้อความที่เปลี่ยนกลับทั้งหมด | ส่งคืน `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | ตอบสนองต่อการร้องขอการอนุญาต | เนื้อความ: `{ response, remember? }` ส่งคืน `boolean` | + +--- + +### ข้อความ + +| วิธี | เส้นทาง | คำอธิบาย | หมายเหตุ | +| ------ | --------------------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `GET` | `/session/:id/message` | แสดงรายการข้อความในเซสชัน | ข้อความค้นหา: `limit?` ส่งคืน `{ info: `ข้อความ`, parts: `ส่วน[]`}[]` | +| `POST` | `/session/:id/message` | ส่งข้อความและรอการตอบกลับ | เนื้อความ: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }` ส่งคืน `{ info: `ข้อความ`, parts: `ส่วน[]`}` | +| `GET` | `/session/:id/message/:messageID` | รับรายละเอียดข้อความ | ส่งคืน `{ info: `ข้อความ`, parts: `ส่วนหนึ่ง[]`}` | +| `POST` | `/session/:id/prompt_async` | ส่งข้อความแบบอะซิงโครนัส (ไม่ต้องรอ) | เนื้อความ: เหมือนกับ `/session/:id/message` ส่งคืน `204 No Content` | +| `POST` | `/session/:id/command` | ดำเนินการคำสั่งเครื่องหมายทับ | เนื้อความ: `{ messageID?, agent?, model?, command, arguments }` ส่งคืน `{ info: `ข้อความ`, parts: `ส่วน[]`}` | +| `POST` | `/session/:id/shell` | รันคำสั่งเชลล์ | เนื้อความ: `{ agent, model?, command }` ส่งคืน `{ info: `ข้อความ`, parts: `ส่วน[]`}` | + +--- + +### คำสั่ง + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ----- | ---------- | ----------------------- | --------------------------------------------- | +| `GET` | `/command` | แสดงรายการคำสั่งทั้งหมด | Command[] | + +--- + +### ไฟล์ + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ----- | ------------------------ | ------------------------------ | ----------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | ค้นหาข้อความในไฟล์ | อาร์เรย์ของวัตถุที่ตรงกับ `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | ค้นหาไฟล์และไดเร็กทอรีตามชื่อ | `string[]` (paths) | +| `GET` | `/find/symbol?query=` | ค้นหาสัญลักษณ์พื้นที่ทำงาน | Symbol[] | +| `GET` | `/file?path=` | แสดงรายการไฟล์และไดเร็กทอรี | FileNode[] | +| `GET` | `/file/content?path=

` | อ่านไฟล์ | เนื้อหาไฟล์ | +| `GET` | `/file/status` | รับสถานะสำหรับไฟล์ที่ถูกติดตาม | File[] | + +#### `/find/file` พารามิเตอร์การสืบค้น + +- `query` (จำเป็น) — สตริงการค้นหา (การจับคู่แบบคลุมเครือ) +- `type` (ไม่บังคับ) — จำกัดผลลัพธ์ไว้ที่ `"file"` หรือ `"directory"` +- `directory` (เป็นทางเลือก) — แทนที่รูทโปรเจ็กต์สำหรับการค้นหา +- `limit` (ไม่บังคับ) — ผลลัพธ์สูงสุด (1–200) +- `dirs` (ไม่บังคับ) — แฟล็กดั้งเดิม (`"false"` ส่งคืนเฉพาะไฟล์) + +--- + +### เครื่องมือ (ทดลอง) + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ----- | ------------------------------------------- | ----------------------------------------------- | ---------------------------------------------------- | +| `GET` | `/experimental/tool/ids` | แสดงรายการรหัสเครื่องมือทั้งหมด | รหัสเครื่องมือ | +| `GET` | `/experimental/tool?provider=

&model=` | แสดงรายการเครื่องมือที่มีสกีมา JSON สำหรับโมเดล | รายการเครื่องมือ | + +--- + +### LSP, ฟอร์แมตเตอร์ & MCP + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ------ | ------------ | ------------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | รับ LSP สถานะเซิร์ฟเวอร์ | LSPStatus[] | +| `GET` | `/formatter` | รับสถานะฟอร์แมตเตอร์ | FormatterStatus[] | +| `GET` | `/mcp` | รับ MCP สถานะเซิร์ฟเวอร์ | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | เพิ่มเซิร์ฟเวอร์ MCP แบบไดนามิก | body: `{ name, config }` ส่งคืนออบเจ็กต์สถานะ MCP | + +--- + +### ตัวแทน + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ----- | -------- | ----------------------------- | -------------------------------------------- | +| `GET` | `/agent` | รายชื่อตัวแทนที่มีอยู่ทั้งหมด | ตัวแทน[] | + +--- + +### การบันทึก + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ------ | ------- | ------------------------------------------------------------------ | ---------- | +| `POST` | `/log` | เขียนรายการบันทึก เนื้อความ: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ------ | ----------------------- | ----------------------------------------------- | --------------- | +| `POST` | `/tui/append-prompt` | เพิ่มข้อความต่อท้ายข้อความแจ้ง | `boolean` | +| `POST` | `/tui/open-help` | เปิดกล่องโต้ตอบความช่วยเหลือ | `boolean` | +| `POST` | `/tui/open-sessions` | เปิดตัวเลือกเซสชัน | `boolean` | +| `POST` | `/tui/open-themes` | เปิดตัวเลือกธีม | `boolean` | +| `POST` | `/tui/open-models` | เปิดตัวเลือกรุ่น | `boolean` | +| `POST` | `/tui/submit-prompt` | ส่งข้อความแจ้งปัจจุบัน | `boolean` | +| `POST` | `/tui/clear-prompt` | ล้างข้อความแจ้ง | `boolean` | +| `POST` | `/tui/execute-command` | ดำเนินการคำสั่ง (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | โชว์ขนมปังปิ้ง (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | รอคำขอควบคุมถัดไป | วัตถุคำขอควบคุม | +| `POST` | `/tui/control/response` | ตอบสนองต่อคำขอควบคุม (`{ body }`) | `boolean` | + +--- + +### การรับรองความถูกต้อง + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ----- | ----------- | --------------------------------------------------------------------------------- | ---------- | +| `PUT` | `/auth/:id` | ตั้งค่าข้อมูลประจำตัวการรับรองความถูกต้อง เนื้อความต้องตรงกับสคีมาของผู้ให้บริการ | `boolean` | + +--- + +### กิจกรรม + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ----- | -------- | ---------------------------------------------------------------------------- | ------------------------------- | +| `GET` | `/event` | สตรีมเหตุการณ์ที่เซิร์ฟเวอร์ส่ง งานแรกคือ `server.connected` จากนั้นงานรถบัส | สตรีมเหตุการณ์ที่เซิร์ฟเวอร์ส่ง | + +--- + +### เอกสาร + +| วิธี | เส้นทาง | คำอธิบาย | การตอบสนอง | +| ----- | ------- | --------------------------- | ---------------------------------- | +| `GET` | `/doc` | ข้อมูลจำเพาะของ OpenAPI 3.1 | HTML หน้าพร้อมข้อมูลจำเพาะ OpenAPI | diff --git a/packages/web/src/content/docs/th/share.mdx b/packages/web/src/content/docs/th/share.mdx new file mode 100644 index 000000000..40b1a66eb --- /dev/null +++ b/packages/web/src/content/docs/th/share.mdx @@ -0,0 +1,128 @@ +--- +title: แบ่งปัน +description: แบ่งปันการสนทนา OpenCode ของคุณ +--- + +คุณลักษณะการแชร์ของ OpenCode ช่วยให้คุณสร้างลิงก์สาธารณะไปยังการสนทนา OpenCode ของคุณ เพื่อให้คุณสามารถทำงานร่วมกับเพื่อนร่วมทีมหรือรับความช่วยเหลือจากผู้อื่นได้ + +:::note +ทุกคนที่มีลิงก์สามารถเข้าถึงการสนทนาที่แชร์ได้แบบสาธารณะ +::: + +--- + +## มันทำงานอย่างไร + +เมื่อคุณแบ่งปันการสนทนา OpenCode: + +1. สร้าง URL สาธารณะที่ไม่ซ้ำสำหรับเซสชันของคุณ +2. ซิงค์ประวัติการสนทนาของคุณกับเซิร์ฟเวอร์ของเรา +3. ทำให้สามารถเข้าถึงการสนทนาผ่านลิงก์ที่แชร์ได้ — `opncd.ai/s/` + +--- + +## การแบ่งปัน + +OpenCode รองรับโหมดการแชร์สามโหมดที่ควบคุมวิธีการแชร์การสนทนา: + +--- + +### คู่มือ (ค่าเริ่มต้น) + +ตามค่าเริ่มต้น OpenCode จะใช้โหมดการแชร์ด้วยตนเอง เซสชันจะไม่ถูกแชร์โดยอัตโนมัติ แต่คุณสามารถแชร์ได้ด้วยตนเองโดยใช้คำสั่ง `/share`: + +``` +/share +``` + +สิ่งนี้จะสร้าง URL ที่ไม่ซ้ำกันซึ่งจะถูกคัดลอกไปยังคลิปบอร์ดของคุณ + +หากต้องการตั้งค่าโหมดแมนนวลอย่างชัดเจนใน [ไฟล์ปรับแต่ง](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### แชร์อัตโนมัติ + +คุณสามารถเปิดใช้งานการแบ่งปันอัตโนมัติสำหรับการสนทนาใหม่ทั้งหมดโดยตั้งค่าตัวเลือก `share` เป็น `"auto"` ใน [ไฟล์กำหนดค่า](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +เมื่อเปิดใช้งานการแชร์อัตโนมัติ ทุกการสนทนาใหม่จะถูกแชร์โดยอัตโนมัติและลิงก์จะถูกสร้างขึ้น + +--- + +### พิการ + +คุณสามารถปิดการแชร์ทั้งหมดได้โดยตั้งค่าตัวเลือก `share` เป็น `"disabled"` ใน [ไฟล์กำหนดค่า](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +หากต้องการบังคับใช้สิ่งนี้กับทีมของคุณสำหรับโปรเจ็กต์ที่กำหนด ให้เพิ่มลงใน `opencode.json` ในโปรเจ็กต์ของคุณและตรวจสอบใน Git + +--- + +## ยกเลิกการแชร์ + +หากต้องการหยุดแชร์การสนทนาและลบออกจากการเข้าถึงแบบสาธารณะ: + +``` +/unshare +``` + +การดำเนินการนี้จะลบลิงก์แชร์และลบข้อมูลที่เกี่ยวข้องกับการสนทนา + +--- + +## ความเป็นส่วนตัว + +มีบางสิ่งที่ต้องคำนึงถึงเมื่อแบ่งปันการสนทนา + +--- + +### การเก็บรักษาข้อมูล + +การสนทนาที่แชร์จะยังสามารถเข้าถึงได้จนกว่าคุณจะยกเลิกการแชร์อย่างชัดเจน นี้ +รวมถึง: + +- ประวัติการสนทนาแบบเต็ม +- ทุกข้อความและการตอบกลับ +- ข้อมูลเมตาของเซสชัน + +--- + +### ข้อแนะนำ + +- แชร์การสนทนาที่ไม่มีข้อมูลที่ละเอียดอ่อนเท่านั้น +- ตรวจสอบเนื้อหาการสนทนาก่อนที่จะแบ่งปัน +- ยกเลิกการแชร์การสนทนาเมื่อการทำงานร่วมกันเสร็จสมบูรณ์ +- หลีกเลี่ยงการแบ่งปันการสนทนาด้วยรหัสที่เป็นกรรมสิทธิ์หรือข้อมูลที่เป็นความลับ +- สำหรับโปรเจ็กต์ที่มีความละเอียดอ่อน ให้ปิดการแชร์ทั้งหมด + +--- + +## สำหรับสถานประกอบการ + +สำหรับการปรับใช้ระดับองค์กร คุณสมบัติการแชร์อาจเป็น: + +- **ปิดการใช้งาน** ทั้งหมดเพื่อความปลอดภัย +- **จำกัด** สำหรับผู้ใช้ที่ผ่านการรับรองความถูกต้องผ่าน SSO เท่านั้น +- **โฮสต์เอง** บนโครงสร้างพื้นฐานของคุณเอง + +[เรียนรู้เพิ่มเติม](/docs/enterprise) เกี่ยวกับการใช้ opencode ในองค์กรของคุณ diff --git a/packages/web/src/content/docs/th/skills.mdx b/packages/web/src/content/docs/th/skills.mdx new file mode 100644 index 000000000..062ec783f --- /dev/null +++ b/packages/web/src/content/docs/th/skills.mdx @@ -0,0 +1,222 @@ +--- +title: “ทักษะตัวแทน” +description: "กำหนดพฤติกรรมที่นำมาใช้ซ้ำได้ผ่านคำจำกัดความ SKILL.md" +--- + +ทักษะของเจ้าหน้าที่ช่วยให้ OpenCode ค้นพบคำแนะนำที่ใช้ซ้ำได้จาก repo หรือโฮมไดเร็กทอรีของคุณ +ทักษะจะถูกโหลดตามความต้องการผ่านเครื่องมือ `skill` ดั้งเดิม ตัวแทนจะเห็นทักษะที่มีอยู่และสามารถโหลดเนื้อหาทั้งหมดได้เมื่อจำเป็น + +--- + +## วางไฟล์ + +สร้างหนึ่งโฟลเดอร์ต่อชื่อทักษะ และใส่ `SKILL.md` ไว้ข้างใน +OpenCode ค้นหาตำแหน่งเหล่านี้: + +- การกำหนดค่าโครงการ: `.opencode/skills//SKILL.md` +- การกำหนดค่าส่วนกลาง: `~/.config/opencode/skills//SKILL.md` +- เข้ากันได้กับโครงการ Claude: `.claude/skills//SKILL.md` +- เข้ากันได้กับ Global Claude: `~/.claude/skills//SKILL.md` +- เข้ากันได้กับตัวแทนโครงการ: `.agents/skills//SKILL.md` +- รองรับตัวแทนทั่วโลก: `~/.agents/skills//SKILL.md` + +--- + +## ทำความเข้าใจกับการค้นพบ + +สำหรับเส้นทางภายในโปรเจ็กต์ OpenCode จะเดินขึ้นมาจากไดเร็กทอรีการทำงานปัจจุบันของคุณจนกว่าจะถึงแผนผังงาน git +โดยจะโหลด `skills/*/SKILL.md` ที่ตรงกันใน `.opencode/` และ `.claude/skills/*/SKILL.md` หรือ `.agents/skills/*/SKILL.md` ที่ตรงกันตลอดทาง + +คำจำกัดความสากลยังโหลดจาก `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` และ `~/.agents/skills/*/SKILL.md` + +--- + +## เขียน frontmatter + +`SKILL.md` แต่ละอันต้องขึ้นต้นด้วย YAML frontmatter +เฉพาะฟิลด์เหล่านี้เท่านั้นที่ได้รับการยอมรับ: + +- `name` (จำเป็น) +- `description` (จำเป็น) +- `license` (ไม่บังคับ) +- `compatibility` (ไม่บังคับ) +- `metadata` (ตัวเลือก แมปแบบสตริงต่อสตริง) + +ช่อง frontmatter ที่ไม่รู้จักจะถูกละเว้น + +--- + +## ตรวจสอบชื่อ + +`name` ต้อง: + +- มีความยาว 1–64 อักขระ +- เป็นตัวพิมพ์เล็กและตัวเลขคละกันที่มีเครื่องหมายยัติภังค์ตัวคั่นเดียว +- ไม่ขึ้นต้นหรือลงท้ายด้วย `-` +- ไม่มี `--` ติดต่อกัน +- จับคู่ชื่อไดเร็กทอรีที่มี `SKILL.md` + +regex ที่เทียบเท่า: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## ปฏิบัติตามกฎความยาว + +`description` ต้องมีความยาว 1-1,024 ตัวอักษร +เจาะจงให้ตัวแทนเลือกได้ถูกต้อง + +--- + +## ใช้ตัวอย่าง + +สร้าง `.opencode/skills/git-release/SKILL.md` แบบนี้: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## รู้จักคำอธิบายเครื่องมือ + +OpenCode แสดงรายการทักษะที่มีอยู่ในคำอธิบายเครื่องมือ `skill` +แต่ละรายการจะมีชื่อทักษะและคำอธิบาย: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +ตัวแทนโหลดทักษะโดยการเรียกเครื่องมือ: + +``` +skill({ name: "git-release" }) +``` + +--- + +## กำหนดค่าสิทธิ์ + +ควบคุมว่าตัวแทนทักษะใดสามารถเข้าถึงโดยใช้สิทธิ์ตามรูปแบบใน `opencode.json`: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| การอนุญาต | พฤติกรรม | +| ---------- | ----------------------------------------- | +| `allow` | โหลดทักษะทันที | +| `deny` | ทักษะถูกซ่อนไม่ให้ตัวแทน การเข้าถึงถูกปฏิเสธ | +| `ask` | ผู้ใช้ได้รับแจ้งให้อนุมัติก่อนที่จะโหลด | + +รูปแบบที่รองรับไวด์การ์ด: `internal-*` ตรงกับ `internal-docs`, `internal-tools` ฯลฯ + +--- + +## แทนที่ต่อตัวแทน + +ให้สิทธิ์แก่ตัวแทนเฉพาะเจาะจงที่แตกต่างจากค่าเริ่มต้นทั่วไป + +**สำหรับตัวแทนแบบกำหนดเอง** (ในตัวแทนส่วนหน้า): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**สำหรับตัวแทนในตัว** (ใน `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## ปิดการใช้งานเครื่องมือทักษะ + +ปิดการใช้งานทักษะโดยสิ้นเชิงสำหรับตัวแทนที่ไม่ควรใช้: + +**สำหรับตัวแทนแบบกำหนดเอง**: + +```yaml +--- +tools: + skill: false +--- +``` + +**สำหรับตัวแทนในตัว**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +เมื่อปิดใช้งาน ส่วน `` จะถูกละเว้นทั้งหมด + +--- + +## แก้ไขปัญหาการโหลด + +หากทักษะไม่แสดง: + +1. ตรวจสอบว่า `SKILL.md` สะกดด้วยตัวพิมพ์ใหญ่ทั้งหมด +2. ตรวจสอบว่าส่วนหน้าประกอบด้วย `name` และ `description` +3. ตรวจสอบให้แน่ใจว่าชื่อทักษะไม่ซ้ำกันในทุกสถานที่ +4. ตรวจสอบการอนุญาต ทักษะที่มี `deny` ถูกซ่อนไม่ให้ตัวแทนเห็น diff --git a/packages/web/src/content/docs/th/themes.mdx b/packages/web/src/content/docs/th/themes.mdx new file mode 100644 index 000000000..d449a9a10 --- /dev/null +++ b/packages/web/src/content/docs/th/themes.mdx @@ -0,0 +1,369 @@ +--- +title: ธีมส์ +description: เลือกธีมในตัวหรือกำหนดธีมของคุณเอง +--- + +ด้วย OpenCode คุณสามารถเลือกจากหนึ่งในธีมที่มีอยู่แล้วภายใน ใช้ธีมที่ปรับให้เข้ากับธีมเทอร์มินัลของคุณ หรือกำหนดธีมที่คุณกำหนดเองได้ + +ตามค่าเริ่มต้น OpenCode จะใช้ธีม `opencode` ของเราเอง + +--- + +## ข้อกำหนดของเทอร์มินัล + +เพื่อให้ธีมแสดงได้อย่างถูกต้องด้วยชุดสีทั้งหมด เทอร์มินัลของคุณต้องรองรับ **truecolor** (สี 24 บิต) เทอร์มินัลสมัยใหม่ส่วนใหญ่จะรองรับสิ่งนี้ตามค่าเริ่มต้น แต่คุณอาจต้องเปิดใช้งาน: + +- **ตรวจสอบการสนับสนุน**: เรียกใช้ `echo $COLORTERM` - ​​ควรส่งออก `truecolor` หรือ `24bit` +- **เปิดใช้งานสีจริง**: ตั้งค่าตัวแปรสภาพแวดล้อม `COLORTERM=truecolor` ในโปรไฟล์เชลล์ของคุณ +- **ความเข้ากันได้ของเทอร์มินัล**: ตรวจสอบให้แน่ใจว่าโปรแกรมจำลองเทอร์มินัลของคุณรองรับสี 24 บิต (เทอร์มินัลที่ทันสมัยที่สุด เช่น iTerm2, Alacritty, Kitty, Windows Terminal และ GNOME Terminal do เวอร์ชันล่าสุด) + +หากไม่รองรับสีจริง ธีมอาจปรากฏขึ้นโดยมีความแม่นยำของสีลดลงหรือกลับไปใช้การประมาณสี 256 สีที่ใกล้ที่สุด + +--- + +## ธีมในตัว + +OpenCode มาพร้อมกับธีมในตัวหลายธีม + +| ชื่อ | คำอธิบาย | +| ---------------------- | ---------------------------------------------------------------------------- | +| `system` | ปรับให้เข้ากับสีพื้นหลังของเทอร์มินัลของคุณ | +| `tokyonight` | อิงตามธีมของ [Tokyonight](https://github.com/folke/tokyonight.nvim) | +| `everforest` | อิงตามธีม [Everforest](https://github.com/sainnhe/everforest) | +| `ayu` | อิงตามธีมสีเข้มของ [Ayu](https://github.com/ayu-theme) | +| `catppuccin` | อิงตามธีม [Catppuccin](https://github.com/catppuccin) | +| `catppuccin-macchiato` | อิงตามธีม [Catppuccin](https://github.com/catppuccin) | +| `gruvbox` | อิงตามธีม [Gruvbox](https://github.com/morhetz/gruvbox) | +| `kanagawa` | อิงตามธีมของ [คานากาว่า](https://github.com/rebelot/kanagawa.nvim) | +| `nord` | อิงตามธีม [Nord](https://github.com/nordtheme/nord) | +| `matrix` | ธีมสีเขียวสไตล์แฮ็กเกอร์บนสีดำ | +| `one-dark` | อิงตามธีม [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) Dark | + +และยิ่งไปกว่านั้น เรายังเพิ่มธีมใหม่ๆ อย่างต่อเนื่อง + +--- + +## ธีมของระบบ + +ธีม `system` ได้รับการออกแบบให้ปรับให้เข้ากับโทนสีของเครื่องเทอร์มินัลของคุณโดยอัตโนมัติ ไม่เหมือนกับธีมดั้งเดิมที่ใช้สีคงที่ ธีม _system_: + +- **สร้างระดับสีเทา**: สร้างระดับสีเทาแบบกำหนดเองตามสีพื้นหลังของเทอร์มินัลของคุณ เพื่อให้มั่นใจว่ามีคอนทราสต์ที่เหมาะสมที่สุด +- **ใช้สี ANSI**: ใช้ประโยชน์จากสี ANSI มาตรฐาน (0-15) สำหรับการเน้นไวยากรณ์และองค์ประกอบ UI ซึ่งเคารพชุดสีของเทอร์มินัลของคุณ +- **รักษาค่าเริ่มต้นของเทอร์มินัล**: ใช้ `none` สำหรับสีข้อความและพื้นหลัง เพื่อรักษารูปลักษณ์ดั้งเดิมของเทอร์มินัลของคุณ + +ธีมของระบบมีไว้สำหรับผู้ใช้ที่: + +- ต้องการให้ OpenCode ตรงกับรูปลักษณ์ของเทอร์มินัล +- ใช้โครงร่างสีเทอร์มินัลแบบกำหนดเอง +- ต้องการรูปลักษณ์ที่สอดคล้องกันในแอปพลิเคชันเทอร์มินัลทั้งหมด + +--- + +## การใช้ธีม + +คุณสามารถเลือกธีมได้โดยเปิดการเลือกธีมขึ้นมาด้วยคำสั่ง `/theme` หรือคุณสามารถระบุได้ใน [config](/docs/config) + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## ธีมที่กำหนดเอง + +OpenCode รองรับระบบธีมที่ใช้ JSON ที่ยืดหยุ่น ซึ่งช่วยให้ผู้ใช้สามารถสร้างและปรับแต่งธีมได้อย่างง่ายดาย + +--- + +### ลำดับชั้น + +ธีมจะถูกโหลดจากหลายไดเร็กทอรีตามลำดับต่อไปนี้ โดยไดเร็กทอรีรุ่นหลังจะแทนที่ไดเร็กทอรีก่อนหน้า: + +1. **ธีมในตัว** - ธีมเหล่านี้ฝังอยู่ในไบนารี +2. **ไดเรกทอรีกำหนดค่าผู้ใช้** - กำหนดใน `~/.config/opencode/themes/*.json` หรือ `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **ไดเรกทอรีรากของโครงการ** - กำหนดไว้ใน `/.opencode/themes/*.json` +4. **ไดเร็กทอรีการทำงานปัจจุบัน** - กำหนดใน `./.opencode/themes/*.json` + +หากหลายไดเร็กทอรีมีธีมที่มีชื่อเดียวกัน ธีมจากไดเร็กทอรีที่มีลำดับความสำคัญสูงกว่าจะถูกนำมาใช้ + +--- + +### การสร้างธีม + +หากต้องการสร้างธีมที่กำหนดเอง ให้สร้างไฟล์ JSON ในไดเร็กทอรีธีมรายการใดรายการหนึ่ง + +สำหรับธีมทั้งผู้ใช้: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +และสำหรับธีมเฉพาะโครงการ + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON รูปแบบ + +ธีมใช้รูปแบบ JSON ที่ยืดหยุ่นพร้อมรองรับ: + +- **สีฐานสิบหก**: `"#ffffff"` +- **ANSI สี**: `3` (0-255) +- **การอ้างอิงสี**: `"primary"` หรือคำจำกัดความที่กำหนดเอง +- **Dark/light ตัวแปร**: `{"dark": "#000", "light": "#fff"}` +- **ไม่มีสี**: `"none"` - ​​ใช้สีเริ่มต้นของเทอร์มินัลหรือโปร่งใส + +--- + +### คำจำกัดความของสี + +ส่วน `defs` เป็นทางเลือก และอนุญาตให้คุณกำหนดสีที่ใช้ซ้ำได้ซึ่งสามารถอ้างอิงในธีมได้ + +--- + +### ค่าเริ่มต้นของเทอร์มินัล + +ค่าพิเศษ `"none"` สามารถใช้กับสีใดก็ได้เพื่อสืบทอดสีเริ่มต้นของเทอร์มินัล สิ่งนี้มีประโยชน์อย่างยิ่งสำหรับการสร้างธีมที่ผสมผสานอย่างลงตัวกับโทนสีของเทอร์มินัลของคุณ: + +- `"text": "none"` - ​​ใช้สีพื้นหน้าเริ่มต้นของเทอร์มินัล +- `"background": "none"` - ​​ใช้สีพื้นหลังเริ่มต้นของเทอร์มินัล + +--- + +### ตัวอย่าง + +นี่คือตัวอย่างของธีมที่กำหนดเอง: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/th/tools.mdx b/packages/web/src/content/docs/th/tools.mdx new file mode 100644 index 000000000..c4e242ab3 --- /dev/null +++ b/packages/web/src/content/docs/th/tools.mdx @@ -0,0 +1,379 @@ +--- +title: เครื่องมือ +description: จัดการเครื่องมือที่ LLM สามารถใช้ได้ +--- + +เครื่องมืออนุญาตให้ LLM ดำเนินการในโค้ดเบสของคุณ OpenCode มาพร้อมกับชุดเครื่องมือในตัว แต่คุณสามารถขยายได้ด้วย [เครื่องมือที่กำหนดเอง](/docs/custom-tools) หรือ [MCP เซิร์ฟเวอร์](/docs/mcp-servers) + +ตามค่าเริ่มต้น เครื่องมือทั้งหมด **เปิดใช้งาน** และไม่จำเป็นต้องมีสิทธิ์ในการทำงาน คุณสามารถควบคุมการทำงานของเครื่องมือผ่าน [สิทธิ์](/docs/permissions) + +--- + +## กำหนดค่า + +ใช้ฟิลด์ `permission` เพื่อควบคุมการทำงานของเครื่องมือ คุณสามารถอนุญาต ปฏิเสธ หรือต้องการการอนุมัติสำหรับเครื่องมือแต่ละรายการได้ + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +คุณยังสามารถใช้ไวด์การ์ดเพื่อควบคุมเครื่องมือหลายรายการพร้อมกันได้ ตัวอย่างเช่น หากต้องการขออนุมัติเครื่องมือทั้งหมดจากเซิร์ฟเวอร์ MCP: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[เรียนรู้เพิ่มเติม](/docs/permissions) เกี่ยวกับการกำหนดค่าสิทธิ์ + +--- + +## บิวท์อิน + +นี่คือเครื่องมือในตัวทั้งหมดที่มีอยู่ใน OpenCode + +--- + +### bash + +ดำเนินการคำสั่งเชลล์ในสภาพแวดล้อมโปรเจ็กต์ของคุณ + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +เครื่องมือนี้อนุญาตให้ LLM รันคำสั่งเทอร์มินัล เช่น `npm install`, `git status` หรือคำสั่งเชลล์อื่น ๆ + +--- + +### edit + +แก้ไขไฟล์ที่มีอยู่โดยใช้การแทนที่สตริงที่แน่นอน + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +เครื่องมือนี้ทำการแก้ไขไฟล์อย่างแม่นยำโดยแทนที่ข้อความที่ตรงกันทุกประการ มันเป็นวิธีหลักที่ LLM แก้ไขโค้ด + +--- + +### write + +สร้างไฟล์ใหม่หรือเขียนทับไฟล์ที่มีอยู่ + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +ใช้สิ่งนี้เพื่ออนุญาตให้ LLM สร้างไฟล์ใหม่ มันจะเขียนทับไฟล์ที่มีอยู่หากมีอยู่แล้ว + +:::note +เครื่องมือ `write` ถูกควบคุมโดยสิทธิ์ `edit` ซึ่งครอบคลุมการแก้ไขไฟล์ทั้งหมด (`edit`, `write`, `patch`, `multiedit`) +::: + +--- + +### read + +อ่านเนื้อหาไฟล์จากโค้ดเบสของคุณ + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +เครื่องมือนี้จะอ่านไฟล์และส่งกลับเนื้อหา รองรับการอ่านช่วงบรรทัดเฉพาะสำหรับไฟล์ขนาดใหญ่ + +--- + +### grep + +ค้นหาเนื้อหาไฟล์โดยใช้นิพจน์ทั่วไป + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +ค้นหาเนื้อหาอย่างรวดเร็วทั่วทั้งโค้ดเบสของคุณ รองรับไวยากรณ์ regex เต็มรูปแบบและการกรองรูปแบบไฟล์ + +--- + +### glob + +ค้นหาไฟล์ตามรูปแบบการจับคู่ + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +ค้นหาไฟล์โดยใช้รูปแบบ glob เช่น `**/*.js` หรือ `src/**/*.ts` ส่งคืนเส้นทางไฟล์ที่ตรงกันโดยจัดเรียงตามเวลาแก้ไข + +--- + +### list + +แสดงรายการไฟล์และไดเร็กทอรีในพาธที่กำหนด + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +เครื่องมือนี้แสดงรายการเนื้อหาไดเร็กทอรี ยอมรับรูปแบบ glob เพื่อกรองผลลัพธ์ + +--- + +### lsp (ทดลอง) + +โต้ตอบกับเซิร์ฟเวอร์ LSP ที่กำหนดค่าของคุณเพื่อรับฟีเจอร์อัจฉริยะด้านโค้ด เช่น คำจำกัดความ การอ้างอิง ข้อมูลโฮเวอร์ และลำดับชั้นการโทร + +:::note +เครื่องมือนี้ใช้ได้เฉพาะเมื่อ `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (หรือ `OPENCODE_EXPERIMENTAL=true`) +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +การดำเนินการที่รองรับ ได้แก่ `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` และ `outgoingCalls` + +หากต้องการกำหนดค่าเซิร์ฟเวอร์ LSP ที่พร้อมใช้งานสำหรับโครงการของคุณ โปรดดู [LSP เซิร์ฟเวอร์](/docs/lsp) + +--- + +### patch + +ใช้แพทช์กับไฟล์ + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +เครื่องมือนี้ใช้ไฟล์แพทช์กับโค้ดเบสของคุณ มีประโยชน์สำหรับการใช้ความแตกต่างและแพตช์จากแหล่งต่างๆ + +:::note +เครื่องมือ `patch` ถูกควบคุมโดยสิทธิ์ `edit` ซึ่งครอบคลุมการแก้ไขไฟล์ทั้งหมด (`edit`, `write`, `patch`, `multiedit`) +::: + +--- + +### skill + +โหลด [ทักษะ](/docs/skills) (ไฟล์ `SKILL.md`) และส่งคืนเนื้อหาในการสนทนา + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todowrite + +จัดการรายการสิ่งที่ต้องทำระหว่างเซสชันการเขียนโค้ด + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +สร้างและอัปเดตรายการงานเพื่อติดตามความคืบหน้าระหว่างการดำเนินการที่ซับซ้อน LLM ใช้สิ่งนี้เพื่อจัดระเบียบงานที่มีหลายขั้นตอน + +:::note +เครื่องมือนี้ปิดใช้งานสำหรับตัวแทนย่อยตามค่าเริ่มต้น แต่คุณสามารถเปิดใช้งานได้ด้วยตนเอง [เรียนรู้เพิ่มเติม](/docs/agents/#สิทธิ์) +::: + +--- + +### todoread + +อ่านรายการสิ่งที่ต้องทำที่มีอยู่ + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +อ่านสถานะรายการสิ่งที่ต้องทำปัจจุบัน ใช้โดย LLM เพื่อติดตามงานที่กำลังรอดำเนินการหรือเสร็จสิ้น + +:::note +เครื่องมือนี้ปิดใช้งานสำหรับตัวแทนย่อยตามค่าเริ่มต้น แต่คุณสามารถเปิดใช้งานได้ด้วยตนเอง [เรียนรู้เพิ่มเติม](/docs/agents/#สิทธิ์) +::: + +--- + +### webfetch + +ดึงเนื้อหาเว็บ + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +อนุญาตให้ LLM ดึงข้อมูลและอ่านหน้าเว็บ มีประโยชน์สำหรับการค้นหาเอกสารหรือค้นคว้าแหล่งข้อมูลออนไลน์ + +--- + +### websearch + +ค้นหาข้อมูลในเว็บ + +:::note +เครื่องมือนี้ใช้ได้เฉพาะเมื่อใช้ผู้ให้บริการ OpenCode หรือเมื่อตัวแปรสภาพแวดล้อม `OPENCODE_ENABLE_EXA` ถูกตั้งค่าเป็นค่าความจริง (เช่น `true` หรือ `1`) + +หากต้องการเปิดใช้งานเมื่อเปิดตัว OpenCode: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +ทำการค้นหาเว็บโดยใช้ Exa AI เพื่อค้นหาข้อมูลที่เกี่ยวข้องทางออนไลน์ มีประโยชน์สำหรับการค้นคว้าหัวข้อ ค้นหาเหตุการณ์ปัจจุบัน หรือการรวบรวมข้อมูลนอกเหนือจากการตัดข้อมูลการฝึกอบรม + +ไม่จำเป็นต้องใช้คีย์ API เครื่องมือนี้เชื่อมต่อโดยตรงกับบริการ MCP ที่โฮสต์ของ Exa AI โดยไม่มีการตรวจสอบสิทธิ์ + +:::tip +ใช้ `websearch` เมื่อคุณต้องการค้นหาข้อมูล (การค้นพบ) และใช้ `webfetch` เมื่อคุณต้องการดึงเนื้อหาจาก URL เฉพาะ (การดึงข้อมูล) +::: + +--- + +### question + +ถามคำถามผู้ใช้ระหว่างการดำเนินการ + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +เครื่องมือนี้อนุญาตให้ LLM ถามคำถามผู้ใช้ระหว่างทำงาน มันมีประโยชน์สำหรับ: + +- การรวบรวมความชอบหรือความต้องการของผู้ใช้ +- ชี้แจงคำแนะนำที่ไม่ชัดเจน +- การตัดสินใจเกี่ยวกับทางเลือกในการดำเนินการ +- เสนอทางเลือกว่าจะไปในทิศทางใด + +คำถามแต่ละข้อประกอบด้วยส่วนหัว ข้อความคำถาม และรายการตัวเลือก ผู้ใช้สามารถเลือกจากตัวเลือกที่มีให้หรือพิมพ์คำตอบที่กำหนดเองได้ เมื่อมีคำถามหลายข้อ ผู้ใช้สามารถสลับไปมาระหว่างคำถามเหล่านั้นก่อนที่จะส่งคำตอบทั้งหมด + +--- + +## เครื่องมือที่กำหนดเอง + +เครื่องมือแบบกำหนดเองช่วยให้คุณสามารถกำหนดฟังก์ชันของคุณเองที่ LLM สามารถเรียกได้ สิ่งเหล่านี้ถูกกำหนดไว้ในไฟล์ปรับแต่งของคุณและสามารถรันโค้ดได้ตามใจชอบ + +[เรียนรู้เพิ่มเติม](/docs/custom-tools) เกี่ยวกับการสร้างเครื่องมือที่กำหนดเอง + +--- + +## MCP เซิร์ฟเวอร์ + +เซิร์ฟเวอร์ MCP (Model Context Protocol) ช่วยให้คุณสามารถรวมเครื่องมือและบริการภายนอกได้ ซึ่งรวมถึงการเข้าถึงฐานข้อมูล การบูรณาการ API และบริการของบุคคลที่สาม + +[เรียนรู้เพิ่มเติม](/docs/mcp-servers) เกี่ยวกับการกำหนดค่าเซิร์ฟเวอร์ MCP + +--- + +## ภายใน + +ภายใน เครื่องมือต่างๆ เช่น `grep`, `glob` และ `list` ใช้ [ripgrep](https://github.com/BurntSushi/ripgrep) ภายใต้ประทุน ตามค่าเริ่มต้น ripgrep เคารพรูปแบบ `.gitignore` ซึ่งหมายความว่าไฟล์และไดเร็กทอรีที่อยู่ใน `.gitignore` ของคุณจะถูกแยกออกจากการค้นหาและรายการ + +--- + +### ละเว้นรูปแบบ + +หากต้องการรวมไฟล์ที่ปกติจะถูกละเว้น ให้สร้างไฟล์ `.ignore` ในรูทโปรเจ็กต์ของคุณ ไฟล์นี้สามารถอนุญาตเส้นทางบางอย่างได้อย่างชัดเจน + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +ตัวอย่างเช่น ไฟล์ `.ignore` นี้อนุญาตให้ ripgrep ค้นหาภายในไดเร็กทอรี `node_modules/`, `dist/` และ `build/` แม้ว่าไดเร็กทอรีเหล่านั้นจะแสดงอยู่ใน `.gitignore` ก็ตาม diff --git a/packages/web/src/content/docs/th/troubleshooting.mdx b/packages/web/src/content/docs/th/troubleshooting.mdx new file mode 100644 index 000000000..c527bd77f --- /dev/null +++ b/packages/web/src/content/docs/th/troubleshooting.mdx @@ -0,0 +1,300 @@ +--- +title: การแก้ไขปัญหา +description: ปัญหาทั่วไปและวิธีแก้ปัญหา +--- + +หากต้องการแก้ไขข้อบกพร่องเกี่ยวกับ OpenCode ให้เริ่มต้นด้วยการตรวจสอบบันทึกและข้อมูลในเครื่องที่จัดเก็บไว้ในดิสก์ + +--- + +## บันทึก + +ไฟล์บันทึกถูกเขียนไปที่: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: กด `WIN+R` แล้ววาง `%USERPROFILE%\.local\share\opencode\log` + +ไฟล์บันทึกจะถูกตั้งชื่อด้วยการประทับเวลา (เช่น `2025-01-09T123456.log`) และไฟล์บันทึกล่าสุด 10 ไฟล์จะถูกเก็บไว้ + +คุณสามารถตั้งค่าระดับการบันทึกด้วยตัวเลือกบรรทัดคำสั่ง `--log-level` เพื่อรับข้อมูลการแก้ไขข้อบกพร่องโดยละเอียดเพิ่มเติม ตัวอย่างเช่น `opencode --log-level DEBUG` + +--- + +## พื้นที่จัดเก็บ + +opencode เก็บข้อมูลเซสชันและข้อมูลแอปพลิเคชันอื่น ๆ ไว้บนดิสก์ที่: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: กด `WIN+R` แล้ววาง `%USERPROFILE%\.local\share\opencode` + +ไดเรกทอรีนี้ประกอบด้วย: + +- `auth.json` - ​​ข้อมูลการตรวจสอบสิทธิ์ เช่น คีย์ API, โทเค็น OAuth +- `log/` - ​​บันทึกแอปพลิเคชัน +- `project/` - ​​ข้อมูลเฉพาะโครงการ เช่น ข้อมูลเซสชันและข้อความ + - หากโปรเจ็กต์อยู่ภายใน repo Git มันจะถูกจัดเก็บไว้ใน `.//storage/` + - หากไม่ใช่ repo Git มันจะถูกเก็บไว้ใน `./global/storage/` + +--- + +## แอปเดสก์ท็อป + +OpenCode Desktop รันเซิร์ฟเวอร์ OpenCode ในเครื่อง (ไฟล์ `opencode-cli` sidecar) ในเบื้องหลัง ปัญหาส่วนใหญ่มีสาเหตุมาจากปลั๊กอินที่ทำงานผิดปกติ แคชเสียหาย หรือการตั้งค่าเซิร์ฟเวอร์ไม่ถูกต้อง + +### การตรวจสอบอย่างรวดเร็ว + +- ออกจากระบบโดยสมบูรณ์แล้วเปิดแอปใหม่อีกครั้ง +- หากแอปแสดงหน้าจอข้อผิดพลาด ให้คลิก **รีสตาร์ท** และคัดลอกรายละเอียดข้อผิดพลาด +- macOS เท่านั้น: เมนู `OpenCode` -> **โหลด Webview ใหม่** (ช่วยได้หาก UI ว่างเปล่า/frozen) + +--- + +### ปิดการใช้งานปลั๊กอิน + +หากแอปเดสก์ท็อปขัดข้องเมื่อเปิดใช้งาน หยุดทำงาน หรือทำงานผิดปกติ ให้เริ่มต้นด้วยการปิดใช้งานปลั๊กอิน + +#### ตรวจสอบการกำหนดค่าส่วนกลาง + +เปิดไฟล์กำหนดค่าส่วนกลางของคุณแล้วมองหาคีย์ `plugin` + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (หรือ `~/.config/opencode/opencode.json`) +- **macOS/Linux** (การติดตั้งเก่ากว่า): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: กด `WIN+R` แล้ววาง `%USERPROFILE%\.config\opencode\opencode.jsonc` + +หากคุณได้กำหนดค่าปลั๊กอินไว้ ให้ปิดการใช้งานชั่วคราวโดยลบคีย์ออกหรือตั้งค่าเป็นอาร์เรย์ว่าง: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### ตรวจสอบไดเร็กทอรีปลั๊กอิน + +OpenCode ยังสามารถโหลดปลั๊กอินในเครื่องจากดิสก์ได้ ย้ายสิ่งเหล่านี้ออกไปชั่วคราว (หรือเปลี่ยนชื่อโฟลเดอร์) และรีสตาร์ทแอปเดสก์ท็อป: + +- **ปลั๊กอินสากล** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: กด `WIN+R` แล้ววาง `%USERPROFILE%\.config\opencode\plugins` +- **ปลั๊กอินโครงการ** (เฉพาะในกรณีที่คุณใช้การกำหนดค่าต่อโครงการ) + - `/.opencode/plugins/` + +หากแอปเริ่มทำงานอีกครั้ง ให้เปิดใช้งานปลั๊กอินอีกครั้งทีละรายการเพื่อดูว่าปลั๊กอินใดเป็นสาเหตุของปัญหา + +--- + +### ล้างแคช + +หากการปิดใช้งานปลั๊กอินไม่ได้ผล (หรือการติดตั้งปลั๊กอินค้าง) ให้ล้างแคชเพื่อให้ OpenCode สามารถสร้างใหม่ได้ + +1. ออกจาก OpenCode Desktop โดยสมบูรณ์ +2. ลบไดเรกทอรีแคช: + +- **macOS**: ตัวค้นหา -> `Cmd+Shift+G` -> วาง `~/.cache/opencode` +- **Linux**: ลบ `~/.cache/opencode` (หรือรัน `rm -rf ~/.cache/opencode`) +- **Windows**: กด `WIN+R` แล้ววาง `%USERPROFILE%\.cache\opencode` + +3. รีสตาร์ทเดสก์ท็อป OpenCode + +--- + +### Fix server connection issues + +OpenCode Desktop สามารถเริ่มต้นเซิร์ฟเวอร์ภายในเครื่องของตนเองได้ (ค่าเริ่มต้น) หรือเชื่อมต่อกับเซิร์ฟเวอร์ URL ที่คุณกำหนดค่าไว้ + +หากคุณเห็นกล่องโต้ตอบ **"การเชื่อมต่อล้มเหลว"** (หรือแอปไม่เคยผ่านหน้าจอเริ่มต้น) ให้ตรวจสอบเซิร์ฟเวอร์ที่กำหนดเอง URL + +#### ล้างเซิร์ฟเวอร์เริ่มต้นของเดสก์ท็อป URL + +จากหน้าจอหลัก คลิกชื่อเซิร์ฟเวอร์ (ที่มีจุดสถานะ) เพื่อเปิดตัวเลือกเซิร์ฟเวอร์ ในส่วน **เซิร์ฟเวอร์เริ่มต้น** คลิก **ล้าง** + +#### ลบ `server.port` / `server.hostname` ออกจากการกำหนดค่าของคุณ + +หาก `opencode.json(c)` ของคุณมีส่วน `server` ให้ลบออกชั่วคราวแล้วรีสตาร์ทแอปเดสก์ท็อป + +#### ตรวจสอบตัวแปรสภาพแวดล้อม + +หากคุณตั้งค่า `OPENCODE_PORT` ในสภาพแวดล้อมของคุณ แอปเดสก์ท็อปจะพยายามใช้พอร์ตนั้นสำหรับเซิร์ฟเวอร์ภายในเครื่อง + +- ยกเลิกการตั้งค่า `OPENCODE_PORT` (หรือเลือกพอร์ตว่าง) แล้วรีสตาร์ท + +--- + +### Linux: ปัญหา Wayland / X11 + +บน Linux การตั้งค่า Wayland บางอย่างอาจทำให้เกิดหน้าต่างว่างหรือข้อผิดพลาดของตัวประกอบ + +- หากคุณอยู่บน Wayland และแอปว่างเปล่า/crashing ให้ลองเปิดใช้งานด้วย `OC_ALLOW_WAYLAND=1` +- หากสิ่งนั้นทำให้สิ่งต่าง ๆ แย่ลง ให้ลบออกแล้วลองเปิดใช้งานภายใต้เซสชัน X11 แทน + +--- + +### Windows: รันไทม์ WebView2 + +บน Windows OpenCode Desktop ต้องใช้ Microsoft Edge **WebView2 Runtime** หากแอปเปิดเป็นหน้าต่างว่างหรือไม่เริ่มทำงาน ให้ติดตั้ง/update WebView2 แล้วลองอีกครั้ง + +--- + +### Windows: ปัญหาด้านประสิทธิภาพทั่วไป + +หากคุณประสบปัญหาประสิทธิภาพการทำงานช้า ปัญหาการเข้าถึงไฟล์ หรือปัญหาเทอร์มินัลบน Windows ให้ลองใช้ [WSL (ระบบย่อย Windows สำหรับ Linux)](/docs/windows-wsl) WSL มอบสภาพแวดล้อม Linux ที่ทำงานร่วมกับคุณสมบัติของ OpenCode ได้อย่างราบรื่นยิ่งขึ้น + +--- + +### การแจ้งเตือนไม่แสดง + +OpenCode Desktop จะแสดงการแจ้งเตือนของระบบเฉพาะเมื่อ: + +- การแจ้งเตือนเปิดใช้งานสำหรับ OpenCode ในการตั้งค่าระบบปฏิบัติการของคุณและ +- หน้าต่างแอพไม่ได้โฟกัส + +--- + +### รีเซ็ตที่เก็บข้อมูลแอปเดสก์ท็อป (วิธีสุดท้าย) + +หากแอปไม่เริ่มทำงานและคุณไม่สามารถล้างการตั้งค่าจากภายใน UI ได้ ให้รีเซ็ตสถานะที่บันทึกไว้ของแอปเดสก์ท็อป + +1. ออกจากเดสก์ท็อป OpenCode +2. ค้นหาและลบไฟล์เหล่านี้ (อยู่ในไดเร็กทอรีข้อมูลแอป OpenCode Desktop): + +- `opencode.settings.dat` (เซิร์ฟเวอร์เริ่มต้นของเดสก์ท็อป URL) +- `opencode.global.dat` และ `opencode.workspace.*.dat` (สถานะ UI เช่น เซิร์ฟเวอร์ล่าสุด/projects) + +หากต้องการค้นหาไดเร็กทอรีอย่างรวดเร็ว: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (จากนั้นค้นหาชื่อไฟล์ด้านบน) +- **Linux**: ค้นหาภายใต้ `~/.local/share` สำหรับชื่อไฟล์ด้านบน +- **Windows**: กด `WIN+R` -> `%APPDATA%` (จากนั้นค้นหาชื่อไฟล์ด้านบน) + +--- + +## การขอความช่วยเหลือ + +หากคุณประสบปัญหากับ OpenCode: + +1. **รายงานปัญหาเกี่ยวกับ GitHub** + + วิธีที่ดีที่สุดในการรายงานจุดบกพร่องหรือขอคุณสมบัติคือผ่านพื้นที่เก็บข้อมูล GitHub ของเรา: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + ก่อนที่จะสร้างปัญหาใหม่ ให้ค้นหาปัญหาที่มีอยู่เพื่อดูว่าปัญหาของคุณได้รับการรายงานแล้วหรือไม่ + +2. **เข้าร่วม Discord ของเรา** + + สำหรับความช่วยเหลือแบบเรียลไทม์และการสนทนาในชุมชน เข้าร่วมเซิร์ฟเวอร์ Discord ของเรา: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## ปัญหาทั่วไป + +ต่อไปนี้เป็นปัญหาทั่วไปบางประการและวิธีแก้ปัญหา + +--- + +### OpenCode จะไม่เริ่มทำงาน + +1. ตรวจสอบบันทึกเพื่อดูข้อความแสดงข้อผิดพลาด +2. ลองรันด้วย `--print-logs` เพื่อดูเอาต์พุตในเทอร์มินัล +3. ตรวจสอบให้แน่ใจว่าคุณมีเวอร์ชันล่าสุดด้วย `opencode upgrade` + +--- + +### ปัญหาการรับรองความถูกต้อง + +1. ลองตรวจสอบความถูกต้องอีกครั้งด้วยคำสั่ง `/connect` ใน TUI +2. ตรวจสอบว่าคีย์ API ของคุณถูกต้อง +3. ตรวจสอบให้แน่ใจว่าเครือข่ายของคุณอนุญาตการเชื่อมต่อกับ API ของผู้ให้บริการ + +--- + +### ไม่มีรุ่น + +1. ตรวจสอบว่าคุณได้รับการรับรองความถูกต้องกับผู้ให้บริการแล้ว +2. ตรวจสอบชื่อรุ่นในการกำหนดค่าของคุณถูกต้อง +3. บางรุ่นอาจต้องมีการเข้าถึงหรือสมัครสมาชิกโดยเฉพาะ + +หากคุณพบ `ProviderModelNotFoundError` เป็นไปได้มากว่าคุณจะคิดผิด +อ้างอิงแบบจำลองที่ไหนสักแห่ง +ควรอ้างอิงโมเดลดังนี้: `/` + +ตัวอย่าง: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +หากต้องการทราบว่าคุณมีสิทธิ์เข้าถึงรุ่นใด ให้เรียกใช้ `opencode models` + +--- + +### ผู้ให้บริการInitError + +หากคุณพบ ProviderInitError คุณอาจมีการกำหนดค่าที่ไม่ถูกต้องหรือเสียหาย + +เพื่อแก้ไขปัญหานี้: + +1. ขั้นแรก ตรวจสอบให้แน่ใจว่าผู้ให้บริการของคุณตั้งค่าอย่างถูกต้องโดยทำตาม [คู่มือผู้ให้บริการ](/docs/providers) +2. หากปัญหายังคงอยู่ ให้ลองล้างการกำหนดค่าที่เก็บไว้: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + บน Windows กด `WIN+R` และลบ: `%USERPROFILE%\.local\share\opencode` + +3. ตรวจสอบความถูกต้องอีกครั้งกับผู้ให้บริการของคุณโดยใช้คำสั่ง `/connect` ใน TUI + +--- + +### ปัญหา AI_APICallError และแพ็คเกจผู้ให้บริการ + +หากคุณพบข้อผิดพลาดในการโทร API อาจเนื่องมาจากแพ็คเกจผู้ให้บริการที่ล้าสมัย opencode จะติดตั้งแพ็คเกจของผู้ให้บริการแบบไดนามิก (OpenAI, Anthropic, Google ฯลฯ) ตามความจำเป็น และแคชไว้ในเครื่อง + +ในการแก้ไขปัญหาแพ็คเกจผู้ให้บริการ: + +1. ล้างแคชแพ็คเกจผู้ให้บริการ: + + ```bash + rm -rf ~/.cache/opencode + ``` + + บน Windows กด `WIN+R` และลบ: `%USERPROFILE%\.cache\opencode` + +2. รีสตาร์ท opencode เพื่อติดตั้งแพ็คเกจผู้ให้บริการล่าสุดอีกครั้ง + +การดำเนินการนี้จะบังคับให้ opencode ดาวน์โหลดแพ็คเกจผู้ให้บริการเวอร์ชันล่าสุด ซึ่งมักจะแก้ไขปัญหาความเข้ากันได้กับพารามิเตอร์โมเดลและการเปลี่ยนแปลง API + +--- + +### Copy/paste ไม่ทำงานบน Linux + +ผู้ใช้ Linux จำเป็นต้องติดตั้งยูทิลิตี้คลิปบอร์ดตัวใดตัวหนึ่งต่อไปนี้เพื่อให้ฟังก์ชัน copy/paste ทำงาน: + +**สำหรับระบบ X11:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**สำหรับระบบ Wayland:** + +```bash +apt install -y wl-clipboard +``` + +**สำหรับสภาพแวดล้อมที่ไม่มีหัว:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode จะตรวจพบว่าคุณใช้ Wayland และชอบ `wl-clipboard` หรือไม่เช่นนั้นจะพยายามค้นหาเครื่องมือคลิปบอร์ดตามลำดับ: `xclip` และ `xsel` diff --git a/packages/web/src/content/docs/th/tui.mdx b/packages/web/src/content/docs/th/tui.mdx new file mode 100644 index 000000000..c24bf6ca6 --- /dev/null +++ b/packages/web/src/content/docs/th/tui.mdx @@ -0,0 +1,390 @@ +--- +title: TUI +description: การใช้อินเทอร์เฟซผู้ใช้เทอร์มินัล OpenCode +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode มีอินเทอร์เฟซเทอร์มินัลแบบโต้ตอบหรือ TUI สำหรับการทำงานในโครงการของคุณด้วย LLM + +การรัน OpenCode จะเริ่มต้น TUI สำหรับไดเร็กทอรีปัจจุบัน + +```bash +opencode +``` + +หรือคุณสามารถเริ่มต้นสำหรับไดเร็กทอรีการทำงานเฉพาะได้ + +```bash +opencode /path/to/project +``` + +เมื่อคุณอยู่ใน TUI แล้ว คุณสามารถแจ้งด้วยข้อความได้ + +```text +Give me a quick summary of the codebase. +``` + +--- + +## การอ้างอิงไฟล์ + +คุณสามารถอ้างอิงไฟล์ในข้อความของคุณโดยใช้ `@` นี่เป็นการค้นหาไฟล์ที่ไม่ชัดเจนในไดเร็กทอรีการทำงานปัจจุบัน + +:::tip +คุณยังสามารถใช้ `@` เพื่ออ้างอิงไฟล์ในข้อความของคุณได้ +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +เนื้อหาของไฟล์จะถูกเพิ่มในการสนทนาโดยอัตโนมัติ + +--- + +## คำสั่งทุบตี + +เริ่มข้อความด้วย `!` เพื่อรันคำสั่งเชลล์ + +```bash frame="none" +!ls -la +``` + +ผลลัพธ์ของคำสั่งจะถูกเพิ่มเข้าไปในการสนทนาซึ่งเป็นผลลัพธ์ของเครื่องมือ + +--- + +## คำสั่ง + +เมื่อใช้ OpenCode TUI คุณสามารถพิมพ์ `/` ตามด้วยชื่อคำสั่งเพื่อดำเนินการอย่างรวดเร็ว ตัวอย่างเช่น: + +```bash frame="none" +/help +``` + +คำสั่งส่วนใหญ่ยังมีการผูกคีย์โดยใช้ `ctrl+x` เป็นคีย์ผู้นำ โดยที่ `ctrl+x` เป็นคีย์ผู้นำเริ่มต้น [เรียนรู้เพิ่มเติม](/docs/keybinds) + +นี่คือคำสั่งสแลชที่ใช้ได้ทั้งหมด: + +--- + +### connect + +เพิ่มผู้ให้บริการให้กับ OpenCode ให้คุณเลือกจากผู้ให้บริการที่มีอยู่และเพิ่มคีย์ API + +```bash frame="none" +/connect +``` + +--- + +### compact + +กระชับเซสชันปัจจุบัน _นามแฝง_: `/summarize` + +```bash frame="none" +/compact +``` + +**ผูกปุ่ม:** `ctrl+x c` + +--- + +### details + +สลับรายละเอียดการดำเนินการของเครื่องมือ + +```bash frame="none" +/details +``` + +**ผูกปุ่ม:** `ctrl+x d` + +--- + +### editor + +เปิดตัวแก้ไขภายนอกเพื่อเขียนข้อความ ใช้ตัวแก้ไขที่ตั้งค่าไว้ในตัวแปรสภาพแวดล้อม `EDITOR` ของคุณ [เรียนรู้เพิ่มเติม](#editor-setup) + +```bash frame="none" +/editor +``` + +**ผูกปุ่ม:** `ctrl+x e` + +--- + +### exit + +ออกจาก OpenCode _นามแฝง_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**ผูกปุ่ม:** `ctrl+x q` + +--- + +### export + +ส่งออกการสนทนาปัจจุบันไปยัง Markdown และเปิดในตัวแก้ไขเริ่มต้นของคุณ ใช้ตัวแก้ไขที่ตั้งค่าไว้ในตัวแปรสภาพแวดล้อม `EDITOR` ของคุณ [เรียนรู้เพิ่มเติม](#editor-setup) + +```bash frame="none" +/export +``` + +**ผูกปุ่ม:** `ctrl+x x` + +--- + +### help + +แสดงกล่องโต้ตอบความช่วยเหลือ + +```bash frame="none" +/help +``` + +**ผูกปุ่ม:** `ctrl+x h` + +--- + +### init + +สร้างหรืออัปเดตไฟล์ `AGENTS.md` [เรียนรู้เพิ่มเติม](/docs/rules) + +```bash frame="none" +/init +``` + +**ผูกปุ่ม:** `ctrl+x i` + +--- + +### models + +รายการรุ่นที่มีจำหน่าย + +```bash frame="none" +/models +``` + +**ผูกปุ่ม:** `ctrl+x m` + +--- + +### new + +เริ่มเซสชันใหม่ _นามแฝง_: `/clear` + +```bash frame="none" +/new +``` + +**ผูกปุ่ม:** `ctrl+x n` + +--- + +### redo + +ทำซ้ำข้อความที่เลิกทำก่อนหน้านี้ ใช้ได้หลังจากใช้ `/undo` เท่านั้น + +:::tip +การเปลี่ยนแปลงไฟล์ใดๆ จะถูกกู้คืนด้วย +::: + +ภายในจะใช้ Git เพื่อจัดการการเปลี่ยนแปลงไฟล์ ดังนั้นโครงการของคุณ **จำเป็นต้อง +เป็นที่เก็บ Git** + +```bash frame="none" +/redo +``` + +**ผูกปุ่ม:** `ctrl+x r` + +--- + +### sessions + +รายการและสลับระหว่างเซสชัน _นามแฝง_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**ผูกปุ่ม:** `ctrl+x l` + +--- + +### share + +แบ่งปันเซสชั่นปัจจุบัน [เรียนรู้เพิ่มเติม](/docs/share) + +```bash frame="none" +/share +``` + +**ผูกปุ่ม:** `ctrl+x s` + +--- + +### themes + +แสดงรายการธีมที่มีอยู่ + +```bash frame="none" +/theme +``` + +**ผูกปุ่ม:** `ctrl+x t` + +--- + +### thinking + +สลับการเปิดเผยการบล็อก thinking/reasoning ในการสนทนา เมื่อเปิดใช้งาน คุณสามารถดูกระบวนการให้เหตุผลของแบบจำลองสำหรับแบบจำลองที่รองรับการคิดแบบขยาย + +:::note +คำสั่งนี้ควบคุมเฉพาะว่าบล็อกการคิด **แสดง** หรือไม่ โดยไม่ได้เปิดใช้งานหรือปิดใช้งานความสามารถในการให้เหตุผลของโมเดล หากต้องการสลับความสามารถในการให้เหตุผลตามจริง ให้ใช้ `ctrl+t` เพื่อหมุนเวียนไปตามตัวแปรโมเดล +::: + +```bash frame="none" +/thinking +``` + +--- + +### undo + +เลิกทำข้อความสุดท้ายในการสนทนา ลบข้อความผู้ใช้ล่าสุด การตอบกลับที่ตามมาทั้งหมด และการเปลี่ยนแปลงไฟล์ใดๆ + +:::tip +การเปลี่ยนแปลงไฟล์ใดๆ ที่ทำจะถูกคืนค่าด้วย +::: + +ภายในจะใช้ Git เพื่อจัดการการเปลี่ยนแปลงไฟล์ ดังนั้นโครงการของคุณ **จำเป็นต้อง +เป็นที่เก็บ Git** + +```bash frame="none" +/undo +``` + +**ผูกปุ่ม:** `ctrl+x u` + +--- + +### unshare + +ยกเลิกการแชร์เซสชันปัจจุบัน [เรียนรู้เพิ่มเติม](/docs/share#un-sharing) + +```bash frame="none" +/unshare +``` + +--- + +## การตั้งค่าตัวแก้ไข + +ทั้งคำสั่ง `/editor` และ `/export` ใช้ตัวแก้ไขที่ระบุในตัวแปรสภาพแวดล้อม `EDITOR` ของคุณ + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + + หากต้องการทำให้เป็นแบบถาวร ให้เพิ่มสิ่งนี้ลงในโปรไฟล์เชลล์ของคุณ + `~/.bashrc`, `~/.zshrc` ฯลฯ + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + + หากต้องการทำให้เป็นแบบถาวร ให้ใช้ **คุณสมบัติของระบบ** > **สภาพแวดล้อม + ตัวแปร**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + + หากต้องการทำให้เป็นแบบถาวร ให้เพิ่มสิ่งนี้ลงในโปรไฟล์ PowerShell ของคุณ + + + + +ตัวเลือกตัวแก้ไขยอดนิยม ได้แก่ : + +- `code` - ​​รหัส Visual Studio +- `cursor` - ​​เคอร์เซอร์ +- `windsurf` - ​​วินด์เซิร์ฟ +- `nvim` - ​​บรรณาธิการ Neovim +- `vim` - ​​โปรแกรมแก้ไขเป็นกลุ่ม +- `nano` - ​​โปรแกรมแก้ไขนาโน +- `notepad` - ​​สมุดบันทึกของ Windows +- `subl` - ​​ข้อความประเสริฐ + +:::note +บรรณาธิการบางคนเช่น VS Code จำเป็นต้องเริ่มต้นด้วยแฟล็ก `--wait` +::: + +ผู้แก้ไขบางรายจำเป็นต้องมีอาร์กิวเมนต์บรรทัดคำสั่งเพื่อทำงานในโหมดการบล็อก แฟล็ก `--wait` ทำให้กระบวนการแก้ไขบล็อกจนกว่าจะปิด + +--- + +## กำหนดค่า + +คุณสามารถปรับแต่งพฤติกรรม TUI ผ่านไฟล์กำหนดค่า OpenCode ของคุณได้ + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### ตัวเลือก + +- `scroll_acceleration` - ​​เปิดใช้งานการเร่งความเร็วการเลื่อนแบบ macOS เพื่อการเลื่อนที่ราบรื่นและเป็นธรรมชาติ เมื่อเปิดใช้งาน ความเร็วในการเลื่อนจะเพิ่มขึ้นตามท่าทางการเลื่อนอย่างรวดเร็ว และคงความแม่นยำไว้สำหรับการเคลื่อนไหวที่ช้าลง **การตั้งค่านี้มีความสำคัญมากกว่า `scroll_speed` และแทนที่เมื่อเปิดใช้งาน** +- `scroll_speed` - ​​ควบคุมความเร็วของการเลื่อน TUI เมื่อใช้คำสั่งการเลื่อน (ขั้นต่ำ: `1`) ค่าเริ่มต้นเป็น `3` **หมายเหตุ: สิ่งนี้จะถูกละเว้นหากตั้งค่า `scroll_acceleration.enabled` เป็น `true`.** + +--- + +## การปรับแต่ง + +คุณสามารถปรับแต่งแง่มุมต่างๆ ของมุมมอง TUI ได้โดยใช้ชุดคำสั่ง (`ctrl+x h` หรือ `/help`) การตั้งค่าเหล่านี้ยังคงมีอยู่ตลอดการรีสตาร์ท + +--- + +#### การแสดงชื่อผู้ใช้ + +สลับว่าจะให้ชื่อผู้ใช้ของคุณปรากฏในข้อความแชทหรือไม่ เข้าถึงสิ่งนี้ผ่าน: + +- จานคำสั่ง: ค้นหา "ชื่อผู้ใช้" หรือ "ซ่อนชื่อผู้ใช้" +- การตั้งค่าจะคงอยู่โดยอัตโนมัติและจะถูกจดจำตลอดเซสชัน TUI diff --git a/packages/web/src/content/docs/th/web.mdx b/packages/web/src/content/docs/th/web.mdx new file mode 100644 index 000000000..5aa57b41a --- /dev/null +++ b/packages/web/src/content/docs/th/web.mdx @@ -0,0 +1,142 @@ +--- +title: เว็บ +description: การใช้ OpenCode ในเบราว์เซอร์ของคุณ +--- + +OpenCode สามารถทำงานเป็นเว็บแอปพลิเคชันในเบราว์เซอร์ของคุณได้ โดยมอบประสบการณ์การเขียนโค้ด AI อันทรงพลังแบบเดียวกันโดยไม่ต้องใช้เทอร์มินัล + +![เว็บ OpenCode - เซสชันใหม่](../../../assets/web/web-homepage-new-session.png) + +## เริ่มต้นใช้งาน + +เริ่มเว็บอินเตอร์เฟสด้วยการรัน: + +```bash +opencode web +``` + +สิ่งนี้จะเริ่มต้นเซิร์ฟเวอร์ท้องถิ่นบน `127.0.0.1` ด้วยพอร์ตที่มีอยู่แบบสุ่มและเปิด OpenCode โดยอัตโนมัติในเบราว์เซอร์เริ่มต้นของคุณ + +:::caution +หากไม่ได้ตั้งค่า `OPENCODE_SERVER_PASSWORD` เซิร์ฟเวอร์จะไม่ปลอดภัย นี่เป็นเรื่องปกติสำหรับการใช้งานภายในเครื่อง แต่ควรตั้งค่าสำหรับการเข้าถึงเครือข่าย +::: + +:::tip[ผู้ใช้วินโดวส์] +เพื่อประสบการณ์ที่ดีที่สุด ให้เรียกใช้ `opencode web` จาก [WSL](/docs/windows-wsl) แทนที่จะเป็น PowerShell สิ่งนี้ทำให้มั่นใจได้ถึงการเข้าถึงระบบไฟล์ที่เหมาะสมและการรวมเทอร์มินัล +::: + +--- + +## การกำหนดค่า + +คุณสามารถกำหนดค่าเว็บเซิร์ฟเวอร์ได้โดยใช้แฟล็กบรรทัดคำสั่งหรือใน [ไฟล์กำหนดค่า](/docs/config) + +### ท่าเรือ + +ตามค่าเริ่มต้น OpenCode จะเลือกพอร์ตที่พร้อมใช้งาน คุณสามารถระบุพอร์ต: + +```bash +opencode web --port 4096 +``` + +### ชื่อโฮสต์ + +ตามค่าเริ่มต้น เซิร์ฟเวอร์จะเชื่อมโยงกับ `127.0.0.1` (เฉพาะโลคัลโฮสต์เท่านั้น) หากต้องการให้ OpenCode เข้าถึงได้บนเครือข่ายของคุณ: + +```bash +opencode web --hostname 0.0.0.0 +``` + +เมื่อใช้ `0.0.0.0` OpenCode จะแสดงทั้งที่อยู่ในท้องถิ่นและเครือข่าย: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### การค้นพบ mDNS + +เปิดใช้งาน mDNS เพื่อให้เซิร์ฟเวอร์ของคุณค้นพบได้บนเครือข่ายท้องถิ่น: + +```bash +opencode web --mdns +``` + +สิ่งนี้จะตั้งชื่อโฮสต์เป็น `0.0.0.0` โดยอัตโนมัติและโฆษณาเซิร์ฟเวอร์เป็น `opencode.local` + +คุณสามารถปรับแต่งชื่อโดเมน mDNS เพื่อเรียกใช้หลายอินสแตนซ์บนเครือข่ายเดียวกันได้: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +หากต้องการอนุญาตโดเมนเพิ่มเติมสำหรับ CORS (มีประโยชน์สำหรับส่วนหน้าที่กำหนดเอง): + +```bash +opencode web --cors https://example.com +``` + +### การรับรองความถูกต้อง + +เพื่อป้องกันการเข้าถึง ให้ตั้งรหัสผ่านโดยใช้ตัวแปรสภาพแวดล้อม `OPENCODE_SERVER_PASSWORD`: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +ชื่อผู้ใช้มีค่าเริ่มต้นเป็น `opencode` แต่สามารถเปลี่ยนได้ด้วย `OPENCODE_SERVER_USERNAME` + +--- + +## การใช้เว็บอินเตอร์เฟส + +เมื่อเริ่มต้นแล้ว เว็บอินเตอร์เฟสจะให้สิทธิ์การเข้าถึงเซสชัน OpenCode ของคุณ + +### เซสชัน + +ดูและจัดการเซสชันของคุณจากหน้าแรก คุณสามารถดูเซสชันที่ใช้งานอยู่และเริ่มต้นเซสชันใหม่ได้ + +![OpenCode Web - เซสชันที่ใช้งานอยู่](../../../assets/web/web-homepage-active-session.png) + +### สถานะเซิร์ฟเวอร์ + +คลิก "ดูเซิร์ฟเวอร์" เพื่อดูเซิร์ฟเวอร์ที่เชื่อมต่อและสถานะ + +![เว็บ OpenCode - ดูเซิร์ฟเวอร์](../../../assets/web/web-homepage-see-servers.png) + +--- + +## การต่อเทอร์มินัล + +คุณสามารถแนบเทอร์มินัล TUI กับเว็บเซิร์ฟเวอร์ที่ทำงานอยู่: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +ซึ่งจะทำให้คุณสามารถใช้ทั้งเว็บอินเทอร์เฟซและเทอร์มินัลพร้อมกัน โดยแชร์เซสชันและสถานะเดียวกัน + +--- + +## ไฟล์กำหนดค่า + +คุณยังสามารถกำหนดการตั้งค่าเซิร์ฟเวอร์ในไฟล์กำหนดค่า `opencode.json` ของคุณได้: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +ธงบรรทัดคำสั่งมีความสำคัญเหนือกว่าการตั้งค่าไฟล์กำหนดค่า diff --git a/packages/web/src/content/docs/th/windows-wsl.mdx b/packages/web/src/content/docs/th/windows-wsl.mdx new file mode 100644 index 000000000..910de4b7c --- /dev/null +++ b/packages/web/src/content/docs/th/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: ใช้ OpenCode บน Windows ผ่าน WSL ให้ลื่นที่สุด +--- + +import { Steps } from "@astrojs/starlight/components" + +แม้ว่า OpenCode จะรันบน Windows ได้โดยตรง แต่เราแนะนำให้ใช้ [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) เพื่อประสบการณ์ที่ดีที่สุด WSL ให้สภาพแวดล้อม Linux ที่ทำงานร่วมกับฟีเจอร์ของ OpenCode ได้อย่างราบรื่น + +:::tip[ทำไมต้องใช้ WSL?] +WSL ให้ประสิทธิภาพระบบไฟล์ที่ดีกว่า รองรับเทอร์มินัลได้เต็มรูปแบบ และเข้ากันได้กับเครื่องมือพัฒนาที่ OpenCode ใช้งาน +::: + +--- + +## การตั้งค่า + + + +1. **ติดตั้ง WSL** + + ถ้ายังไม่ได้ติดตั้ง ให้ทำตามคู่มือทางการของ Microsoft เพื่อ [ติดตั้ง WSL](https://learn.microsoft.com/en-us/windows/wsl/install) + +2. **ติดตั้ง OpenCode ใน WSL** + + เมื่อตั้งค่า WSL เสร็จแล้ว ให้เปิดเทอร์มินัล WSL และติดตั้ง OpenCode ด้วย [วิธีติดตั้ง](/docs/) แบบใดแบบหนึ่ง + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **ใช้งาน OpenCode จาก WSL** + + ไปที่ไดเรกทอรีโปรเจกต์ของคุณ (เข้าถึงไฟล์ Windows ผ่าน `/mnt/c/`, `/mnt/d/` เป็นต้น) แล้วรัน OpenCode + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## เดสก์ท็อปแอป + เซิร์ฟเวอร์บน WSL + +ถ้าคุณต้องการใช้ OpenCode Desktop แต่ให้เซิร์ฟเวอร์ทำงานบน WSL: + +1. **เริ่มเซิร์ฟเวอร์ใน WSL** โดยใช้ `--hostname 0.0.0.0` เพื่อให้เชื่อมต่อจากภายนอกได้: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **เชื่อมต่อเดสก์ท็อปแอป** ไปที่ `http://localhost:4096` + +:::note +ถ้า `localhost` ใช้งานไม่ได้ในสภาพแวดล้อมของคุณ ให้ใช้ IP ของ WSL แทน (จาก WSL: `hostname -I`) แล้วเชื่อมต่อที่ `http://:4096` +::: + +:::caution +เมื่อใช้ `--hostname 0.0.0.0` ให้ตั้งค่า `OPENCODE_SERVER_PASSWORD` เพื่อป้องกันเซิร์ฟเวอร์ + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## เว็บไคลเอนต์ + WSL + +เพื่อประสบการณ์เว็บที่ดีที่สุดบน Windows: + +1. **รัน `opencode web` ในเทอร์มินัล WSL** แทน PowerShell: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **เข้าจากเบราว์เซอร์บน Windows** ที่ `http://localhost:` (OpenCode จะแสดง URL ให้) + +การรัน `opencode web` จาก WSL ช่วยให้เข้าถึงระบบไฟล์และใช้งานเทอร์มินัลได้ถูกต้อง พร้อมเปิดใช้งานผ่านเบราว์เซอร์ Windows ได้เหมือนเดิม + +--- + +## การเข้าถึงไฟล์ Windows + +WSL สามารถเข้าถึงไฟล์ Windows ทั้งหมดของคุณได้ผ่านไดเรกทอรี `/mnt/`: + +- `C:` drive → `/mnt/c/` +- `D:` drive → `/mnt/d/` +- ไดรฟ์อื่นก็ใช้รูปแบบเดียวกัน + +ตัวอย่าง: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +เพื่อให้ใช้งานได้ลื่นที่สุด แนะนำให้โคลนหรือคัดลอกรีโปไปไว้ในไฟล์ซิสเต็มของ WSL (เช่น `~/code/`) แล้วรัน OpenCode จากที่นั่น +::: + +--- + +## เคล็ดลับ + +- แม้โปรเจกต์จะอยู่บนไดรฟ์ Windows ก็ควรรัน OpenCode ใน WSL เพื่อการเข้าถึงไฟล์ที่ลื่นกว่า +- ใช้ OpenCode ควบคู่กับ [WSL extension ของ VS Code](https://code.visualstudio.com/docs/remote/wsl) เพื่อเวิร์กโฟลว์ที่ต่อเนื่อง +- การตั้งค่าและเซสชันของ OpenCode จะถูกเก็บในสภาพแวดล้อม WSL ที่ `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/th/zen.mdx b/packages/web/src/content/docs/th/zen.mdx new file mode 100644 index 000000000..b0d6f0c35 --- /dev/null +++ b/packages/web/src/content/docs/th/zen.mdx @@ -0,0 +1,254 @@ +--- +title: เซน +description: รายการโมเดลที่คัดสรรโดย OpenCode +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen คือรายการโมเดลที่ได้รับการทดสอบและตรวจสอบแล้วโดยทีมงาน OpenCode + +:::note +OpenCode Zen ปัจจุบันอยู่ในช่วงเบต้า +::: + +Zen ทำงานเหมือนกับผู้ให้บริการรายอื่นๆ ใน OpenCode คุณเข้าสู่ระบบ OpenCode Zen และรับ +รหัส API ของคุณ มันเป็น **ทางเลือกโดยสมบูรณ์** และคุณไม่จำเป็นต้องใช้มันเพื่อใช้งาน +โอเพ่นโค้ด + +--- + +## พื้นหลัง + +มีหลายรุ่นครับ แต่มีเพียงไม่กี่รุ่นเท่านั้น +โมเดลเหล่านี้ทำงานได้ดีในฐานะตัวแทนการเข้ารหัส นอกจากนี้ผู้ให้บริการส่วนใหญ่ก็มี +กำหนดค่าแตกต่างกันมาก ดังนั้นคุณจึงได้รับประสิทธิภาพและคุณภาพที่แตกต่างกันมาก + +:::tip +เราได้ทดสอบกลุ่มโมเดลและผู้ให้บริการที่เลือกซึ่งทำงานได้ดีกับ OpenCode +::: + +ดังนั้นหากคุณใช้โมเดลผ่าน OpenRouter คุณจะไม่มีวันเป็นเช่นนั้น +แน่ใจว่าคุณได้รับรุ่นที่ดีที่สุดของรุ่นที่คุณต้องการหรือไม่ + +เพื่อแก้ไขปัญหานี้ เราได้ทำสองสิ่ง: + +1. เราได้ทดสอบกลุ่มโมเดลที่ได้รับการคัดเลือกและพูดคุยกับทีมของพวกเขาเกี่ยวกับวิธีการ + ดีที่สุดเรียกใช้พวกเขา +2. จากนั้นเราทำงานร่วมกับผู้ให้บริการบางรายเพื่อให้แน่ใจว่าผู้ให้บริการเหล่านี้ได้รับบริการแล้ว + อย่างถูกต้อง +3. ในที่สุด เราก็เปรียบเทียบการรวมกันของ model/provider และได้ผลลัพธ์ออกมา + กับรายการที่เรารู้สึกดีมาแนะนำ + +OpenCode Zen เป็นเกตเวย์ AI ที่ให้คุณเข้าถึงโมเดลเหล่านี้ + +--- + +## มันทำงานอย่างไร + +OpenCode Zen ทำงานเหมือนกับผู้ให้บริการรายอื่นๆ ใน OpenCode + +1. คุณลงชื่อเข้าใช้ **OpenCode Zen** เพิ่มการเรียกเก็บเงินของคุณ + รายละเอียดและคัดลอกรหัส API ของคุณ +2. คุณรันคำสั่ง `/connect` ใน TUI เลือก OpenCode Zen และวางคีย์ API ของคุณ +3. เรียกใช้ `/models` ใน TUI เพื่อดูรายการรุ่นที่เราแนะนำ + +คุณจะถูกเรียกเก็บเงินตามคำขอและคุณสามารถเพิ่มเครดิตให้กับบัญชีของคุณได้ + +--- + +## จุดสิ้นสุด + +คุณยังสามารถเข้าถึงโมเดลของเราผ่านทางจุดสิ้นสุด API ต่อไปนี้ + +| แบบอย่าง | รหัสรุ่น | จุดสิ้นสุด | แพ็คเกจ AI SDK | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | GPT-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 โคเด็กซ์ | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | GPT-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 โคเด็กซ์ | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 โคเด็กซ์สูงสุด | gpt-5.1-codex-สูงสุด | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 โคเด็กซ์มินิ | gpt-5.1-codex-mini.php | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | GPT-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 โคเด็กซ์ | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5นาโน | gpt-5-นาโน | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| คล็อด ซอนเน็ต 4.5 | คลอด-โคลง-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| คลอดด์ ซอนเน็ต 4 | คลอด-โคลง-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| คล็อด ไฮกุ 4.5 | คลอดด์-ไฮกุ-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| คล็อด ไฮกุ 3.5 | คลอด-3-5-ไฮกุ | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| คลอดด์บทประพันธ์ 4.6 | คลอด-บทประพันธ์-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| คลอดด์บทประพันธ์ 4.5 | คลอด-บทประพันธ์-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| คลอดด์บทประพันธ์ 4.1 | คลอด-บทประพันธ์-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| เจมินี่ 3 โปร | ราศีเมถุน-3-โปร | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| ราศีเมถุน 3 แฟลช | ราศีเมถุน-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| มินิแม็กซ์ M2.1 | มินิแม็กซ์-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 ฟรี | minimax-m2.1-ฟรี | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 ฟรี | ปราศจาก glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| คิมิ K2.5 | คิมิ-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 ฟรี | คิมิ-k2.5-ฟรี | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| คิมิ K2 กำลังคิด | kimi-k2-คิด | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| คิมิ K2 | คิมิ-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| คิวเวน3 โคเดอร์ 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| บิ๊กดอง | ดองใหญ่ | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +[model id](/docs/config/#models) ในการกำหนดค่า OpenCode ของคุณ +ใช้รูปแบบ `opencode/` ตัวอย่างเช่น สำหรับ GPT 5.2 Codex คุณจะต้อง +ใช้ `opencode/gpt-5.2-codex` ในการกำหนดค่าของคุณ + +--- + +### โมเดล + +คุณสามารถดึงรายชื่อรุ่นที่มีจำหน่ายและข้อมูลเมตาทั้งหมดได้จาก: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## ราคา + +เราสนับสนุนรูปแบบการจ่ายเงินตามการใช้งาน ด้านล่างนี้คือราคา **ต่อโทเค็น 1M** + +| แบบอย่าง | ป้อนข้อมูล | เอาท์พุต | แคชอ่าน | เขียนในแคช | +| --------------------------------- | ------ | ------ | ----------- | ------------ | +| บิ๊กดอง | ฟรี | ฟรี | ฟรี | - | +| MiniMax M2.1 ฟรี | ฟรี | ฟรี | ฟรี | - | +| มินิแม็กซ์ M2.1 | $0.30 | $1.20 | $0.10 | - | +| GLM 4.7 ฟรี | ฟรี | ฟรี | ฟรี | - | +| GLM 4.7 | $0.60 | $2.20 | $0.10 | - | +| GLM 4.6 | $0.60 | $2.20 | $0.10 | - | +| Kimi K2.5 ฟรี | ฟรี | ฟรี | ฟรี | - | +| คิมิ K2.5 | $0.60 | $3.00 | $0.08 | - | +| คิมิ K2 กำลังคิด | $0.40 | $2.50 | - | - | +| คิมิ K2 | $0.40 | $2.50 | - | - | +| คิวเวน3 โคเดอร์ 480B | $0.45 | $1.50 | - | - | +| Claude Sonnet 4.5 (โทเค็น ≤ 200K) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4.5 (> โทเค็น 200,000) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Sonnet 4 (โทเค็น 200,000 โทเค็น) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4 (> โทเค็น 200,000) | $6.00 | $22.50 | $0.60 | $7.50 | +| คล็อด ไฮกุ 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | +| คล็อด ไฮกุ 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | +| Claude Opus 4.6 (โทเค็น ≤ 200K) | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.6 (> โทเค็น 200,000) | $10.00 | $37.50 | $1.00 | $12.50 | +| คลอดด์บทประพันธ์ 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | +| คลอดด์บทประพันธ์ 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | +| Gemini 3 Pro (โทเค็น ≤ 200,000) | 2.00 ดอลลาร์ | $12.00 | $0.20 | - | +| Gemini 3 Pro (โทเค็น> 200,000) | $4.00 | $18.00 | $0.40 | - | +| ราศีเมถุน 3 แฟลช | $0.50 | $3.00 | $0.05 | - | +| GPT 5.2 | $1.75 | $14.00 | 0.175 ดอลลาร์ | - | +| GPT 5.2 โคเด็กซ์ | $1.75 | $14.00 | 0.175 ดอลลาร์ | - | +| GPT 5.1 | $1.07 | 8.50 ดอลลาร์ | $0.107 | - | +| GPT 5.1 โคเด็กซ์ | $1.07 | 8.50 ดอลลาร์ | $0.107 | - | +| GPT 5.1 โคเด็กซ์สูงสุด | $1.25 | $10.00 | $0.125 | - | +| GPT 5.1 โคเด็กซ์มินิ | $0.25 | 2.00 ดอลลาร์ | 0.025 ดอลลาร์ | - | +| GPT 5 | $1.07 | 8.50 ดอลลาร์ | $0.107 | - | +| GPT 5 โคเด็กซ์ | $1.07 | 8.50 ดอลลาร์ | $0.107 | - | +| GPT 5นาโน | ฟรี | ฟรี | ฟรี | - | + +คุณอาจสังเกตเห็น _Claude Haiku 3.5_ ในประวัติการใช้งานของคุณ นี่คือ [โมเดลราคาประหยัด](/docs/config/#models) ที่ใช้ในการสร้างชื่อเซสชันของคุณ + +:::note +ค่าธรรมเนียมบัตรเครดิตจะถูกส่งต่อในราคาต้นทุน (4.4% + 0.30 ดอลลาร์สหรัฐฯ ต่อธุรกรรม) เราไม่คิดค่าใช้จ่ายใดๆ นอกเหนือจากนั้น +::: + +รุ่นฟรี: + +- GLM 4.7 ใช้งานได้ฟรีบน OpenCode ในระยะเวลาจำกัด ทีมงานใช้เวลานี้เพื่อรวบรวมคำติชมและปรับปรุงโมเดล +- Kimi K2.5 Free พร้อมใช้งานบน OpenCode ในระยะเวลาจำกัด ทีมงานใช้เวลานี้เพื่อรวบรวมคำติชมและปรับปรุงโมเดล +- MiniMax M2.1 Free พร้อมใช้งานบน OpenCode ในระยะเวลาจำกัด ทีมงานใช้เวลานี้เพื่อรวบรวมคำติชมและปรับปรุงโมเดล +- Big Pickle เป็นโมเดลล่องหนที่ให้บริการฟรีบน OpenCode ในระยะเวลาจำกัด ทีมงานใช้เวลานี้เพื่อรวบรวมคำติชมและปรับปรุงโมเดล + +Contact us if you have any questions. + +--- + +### โหลดซ้ำอัตโนมัติ + +หากยอดคงเหลือของคุณต่ำกว่า $5 Zen จะโหลด $20 อีกครั้งโดยอัตโนมัติ + +คุณสามารถเปลี่ยนจำนวนการโหลดอัตโนมัติได้ คุณยังสามารถปิดการโหลดอัตโนมัติทั้งหมดได้อีกด้วย + +--- + +### ขีดจำกัดรายเดือน + +คุณยังสามารถกำหนดขีดจำกัดการใช้งานรายเดือนสำหรับพื้นที่ทำงานทั้งหมดและสำหรับแต่ละรายการได้ +สมาชิกในทีมของคุณ + +ตัวอย่างเช่น สมมติว่าคุณกำหนดขีดจำกัดการใช้งานรายเดือนไว้ที่ 20 ดอลลาร์ Zen จะไม่ใช้ +มากกว่า $20 ในหนึ่งเดือน แต่ถ้าคุณเปิดใช้งานการโหลดซ้ำอัตโนมัติ Zen อาจจะจบลง +เรียกเก็บเงินคุณมากกว่า $20 หากยอดคงเหลือของคุณต่ำกว่า $5 + +--- + +## ความเป็นส่วนตัว + +โมเดลทั้งหมดของเราโฮสต์ในสหรัฐอเมริกา ผู้ให้บริการของเราปฏิบัติตามนโยบายการเก็บรักษาเป็นศูนย์ และไม่ใช้ข้อมูลของคุณสำหรับการฝึกโมเดล โดยมีข้อยกเว้นต่อไปนี้: + +- Big Pickle: ในช่วงระยะเวลาว่าง ข้อมูลที่รวบรวมอาจนำไปใช้ในการปรับปรุงโมเดลได้ +- GLM 4.7 ฟรี: ในช่วงระยะเวลาฟรี ข้อมูลที่รวบรวมอาจนำไปใช้ในการปรับปรุงโมเดล +- Kimi K2.5 ฟรี: ในช่วงระยะเวลาฟรี ข้อมูลที่รวบรวมอาจนำไปใช้ในการปรับปรุงโมเดล +- MiniMax M2.1 ฟรี: ในช่วงระยะเวลาฟรี ข้อมูลที่รวบรวมอาจนำไปใช้ในการปรับปรุงโมเดล +- OpenAI API: คำขอจะถูกเก็บไว้เป็นเวลา 30 วันตาม [นโยบายข้อมูลของ OpenAI](https://platform.openai.com/docs/guides/your-data) +- Anthropic API: คำขอจะถูกเก็บไว้เป็นเวลา 30 วันตาม [นโยบายข้อมูลของ Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage) + +--- + +## สำหรับทีม + +Zen ยังใช้งานได้ดีกับทีมอีกด้วย คุณสามารถเชิญเพื่อนร่วมทีม กำหนดบทบาท ดูแลจัดการได้ +โมเดลที่ทีมของคุณใช้ และอื่นๆ + +:::note +ขณะนี้พื้นที่ทำงานให้บริการฟรีสำหรับทีมโดยเป็นส่วนหนึ่งของเวอร์ชันเบต้า +::: + +ขณะนี้การจัดการพื้นที่ทำงานของคุณให้บริการฟรีสำหรับทีมโดยเป็นส่วนหนึ่งของเวอร์ชันเบต้า เราจะเป็น +แบ่งปันรายละเอียดเพิ่มเติมเกี่ยวกับราคาเร็ว ๆ นี้ + +--- + +### บทบาท + +คุณสามารถเชิญเพื่อนร่วมทีมเข้ามาในพื้นที่ทำงานของคุณและมอบหมายบทบาทได้: + +- **ผู้ดูแลระบบ**: จัดการโมเดล สมาชิก คีย์ API และการเรียกเก็บเงิน +- **สมาชิก**: จัดการเฉพาะคีย์ API ของตนเองเท่านั้น + +ผู้ดูแลระบบยังสามารถกำหนดวงเงินการใช้จ่ายรายเดือนสำหรับสมาชิกแต่ละคนเพื่อควบคุมค่าใช้จ่ายได้ + +--- + +### การเข้าถึงโมเดล + +ผู้ดูแลระบบสามารถเปิดหรือปิดใช้งานโมเดลเฉพาะสำหรับพื้นที่ทำงานได้ คำขอที่ทำกับโมเดลที่ถูกปิดใช้งานจะส่งคืนข้อผิดพลาด + +สิ่งนี้มีประโยชน์สำหรับกรณีที่คุณต้องการปิดการใช้งานโมเดลนั้น +รวบรวมข้อมูล + +--- + +### นำกุญแจมาเอง + +คุณสามารถใช้ปุ่ม OpenAI หรือ Anthropic API ของคุณเองในขณะที่ยังเข้าถึงรุ่นอื่นๆ ใน Zen ได้ + +เมื่อคุณใช้คีย์ของคุณเอง โทเค็นจะถูกเรียกเก็บเงินโดยตรงจากผู้ให้บริการ ไม่ใช่โดย Zen + +ตัวอย่างเช่น องค์กรของคุณอาจมีคีย์สำหรับ OpenAI หรือ Anthropic อยู่แล้ว +และคุณต้องการใช้สิ่งนั้นแทนอันที่ Zen มอบให้ + +--- + +## เป้าหมาย + +เราสร้าง OpenCode Zen เพื่อ: + +1. **เกณฑ์มาตรฐาน** โมเดลที่ดีที่สุด/providers สำหรับตัวแทนการเข้ารหัส +2. เข้าถึงตัวเลือก **คุณภาพสูงสุด** และไม่ดาวน์เกรดประสิทธิภาพหรือเปลี่ยนเส้นทางไปยังผู้ให้บริการที่ราคาถูกกว่า +3. ส่งต่อ **ราคาที่ลดลง** โดยการขายในราคาต้นทุน ดังนั้นมาร์กอัปเพียงอย่างเดียวคือครอบคลุมค่าธรรมเนียมการดำเนินการของเรา +4. **ไม่มีการล็อคอิน** โดยอนุญาตให้คุณใช้กับเอเจนต์การเขียนโค้ดอื่นๆ และให้คุณใช้ผู้ให้บริการรายอื่นกับ OpenCode ได้เช่นกัน diff --git a/packages/web/src/content/docs/tr/1-0.mdx b/packages/web/src/content/docs/tr/1-0.mdx new file mode 100644 index 000000000..56d204a3f --- /dev/null +++ b/packages/web/src/content/docs/tr/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: 1.0'a geçiş +description: OpenCode 1.0'daki yenilikler. +--- + +OpenCode 1.0, TUI'un tamamen yeniden yazılmasıdır. + +Performans ve yetenek sorunları olan go+bubbletea tabanlı TUI'dan zig+solidjs ile yazılmış şirket içi bir çerçeveye (OpenTUI) geçtik. + +Yeni TUI aynı açık kod sunucusuna bağlandığı için eskisi gibi çalışıyor. + +--- + +## Upgrading + +Şu anda daha önceki bir sürümü kullanıyorsanız, otomatik olarak 1.0'a yükseltilmemelisiniz. +version. However some older versions of OpenCode always grab latest. + +Manuel olarak yükseltmek için çalıştırın + +```bash +$ opencode upgrade 1.0.0 +``` + +0.x'e geri dönmek için şunu çalıştırın: + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## Kullanıcı deneyimi değiştirildi + +Oturum geçmişi daha sıkıştırılmıştır ve yalnızca düzenleme ve bash aracının tüm ayrıntılarını gösterir. + +Neredeyse onun içinden aktığı bir komut çubuğu ekledik. Her şeyi görmek için ctrl+p tuşlarına basın. + +Yararlı bilgileri içeren bir kayıt kenarı sürüklenebilir (değiştirilebilir). + +Kimsenin gerçekten çalıştığından emin olmadığımız bazı şeyleri kaldırabildik. Önemli bir şeyin eksik olması durumunda lütfen bir konuyu açın; biz de hızla geri ekleyelim. + +--- + +## Breaking changes + +### Keybinds renamed + +- messages_revert -> messages_undo +- switch_agent -> agent_cycle +- switch_agent_reverse -> agent_cycle_reverse +- switch_mode -> agent_cycle +- switch_mode_reverse -> agent_cycle_reverse + +### Keybinds removed + +- messages_layout_toggle +- messages_next +- messages_previous +- file_diff_toggle +- file_search +- file_close +- file_list +- app_help +- project_init +- tool_details +- thinking_blocks diff --git a/packages/web/src/content/docs/tr/acp.mdx b/packages/web/src/content/docs/tr/acp.mdx new file mode 100644 index 000000000..5de4fcb84 --- /dev/null +++ b/packages/web/src/content/docs/tr/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACP Destek +description: OpenCode'u ACP uyumlu herhangi bir sürdürülebilirde kullanın. +--- + +OpenCode, [Agent Client Protocol](https://agentclientprotocol.com) veya (ACP) dosyalarını destekleyerek onu doğrudan uyumlu tamamlayıcılarda ve IDE'lerde kullanmanızı sağlar. + +:::uç +ACP'yi destekleyenlerin ve araçların listesi için [ACP progress report](https://zed.dev/blog/acp-progress-report#available-now)'e bakın. +::: + +ACP, kod editörleri ile AI kullanma araçları arasındaki iletişimi standartlaştıran açık bir protokoldür. + +--- + +## Yapılandır + +OpenCode'u ACP aracılığıyla kullanmak için düzenleyicinizi `opencode acp` komutunu çalıştıracak şekilde yapılandırın. + +Komut, OpenCode'u, editörünüzle stdio aracılığıyla JSON-RPC üzerinden iletişim kuran ACP uyumlu bir alt süreç olarak başlatır. + +Aşağıda ACP'yi destekleyen popüler düzenleyicilere ilişkin örnekler verilmiştir. + +--- + +### Zed + +[Zed](https://zed.dev) bakımınıza (`~/.config/zed/settings.json`) ekleyin: + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +Açmak için **Komut Paleti**'ndeki `agent: new thread` eylemini kullanın. + +`keymap.json` dosyanızı düzenleyerek de bir klavye kısayolunu bağlayabilirsiniz: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### JetBrains IDEs + +[documentation](https://www.jetbrains.com/help/ai-assistant/acp.html) uyarınca [JetBrains IDE](https://www.jetbrains.com/) acp.json dosyanıza ekleyin: + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +Açmak için AI Sohbet temsilcisi seçicisindeki yeni 'OpenCode' aracısını kullanın. + +--- + +### Avante.nvim + +[Avante.nvim](https://github.com/yetone/avante.nvim) miktarınıza ekleyin: + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +Ortam değişkenlerini iletmeniz gerekiyor: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### CodeCompanion.nvim + +OpenCode'u [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim)'de ACP aracısı olarak kullanmak için Neovim yapılandırmanıza aşağıdakileri ekleyin: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +Bu yapılandırma, CodeCompanion'ı OpenCode'u sohbet için ACP aracısı olarak kullanacak şekilde ayarlar. + +Ortam değişkenlerini (`OPENCODE_API_KEY` gibi) iletmeniz gerekiyorsa, tüm ayrıntılar için CodeCompanion.nvim belgelerindeki [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key)'ye bakın. + +## Destek + +OpenCode, terminalde olduğu gibi ACP aracılığıyla aynı şekilde çalışır. Tüm özellikler desteklenir: + +:::note +`/undo` ve `/redo` gibi bazı yerleşik eğik çizgi komutları şu anda desteklenmemektedir. +::: + +- Yerleşik araçlar (dosya işlemleri, terminal komutları vb.) +- Özel araçlar ve eğik çizgi komutları +- OpenCode yapılandırmanızda yapılandırılmış MCP sunucuları +- `AGENTS.md`'dan projeye özel kurallar +- Özel formatlayıcılar ve linterler +- Aracılar ve izin sistemi diff --git a/packages/web/src/content/docs/tr/agents.mdx b/packages/web/src/content/docs/tr/agents.mdx new file mode 100644 index 000000000..3cd0e029f --- /dev/null +++ b/packages/web/src/content/docs/tr/agents.mdx @@ -0,0 +1,747 @@ +--- +title: Temsilciler +description: Özel araçları yapılandırın ve kullanın. +--- + +Aracılar, belirli görevler ve iş akışları için yapılandırılabilen uzmanlaşmış yapay zeka asistanlarıdır. Özel istemler, modeller ve araç erişimiyle odaklanmış araçlar oluşturmanıza olanak tanır. + +:::tip +Herhangi bir kod değişikliği yapmadan kodu analiz etmek ve önerileri gözden geçirmek için plan aracısını kullanın. +::: + +Bir oturum sırasında temsilciler arasında geçiş yapabilir veya onları `@` ifadesi ile çağırabilirsiniz. + +--- + +## Types + +OpenCode'da iki tür aracı vardır; birincil ajanlar ve alt ajanlar. + +--- + +### Birincil ajanlar + +Birincil aracılar, doğrudan etkileşim kurduğunuz ana yardımcılardır. **Sekme** tuşunu veya yapılandırılmış `switch_agent` tuş atamanızı kullanarak bunlar arasında geçiş yapabilirsiniz. Bu temsilciler ana görüşmenizi yönetir. Araç erişimi, izinler aracılığıyla yapılandırılır; örneğin, Plan kısıtlıyken Build'de tüm araçlar etkindir. + +:::tip +Bir oturum sırasında birincil aracılar arasında geçiş yapmak için **Sekme** tuşunu kullanabilirsiniz. +::: + +OpenCode, **Build** ve **Plan** olmak üzere iki yerleşik birincil aracıyla birlikte gelir. Kuyu +aşağıdakilere bakın. + +--- + +### Subagents + +Alt temsilciler, birincil aracıların belirli görevler için çağırabileceği uzman yardımcılardır. Ayrıca mesajlarınızda **@ bahsederek** bunları manuel olarak da çağırabilirsiniz. + +OpenCode, **Genel** ve **Keşfet** olmak üzere iki yerleşik alt aracıyla birlikte gelir. Buna aşağıda bakacağız. + +--- + +## Yerleşik + +OpenCode iki yerleşik birincil aracı ve iki yerleşik alt aracıyla birlikte gelir. + +--- + +### Derlemeyi kullan + +_Mode_: `primary` + +Build, tüm araçların etkin olduğu **varsayılan** birincil aracıdır. Bu, dosya işlemlerine ve sistem komutlarına tam erişime ihtiyaç duyduğunuz geliştirme çalışmaları için standart aracıdır. + +--- + +### Planı kullan + +_Mod_: `primary` + +Planlama ve analiz için tasarlanmış kısıtlı bir aracı. Size daha fazla kontrol sağlamak ve istenmeyen değişiklikleri önlemek için bir izin sistemi kullanıyoruz. +Varsayılan olarak aşağıdakilerin tümü `ask` olarak ayarlanmıştır: + +- `file edits`: Tüm yazmalar, yamalar ve düzenler +- `bash`: Tüm bash komutları + +Bu aracı, LLM'ın kodu analiz etmesini, değişiklik önermesini veya kod tabanınızda herhangi bir gerçek değişiklik yapmadan plan oluşturmasını istediğinizde kullanışlıdır. + +--- + +### Genel kullan + +_Mode_: `subagent` + +Karmaşık soruları araştırmak ve çok adımlı görevleri yürütmek için genel amaçlı bir aracı. Tam araç erişimine sahiptir (yapılacaklar hariç), böylece gerektiğinde dosya değişiklikleri yapabilir. Birden fazla iş birimini paralel olarak çalıştırmak için bunu kullanın. + +--- + +### Keşfet'i kullan + +_Mod_: `subagent` + +Kod tabanlarını keşfetmeye yönelik hızlı, salt okunur bir aracı. Dosyalar değiştirilemiyor. Dosyaları kalıplara göre hızla bulmanız, anahtar sözcükler için kod aramanız veya kod tabanıyla ilgili soruları yanıtlamanız gerektiğinde bunu kullanın. + +--- + +### Sıkıştırmayı kullanın + +_Mode_: `primary` + +Uzun bağlamı daha küçük bir özete sıkıştıran gizli sistem aracısı. Gerektiğinde otomatik olarak çalışır ve kullanıcı arayüzünde seçilemez. + +--- + +### Başlığı kullan + +_Mod_: `primary` + +Kısa oturum başlıkları oluşturan gizli sistem aracısı. Otomatik olarak çalışır ve kullanıcı arayüzünde seçilemez. + +--- + +### Özeti kullan + +_Mode_: `primary` + +Oturum özetleri oluşturan gizli sistem aracısı. Otomatik olarak çalışır ve kullanıcı arayüzünde seçilemez. + +--- + +## Kullanım + +1. Birincil aracılar için, oturum sırasında bunlar arasında geçiş yapmak için **Sekme** tuşunu kullanın. Yapılandırılmış `switch_agent` tuş bağınızı da kullanabilirsiniz. + +2. Alt aracılar çağrılabilir: + - Açıklamalarına göre özel görevler için birincil temsilciler tarafından **otomatik olarak**. + - Mesajınızda bir alt temsilciden **@ bahsederek** manuel olarak. Örneğin. + + ```txt frame="none" + @general help me search for this function + ``` + +3. **Oturumlar arasında gezinme**: Alt aracılar kendi alt oturumlarını oluşturduğunda, aşağıdakileri kullanarak ana oturum ile tüm alt oturumlar arasında gezinebilirsiniz: + - **\+Right** (veya yapılandırılmış `session_child_cycle` tuş atamanız) ebeveyn → çocuk1 → çocuk2 → ... → ebeveyn arasında ileri doğru geçiş yapmak için + - **\+Left** (veya yapılandırılmış `session_child_cycle_reverse` tuş atamanız) ebeveyn ← çocuk1 ← çocuk2 ← ... ← ebeveyn arasında geriye doğru geçiş yapmak için + + Bu, ana görüşme ile özel alt temsilci çalışması arasında sorunsuz bir şekilde geçiş yapmanıza olanak tanır. + +--- + +## Yapılandır + +Yerleşik aracıları özelleştirebilir veya yapılandırma yoluyla kendinizinkini oluşturabilirsiniz. Aracılar iki şekilde yapılandırılabilir: + +--- + +### JSON + +Aracıları `opencode.json` yapılandırma dosyanızda yapılandırın: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Markdown + +Ayrıca aracıları işaretleme dosyalarını kullanarak da tanımlayabilirsiniz. Bunları şuraya yerleştirin: + +- Global: `~/.config/opencode/agents/` +- Per-project: `.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Markdown dosyasının adı aracının adı olur. Örneğin, `review.md` bir `review` aracısı oluşturur. + +--- + +## Seçenekler + +Bu yapılandırma seçeneklerine ayrıntılı olarak bakalım. + +--- + +### Tanım + +Aracının ne yaptığına ve ne zaman kullanılacağına ilişkin kısa bir açıklama sağlamak için `description` seçeneğini kullanın. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +Bu **gerekli** bir yapılandırma seçeneğidir. + +--- + +### Sıcaklık + +LLM'nin yanıtlarının rastgeleliğini ve yaratıcılığını `temperature` yapılandırmasıyla kontrol edin. + +Düşük değerler yanıtları daha odaklı ve belirleyici hale getirirken, yüksek değerler yaratıcılığı ve değişkenliği artırır. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Sıcaklık değerleri tipik olarak 0,0 ila 1,0 arasındadır: + +- **0,0-0,2**: Çok odaklı ve belirleyici yanıtlar, kod analizi ve planlama için idealdir +- **0,3-0,5**: Biraz yaratıcılık içeren dengeli yanıtlar, genel gelişim görevleri için iyi +- **0,6-1,0**: Daha yaratıcı ve çeşitli yanıtlar, beyin fırtınası ve keşif için yararlı + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Sıcaklık belirtilmezse OpenCode modeline özgü varsayılanları kullanır; çoğu model için genellikle 0, Qwen modelleri için 0,55. + +--- + +### Max steps + +Bir aracının yalnızca metinle yanıt vermeye zorlanmadan önce gerçekleştirebileceği maksimum aracı yineleme sayısını kontrol edin. Bu, maliyetleri kontrol etmek isteyen kullanıcıların aracılık eylemlerine bir sınır koymasına olanak tanır. + +Bu ayarlanmazsa, model durmayı seçene veya kullanıcı oturumu kesene kadar aracı yinelemeye devam edecektir. + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +Sınıra ulaşıldığında, aracı, işinin özeti ve önerilen kalan görevlerin bir özetiyle yanıt vermesi talimatını veren özel bir sistem istemi alır. + +:::caution +Eski `maxSteps` alanı kullanımdan kaldırıldı. Bunun yerine `steps` kullanın. +::: + +--- + +### Devre dışı bırakmak + +Aracıyı devre dışı bırakmak için `true` olarak ayarlayın. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Çabuk + +Bu aracı için `prompt` yapılandırmasıyla özel bir sistem bilgi istemi dosyası belirtin. Bilgi istemi dosyası, aracının amacına özel talimatlar içermelidir. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Bu yol, yapılandırma dosyasının bulunduğu yere göredir. Yani bu hem global OpenCode yapılandırması hem de projeye özel yapılandırma için işe yarar. + +--- + +### Modeli + +Bu aracın kodu geçersiz için `model` ayarını kullanın. Farklı bölümler için optimize edilmiş farklı modelleri kullanmak için kullanışlıdır. Örneğin planlama için daha hızlı bir model, uygulama için daha yetenekli bir model. + +:::tip +Bir model belirtmezseniz, birincil araçlar [model globally configured](/docs/config#models)'yi kullanırken alt araçlar, alt aracı çağıran birincil aracın kullanıcı adını kullanır. +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +OpenCode hesabınızdaki model kimliğini `provider/model-id` biçimini kullanır. Örneğin, [OpenCode Zen](/docs/zen) kullanıyorsanız, GPT 5.1 Codex için `opencode/gpt-5.1-codex` kullanırsınız. + +--- + +### Tools + +`tools` yapılandırmasıyla bu aracıda hangi araçların mevcut olduğunu kontrol edin. Belirli araçları `true` veya `false` olarak ayarlayarak etkinleştirebilir veya devre dışı bırakabilirsiniz. + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +Aracıya özgü yapılandırma, genel yapılandırmayı geçersiz kılar. +::: + +Aynı anda birden fazla aracı kontrol etmek için joker karakterleri de kullanabilirsiniz. Örneğin, bir MCP sunucusundaki tüm araçları devre dışı bırakmak için: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[Learn more about tools](/docs/tools). + +--- + +### İzinler + +Bir aracının gerçekleştirebileceği eylemleri yönetmek için izinleri yapılandırabilirsiniz. Şu anda `edit`, `bash` ve `webfetch` araçlarının izinleri şu şekilde yapılandırılabilir: + +- `"ask"` — Aracı çalıştırmadan önce onay iste +- `"allow"` — Onay olmadan tüm işlemlere izin ver +- `"deny"` — Aracı devre dışı bırakır + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +Bu izinleri aracı başına geçersiz kılabilirsiniz. + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +İzinleri Markdown aracılarında da ayarlayabilirsiniz. + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +Belirli bash komutları için izinleri ayarlayabilirsiniz. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +Bu küresel bir desen alabilir. + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +Ayrıca tüm komutların izinlerini yönetmek için `*` joker karakterini de kullanabilirsiniz. +Son eşleşen kural öncelikli olduğundan, `*` joker karakterini ilk sıraya ve belirli kuralları sonraya koyun. + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[Learn more about permissions](/docs/permissions). + +--- + +### Mode + +Aracının modunu `mode` yapılandırmasıyla kontrol edin. `mode` seçeneği aracının nasıl kullanılabileceğini belirlemek için kullanılır. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +`mode` seçeneği `primary`, `subagent` veya `all` olarak ayarlanabilir. `mode` belirtilmezse varsayılan olarak `all` olur. + +--- + +### Gizlenmiş + +`@` otomatik tamamlama menüsünden bir alt aracıyı `hidden: true` ile gizleyin. Yalnızca diğer aracılar tarafından Görev aracı aracılığıyla programlı olarak çağrılması gereken dahili alt aracılar için kullanışlıdır. + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +Bu yalnızca otomatik menüdeki kullanıcının görünümlerinin etkileri. İzinler izin vermesine, gizli araçlar modeli tarafından Görev aracı aracılığıyla çağrılmaya devam edilebilir. + +:::note +Yalnızca `mode: subagent` acenteleri için geçerlidir. +::: + +--- + +### Task permissions + +`permission.task` ile bir aracının Görev aracı aracılığıyla hangi alt aracıları çağırabileceğini kontrol edin. Esnek eşleştirme için küresel desenleri kullanır. + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +`deny` olarak ayarlandığında, alt aracı Görev aracı açıklamasından tamamen kaldırılır, böylece model onu çağırmaya çalışmaz. + +:::tip +Kurallar sırayla değerlendirilir ve **son eşleşen kural kazanır**. Yukarıdaki örnekte `orchestrator-planner`, hem `*` (reddet) hem de `orchestrator-*` (izin ver) ile eşleşir, ancak `orchestrator-*`, `*`'den sonra geldiğinden sonuç `allow` olur. +::: + +:::tip +Kullanıcılar, aracının görev izinleri bunu reddetse bile, her zaman herhangi bir alt aracıyı `@` otomatik tamamlama menüsü aracılığıyla doğrudan çağırabilir. +::: + +--- + +### Renk + +Aracının kullanıcı arayüzündeki görsel görünümünü `color` seçeneğiyle özelleştirin. Bu, aracının arayüzde nasıl göründüğünü etkiler. + +cebeli bir onaltılık renk (ör. `#FF5733`) veya tema rengini kullanın: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### Top P + +`top_p` seçeneğiyle yanıt çeşitliliğini kontrol edin. Rastgeleliği kontrol etmek için sıcaklığa alternatif. + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +Değerler 0,0 ile 1,0 arasında değişir. Düşük değerler daha odaklıdır, yüksek değerler ise daha çeşitlidir. + +--- + +### Ek olarak + +Temsilci yapılandırmanızdaki düzenlemeleriniz diğer seçenekler, model seçenekleri olarak **doğrudan sağlayıcıya** iletilecektir. Bu, sağlayıcıya özgü özelliklerin ve serbest bırakılmasını sağlar. + +Örneğin OpenAI'nin akıl yürütme modelleriyle akıl yürütme çabasını kontrol edebilirsiniz: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +Bu ek seçenekler modele ve sağlayıcıya özeldir. Kullanılabilir parametreler için sağlayıcınızın belgelerine bakın. + +:::tip +Mevcut modellerin listesini görmek için `opencode models` komutunu çalıştırın. +::: + +--- + +## Temsilci oluştur + +Aşağıdaki komutu kullanarak yeni aracılar oluşturabilirsiniz: + +```bash +opencode agent create +``` + +Bu etkileşimli komut şunları sağlayacaktır: + +1. Temsilciyi nereye kaydedeceğinizi sorun; küresel veya projeye özel. +2. Temsilcinin ne yapması gerektiğinin açıklaması. +3. Uygun bir sistem istemi ve tanımlayıcı oluşturun. +4. Aracının hangi araçlara erişebileceğini seçmenize izin verin. +5. Son olarak aracı yapılandırmasıyla bir işaretleme dosyası oluşturun. + +--- + +## Kullanım durumları + +Farklı aracılara yönelik bazı yaygın kullanım durumları aşağıda verilmiştir. + +- **Yapı aracısı**: Tüm araçların etkinleştirildiği tam geliştirme çalışması +- **Plan aracısı**: Değişiklik yapmadan analiz ve planlama +- **İnceleme aracısı**: Salt okunur erişim ve belgeleme araçlarıyla kod incelemesi +- **Hata ayıklama aracısı**: Bash ve okuma araçları etkinken araştırmaya odaklanmıştır +- **Dokümanlar aracısı**: Dosya işlemleriyle ancak sistem komutları olmadan belge yazma + +--- + +## Examples + +Yararlı bulabileceğiniz bazı örnek aracıları burada bulabilirsiniz. + +:::tip +Paylaşmak istediğiniz bir temsilciniz var mı? [Submit a PR](https://github.com/anomalyco/opencode). +::: + +--- + +### Dokümantasyon temsilcisi + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### Security auditor + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/tr/cli.mdx b/packages/web/src/content/docs/tr/cli.mdx new file mode 100644 index 000000000..26a3efa9f --- /dev/null +++ b/packages/web/src/content/docs/tr/cli.mdx @@ -0,0 +1,601 @@ +--- +title: CLI +description: OpenCode CLI seçenekleri ve komutları. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode CLI herhangi bir argüman olmadan çalıştırıldığında varsayılan olarak [TUI](/docs/tui)'yi başlatır. + +```bash +opencode +``` + +Ancak bu sayfada belgelendiği gibi komutları da kabul eder. Bu, OpenCode ile programlı olarak etkileşim kurmanıza olanak tanır. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui + +OpenCode terminali kullanıcı arayüzünü başlatın. + +```bash +opencode [project] +``` + +#### Flags + +| Bayrak | Kısa | Açıklama | +| ------------ | ---- | ------------------------------------------- | +| `--continue` | `-c` | Son oturuma devam et | +| `--session` | `-s` | Devam edecek oturum kimliği | +| `--prompt` | | Kullanma istemi | +| `--model` | `-m` | provider/model biçiminde kullanılacak model | +| `--agent` | | Kullanılacak temsilci | +| `--port` | | Port to listen on | +| `--hostname` | | Hostname to listen on | + +--- + +## Komutlar + +OpenCode CLI ayrıca aşağıdaki komutlara da sahiptir. + +--- + +### agent + +OpenCode için aracıları yönetin. + +```bash +opencode agent [command] +``` + +--- + +### attach + +`serve` veya `web` komutlarıyla başlatılan, halihazırda çalışan bir OpenCode arka uç sunucusuna bir terminal ekleyin. + +```bash +opencode attach [url] +``` + +Bu, TUI öğesinin uzak bir OpenCode arka ucuyla kullanılmasına olanak tanır. Örneğin: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### Bayraklar + +| Bayrak | Kısa | Tanım | +| ----------- | ---- | ------------------------------------ | +| `--dir` | | TUI'yi başlatmak için çalışma dizini | +| `--session` | `-s` | Devam edecek oturum açma bilgileri | + +--- + +#### yaratmak + +Özel yapılandırmaya sahip yeni bir aracı oluşturun. + +```bash +opencode agent create +``` + +Bu komut, özel sistem istemi ve araç yapılandırmasıyla yeni bir aracı oluşturma konusunda size yol gösterecektir. + +--- + +#### liste + +Mevcut tüm acenteleri listeleyin. + +```bash +opencode agent list +``` + +--- + +### auth + +Sağlayıcılar için kimlik bilgilerini ve oturum açmayı yönetme komutu. + +```bash +opencode auth [command] +``` + +--- + +#### login + +OpenCode, [Models.dev](https://models.dev) adresindeki sağlayıcı listesi tarafından desteklenmektedir, dolayısıyla kullanmak istediğiniz herhangi bir sağlayıcı için API anahtarlarını ayarlamak üzere `opencode auth login` kullanabilirsiniz. Bu `~/.local/share/opencode/auth.json`'de saklanıyor. + +```bash +opencode auth login +``` + +OpenCode başlatıldığında, sağlayıcıları kimlik bilgileri dosyasından yükler. Ortamlarınızda tanımlanmış herhangi bir anahtar veya projenizde bir `.env` dosyası varsa. + +--- + +#### liste + +Kimlik bilgileri dosyasında depolanan tüm kimliği doğrulanmış sağlayıcıları listeler. + +```bash +opencode auth list +``` + +Veya kısa versiyonu. + +```bash +opencode auth ls +``` + +--- + +#### logout + +Bir sağlayıcıyı kimlik bilgileri dosyasından temizleyerek oturumunuzu kapatır. + +```bash +opencode auth logout +``` + +--- + +### github + +Depo otomasyonu için GitHub aracısını yönetin. + +```bash +opencode github [command] +``` + +--- + +#### düzenlemek + +GitHub aracısını deponuza yükleyin. + +```bash +opencode github install +``` + +Bu, gerekli GitHub Eylemlerinin iş ayrıntılandırma ayarlarını ve süreç sürecini boyut boyunca gösterir. [Learn more](/docs/github). + +--- + +#### koşmak + +GitHub aracısını çalıştırın. Bu genellikle GitHub Eylemlerinde kullanılır. + +```bash +opencode github run +``` + +##### Flags + +| Bayrak | Açıklama | +| --------- | ------------------------------------------- | +| `--event` | Aracıyı çalıştırmak için GitHub sahte olayı | +| `--token` | GitHub personal access token | + +--- + +### mcp + +Model Bağlam Protokolü sunucularını yönetin. + +```bash +opencode mcp [command] +``` + +--- + +#### add + +Yapılandırmanıza bir MCP sunucusu ekleyin. + +```bash +opencode mcp add +``` + +Bu komut, yerel veya uzak bir MCP sunucusu ekleme konusunda size yol gösterecektir. + +--- + +#### liste + +Yapılandırılmış tüm MCP sunucularını ve bağlantı durumlarını listeleyin. + +```bash +opencode mcp list +``` + +Veya kısa versiyonunu kullanın. + +```bash +opencode mcp ls +``` + +--- + +#### auth + +OAuth'un etkin olduğu bir MCP sunucusuyla kimlik doğrulaması yapın. + +```bash +opencode mcp auth [name] +``` + +Sunucu adı belirtmezseniz mevcut OAuth özellikli sunucular arasından seçim yapmanız istenir. + +Ayrıca OAuth özellikli sunucuları ve bunların kimlik doğrulama durumlarını da listeleyebilirsiniz. + +```bash +opencode mcp auth list +``` + +Veya kısa versiyonunu kullanın. + +```bash +opencode mcp auth ls +``` + +--- + +#### logout + +MCP sunucusu için OAuth kimlik bilgilerini kaldırın. + +```bash +opencode mcp logout [name] +``` + +--- + +#### hata ayıklama + +MCP sunucusu için OAuth bağlantı sorunlarının hatalarını ayıklayın. + +```bash +opencode mcp debug +``` + +--- + +### models + +Yapılandırılmış sağlayıcıların tüm mevcut modellerini listeleyin. + +```bash +opencode models [provider] +``` + +Bu komut, sağlayıcılarınızda bulunan tüm modeller `provider/model` oluşturulan görüntüler. + +Bu, [your config](/docs/config/)'da kullanılacak tam modelin adını bulmak için kullanışlıdır. + +Modelleri bu sağlayıcıya göre filtrelemek için isteğe bağlı olarak bir sağlayıcı kimliğini iletebilirsiniz. + +```bash +opencode models anthropic +``` + +#### Bayraklar + +| Bayrak | Tanım | +| ----------- | --------------------------------------------------------------------------- | +| `--refresh` | Modeller.dev'den model önbelleğini yenileyin | +| `--verbose` | Daha ayrıntılı model çıktısı kullanın (maliyetler gibi meta veriler içerir) | + +Önbelleğe alınan model listesini güncellemek için `--refresh` bayrağını kullanın. Bu, bir sağlayıcıya yeni modeller eklendiğinde ve bunları OpenCode'da görmek istediğinizde kullanışlıdır. + +```bash +opencode models --refresh +``` + +--- + +### koşmak + +Doğrudan bir istem ileterek açık kodu etkileşimli olmayan modda çalıştırın. + +```bash +opencode run [message..] +``` + +Bu, komut dosyası oluşturma, otomasyon veya TUI'un tamamını başlatmadan hızlı bir yanıt istediğinizde kullanışlıdır. Örneğin. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +Ayrıca, her çalıştırmada MCP sunucusunun soğuk önyükleme sürelerini önlemek için çalışan bir `opencode serve` örneğine de ekleyebilirsiniz: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### Flags + +| Bayrak | Kısa | Açıklama | +| ------------ | ---- | --------------------------------------------------------------------------------- | +| `--command` | | Çalıştırılacak komut, args için mesajı kullanın | +| `--continue` | `-c` | Son oturuma devam et | +| `--session` | `-s` | Devam edecek oturum kimliği | +| `--share` | | Oturumu paylaşın | +| `--model` | `-m` | provider/model biçiminde kullanılacak model | +| `--agent` | | Kullanılacak temsilci | +| `--file` | `-f` | Mesaja eklenecek dosya(lar) | +| `--format` | | Biçim: varsayılan (biçimlendirilmiş) veya json (ham JSON olayları) | +| `--title` | | Oturumun başlığı (değer sağlanmazsa kısaltılmış bilgi istemi kullanılır) | +| `--attach` | | Çalışan bir açık kod sunucusuna ekleyin (ör. http://localhost:4096) | +| `--port` | | Yerel sunucunun bağlantı noktası (varsayılan olarak rastgele bağlantı noktasıdır) | + +--- + +### serve + +API erişimi için başsız bir OpenCode tarayıcısı başlatılır. Tam HTTP arayüzü için [server docs](/docs/server)'e göz atın. + +```bash +opencode serve +``` + +Bu, TUI arayüzü olmadan açık kod işlevselliğine API erişimi sağlayan bir HTTP sunucusunu başlatır. HTTP temel kimlik doğrulamasını etkinleştirmek için `OPENCODE_SERVER_PASSWORD` öğesini ayarlayın (kullanıcı adı varsayılan olarak `opencode` şeklindedir). + +#### Bayraklar + +| Bayrak | Tanım | +| ------------ | ------------------------------------------ | +| `--port` | Dinlenecek bağlantı noktası | +| `--hostname` | Dinlenecek ana bilgisayar adı | +| `--mdns` | mDNS bulmayı etkinleştir | +| `--cors` | CORS'a izin verecek ek tarayıcı kaynakları | + +--- + +### oturum + +Manage OpenCode sessions. + +```bash +opencode session [command] +``` + +--- + +#### liste + +Tüm OpenCode oturumlarını listeleyin. + +```bash +opencode session list +``` + +##### Bayraklar + +| Bayrak | Kısa | Tanım | +| ------------- | ---- | -------------------------------------- | +| `--max-count` | `-n` | En son N oturumla sınırla | +| `--format` | | Çıkış formatı: tablo veya json (tablo) | + +--- + +### stats + +OpenCode oturumlarınız için belirteç kullanımı ve maliyet istatistiklerini gösterin. + +```bash +opencode stats +``` + +#### Flags + +| Bayrak | Açıklama | +| ----------- | ----------------------------------------------------------------------------------------------------------- | +| `--days` | Son N güne ait istatistikleri göster (tüm zamanlar) | +| `--tools` | Number of tools to show (all) | +| `--models` | Model kullanım dökümünü göster (varsayılan olarak gizlidir). En üstteki N'yi göstermek için bir sayı iletin | +| `--project` | Filter by project (all projects, empty string: current project) | + +--- + +### export + +Oturum verilerini JSON olarak dışa aktarın. + +```bash +opencode export [sessionID] +``` + +Bir oturum kimliği sağlamazsanız mevcut oturumlar arasından seçim yapmanız istenir. + +--- + +### import + +Bir JSON dosyasından veya OpenCode paylaşımından URL oturum verilerini içe aktarın. + +```bash +opencode import +``` + +Yerel bir dosyadan veya OpenCode paylaşımından (URL) içe aktarabilirsiniz. + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### web + +Web arayüzüyle başsız bir OpenCode sunucusu başlatın. + +```bash +opencode web +``` + +Bu, bir HTTP sunucusunu başlatır ve bir web arayüzü aracılığıyla OpenCode'a erişmek için bir web tarayıcısı açar. HTTP temel kimlik doğrulamasını etkinleştirmek için `OPENCODE_SERVER_PASSWORD` öğesini ayarlayın (kullanıcı adı varsayılan olarak `opencode` şeklindedir). + +#### Bayraklar + +| Bayrak | Tanım | +| ------------ | ------------------------------------------ | +| `--port` | Dinlenecek bağlantı noktası | +| `--hostname` | Dinlenecek ana bilgisayar adı | +| `--mdns` | mDNS bulmayı etkinleştir | +| `--cors` | CORS'a izin verecek ek tarayıcı kaynakları | + +--- + +### acp + +Bir ACP (Ajan İstemci Protokolü) sunucusu başlatın. + +```bash +opencode acp +``` + +Bu komut, nd-JSON kullanarak stdin/stdout aracılığıyla iletişim kuran bir ACP sunucusunu başlatır. + +#### Flags + +| Bayrak | Açıklama | +| ------------ | --------------------- | +| `--cwd` | Çalışma dizini | +| `--port` | Port to listen on | +| `--hostname` | Hostname to listen on | + +--- + +### uninstall + +OpenCode'u kaldırın ve ilgili tüm dosyaları kaldırın. + +```bash +opencode uninstall +``` + +#### Bayraklar + +| Bayrak | Kısa | Tanım | +| --------------- | ---- | ----------------------------------------------- | +| `--keep-config` | `-c` | Yapılandırma dosyalarını sakla | +| `--keep-data` | `-d` | Oturum verilerini ve anlık görüntüleri saklayın | +| `--dry-run` | | Nelerin kaldırılmadan kaldırılacağı göster | +| `--force` | `-f` | Onay istemlerini atla | + +--- + +### upgrade + +Açık kodu en son sürüme veya belirli bir sürüme günceller. + +```bash +opencode upgrade [target] +``` + +En son sürüme yükseltmek için. + +```bash +opencode upgrade +``` + +To upgrade to a specific version. + +```bash +opencode upgrade v0.1.48 +``` + +#### Flags + +| Bayrak | Kısa | Açıklama | +| ---------- | ---- | ----------------------------------------------------------- | +| `--method` | `-m` | Kullanılan kurulum yöntemi; bukle, npm, npm, topuz, demleme | + +--- + +## Küresel Bayraklar + +CLI açık kodu aşağıdaki genel bayrakları alır. + +| Bayrak | Kısa | Tanım | +| -------------- | ---- | ---------------------------------------- | +| `--help` | `-h` | Yardımı görüntüle | +| `--version` | `-v` | Sürüm numarasını yazdır | +| `--print-logs` | | Günlükleri stderr'e yazdır | +| `--log-level` | | Günlük düzeyi (DEBUG, INFO, WARN, ERROR) | + +--- + +## Environment variables + +OpenCode ortam değişkenleri kullanılarak yapılandırılabilir. + +| Değişken | Tür | Açıklama | +| ------------------------------------- | ------- | --------------------------------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | boole | Oturumları otomatik olarak paylaş | +| `OPENCODE_GIT_BASH_PATH` | dize | Windows'ta yürütülebilir Git Bash'in Yolu | +| `OPENCODE_CONFIG` | dize | Yapılandırma dosyasının yolu | +| `OPENCODE_CONFIG_DIR` | dize | Yapılandırma dizinine giden yol | +| `OPENCODE_CONFIG_CONTENT` | string | Inline json config content | +| `OPENCODE_DISABLE_AUTOUPDATE` | boolean | Disable automatic update checks | +| `OPENCODE_DISABLE_PRUNE` | boolean | Disable pruning of old data | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | boole | Otomatik terminal başlığı güncellemelerini devre dışı bırakın | +| `OPENCODE_PERMISSION` | string | Inlined json permissions config | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | boole | Varsayılan eklentileri devre dışı bırakın | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | boole | Otomatik LSP sunucu indirmelerini devre dışı bırakın | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | boolean | Enable experimental models | +| `OPENCODE_DISABLE_AUTOCOMPACT` | boolean | Disable automatic context compaction | +| `OPENCODE_DISABLE_CLAUDE_CODE` | boole | `.claude`'den okumayı devre dışı bırak (istem + beceriler) | +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | boolean | Disable reading `~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | boolean | Disable loading `.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | boole | Uzak kaynaklardan model getirmeyi devre dışı bırakın | +| `OPENCODE_FAKE_VCS` | dize | Test amaçlı sahte VCS sağlayıcısı | +| `OPENCODE_DISABLE_FILETIME_CHECK` | boole | Optimizasyon için dosya süresi kontrolünü devre dışı bırakın | +| `OPENCODE_CLIENT` | string | Client identifier (defaults to `cli`) | +| `OPENCODE_ENABLE_EXA` | boolean | Enable Exa web search tools | +| `OPENCODE_SERVER_PASSWORD` | dize | `serve`/`web` için temel kimlik doğrulamayı etkinleştirin | +| `OPENCODE_SERVER_USERNAME` | dize | Temel kimlik doğrulama kullanıcı adını geçersiz kıl (varsayılan `opencode`) | +| `OPENCODE_MODELS_URL` | dize | Model yapılandırmasını almak için özel URL | + +--- + +### Deneysel + +Bu ortam değişkenleri değişebilecek veya kaldırılabilecek deneysel özellikleri etkinleştirir. + +| Değişken | Tip | Tanım | +| ----------------------------------------------- | ------- | ------------------------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | boolean | Tüm deneysel özellikleri etkinleştir | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | boolean | Simge bulmayı etkinleştir | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | boolean | TUI'da seçim yapıldığında kopyalamayı devre dışı bırak | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | sayı | MS cinsinden bash komutları için varsayılan zaman aşımı | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | sayı | LLM yanıtları için maksimum çıktı belirteçleri | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | boolean | Tüm dizin için dosya izleyiciyi etkinleştir | +| `OPENCODE_EXPERIMENTAL_OXFMT` | boolean | Oxfmt biçimlendiriciyi etkinleştir | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | boolean | Deneysel LSP aracını etkinleştir | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | boolean | Dosya izleyiciyi devre dışı bırak | +| `OPENCODE_EXPERIMENTAL_EXA` | boolean | Deneysel Exa özelliklerini etkinleştirin | +| `OPENCODE_EXPERIMENTAL_LSP_TY` | boolean | Deneysel LSP tür denetimini etkinleştir | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | boolean | Deneysel işaretleme özelliklerini etkinleştir | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` | boolean | Plan modunu etkinleştir | diff --git a/packages/web/src/content/docs/tr/commands.mdx b/packages/web/src/content/docs/tr/commands.mdx new file mode 100644 index 000000000..6ccd966d7 --- /dev/null +++ b/packages/web/src/content/docs/tr/commands.mdx @@ -0,0 +1,323 @@ +--- +title: Komutlar +description: Tekrarlanan görevler için özel komutlar oluşturulur. +--- + +Özel komutlar, söz konusu komut TUI'da yürütüldüğünde çalıştırmak istediğiniz istemi belirtmenize olanak tanır. + +```bash frame="none" +/my-command +``` + +Özel komutlar, `/init`, `/undo`, `/redo`, `/share`, `/help` gibi komutlara ek olarak sunulur. [Learn more](/docs/tui#commands). + +--- + +## Komut dosyaları oluşturun + +Özel komutları tanımlamak için `commands/` dizininde işaretleme dosyaları oluşturun. + +`.opencode/commands/test.md` oluştur: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Ön madde komut özelliklerini tanımlar. İçerik şablon haline gelir. + +`/` ve ardından komut adını yazarak komutu kullanın. + +```bash frame="none" +"/test" +``` + +--- + +## Yapılandır + +OpenCode işlemleri aracılığıyla veya `commands/` dizininde işaretleme dosyalarının oluşturulması özel komutlar ile yapılabilir. + +--- + +### JSON + +OpenCode [config](/docs/config)'deki `command` seçeneğini kullanın: + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Artık bu komutu TUI'da çalıştırabilirsiniz: + +```bash frame="none" +/test +``` + +--- + +### İndirim + +Markdown dosyalarını kullanarak komutları da tanımlayabilirsiniz. Bunları şuraya yerleştirin: + +- Küresel: `~/.config/opencode/commands/` +- Proje başına: `.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Markdown dosyasının adı komut adı olur. Örneğin, `test.md` şunu sağlar: +sen koşuyorsun: + +```bash frame="none" +/test +``` + +--- + +## İstem yapılandırması + +Özel komut istemleri birçok özel yer tutucuyu ve sözdizimini destekler. + +--- + +### Argümanlar + +`$ARGUMENTS` yer tutucusunu kullanarak komutlara argümanları iletin. + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +Komutu bağımsız değişkenlerle çalıştırın: + +```bash frame="none" +/component Button +``` + +Ve `$ARGUMENTS`, `Button` ile değiştirilecektir. + +Konumsal parametreleri kullanarak bağımsız değişkenlere de erişebilirsiniz: + +- `$1` - İlk argüman +- `$2` - İkinci argüman +- `$3` - Üçüncü argüman +- Ve benzeri... + +Örneğin: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +Komutu çalıştırın: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +Bu şunun yerini alır: + +- `$1` ile `config.json` +- `$2` ile `src` +- `$3` ile `{ "key": "value" }` + +--- + +### Shell output + +İsteminize [bash command](/docs/tui#bash-commands) çıktısını enjekte etmek için \__!`command`_ kullanın. + +Örneğin, test kapsamını analiz eden özel bir komut oluşturmak için: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +Or to review recent changes: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +Komutlar projenizin kök dizininde çalışır ve çıktıları istemin bir parçası olur. + +--- + +### Dosya referansları + +Komutunuza `@` ve ardından dosya adını kullanarak dosyaları ekleyin. + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +Dosya içeriği otomatik olarak istemde yer alır. + +--- + +## Options + +Yapılandırma seçeneklerine ayrıntılı olarak bakalım. + +--- + +### Şablon + +`template` seçeneği, komut yürütüldüğünde LLM'ye gönderilecek olan istemi tanımlar. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +Bu **gerekli** bir yapılandırma seçeneğidir. + +--- + +### Tanım + +Komutun ne yaptığına ilişkin kısa bir açıklama sağlamak için `description` seçeneğini kullanın. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +Bu, komutu yazdığınızda TUI içindeki açıklama olarak gösterilir. + +--- + +### Ajan + +İsteğe bağlı olarak bu komutu hangi [agent](/docs/agents)'nin yürütmesi gerektiğini belirtmek için `agent` yapılandırmasını kullanın. +Bu bir [subagent](/docs/agents/#subagents) ise, komut varsayılan olarak bir alt aracı çağrısını tetikleyecektir. +Bu davranışı devre dışı bırakmak için `subtask` öğesini `false` olarak ayarlayın. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +Bu **isteğe bağlı** bir yapılandırma seçeneğidir. Belirtilmemişse, varsayılan olarak mevcut temsilciniz kullanılır. + +--- + +### Subtask + +Komutu bir [subagent](/docs/agents/#subagents) çağrısını tetiklemeye zorlamak için `subtask` boolean'ını kullanın. +Bu, komutun birincil bağlamınızı kirletmemesini ve aracıyı bir alt aracı olarak davranmaya **zorlamasını** istiyorsanız kullanışlıdır. +`mode`, [agent](/docs/agents) yapılandırmasında `primary` olarak ayarlanmış olsa bile. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +Bu **isteğe bağlı** bir yapılandırma seçeneğidir. + +--- + +### Modeli + +Bu parçanın varsayılan kodu geçersiz için `model` kontrolünü kullanın. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +Bu **isteğe bağlı** bir yapılandırma seçeneğidir. + +--- + +## Built-in + +opencode, `/init`, `/undo`, `/redo`, `/share`, `/help` gibi çeşitli yerleşik komutlar içerir; [learn more](/docs/tui#commands). + +:::note +Özel komutlar yerleşik komutları geçersiz kılabilir. +::: + +Aynı adda özel bir komut tanımlarsanız yerleşik komutu geçersiz kılar. diff --git a/packages/web/src/content/docs/tr/config.mdx b/packages/web/src/content/docs/tr/config.mdx new file mode 100644 index 000000000..8cbd34bad --- /dev/null +++ b/packages/web/src/content/docs/tr/config.mdx @@ -0,0 +1,685 @@ +--- +title: Yapılandırma +description: OpenCode JSON devresini kullanmıyor. +--- + +OpenCode'u JSON yapılandırma dosyası kullanarak yapılandırabilirsiniz. + +--- + +## Format + +OpenCode hem **JSON** hem de **JSONC** (JSON Yorumlarla birlikte) formatlarını destekler. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## Konumlar + +Yapılandırmanızı birkaç farklı konuma yerleştirebilirsiniz ve bunların +farklı öncelik sırası. + +:::note +Yapılandırma dosyaları **birleştirilir**, değiştirilmez. +::: + +Yapılandırma dosyaları değiştirilmez, birleştirilir. Aşağıdaki yapılandırma konumlarındaki ayarlar birleştirilir. Daha sonraki yapılandırmalar, yalnızca çakışan anahtarlar için önceki yapılandırmaları geçersiz kılar. Tüm yapılandırmalardaki çakışmayan ayarlar korunur. + +Örneğin, genel ayarınız `theme: "opencode"` ve `autoupdate: true`'yi ayarlıyorsa ve proje ayarlarınız `model: "anthropic/claude-sonnet-4-5"`'yi ayarlıyorsa, son tork ayarının tümünü dikkate alır. + +--- + +### Precedence order + +Yapılandırma kaynakları bu sırayla yüklenir (sonraki kaynaklar öncekileri geçersiz kılar): + +1. **Uzaktan yapılandırma** (`.well-known/opencode`'dan) - kurumsal varsayılanlar +2. **Global config** (`~/.config/opencode/opencode.json`) - user preferences +3. **Custom config** (`OPENCODE_CONFIG` env var) - custom overrides +4. **Project config** (`opencode.json` in project) - project-specific settings +5. **`.opencode` dizinleri** - aracılar, komutlar, eklentiler +6. **Inline config** (`OPENCODE_CONFIG_CONTENT` env var) - runtime overrides + +Bu, proje yapılandırmalarının genel varsayılanları geçersiz kılabileceği ve genel yapılandırmaların uzak organizasyonel varsayılanları geçersiz kılabileceği anlamına gelir. + +:::note +`.opencode` ve `~/.config/opencode` dizinleri alt dizinler için **çoğul adlar** kullanır: `agents/`, `commands/`, `modes/`, `plugins/`, `skills/`, `tools/` ve `themes/`. Tekil adlar (örneğin, `agent/`) da geriye dönük uyumluluk açısından desteklenir. +::: + +--- + +### Uzak + +Kuruluşlar, `.well-known/opencode` uç noktası aracılığıyla varsayılan yapılandırmayı sağlayabilir. Bu, onu destekleyen bir sağlayıcıyla kimlik doğrulaması yaptığınızda otomatik olarak alınır. + +Remote config ilk olarak yüklenir ve temel katman görevi görür. Diğer tüm yapılandırma kaynakları (genel, proje) bu varsayılanları geçersiz kılabilir. + +Örneğin, kuruluşunuz varsayılan olarak devre dışı bırakılan MCP sunucuları sağlıyorsa: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +Yerel yapılandırmanızda belirli sunucuları etkinleştirebilirsiniz: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### Global + +Global OpenCode yapılandırmanızı `~/.config/opencode/opencode.json` içine yerleştirin. Temalar, sağlayıcılar veya tuş atamaları gibi kullanıcı çapındaki tercihler için genel yapılandırmayı kullanın. + +Global config overrides remote organizational defaults. + +--- + +### Proje başına + +Proje kökünüze `opencode.json` ekleyin. Proje yapılandırması, standart yapılandırma dosyaları arasında en yüksek önceliğe sahiptir; hem genel hem de uzak yapılandırmaları geçersiz kılar. + +:::tip +Projeye özel yapılandırmayı projenizin köküne yerleştirin. +::: + +OpenCode başlatıldığında geçerli dizinde bir yapılandırma dosyası arar veya en yakın Git dizinine gider. + +Bunun Git'te kontrol edilmesi de güvenlidir ve global olanla aynı şemayı kullanır. + +--- + +### Özel yol + +`OPENCODE_CONFIG` ortam değişkenini kullanarak özel bir yapılandırma dosyası yolu belirtin. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +Özel yapılandırma genel ve proje yapılandırmaları arasında öncelik sırasına göre yüklenir. + +--- + +### Özel dizin + +`OPENCODE_CONFIG_DIR` kullanarak özel bir yapılandırma dizini belirtin +ortam değişkeni. Bu dizin aracılar, komutlar için aranacaktır. +modlar ve eklentiler tıpkı standart `.opencode` dizini gibi olmalıdır ve +aynı yapıyı takip edin. + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +Özel dizin, genel yapılandırma ve `.opencode` dizinlerinden sonra yüklenir, böylece bunların ayarlarını **geçersiz kılabilir**. + +--- + +## Schema + +Yapılandırma dosyası [**`opencode.ai/config.json`**](https://opencode.ai/config.json)'da tanımlanan bir şemaya sahiptir. + +Editörünüz şemaya göre doğrulama ve otomatik tamamlama yapabilmelidir. + +--- + +### TUI + +TUI'ye özgü ayarları `tui` seçeneği aracılığıyla yapılandırabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +Mevcut seçenekler: + +- `scroll_acceleration.enabled` - MacOS tarzı kaydırma hızlandırmayı etkinleştirin. **`scroll_speed`'ye göre önceliklidir.** +- `scroll_speed` - Özel kaydırma hızı çarpanı (varsayılan: `3`, minimum: `1`). `scroll_acceleration.enabled` `true` ise dikkate alınmaz. +- `diff_style` - Fark oluşturmayı kontrol edin. `"auto"` terminal genişliğine uyum sağlar, `"stacked"` her zaman tek sütunu gösterir. + +[Learn more about using the TUI here](/docs/tui). + +--- + +### Sunucu + +`opencode serve` ve `opencode web` komutları için sunucu ayarlarını `server` seçeneği aracılığıyla yapılandırabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +Mevcut seçenekler: + +- `port` - Port to listen on. +- `hostname` - Dinlenecek ana bilgisayar adı. `mdns` etkinleştirildiğinde ve hiçbir ana bilgisayar adı ayarlanmadığında, varsayılan değer `0.0.0.0` olur. +- `mdns` - mDNS hizmet bulmayı etkinleştirin. Bu, ağdaki diğer cihazların OpenCode sunucunuzu keşfetmesine olanak tanır. +- `mdnsDomain` - mDNS hizmeti için özel alan adı. Varsayılan olarak `opencode.local` şeklindedir. Aynı ağda birden fazla örneği çalıştırmak için kullanışlıdır. +- `cors` - Tarayıcı tabanlı bir istemciden HTTP sunucusunu kullanırken CORS'ye izin verecek ek kaynaklar. Değerler tam kaynaklar olmalıdır (şema + ana bilgisayar + isteğe bağlı bağlantı noktası), örneğin `https://app.example.com`. + +[Learn more about the server here](/docs/server). + +--- + +### Aletler + +Bir LLM'nin kullanabileceği araçları `tools` seçeneği aracılığıyla yönetebilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[Learn more about tools here](/docs/tools). + +--- + +### Models + +OpenCode yapılandırmanızda kullanmak istediğiniz sağlayıcıları ve modelleri `provider`, `model` ve `small_model` seçenekleri aracılığıyla yapılandırabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +`small_model` seçeneği, başlık oluşturma gibi hafif görevler için ayrı bir model yapılandırır. Varsayılan olarak OpenCode, sağlayıcınızda mevcutsa daha ucuz bir model kullanmaya çalışır, aksi takdirde ana modelinize geri döner. + +Sağlayıcı seçenekleri `timeout` ve `setCacheKey` içerebilir: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - Milisaniye cinsinden istek zaman aşımı (varsayılan: 300000). Devre dışı bırakmak için `false` olarak ayarlayın. +- `setCacheKey` - Belirlenen sağlayıcı için her zaman bir önbellek anahtarının ayarlandığından emin olun. + +Ayrıca [local models](/docs/models#local) öğesini de yapılandırabilirsiniz. [Learn more](/docs/models). + +--- + +#### Sağlayıcıya Özel Seçenekler + +Bazı sağlayıcılar genel `timeout` ve `apiKey` ayarlarının ötesinde ek yapılandırma seçeneklerini destekler. + +##### Amazon Ana Kayası + +Amazon Bedrock, AWS'a özgü yapılandırmayı destekler: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - Bedrock için AWS bölgesi (varsayılanı `AWS_REGION` env var veya `us-east-1`'dir) +- `profile` - `~/.aws/credentials`'den AWS adlı profil (varsayılanı `AWS_PROFILE` env var'dır) +- `endpoint` - VPC uç noktaları için özel uç nokta URL. Bu, AWS'e özgü terminolojiyi kullanan genel `baseURL` seçeneğinin takma adıdır. Her ikisi de belirtilirse `endpoint` öncelikli olur. + +:::note +Taşıyıcı belirteçleri (`AWS_BEARER_TOKEN_BEDROCK` veya `/connect`) profil tabanlı kimlik doğrulamaya göre önceliklidir. Ayrıntılar için [authentication precedence](/docs/providers#authentication-precedence)'ye bakın. +::: + +[Learn more about Amazon Bedrock configuration](/docs/providers#amazon-bedrock). + +--- + +### Themes + +OpenCode yapılandırmanızda kullanmak istediğiniz temayı `theme` seçeneği aracılığıyla yapılandırabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[Learn more here](/docs/themes). + +--- + +### Temsilciler + +`agent` seçeneği aracılığıyla özel görevlere yönelik özel aracıları yapılandırabilirsiniz. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +Aracıları ayrıca `~/.config/opencode/agents/` veya `.opencode/agents/` İçindeki etiketleme etiketlerini kullanarak da tanımlayabilirsiniz. [Learn more here](/docs/agents). + +--- + +### Varsayılan temsilci + +`default_agent` seçeneğini kullanarak varsayılan aracıyı ayarlayabilirsiniz. Bu, hiçbiri açıkça belirtilmediğinde hangi aracının kullanılacağını belirler. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +Varsayılan aracı, birincil aracı olmalıdır (alt aracı değil). Bu, `"build"` veya `"plan"` gibi yerleşik bir aracı ya da tanımladığınız bir [custom agent](/docs/agents) olabilir. Belirtilen aracı mevcut değilse veya bir alt aracı ise, OpenCode bir uyarıyla birlikte `"build"`'ye geri döner. + +Bu ayar tüm arayüzler için geçerlidir: TUI, CLI (`opencode run`), masaüstü uygulaması ve GitHub Action. + +--- + +### Paylaşma + +[share](/docs/share) özelliği `share` seçeneğini aracılığıyla yapılandırabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +Bu şunları gerektirir: + +- `"manual"` - Komutlar aracılığıyla manuel paylaşıma izin ver (varsayılan) +- `"auto"` - Yeni konuşmaları otomatik olarak paylaş +- `"disabled"` - Paylaşımı tamamen devre dışı bırak + +Varsayılan olarak paylaşım, `/share` yoğunluğu kullanılarak konuşmaları açıkça paylaşmanız gereken manuel moda ayarlanmıştır. + +--- + +### Komutlar + +`command` seçeneği aracılığıyla tekrarlanan görevler için özel komutlar yapılandırabilirsiniz. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +Komutları `~/.config/opencode/commands/` veya `.opencode/commands/` içindeki işaretleme dosyalarını kullanarak da tanımlayabilirsiniz. [Learn more here](/docs/commands). + +--- + +### Tuş bağlantıları + +Tuş atamalarınızı `keybinds` seçeneği aracılığıyla özelleştirebilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[Learn more here](/docs/keybinds). + +--- + +### Autoupdate + +OpenCode başlatıldığında yeni güncellemeleri otomatik olarak indirecektir. Bunu `autoupdate` seçeneğiyle devre dışı bırakabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +Güncelleme istemiyor ancak yeni bir sürüm mevcut olduğunda bilgilendirilmek istiyorsanız `autoupdate` öğesini `"notify"` olarak ayarlayın. +Bunun yalnızca Homebrew gibi bir paket yöneticisi kullanılarak yüklenmemişse işe yaradığına dikkat edin. + +--- + +### Biçimlendiriciler + +Kod formatlayıcılarını `formatter` seçeneği aracılığıyla yapılandırabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[Learn more about formatters here](/docs/formatters). + +--- + +### Permissions + +Varsayılan olarak, açık kod açık bir onay gerektirmeden **tüm işlemlere izin verir**. `permission` seçeneğini kullanarak bunu değiştirebilirsiniz. + +Örneğin, `edit` ve `bash` araçlarının kullanıcı onayı gerektirdiğinden emin olmak için: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[Learn more about permissions here](/docs/permissions). + +--- + +### Sıkıştırma + +Bağlam sıkıştırma davranışını `compaction` seçeneği aracılığıyla kontrol edebilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - Bağlam dolduğunda oturumu otomatik olarak sıkıştırır (varsayılan: `true`). +- `prune` - Belirteçleri kaydetmek için eski araç çıktılarını kaldırın (varsayılan: `true`). + +--- + +### Watcher + +Dosya izleyicinin yok sayma kalıplarını `watcher` seçeneği aracılığıyla yapılandırabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +Desenler glob sözdizimini takip eder. Gürültülü dizinleri dosya izlemenin dışında bırakmak için bunu kullanın. + +--- + +### MCP sunucuları + +Kullanmak istediğiniz MCP sunucularını `mcp` seçeneği aracılığıyla yapılandırabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[Learn more here](/docs/mcp-servers). + +--- + +### Plugins + +[Plugins](/docs/plugins) OpenCode'u özel araçlar, kancalar ve entegrasyonlarla genişletin. + +Eklenti dosyalarını `.opencode/plugins/` veya `~/.config/opencode/plugins/` içine yerleştirin. Ayrıca eklentileri `plugin` seçeneği aracılığıyla npm'den de yükleyebilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[Learn more here](/docs/plugins). + +--- + +### Talimatlar + +Kullandığınız modele ilişkin talimatları `instructions` seçeneği aracılığıyla yapılandırabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Bu, talimat dosyalarına giden bir dizi yolu ve glob desenini alır. [Daha fazla bilgi edin +kurallar hakkında burada](/docs/rules). + +--- + +### Disabled providers + +`disabled_providers` seçeneği aracılığıyla otomatik olarak yüklenen sağlayıcıları devre dışı bırakabilirsiniz. Bu, belirli sağlayıcıların kimlik bilgileri mevcut olsa bile yüklenmesini engellemek istediğinizde kullanışlıdır. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +`disabled_providers`, `enabled_providers`'ye göre önceliklidir. +::: + +`disabled_providers` seçeneği bir dizi sağlayıcı kimliğini kabul eder. Bir sağlayıcı devre dışı bırakıldığında: + +- It won't be loaded even if environment variables are set. +- API anahtarları `/connect` komutu aracılığıyla yapılandırılsa bile yüklenmeyecektir. +- Sağlayıcının modelleri, model seçim listesinde görünmez. + +--- + +### Etkin sağlayıcılar + +`enabled_providers` seçeneğini kullanarak sağlayıcıların izin verilenler listesini belirtebilirsiniz. Ayarlandığında yalnızca belirtilen sağlayıcılar etkinleştirilecek ve diğerleri göz ardı edilecektir. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +Bu, OpenCode'u tek tek devre dışı bırakmak yerine yalnızca belirli sağlayıcıları kullanacak şekilde kısıtlamak istediğinizde kullanışlıdır. + +:::note +`disabled_providers`, `enabled_providers`'ye göre önceliklidir. +::: + +Bir sağlayıcı hem `enabled_providers` hem de `disabled_providers`'de görünüyorsa, geriye dönük uyumluluk için `disabled_providers` önceliğe sahiptir. + +--- + +### Experimental + +`experimental` anahtarı aktif olarak geliştirilmekte olan seçenekleri içerir. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::caution +Experimental options are not stable. They may change or be removed without notice. +::: + +--- + +## Değişkenler + +Ortam değişkenlerine ve dosya içeriklerine referans vermek için yapılandırma dosyalarınızda değişken değiştirmeyi kullanabilirsiniz. + +--- + +### Env vars + +Ortam değişkenlerini değiştirmek için `{env:VARIABLE_NAME}` kullanın: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +Ortam değişkeni ayarlanmamışsa boş bir dizeyle değiştirilecektir. + +--- + +### Dosyalar + +Bir dosyanın biçimini değiştirmek için `{file:path/to/file}` kullanın: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +Dosya yolları şunlar olabilir: + +- Yapılandırma dosyası dizinine göre +- Veya `/` veya `~` ile başlayan mutlak yollar + +Bunlar aşağıdakiler için faydalıdır: + +- API anahtarları gibi hassas verileri ayrı dosyalarda tutmak. +- Yapılandırmanızı karmaşıklaştırmadan büyük talimat dosyaları içerir. +- Birden fazla yapılandırma dosyasında ortak yapılandırma parçacıklarının paylaşılması. diff --git a/packages/web/src/content/docs/tr/custom-tools.mdx b/packages/web/src/content/docs/tr/custom-tools.mdx new file mode 100644 index 000000000..68ca16b96 --- /dev/null +++ b/packages/web/src/content/docs/tr/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: Özel Araçlar +description: LLM'un açık kodda çağırabileceği araçları birleştirebilir. +--- + +Özel araçlar, LLM'un konuşmalar sırasında arayabileceği, oluşturduğunuz işlevlerdir. Açık kodun [built-in tools](/docs/tools) ile birlikte `read`, `write` ve `bash` gibi çalışırlar. + +--- + +## Creating a tool + +Araçlar **TypeScript** veya **JavaScript** dosyaları olarak tanımlanır. Ancak araç tanımı **herhangi bir dilde** yazılmış komut dosyalarını çağırabilir; TypeScript veya JavaScript yalnızca araç tanımının kendisi için kullanılır. + +--- + +### Konum + +Bunlar tanımlanabilir: + +- Yerel olarak bunları projenizin `.opencode/tools/` dizinine yerleştirerek. +- Veya küresel olarak bunları `~/.config/opencode/tools/` içine yerleştirerek. + +--- + +### Structure + +Araç oluşturmanın en kolay yolu, tür güvenliği ve doğrulama sağlayan `tool()` yardımcısını kullanmaktır. + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +**dosya adı**, **araç adı** olur. Yukarıdakiler bir `database` aracı oluşturur. + +--- + +#### Dosya başına birden fazla araç + +Ayrıca tek bir dosyadan birden fazla aracı dışa aktarabilirsiniz. Her dışa aktarma, **`_`** adıyla **ayrı bir araç** haline gelir: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +Bu iki araç oluşturur: `math_add` ve `math_multiply`. + +--- + +### Arguments + +Bağımsız değişken türlerini tanımlamak için yalnızca [Zod](https://zod.dev) olan `tool.schema` öğesini kullanabilirsiniz. + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +Ayrıca [Zod](https://zod.dev) öğesini doğrudan içe aktarabilir ve düz bir nesne döndürebilirsiniz: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### Bağlam + +Araçlar geçerli oturumla ilgili bağlamı alır: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +Oturum çalışma dizisi için `context.directory` kullanın. +Git çalışma ağacı kökü için `context.worktree` kullanın. + +--- + +## Examples + +### Write a tool in Python + +Araçlarınızı dilediğiniz dilde yazabilirsiniz. İşte Python kullanarak iki sayıyı toplayan bir örnek. + +Öncelikle aracı bir Python betiği olarak oluşturun: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +Ardından onu çağıran araç tanımını oluşturun: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +Burada Python betiğini çalıştırmak için [`Bun.$`](https://bun.com/docs/runtime/shell) yardımcı programını kullanıyoruz. diff --git a/packages/web/src/content/docs/tr/ecosystem.mdx b/packages/web/src/content/docs/tr/ecosystem.mdx new file mode 100644 index 000000000..b36538353 --- /dev/null +++ b/packages/web/src/content/docs/tr/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: Ekosistem +description: OpenCode ile ilgili tasarımlar ve entegrasyonlar. +--- + +OpenCode üzerine inşa edilmiş bir topluluk projeleri koleksiyonu. + +:::note +OpenCode ile ilgili projenizi bu listeye eklemek ister misiniz? Bir PR gönderin. +::: + +Ayrıca ekosistemi ve topluluğu bir araya getiren bir topluluk olan [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) ve [opencode.cafe](https://opencode.cafe)'e de göz atabilirsiniz. + +--- + +## Plugins + +| İsim | Açıklama | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| [opencode-daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | OpenCode oturumlarını git senkronizasyonu ve canlı önizlemelerle izole Daytona sanal alanlarında otomatik olarak çalıştırın | +| [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | İstek gruplaması için Helicone oturum başlıklarını otomatik olarak ekleme | +| [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Arama araçlarıyla TypeScript/Svelte türlerini dosya okumalarına otomatik olarak enjekte edin | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | API kredisi yerine ChatGPT Plus/Pro aboneliğinizi kullanın | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | API faturalandırma yerine mevcut Gemini planınızı kullanın | +| [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | API faturalandırma yerine Antigravity'nin ücretsiz modellerini kullanın | +| [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Sığ klonlar ve otomatik atanan bağlantı noktalarıyla çok dallı devcontainer izolasyonu | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Arama desteği ve daha sağlam API işleme özelliğiyle Google Antigravity OAuth Eklentisi | +| [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Optimize token usage by pruning obsolete tool outputs | +| [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Desteklenen sağlayıcılar için Google tabanlı stil ile yerel web araması desteği ekleyin | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Yapay zeka aracılarının bir PTY'de arka plan işlemlerini çalıştırmasına ve onlara etkileşimli girdi göndermesine olanak tanır. | +| [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Etkileşimli olmayan kabuk komutlarına yönelik talimatlar - TTY bağımlı işlemlerden kaynaklanan askıda kalmaları önler | +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Wakatime ile OpenCode kullanımını izleyin | +| [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Clean up markdown tables produced by LLMs | +| [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | Morph Fast Apply API ve yavaş düzenleme işaretçileriyle 10 kat daha hızlı kod düzenleme | +| [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Background agents, pre-built LSP/AST/MCP tools, curated agents, Claude Code compatible | +| [opencode-notificator](https://github.com/panta82/opencode-notificator) | OpenCode oturumları için masaüstü bildirimleri ve sesli uyarılar | +| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | İzin, tamamlama ve hata olayları için masaüstü bildirimleri ve sesli uyarılar | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | OpenCode bağlamına dayalı yapay zeka destekli otomatik Zellij oturumu adlandırma | +| [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | OpenCode temsilcilerinin, beceri keşfi ve ekleme ile istek üzerine istemleri yavaş yüklemesine izin verin | +| [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Supermemory kullanarak oturumlar arasında kalıcı hafıza | +| [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Görsel açıklama ve private/offline paylaşımıyla etkileşimli plan incelemesi | +| [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Açık kodu/komutları ayrıntılı akış kontrolüyle güçlü bir orkestrasyon sistemine genişletin | +| [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Cron sözdizimi ile launchd (Mac) veya systemd (Linux) kullanarak yinelenen işleri planlayın | +| [micode](https://github.com/vtemian/micode) | Yapılandırılmış Beyin Fırtınası → Planla → Oturum sürekliliği ile iş akışını uygulama | +| [octto](https://github.com/vtemian/octto) | Çoklu soru formlarıyla yapay zeka beyin fırtınası için etkileşimli tarayıcı arayüzü | +| [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Eşzamansız delegasyon ve bağlam kalıcılığına sahip Claude Code tarzı arka plan aracıları | +| [opencode-notify](https://github.com/kdcokenny/opencode-notify) | OpenCode için yerel işletim sistemi bildirimleri – görevlerin ne zaman tamamlandığını bilin | +| [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Birlikte verilen çok aracılı orkestrasyon donanımı – 16 bileşen, tek kurulum | +| [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | OpenCode için sıfır sürtünmeli git çalışma ağaçları | + +--- + +## Projeler + +| İsim | Tanım | +| ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- | +| [kimaki](https://github.com/remorses/kimaki) | SDK üzerine kurulu OpenCode oturumlarını kontrol eden Discord botu | +| [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | API temel alınarak oluşturulmuş, editöre duyarlı istemler için Neovim eklentisi | +| [portal](https://github.com/hosenur/portal) | Tailscale/VPN üzerinden OpenCode için mobil öncelikli web kullanıcı arayüzü | +| [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | OpenCode eklentileri oluşturmak için şablon | +| [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Açık kod için Neovim ön ucu - terminal tabanlı bir AI kodlama aracısı | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | @opencode-ai/sdk aracılığıyla OpenCode'u kullanmak için Vercel AI SDK sağlayıcısı | +| [OpenChamber](https://github.com/btriapitsyn/openchamber) | OpenCode için Web / Masaüstü Uygulaması ve VS Code Uzantısı | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | OpenCode'u Obsidian'ın kullanıcı arayüzüne yerleştiren Obsidian eklentisi | +| [OpenWork](https://github.com/different-ai/openwork) | OpenCode tarafından desteklenen, Claude Cowork'e açık kaynaklı bir alternatif | +| [ocx](https://github.com/kdcokenny/ocx) | Taşınabilir, yalıtılmış profillere sahip OpenCode uzantı yöneticisi. | +| [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | OpenCode için Masaüstü, Web, Mobil ve Uzak İstemci Uygulaması | + +--- + +## Agents + +| İsim | Açıklama | +| ----------------------------------------------------------------- | --------------------------------------------------------------------------- | +| [Agentic](https://github.com/Cluster444/agentic) | Yapılandırılmış geliştirme için modüler yapay zeka aracıları ve komutları | +| [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Gelişmiş iş akışları için yapılandırmalar, istemler, aracılar ve eklentiler | diff --git a/packages/web/src/content/docs/tr/enterprise.mdx b/packages/web/src/content/docs/tr/enterprise.mdx new file mode 100644 index 000000000..c40d3d296 --- /dev/null +++ b/packages/web/src/content/docs/tr/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: Girişim +description: OpenCode'u kısıtlamanızda güvenli bir şekilde kullanma. +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise, kodlarının ve verilerinin altyapılarından asla ayrılmamasını sağlamak isteyen kuruluşlar içindir. Bunu, SSO ve dahili AI ağ geçidinizle entegre olan merkezi bir yapılandırma kullanarak yapabilir. + +:::note +OpenCode kodunuzu veya içerik verilerinizi saklamaz. +::: + +OpenCode Enterprise'ı kullanmaya başlamak için: + +1. Ekibinizle dahili olarak bir deneme yapın. +2. Fiyatlandırma ve uygulama seçeneklerini görüşmek için **bize ulaşın**. + +--- + +## Trial + +OpenCode açık kaynaktır ve herhangi bir kodunuzu veya içerik verilerinizi saklamaz; böylece geliştiricileriniz [get started](/docs/) yapıp bir deneme gerçekleştirebilir. + +--- + +### Veri işleme + +**OpenCode, kodunuzu veya içerik verilerinizi saklamaz.** Tüm işlemler yerel olarak veya AI sağlayıcınıza doğrudan API çağrıları yoluyla gerçekleştirilir. + +Bu, güvendiğiniz bir sağlayıcıyı veya dahili bir sağlayıcıyı kullandığınız sürece +AI ağ geçidi, OpenCode'u güvenli bir şekilde kullanabilirsiniz. + +saklama alanının tek izolasyonuna bağlı `/share` özelliğidir. + +--- + +#### Sharing conversations + +Bir kullanıcı `/share` özelliğini etkinleştirirse, görüşme ve onunla ilişkili veriler, bu paylaşım sayfalarını opencode.ai'de barındırmak için kullandığımız hizmete gönderilir. + +Veriler şu anda CDN uç ağımız üzerinden sunuluyor ve kullanıcılarınızın yakınındaki uçta önbelleğe alınıyor. + +Deneme süreniz için bunu devre dışı bırakmanızı öneririz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[Learn more about sharing](/docs/share). + +--- + +### Kod sahipliği + +**OpenCode tarafından üretilen tüm kodlara sahipsiniz.** Herhangi bir lisans kısıtlaması veya mülkiyet iddiası yoktur. + +--- + +## Pricing + +OpenCode Enterprise için bilgisayar başına model kullanıyoruz. Kendi LLM ağ geçidiniz varsa, kullanılan jetonlar için ücret talep etmiyoruz. Fiyatlandırma ve uygulama seçenekleri hakkında daha fazla ayrıntı için **bize ulaşın**. + +--- + +## Dağıtım + +Deneme sürenizi tamamladıktan ve OpenCode'u şu adreste kullanmaya hazır olduğunuzda: +kuruluşunuz hakkında görüşmek üzere **bizimle iletişime geçebilirsiniz** +fiyatlandırma ve uygulama seçenekleri. + +--- + +### Central Config + +OpenCode'u tüm organizasyonunuz için tek bir merkezi yapılandırma kullanacak şekilde ayarlayabiliriz. + +Bu merkezi yapılandırma, SSO sağlayıcınızla entegre olabilir ve tüm kullanıcıların yalnızca dahili AI ağ geçidinize erişmesini sağlar. + +--- + +### SSO entegrasyonu + +Merkezi yapılandırma aracılığıyla OpenCode, kimlik doğrulama için kuruluşunuzun SSO sağlayıcısıyla entegre olabilir. + +Bu, OpenCode'un mevcut kimlik yönetimi sisteminiz aracılığıyla dahili AI ağ geçidiniz için kimlik bilgileri almasına olanak tanır. + +--- + +### Internal AI gateway + +Merkezi yapılandırmayla OpenCode yalnızca dahili AI ağ geçidinizi kullanacak şekilde de yapılandırılabilir. + +Ayrıca tüm isteklerin kuruluşunuzun onaylı altyapısından geçmesini sağlayarak diğer tüm AI sağlayıcılarını devre dışı bırakabilirsiniz. + +--- + +### Kendi kendine barındırma + +Verilerinizin asla silinmediğinden emin olmak için paylaşım sayfalarını devre dışı bırakmanızı öneririz. +Kuruluşunuzda, bunları altyapınızda kendiniz barındırmanıza da yardımcı olabiliriz. + +Bu şu anda yol haritamızda yer alıyor. İlgileniyorsanız **bize bildirin**. + +--- + +## FAQ + +

+What is OpenCode Enterprise? + +OpenCode Enterprise, kodlarının ve verilerinin altyapılarından asla ayrılmamasını sağlamak isteyen kuruluşlar içindir. Bunu, SSO ve dahili AI ağ geçidinizle entegre olan merkezi bir yapılandırma kullanarak yapabilir. + +
+ +
+How do I get started with OpenCode Enterprise? + +Ekibinizle dahili bir denemeyle başlayın. OpenCode varsayılan olarak kodunuzu veya içerik verilerinizi saklamaz, bu da başlamayı kolaylaştırır. + +Daha sonra fiyatlandırma ve uygulama seçeneklerini görüşmek için **bizimle iletişime geçin**. + +
+ +
+How does enterprise pricing work? + +Koltuk başına kurumsal fiyatlandırma sunuyoruz. Kendi LLM ağ geçidiniz varsa, kullanılan jetonlar için ücret talep etmiyoruz. Daha fazla ayrıntı için kuruluşunuzun ihtiyaçlarına göre özel bir fiyat teklifi almak üzere **bize ulaşın**. + +
+ +
+Is my data secure with OpenCode Enterprise? + +Evet. OpenCode kodunuzu veya içerik verilerinizi saklamaz. Tüm işlemler yerel olarak veya AI sağlayıcınıza doğrudan API çağrıları yoluyla gerçekleşir. Merkezi yapılandırma ve SSO entegrasyonuyla verileriniz kuruluşunuzun altyapısında güvende kalır. + +
+ +
+Can we use our own private NPM registry? + +OpenCode, Bun'un yerel `.npmrc` dosya desteği aracılığıyla özel npm kayıtlarını destekler. Kuruluşunuz JFrog Artifactory, Nexus veya benzeri gibi özel bir kayıt defteri kullanıyorsa, OpenCode'u çalıştırmadan önce geliştiricilerin kimlik doğrulamasının yapıldığından emin olun. + +Özel kayıt defterinizle kimlik doğrulamayı ayarlamak için: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +Bu, kimlik doğrulama ayrıntılarını içeren `~/.npmrc` öğesini oluşturur. OpenCode otomatik olarak +şunu al. + +:::caution +OpenCode'u çalıştırmadan önce özel kayıt defterinde oturum açmalısınız. +::: + +Alternatif olarak, bir `.npmrc` dosyasını manuel olarak yapılandırabilirsiniz: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Paketlerin kurumsal kayıt defterinizden yüklenebildiğinden emin olmak için geliştiricilerin OpenCode'u çalıştırmadan önce özel kayıt defterinde oturum açmaları gerekir. + +
diff --git a/packages/web/src/content/docs/tr/formatters.mdx b/packages/web/src/content/docs/tr/formatters.mdx new file mode 100644 index 000000000..fefee9e75 --- /dev/null +++ b/packages/web/src/content/docs/tr/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: Biçimlendiriciler +description: OpenCode dile özgü biçimlendiriciler kullanır. +--- + +OpenCode, dosyaları dile özgü formatlayıcılar kullanılarak yazıldıktan veya düzenlendikten sonra otomatik olarak formatlar. Bu, oluşturulan kodun projenizin kod stillerine uymasını sağlar. + +--- + +## Built-in + +OpenCode, popüler diller ve çerçeveler için çeşitli yerleşik biçimlendiricilerle birlikte gelir. Aşağıda ihtiyaç duyduğu biçimlendiricilerin, desteklenen dosya uzantılarının ve komutların veya yapılandırma seçeneklerinin bir listesi bulunmaktadır. + +| Formatter | Extensions | Requirements | +| ------------------ | ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | +| gofmt | .go | `gofmt` komutu mevcut | +| karışım | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` komutu mevcut | +| daha güzel | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml ve [more](https://prettier.io/docs/en/index.html) | `prettier` bağımlılığı `package.json`'de | +| biyom | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml ve [more](https://biomejs.dev/) | `biome.json(c)` yapılandırma dosyası | +| zig | .zig, .zon | `zig` komutu mevcut | +| clang formatı | .c, .cpp, .h, .hpp, .ino ve [more](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` yapılandırma dosyası | +| klint | .kt, .kts | `ktlint` komutu mevcut | +| fırfır | .py, .pyi | `ruff` komutu yapılandırmayla kullanılabilir | +| pas fmt | .rs | `rustfmt` komutu mevcut | +| kargo fmt | .rs | `cargo fmt` komutu mevcut | +| UV | .py, .pyi | `uv` komutu mevcut | +| rubokop | .rb, .rake, .gemspec, .ru | `rubocop` komutu mevcut | +| standartrb | .rb, .rake, .gemspec, .ru | `standardrb` komutu mevcut | +| htmlgüzelleştirici | .erb, .html.erb | `htmlbeautifier` komutu mevcut | +| hava | .R | `air` komutu mevcut | +| dart | .dart | `dart` komutu mevcut | +| ocamlformat | .ml, .mli | `ocamlformat` komutu mevcut ve `.ocamlformat` yapılandırma dosyası | +| yeryüzü | .tf, .tfvars | `terraform` komutu mevcut | +| parıltı | .gliam | `gleam` komutu mevcut | +| nixfmt | .nix | `nixfmt` komutu mevcut | +| shfmt | .sh, .bash | `shfmt` komutu mevcut | +| pint | .php | `laravel/pint` dependency in `composer.json` | +| oxfmt (Deneysel) | .js, .jsx, .ts, .tsx | `package.json` içindeki `oxfmt` bağımlılığı ve [experimental env variable flag](/docs/cli/#experimental) | +| ormolu | .hs | `ormolu` komutu mevcut | + +Yani eğer projenizin `package.json` dosyasında `prettier` varsa, OpenCode bunu otomatik olarak kullanacaktır. + +--- + +## Nasıl çalışır? + +OpenCode bir dosyayı yazdığında veya düzenlediğinde: + +1. Dosya uzantısını tüm etkin formatlayıcılara göre kontrol eder. +2. Dosyada uygun biçimlendirici komutunu çalıştırır. +3. Biçimlendirme değişikliklerini otomatik olarak uygular. + +Bu işlem arka planda gerçekleşir ve kod stillerinizin herhangi bir manuel adım olmadan korunmasını sağlar. + +--- + +## Yapılandır + +Biçimlendiricileri OpenCode yapılandırmanızdaki `formatter` bölümü aracılığıyla özelleştirebilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +Her formatlayıcı yapılandırması aşağıdakileri destekler: + +| Emlak | Tür | Açıklama | +| ------------- | ------ | ---------------------------------------------------------------------- | +| `disabled` | boole | Biçimlendiriciyi devre dışı bırakmak için bunu `true` olarak ayarlayın | +| `command` | dize[] | Biçimlendirme için çalıştırılacak komut | +| `environment` | nesne | Biçimlendiriciyi çalıştırırken ayarlanacak ortam değişkenleri | +| `extensions` | dize[] | Bu formatlayıcının işlemesi gereken dosya uzantıları | + +Let's look at some examples. + +--- + +### Biçimlendiricileri devre dışı bırakma + +**tüm** biçimlendiricileri genel olarak devre dışı bırakmak için `formatter` değerini `false` olarak ayarlayın: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +**Belirli** bir biçimlendiriciyi devre dışı bırakmak için `disabled` değerini `true` olarak ayarlayın: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Custom formatters + +Komutu, ortam değişkenlerini ve dosya uzantılarını belirterek yerleşik biçimlendiricileri geçersiz kılabilir veya yenilerini ekleyebilirsiniz: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +Komuttaki **`$FILE` yer tutucusu**, biçimlendirilen dosyanın yolu ile değiştirilecektir. diff --git a/packages/web/src/content/docs/tr/github.mdx b/packages/web/src/content/docs/tr/github.mdx new file mode 100644 index 000000000..975142566 --- /dev/null +++ b/packages/web/src/content/docs/tr/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: GitHub sorunlarında ve çekme isteklerinde OpenCode'u kullanın. +--- + +OpenCode, GitHub iş akışınızla bütünleşir. Yorumunuzda `/opencode` veya `/oc`'den bahsedin; OpenCode, GitHub Actions çalıştırıcınızdaki görevleri yürütecektir. + +--- + +## Features + +- **Sorunları önceliklendirin**: OpenCode'dan bir sorunu araştırıp size açıklamasını isteyin. +- **Düzelt ve uygula**: OpenCode'dan bir sorunu düzeltmesini veya bir özelliği uygulamasını isteyin. Ve yeni bir şubede çalışacak ve tüm değişiklikleri içeren bir PR gönderecek. +- **Güvenli**: OpenCode, GitHub'ınızın çalıştırıcılarının içinde çalışır. + +--- + +## Kurulum + +GitHub deposundaki bir projede aşağıdaki komutu çalıştırın: + +```bash +opencode github install +``` + +Bu size GitHub uygulamasını yükleme, iş akışını oluşturma ve gizli dizileri ayarlama adımlarında yol gösterecektir. + +--- + +### Manual Setup + +Veya manuel olarak ayarlayabilirsiniz. + +1. **GitHub uygulamasını yükleyin** + + [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent)'a gidin. Hedef depoya kurulu olduğundan emin olun. + +2. **İş akışını ekleyin** + + Aşağıdaki iş akışı dosyasını deponuzdaki `.github/workflows/opencode.yml`'a ekleyin. `env`'de uygun `model` ve gerekli API anahtarlarını ayarladığınızdan emin olun. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. **API anahtarlarını gizli olarak saklayın** + + Kuruluşunuzda veya projenizde **ayarlarda**, soldaki **Gizli bilgiler ve değişkenler**'i genişletin ve **Eylemler**'i seçin. Ve gerekli API anahtarlarını ekleyin. + +--- + +## Yapılandırma + +- `model`: OpenCode ile kullanılacak model. `provider/model` biçimini alır. Bu **gerekli**. +- `agent`: Kullanılacak aracı. Birincil ajan olmalı. Yapılandırmadan `default_agent`'ye veya bulunamazsa `"build"`'ye geri döner. +- `share`: OpenCode hesabının paylaşılıp paylaşılmayacağı. Genel depolar için varsayılan olarak **true** olur. +- `prompt`: Varsayılan çalışma geçersiz olduğundan dolayı özel istem. OpenCode'un işleme biçimini kişiselleştirmek için bunu kullanın. +- `token`: Yorum oluşturma, değişiklik yapma ve çekme isteklerini açma gibi işlemleri gerçekleştirmek için isteğe bağlı GitHub erişim belirteci. Varsayılan olarak OpenCode, OpenCode GitHub Uygulamasındaki kurulum erişim belirtecini kullanır, bu nedenle taahhütler, yorumlar ve çekme istekleri uygulamadan geliyormuş gibi görünür. + + Alternatif olarak, OpenCode GitHub'u yüklemeden GitHub Eylem çalıştırıcısının [built-in `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) akışını kullanabilirsiniz. İşinizde gerekli izinlere sahip olduğunuzdan emin olun: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + Tercih edilirse [personal access tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) de kullanabilirsiniz. + +--- + +## Supported Events + +OpenCode aşağıdaki GitHub olayları tarafından tetiklenebilir: + +| Event Type | Triggered By | Details | +| ----------------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `issue_comment` | Bir soruna veya halkla ilişkilere yorum yapın | Yorumunuzda `/opencode` veya `/oc`'den bahsedin. OpenCode bağlamı okur ve şubeler oluşturabilir, PR'leri açabilir veya yanıt verebilir. | +| `pull_request_review_comment` | PR'deki belirli kod satırlarına yorum yapın | Kodu incelerken `/opencode` veya `/oc`'den bahsedin. OpenCode dosya yolunu, satır numaralarını ve fark içeriğini alır. | +| `issues` | Sayı açıldı veya düzenlendi | Sorunlar oluşturulduğunda veya değiştirildiğinde OpenCode'u otomatik olarak tetikleyin. `prompt` girişi gerektirir. | +| `pull_request` | PR açıldı veya güncellendi | PR'ler açıldığında, senkronize edildiğinde veya yeniden açıldığında OpenCode'u otomatik olarak tetikleyin. Otomatik incelemeler için kullanışlıdır. | +| `schedule` | Cron tabanlı program | OpenCode'u bir programa göre çalıştırın. `prompt` girişi gerektirir. Çıktı, günlüklere ve PR'lere gider (yorum yapılacak bir sorun yoktur). | +| `workflow_dispatch` | GitHub kullanıcı arayüzünden manuel tetikleme | Eylemler sekmesi aracılığıyla OpenCode'u isteğe bağlı olarak tetikleyin. `prompt` girişi gerektirir. Çıktı günlüklere ve PR'lere gider. | + +### Schedule Example + +Otomatik görevleri gerçekleştirmek için OpenCode'u bir zamanlamaya göre çalıştırın: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +Zamanlanmış etkinlikler için, talimatların alınabileceği bir yorum bulunmadığından `prompt` girişi **gereklidir**. Zamanlanmış iş akışları, izin kontrolü yapılacak bir kullanıcı bağlamı olmadan çalışır; bu nedenle, OpenCode'un şubeler veya PR'ler oluşturmasını bekliyorsanız iş akışının `contents: write` ve `pull-requests: write` vermesi gerekir. + +--- + +### Çekme İsteği Örneği + +PR'leri açıldığında veya güncellendiğinde otomatik olarak inceleyin: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +`pull_request` olaylar için, `prompt` sağlanmazsa, OpenCode varsayılan olarak çekme isteklerini inceler. + +--- + +### Issues Triage Example + +Yeni sorunları otomatik olarak önceliklendirin. Bu örnek, spam'i azaltmak için 30 günden eski hesapları filtreler: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +`issues` olayları için, talimatların çıkarılacağı bir yorum olmadığından `prompt` girişi **gereklidir**. + +--- + +## Özel istemler + +OpenCode'un davranışını iş akışınız için özelleştirmek için varsayılan istemi geçersiz kılın. + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +Bu, projenizle ilgili spesifik inceleme kriterlerini, kodlama standartlarını veya odak alanlarını uygulamak için kullanışlıdır. + +--- + +## Examples + +GitHub'da OpenCode'u nasıl kullanabileceğinize dair bazı örnekleri burada bulabilirsiniz. + +- **Explain an issue** + + Bu yorumu GitHub sayısına ekleyin. + + ``` + /opencode explain this issue + ``` + + OpenCode, tüm yorumlar da dahil olmak üzere ileti dizisinin tamamını okuyacak ve net bir açıklama ile yanıt verecektir. + +- **Fix an issue** + + In a GitHub issue, say: + + ``` + /opencode fix this + ``` + + Ve OpenCode yeni bir şube oluşturacak, değişiklikleri uygulayacak ve değişiklikleri içeren bir PR açacak. + +- **PR'leri inceleyin ve değişiklik yapın** + + GitHub PR'a aşağıdaki yorumu bırakın. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + OpenCode istenen değişikliği uygulayacak ve aynı PR'ye uygulayacaktır. + +- **Review specific code lines** + + PR'nin "Dosyalar" sekmesindeki kod satırlarına doğrudan yorum bırakın. OpenCode, kesin yanıtlar sağlamak için dosyayı, satır numaralarını ve fark içeriğini otomatik olarak algılar. + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + When commenting on specific lines, OpenCode receives: + - İncelenmekte olan dosyanın tamamı + - Belirli kod satırları + - Çevreleyen fark bağlamı + - Line number information + + Bu, dosya yollarını veya satır numaralarını manuel olarak belirtmeye gerek kalmadan daha hedefli isteklere olanak tanır. diff --git a/packages/web/src/content/docs/tr/gitlab.mdx b/packages/web/src/content/docs/tr/gitlab.mdx new file mode 100644 index 000000000..9418c37ce --- /dev/null +++ b/packages/web/src/content/docs/tr/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: GitLab sorunlarında ve parçalanma isteğinde OpenCode'u kullanın. +--- + +OpenCode, GitLab CI/CD ardışık düzeniniz veya GitLab Duo aracılığıyla GitLab iş akışınızla bütünleşir. + +Her iki durumda da OpenCode, GitLab çalıştırıcılarınızda çalışacaktır. + +--- + +## GitLab CI + +OpenCode normal bir GitLab hattında çalışır. Bunu bir [CI component](https://docs.gitlab.com/ee/ci/components/) olarak bir boru hattına oluşturabilirsiniz. + +Burada OpenCode için topluluk tarafından oluşturulan bir CI/CD bileşeni kullanıyoruz — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode). + +--- + +### Özellikler + +- **İş başına özel işlemleri kullanın**: OpenCode parçalarının kullanıma veya devre dışı bırakmak için OpenCode'u özel bir yapılandırma dizini ile yapılandırın; örneğin `./config/#custom-directory`. +- **Minimum kurulum**: CI bileşeni OpenCode'u arka planda kurar; yalnızca OpenCode yapılandırmasını ve ilk istemi oluşturmanız gerekir. +- **Esnek**: CI bileşeni, davranışını özelleştirmek için çeşitli girişleri destekler + +--- + +### Setup + +1. OpenCode kimlik doğrulamanızı JSON **Ayarlar** > **CI/CD** > **Değişkenler** altında Dosya türü CI ortam değişkenleri olarak saklayın. Bunları "Maskeli ve gizli" olarak işaretlediğinizden emin olun. +2. Aşağıdakileri `.gitlab-ci.yml` dosyanıza ekleyin. + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +Daha fazla girdi ve bu bileşene yönelik kullanım durumları için [check out the docs](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode). + +--- + +## GitLab Duo + +OpenCode, GitLab iş akışınızla bütünleşir. +Bir yorumda `@opencode`'dan bahsedin; OpenCode, GitLab CI işlem hattınızdaki görevleri yürütecektir. + +--- + +### Features + +- **Sorunları önceliklendirin**: OpenCode'dan bir sorunu araştırıp size açıklamasını isteyin. +- **Düzelt ve uygula**: OpenCode'dan bir sorunu düzeltmesini veya bir özelliği uygulamasını isteyin. + Yeni bir şube oluşturacak ve değişikliklerle birlikte bir birleştirme isteği oluşturacaktır. +- **Güvenli**: OpenCode, GitLab çalıştırıcılarınızda çalışır. + +--- + +### Kurmak + +OpenCode, GitLab CI/CD işlem hattınızda çalışır; bunu ayarlamak için ihtiyacınız olacaklar: + +:::tip +Güncel talimatlar için [**GitLab docs**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/)'a göz atın. +::: + +1. GitLab ortamınızı yapılandırın +2. CI/CD'yi kurma +3. Bir AI model sağlayıcısı API anahtarını gösterir +4. Hizmet hesabı oluşturun +5. CI/CD değişkenlerini yapılandırma +6. Bir akış yapılandırma dosyası oluşturun; işte bir örnek: + + + + Akış yapılandırması + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + + + +Ayrıntılı talimatlar için [GitLab CLI agents docs](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/)'a başvurabilirsiniz. + +--- + +### Examples + +GitLab'da OpenCode'u nasıl kullanabileceğinize dair bazı örnekleri burada bulabilirsiniz. + +:::tip +`@opencode`'dan farklı bir tetikleyici ifade kullanacak şekilde yapılandırabilirsiniz. +::: + +- **Explain an issue** + + Bu yorumu bir GitLab sayısına ekleyin. + + ``` + @opencode explain this issue + ``` + + OpenCode konuyu okuyacak ve net bir açıklama ile yanıt verecektir. + +- **Fix an issue** + + In a GitLab issue, say: + + ``` + @opencode fix this + ``` + + OpenCode yeni bir şube oluşturacak, değişiklikleri uygulayacak ve değişiklikleri içeren bir birleştirme isteği açacaktır. + +- **Review merge requests** + + GitLab birleştirme isteğine aşağıdaki yorumu bırakın. + + ``` + @opencode review this merge request + ``` + + OpenCode, birleştirme isteğini inceleyecek ve geri bildirim sağlayacaktır. diff --git a/packages/web/src/content/docs/tr/ide.mdx b/packages/web/src/content/docs/tr/ide.mdx new file mode 100644 index 000000000..251dfd92d --- /dev/null +++ b/packages/web/src/content/docs/tr/ide.mdx @@ -0,0 +1,48 @@ +--- +title: IDE +description: VS Code, Cursor ve diğer IDE'ler için OpenCode uzantısı +--- + +OpenCode, VS Code, Cursor veya bir terminali destekleyen herhangi bir IDE ile entegre olur. Başlamak için terminalde `opencode` komutunu çalıştırmanız yeterli. + +--- + +## Usage + +- **Hızlı Başlatma**: OpenCode'u bölünmüş terminal görünümünde açmak veya zaten çalışıyorsa mevcut bir terminal oturumuna odaklanmak için `Cmd+Esc` (Mac) veya `Ctrl+Esc` (Windows/Linux) kullanın. +- **Yeni Oturum**: Zaten açık olsa bile yeni bir OpenCode terminal oturumu başlatmak için `Cmd+Shift+Esc` (Mac) veya `Ctrl+Shift+Esc` (Windows/Linux) kullanın. Ayrıca kullanıcı arayüzündeki OpenCode düğmesini de tıklayabilirsiniz. +- **Bağlam Farkındalığı**: Geçerli seçiminizi veya sekmenizi OpenCode ile otomatik olarak paylaşın. +- **Dosya Referansı Kısayolları**: Dosya referansları eklemek için `Cmd+Option+K` (Mac) veya `Alt+Ctrl+K` (Linux/Windows) kullanın. Örneğin, `@File#L37-42`. + +--- + +## Kurulum + +OpenCode'u VS Code'a ve Cursor, Windsurf, VSCodium gibi popüler çatallara yüklemek için: + +1. VS Kodunu Aç +2. Entegre terminali açın +3. `opencode` komutunu çalıştırın - uzantı otomatik olarak yüklenir + +Öte yandan, TUI'den `/editor` veya `/export` çalıştırdığınızda kendi IDE'nizi kullanmak istiyorsanız, `export EDITOR="code --wait"` ayarlamanız gerekir. [Learn more](/docs/tui/#editor-setup). + +--- + +### Manuel Kurulum + +Extension Marketplace'te **OpenCode**'u arayın ve **Yükle**'ye tıklayın. + +--- + +### Sorun giderme + +Uzantı otomatik olarak yüklenemezse: + +- Entegre terminalde `opencode` çalıştırdığınızdan emin olun. +- IDE cihazınız için CLI'nin kurulu olduğunu doğrulayın: + - VS Kodu için: `code` komutu + - İmleç için: `cursor` komutu + - Rüzgar Sörfü için: `windsurf` komutu + - VSCodium için: `codium` komutu + - Değilse, `Cmd+Shift+P` (Mac) veya `Ctrl+Shift+P` (Windows/Linux) çalıştırılır ve "Shell Command: Install 'code' command in PATH" (veya IDE'niz için bağlantıyı) dinleyin. +- VS Code'un uzantı yükleme iznine sahip olduğundan emin olun diff --git a/packages/web/src/content/docs/tr/index.mdx b/packages/web/src/content/docs/tr/index.mdx new file mode 100644 index 000000000..b0730adcf --- /dev/null +++ b/packages/web/src/content/docs/tr/index.mdx @@ -0,0 +1,359 @@ +--- +title: Giriş +description: OpenCode'u kullanmaya başlayın. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**OpenCode**](/) açık kaynaklı bir AI kodlama aracısıdır. Terminal tabanlı bir arayüz, masaüstü uygulaması veya IDE uzantısı olarak mevcuttur. + +![OpenCode TUI with the opencode theme](../../../assets/lander/screenshot.png) + +Hadi başlayalım. + +--- + +#### Prerequisites + +OpenCode'u terminalinizde kullanmak için ihtiyacınız olacak: + +1. Şu gibi modern bir terminal emülatörü: + - [WezTerm](https://wezterm.org), cross-platform + - [Alacritty](https://alacritty.org), cross-platform + - [Ghostty](https://ghostty.org), Linux ve macOS + - [Kitty](https://sw.kovidgoyal.net/kitty/), Linux ve macOS + +2. Kullanmak istediğiniz LLM sağlayıcılarının API anahtarları. + +--- + +## Düzenlemek + +OpenCode'u kurmanın en kolay yolu kurulum betiğidir. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +Ayrıca aşağıdaki komutlarla da yükleyebilirsiniz: + +- **Node.js'yi kullanma** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **Homebrew'u macOS ve Linux'ta kullanma** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > En güncel sürümler için OpenCode dokunuşunu kullanmanızı öneririz. Resmi `brew install opencode` formülü Homebrew ekibi tarafından korunur ve daha sık güncellenir. + +- **Paru'yu Arch Linux'ta kullanma** + + ```bash + paru -S opencode-bin + ``` + +#### Windows + +:::tip[Önerilen: WSL kullanın] +Windows'ta en iyi deneyim için [Windows Subsystem for Linux (WSL)](/docs/windows-wsl) kullanılmasını öneririz. Daha iyi performans ve OpenCode'un özellikleriyle tam uyumluluğu sağlar. +::: + +- **Çikolata Kullanımı** + + ```bash + choco install opencode + ``` + +- **Kepçe Kullanımı** + + ```bash + scoop install opencode + ``` + +- **NPM kullanarak** + + ```bash + npm install -g opencode-ai + ``` + +- **Mise Kullanımı** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **Docker'ı kullanma** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +OpenCode'un Bun kullanılarak Windows'a yüklenmesine yönelik destek şu anda devam etmektedir. + +İkili dosyayı [Releases](https://github.com/anomalyco/opencode/releases)'dan da alabilirsiniz. + +--- + +## Yapılandır + +OpenCode ile herhangi bir LLM sağlayıcısının API anahtarlarını yapılandırarak kullanabilirsiniz. + +LLM sağlayıcılarını kullanmaya yeni başlıyorsanız, [OpenCode Zen](/docs/zen) kullanmanızı öneririz. +OpenCode tarafından test edilmiş ve doğrulanmış modellerin seçilmiş bir listesidir +team. + +1. TUI'de `/connect` komutunu çalıştırın, açık kodu seçin ve [opencode.ai/auth](https://opencode.ai/auth)'ye gidin. + + ```txt + /connect + ``` + +2. Oturum açın, fatura ayrıntılarınızı ekleyin ve API anahtarınızı kopyalayın. + +3. API anahtarınızı yapıştırın. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +Alternatif olarak diğer sağlayıcılardan birini seçebilirsiniz. [Daha fazla bilgi](/docs/providers#directory). + +--- + +## Başlat + +Artık bir sağlayıcı yapılandırdığınıza göre, bir projeye gidebilirsiniz. +üzerinde çalışmak istiyorsun. + +```bash +cd /path/to/project +``` + +Ve OpenCode'u çalıştırın. + +```bash +opencode +``` + +Daha sonra aşağıdaki komutu çalıştırarak proje için OpenCode'u başlatın. + +```bash frame="none" +/init +``` + +Bu, OpenCode'un projenizi analiz etmesini ve bir `AGENTS.md` dosyası oluşturmasını sağlayacaktır. +proje kökü. + +:::tip +Projenizin `AGENTS.md` dosyasını Git'e göndermelisiniz. +::: + +Bu, OpenCode'un proje yapısını ve kodlama modellerini anlamasına yardımcı olur +kullanılmış. + +--- + +## Usage + +Artık projeniz üzerinde çalışmak için OpenCode'u kullanmaya hazırsınız. Sormaktan çekinmeyin +anything! + +Yapay zeka kodlama aracısını kullanma konusunda yeniyseniz aşağıda bazı örnekleri bulabilirsiniz: +help. + +--- + +### Soru sor + +OpenCode'dan kod tabanını size açıklamasını isteyebilirsiniz. + +:::tip +Projedeki dosyaları bulanık aramak için `@` tuşunu kullanın. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +Kod tabanının üzerinde çalışmadığınız bir kısmı varsa bu yararlı olur. + +--- + +### Add features + +OpenCode'dan projenize yeni özellikler eklemesini isteyebilirsiniz. Yine de öncelikle ondan bir plan oluşturmasını istemenizi öneririz. + +1. **Bir plan oluşturun** + + OpenCode, değişiklik yapma yeteneğini devre dışı bırakan bir _Plan moduna_ sahiptir ve + bunun yerine özelliğin nasıl uygulanacağını önerin. + + **Sekme** tuşunu kullanarak buna geçin. Bunun için sağ alt köşede bir gösterge göreceksiniz. + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + Now let's describe what we want it to do. + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + OpenCode'a ne istediğinizi anlamak için yeterli ayrıntıyı vermek istiyorsunuz. Yardımcı olur + onunla ekibinizdeki kıdemsiz bir geliştiriciyle konuşuyormuş gibi konuşmak. + + :::tip + OpenCode'a, ne anladığınızı anlamasına yardımcı olacak bol miktarda bağlam ve örnek verin. + want. + ::: + +2. **Planı yineleyin** + + Size bir plan sunduğunda ona geri bildirimde bulunabilir veya daha fazla ayrıntı ekleyebilirsiniz. + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::tip + İsteme eklemek için görüntüleri terminale sürükleyip bırakın. + ::: + + OpenCode, verdiğiniz tüm görselleri tarayabilir ve istemlere ekleyebilir. Yapabilirsiniz + bunu bir görüntüyü terminale sürükleyip bırakarak yapın. + +3. **Özelliği oluşturun** + + Plan konusunda kendinizi rahat hissettiğinizde, şu şekilde _Oluşturma moduna_ geri dönün: + **Sekme** tuşuna tekrar basmak. + + ```bash frame="none" + + ``` + + Ve ondan değişiklikleri yapmasını istiyoruz. + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### Değişiklik yap + +Daha basit değişiklikler için OpenCode'dan bunu doğrudan oluşturmasını isteyebilirsiniz. +Önce planı gözden geçirmeye gerek kalmadan. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +OpenCode'un doğru kararı vermesi için yeterli miktarda ayrıntı sağladığınızdan emin olmak istiyorsunuz. +değişiklikler. + +--- + +### Undo changes + +Diyelim ki OpenCode'dan bazı değişiklikler yapmasını istediniz. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Ama istediğinin bu olmadığını anlıyorsun. Değişiklikleri **geri alabilirsiniz** +`/undo` komutunu kullanarak. + +```bash frame="none" +/undo +``` + +OpenCode artık yaptığınız değişiklikleri geri alacak ve orijinal mesajınızı gösterecek +again. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +Buradan komut isteminde ince ayar yapabilir ve OpenCode'dan tekrar denemesini isteyebilirsiniz. + +:::tip +Birden çok değişikliği geri almak için `/undo` komutunu birden çok kez çalıştırabilirsiniz. +::: + +Veya `/redo` komutunu kullanarak değişiklikleri **yeniden yapabilirsiniz**. + +```bash frame="none" +/redo +``` + +--- + +## Paylaşmak + +OpenCode ile yaptığınız görüşmeler [eşinizle paylaşılabilir] +takım](/docs/share). + +```bash frame="none" +/share +``` + +Bu, mevcut konuşmaya bir bağlantı oluşturacak ve bunu panonuza kopyalayacaktır. + +:::note +Konuşmalar varsayılan olarak paylaşılmaz. +::: + +İşte OpenCode'lu bir [örnek konuşma](https://opencode.ai/s/4XP1fce5). + +--- + +## Customize + +İşte bu kadar! Artık OpenCode'u kullanma konusunda profesyonelsiniz. + +Kendinize ait hale getirmek için [picking a theme](/docs/themes), [customizing the keybinds](/docs/keybinds), [configuring code formatters](/docs/formatters), [creating custom commands](/docs/commands) veya [OpenCode config](/docs/config) ile oynamanızı öneririz. diff --git a/packages/web/src/content/docs/tr/keybinds.mdx b/packages/web/src/content/docs/tr/keybinds.mdx new file mode 100644 index 000000000..790383b3e --- /dev/null +++ b/packages/web/src/content/docs/tr/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: Tuş bağlantıları +description: Tuş bağlantılarınızı özelleştirin. +--- + +OpenCode, OpenCode yapılandırması aracılığıyla özelleştirebileceğiniz bir tuş bağlantıları listesine sahiptir. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## Leader key + +OpenCode çoğu tuş ataması için `leader` anahtarını kullanır. Bu, terminalinizdeki çakışmaları önler. + +Varsayılan olarak `ctrl+x` lider tuştur ve çoğu eylem önce lider tuşa, ardından kısayola basmanızı gerektirir. Örneğin, yeni bir oturum başlatmak için önce `ctrl+x` tuşuna, ardından `n` tuşuna basarsınız. + +Tuş atamalarınız için lider anahtar kullanmanıza gerek yoktur ancak bunu yapmanızı öneririz. + +--- + +## Tuş atamasını devre dışı bırak + +Anahtarı yapılandırmanıza "none" değeriyle ekleyerek bir tuş atamasını devre dışı bırakabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## Masaüstü istemi kısayolları + +OpenCode masaüstü uygulaması bilgi istemi girişi, metni düzenlemek için yaygın Readline/Emacs tarzı kısayolları destekler. Bunlar yerleşiktir ve şu anda `opencode.json` aracılığıyla yapılandırılamaz. + +| Shortcut | Action | +| -------- | ---------------------------------------- | +| `ctrl+a` | Geçerli satırın başına git | +| `ctrl+e` | Move to end of current line | +| `ctrl+b` | Move cursor back one character | +| `ctrl+f` | Move cursor forward one character | +| `alt+b` | Move cursor back one word | +| `alt+f` | Move cursor forward one word | +| `ctrl+d` | Delete character under cursor | +| `ctrl+k` | Kill to end of line | +| `ctrl+u` | Satırın başına kadar öldür | +| `ctrl+w` | Kill previous word | +| `alt+d` | Kill next word | +| `ctrl+t` | Transpose characters | +| `ctrl+g` | Cancel popovers / abort running response | + +--- + +## Shift+Enter + +Bazı terminaller varsayılan olarak Enter ile değiştirici tuşlar göndermez. Terminalinizi, kaçış dizisi olarak `Shift+Enter` gönderecek şekilde yapılandırmanız gerekebilir. + +### Windows Terminali + +`settings.json` cihazınızı şu adreste açın: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +Bunu kök düzeyindeki `actions` dizisine ekleyin: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Bunu kök düzeyindeki `keybindings` dizisine ekleyin: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +Dosyayı kaydedin ve Windows Terminalini yeniden başlatın veya yeni bir sekme açın. diff --git a/packages/web/src/content/docs/tr/lsp.mdx b/packages/web/src/content/docs/tr/lsp.mdx new file mode 100644 index 000000000..6c06392f1 --- /dev/null +++ b/packages/web/src/content/docs/tr/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: LSP Sunucular +description: OpenCode, LSP sunucularınızla bütünleşir. +--- + +OpenCode, LLM'nin kod tabanınızla etkileşime girmesine yardımcı olmak için Dil Sunucusu Protokolünüzle (LSP) bütünleşir. LLM'ye geri bildirim sağlamak için tanılamayı kullanır. + +--- + +## Built-in + +OpenCode, popüler diller için çeşitli yerleşik LSP sunucularıyla birlikte gelir: + +| LSP Sunucu | Uzantılar | Gereksinimler | +| ------------------- | ------------------------------------------------------------------- | --------------------------------------------------------------------- | +| astro | .astro | Astro projeleri için otomatik kurulumlar | +| bash | .sh, .bash, .zsh, .ksh | Bash-dil-sunucusunu otomatik olarak yükler | +| çıngırak | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | C/C++ projeleri için otomatik kurulumlar | +| csharp | .cs | `.NET SDK` installed | +| clojure-lsp | .clj, .cljs, .cljc, .edn | `clojure-lsp` komutu mevcut | +| dart | .dart | `dart` komutu mevcut | +| den | .ts, .tsx, .js, .jsx, .mjs | `deno` komutu mevcut (deno.json/deno.jsonc otomatik olarak algılanır) | +| iksir-ls | .ex, .exs | `elixir` komutu mevcut | +| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` dependency in project | +| fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` installed | +| parıltı | .gliam | `gleam` komutu mevcut | +| lütfen | .go | `go` komutu mevcut | +| hls | .hs, .lhs | `haskell-language-server-wrapper` komutu mevcut | +| jdtls | .java | `Java SDK (version 21+)` installed | +| kotlin-ls | .kt, .kts | Kotlin projeleri için otomatik kurulumlar | +| lua-ls | .lua | Lua projeleri için otomatik kurulumlar | +| hayır | .nix | `nixd` komutu mevcut | +| ocaml-lsp | .ml, .mli | `ocamllsp` komutu mevcut | +| oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | `oxlint` dependency in project | +| php internet | .php | PHP projeleri için otomatik yüklemeler | +| prizma | .prizma | `prisma` komutu mevcut | +| pyright | .py, .pyi | `pyright` dependency installed | +| yakut-lsp (rubocop) | .rb, .rake, .gemspec, .ru | `ruby` ve `gem` komutları mevcut | +| pas | .rs | `rust-analyzer` komutu mevcut | +| sourcekit-lsp | .swift, .objc, .objcpp | `swift` installed (`xcode` on macOS) | +| ince | .svelte | Svelte projeleri için otomatik kurulumlar | +| yeryüzü | .tf, .tfvars | GitHub sürümlerinden otomatik yüklemeler | +| minik sis | .typ, .typc | GitHub sürümlerinden otomatik yüklemeler | +| typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` dependency in project | +| vue | .vue | Vue projeleri için otomatik yüklemeler | +| yaml-ls | .yaml, .yml | Red Hat yaml-dil-sunucusunu otomatik olarak yükler | +| zl'ler | .zig, .zon | `zig` komutu mevcut | + +Yukarıdaki dosya uzantılarından biri tespit edildiğinde ve gereksinimler karşılandığında LSP sunucuları otomatik olarak etkinleştirilir. + +:::note +`OPENCODE_DISABLE_LSP_DOWNLOAD` ortam değişkenini `true` olarak ayarlayarak otomatik LSP sunucu indirmelerini devre dışı bırakabilirsiniz. +::: + +--- + +## Nasıl Çalışır? + +Opencode bir dosyayı açtığında: + +1. Dosya uzantısını tüm etkin LSP sunucularına göre kontrol eder. +2. Henüz çalışmıyorsa uygun LSP sunucusunu başlatır. + +--- + +## Yapılandır + +LSP sunucularını, açık kod yapılandırmanızdaki `lsp` bölümü aracılığıyla özelleştirebilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Her LSP sunucusu aşağıdakileri destekler: + +| Emlak | Tür | Açıklama | +| ---------------- | ------ | -------------------------------------------------------------------- | +| `disabled` | boole | LSP sunucusunu devre dışı bırakmak için bunu `true` olarak ayarlayın | +| `command` | dize[] | LSP sunucusunu başlatma komutu | +| `extensions` | dize[] | Bu LSP sunucusunun işlemesi gereken dosya uzantıları | +| `env` | nesne | Sunucuyu başlatırken ayarlanacak ortam değişkenleri | +| `initialization` | nesne | LSP sunucusuna gönderilecek başlatma seçenekleri | + +Let's look at some examples. + +--- + +### Ortam değişkenleri + +LSP sunucusunu başlatırken ortam değişkenlerini ayarlamak için `env` özelliğini kullanın: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### Initialization options + +Başlatma seçeneklerini LSP sunucusuna iletmek için `initialization` özelliğini kullanın. Bunlar LSP `initialize` isteği sırasında gönderilen sunucuya özel ayarlardır: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +Başlatma seçenekleri LSP sunucusuna göre değişir. Mevcut seçenekler için LSP sunucunuzun belgelerine bakın. +::: + +--- + +### LSP sunucularını devre dışı bırakma + +**tüm** LSP sunucularını genel olarak devre dışı bırakmak için `lsp`'yi `false` olarak ayarlayın: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +**Belirli** bir LSP sunucusunu devre dışı bırakmak için `disabled`'yi `true` olarak ayarlayın: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Custom LSP servers + +Komutu ve dosya uzantılarını belirterek özel LSP sunucuları ekleyebilirsiniz: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## Ek Bilgiler + +### PHP Intelephense + +PHP Intelephense, bir lisans anahtarı aracılığıyla premium özellikler sunar. Anahtarı (yalnızca) şu adresteki bir metin dosyasına yerleştirerek bir lisans anahtarı sağlayabilirsiniz: + +- MacOS/Linux'ta: `$HOME/intelephense/licence.txt` +- Windows'ta: `%USERPROFILE%/intelephense/licence.txt` + +Dosya, ek içerik olmadan yalnızca lisans anahtarını içermelidir. diff --git a/packages/web/src/content/docs/tr/mcp-servers.mdx b/packages/web/src/content/docs/tr/mcp-servers.mdx new file mode 100644 index 000000000..b81290b76 --- /dev/null +++ b/packages/web/src/content/docs/tr/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: MCP sunucuları +description: Yerel ve uzak MCP araçlarını ekleyin. +--- + +_Model Bağlam Protokolü_ veya MCP kullanarak OpenCode'a harici araçlar ekleyebilirsiniz. OpenCode hem yerel hem de uzak sunucuları destekler. + +MCP araçları eklendikten sonra yerleşik araçların yanı sıra LLM tarafından otomatik olarak kullanılabilir. + +--- + +#### Caveats + +Bir MCP sunucusu kullandığınızda bağlama eklenir. Çok fazla aletiniz varsa, bu hızla artabilir. Bu nedenle hangi MCP sunucularını kullandığınıza dikkat etmenizi öneririz. + +:::tip +MCP sunucuları içeriğinize katkıda bulunur, bu nedenle hangilerini etkinleştirdiğinize dikkat etmek istersiniz. +::: + +GitHub MCP sunucusu gibi belirli MCP sunucuları çok sayıda belirteç ekleme eğilimindedir ve bağlam sınırını kolayca aşabilir. + +--- + +## Olanak vermek + +MCP sunucularını [OpenCode Config](https://opencode.ai/docs/config/)'nizde `mcp` altında tanımlayabilirsiniz. Her MCP'ü benzersiz bir adla ekleyin. LLM isteminde bulunurken bu MCP adına başvurabilirsiniz. + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +Ayrıca `enabled` öğesini `false` olarak ayarlayarak bir sunucuyu devre dışı bırakabilirsiniz. Bir sunucuyu yapılandırmanızdan kaldırmadan geçici olarak devre dışı bırakmak istiyorsanız bu kullanışlıdır. + +--- + +### Overriding remote defaults + +Kuruluşlar, `.well-known/opencode` uç noktaları aracılığıyla varsayılan MCP sunucularını sağlayabilir. Bu sunucular varsayılan olarak devre dışı bırakılarak kullanıcıların ihtiyaç duydukları sunucuları seçmelerine olanak tanınabilir. + +Kuruluşunuzun uzak yapılandırmasından belirli bir sunucuyu etkinleştirmek için onu `enabled: true` ile yerel yapılandırmanıza ekleyin: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +Yerel yapılandırma değerleriniz uzak varsayılanları geçersiz kılar. Daha fazla ayrıntı için [config precedence](/docs/config#precedence-order)'a bakın. + +--- + +## Yerel + +`type` kullanarak yerel MCP sunucularını MCP nesnesi içindeki `"local"`'ye ekleyin. + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +Komut, yerel MCP sunucusunun nasıl başlatıldığıdır. Ayrıca ortam değişkenlerinin bir listesini de iletebilirsiniz. + +Örneğin, [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP test sunucusunu şu şekilde görebilirsiniz. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +Ve bunu kullanmak için istemlerime `use the mcp_everything tool` kullanıyorum. + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### Options + +Yerel bir MCP sunucusunu yapılandırmak için tüm seçenekler burada verilmiştir. + +| Seçenek | Tür | Gerekli | Açıklama | +| ------------- | ------- | ------- | ---------------------------------------------------------------------------------------------- | +| `type` | Dize | Y | MCP sunucu bağlantısı türü, `"local"` olmalıdır. | +| `command` | Dizi | Y | MCP sunucusunu çalıştırmak için komut ve argümanlar. | +| `environment` | Nesne | | Sunucuyu çalıştırırken ayarlanacak ortam değişkenleri. | +| `enabled` | Boolean | | Başlangıçta MCP sunucusunu etkinleştirin veya devre dışı bırakın. | +| `timeout` | Sayı | | MCP sunucusundan araçları getirirken ms cinsinden zaman aşımı. Varsayılan 5000'dir (5 saniye). | + +--- + +## Uzak + +`type`'yi `"remote"` olarak ayarlayarak uzak MCP sunucularını ekleyin. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` uzak MCP sunucusunun URL'sidir ve `headers` seçeneğiyle bir başlık listesi iletebilirsiniz. + +--- + +#### Options + +| Seçenek | Tür | Gerekli | Açıklama | +| --------- | ------- | ------- | ---------------------------------------------------------------------------------------------- | +| `type` | Dize | Y | MCP sunucu bağlantısı türü, `"remote"` olmalıdır. | +| `url` | Dize | Y | Uzak MCP sunucusunun URL. | +| `enabled` | Boolean | | Başlangıçta MCP sunucusunu etkinleştirin veya devre dışı bırakın. | +| `headers` | Nesne | | İstekle birlikte gönderilecek başlıklar. | +| `oauth` | Object | | OAuth authentication configuration. See [OAuth](#oauth) section below. | +| `timeout` | Sayı | | MCP sunucusundan araçları getirirken ms cinsinden zaman aşımı. Varsayılan 5000'dir (5 saniye). | + +--- + +## OAuth + +OpenCode, uzak MCP sunucuları için OAuth kimlik doğrulamasını otomatik olarak yönetir. Bir sunucu kimlik doğrulaması gerektirdiğinde OpenCode şunları yapar: + +1. 401 yanıtını tespit edin ve OAuth akışını başlatın +2. Sunucu tarafından destekleniyorsa **Dinamik İstemci Kaydı (RFC 7591)** kullanın +3. Gelecekteki istekler için belirteçleri güvenli bir şekilde saklayın + +--- + +### Automatic + +OAuth'un etkin olduğu çoğu MCP sunucusu için özel bir yapılandırmaya gerek yoktur. Uzak sunucuyu yapılandırmanız yeterli: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +Sunucu kimlik doğrulama gerektiriyorsa OpenCode, onu ilk kez kullanmaya çalıştığınızda kimlik doğrulamanızı isteyecektir. Değilse, `opencode mcp auth ` ile [manually trigger the flow](#authenticating) yapabilirsiniz. + +--- + +### Ön kayıtlı + +MCP sunucu sağlayıcısından istemci kimlik bilgileriniz varsa, bunları yapılandırabilirsiniz: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### Authenticating + +Kimlik doğrulamayı manuel olarak tetikleyebilir veya kimlik bilgilerini yönetebilirsiniz. + +Belirli bir MCP sunucusuyla kimlik doğrulaması yapın: + +```bash +opencode mcp auth my-oauth-server +``` + +Tüm MCP sunucularını ve kimlik doğrulama durumlarını listeleyin: + +```bash +opencode mcp list +``` + +Remove stored credentials: + +```bash +opencode mcp logout my-oauth-server +``` + +`mcp auth` komutu tarayıcınızı yetkilendirme için açacaktır. Yetkilendirmenizin ardından OpenCode, belirteçleri `~/.local/share/opencode/mcp-auth.json`'de güvenli bir şekilde saklar. + +--- + +#### OAuth'u devre dışı bırakma + +Bir sunucu için otomatik OAuth'u devre dışı bırakmak istiyorsanız (örneğin, bunun yerine API anahtarlarını kullanan sunucular için), `oauth`'yi `false` olarak ayarlayın: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### OAuth Options + +| Seçenek | Tür | Açıklama | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` | Object \| false | OAuth config object, or `false` to disable OAuth auto-detection. | +| `clientId` | Dize | OAuth istemci kimliği. Sağlanmadığı takdirde dinamik müşteri kaydı denenecektir. | +| `clientSecret` | Dize | Yetkilendirme sunucusu gerektiriyorsa OAuth istemci sırrı. | +| `scope` | String | OAuth scopes to request during authorization. | + +#### Debugging + +Uzak bir MCP sunucusunun kimlik doğrulaması başarısız olursa aşağıdakileri kullanarak sorunları teşhis edebilirsiniz: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +`mcp debug` komutu mevcut kimlik doğrulama durumunu gösterir, HTTP bağlantısını test eder ve OAuth bulma akışını dener. + +--- + +## Üstesinden gelmek + +MCP'leriniz yerleşik araçların yanı sıra OpenCode'da araç olarak mevcuttur. Böylece bunları diğer araçlar gibi OpenCode yapılandırması aracılığıyla yönetebilirsiniz. + +--- + +### Global + +Bu, bunları global olarak etkinleştirebileceğiniz veya devre dışı bırakabileceğiniz anlamına gelir. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +Eşleşen tüm MCP'leri devre dışı bırakmak için bir glob modeli de kullanabiliriz. + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +Burada tüm MCP'leri devre dışı bırakmak için `my-mcp*` glob modelini kullanıyoruz. + +--- + +### Temsilci başına + +Çok sayıda MCP sunucunuz varsa, bunları yalnızca aracı başına etkinleştirmek ve genel olarak devre dışı bırakmak isteyebilirsiniz. Bunu yapmak için: + +1. Global olarak bir araç olarak devre dışı bırakın. +2. [agent config](/docs/agents#tools)'nizde, MCP sunucusunu bir araç olarak etkinleştirin. + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### Glob patterns + +Glob modeli, basit normal ifade globbing modellerini kullanır: + +- `*` herhangi bir karakterin sıfır veya daha fazlasıyla eşleşir (örneğin, `"my-mcp*"` `my-mcp_search`, `my-mcp_list` vb. ile eşleşir) +- `?` matches exactly one character +- All other characters match literally + +:::note +MCP sunucu araçları önek olarak sunucu adıyla kayıtlıdır, dolayısıyla bir sunucuya ilişkin tüm araçları devre dışı bırakmak için aşağıdakileri kullanmanız yeterlidir: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## Örnekler + +Aşağıda bazı yaygın MCP sunucularının örnekleri verilmiştir. Diğer sunucuları belgelemek istiyorsanız PR gönderebilirsiniz. + +--- + +### Sentry + +Sentry projelerinizle ve sorunlarınızla etkileşimde bulunmak için [Sentry MCP server](https://mcp.sentry.dev) ekleyin. + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +Yapılandırmayı ekledikten sonra Sentry ile kimlik doğrulaması yapın: + +```bash +opencode mcp auth sentry +``` + +Bu, OAuth akışını tamamlamak ve OpenCode'u Sentry hesabınıza bağlamak için bir tarayıcı penceresi açacaktır. + +Kimlik doğrulaması yapıldıktan sonra sorunları, projeleri ve hata verilerini sorgulamak için istemlerinizde Sentry araçlarını kullanabilirsiniz. + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### Bağlam7 + +Dokumanlar arasında arama yapmak için [Context7 MCP server](https://github.com/upstash/context7) ekleyin. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +Ücretsiz bir hesaba kaydolduysanız API anahtarınızı kullanarak daha yüksek ücret limitleri elde edebilirsiniz. + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +Burada `CONTEXT7_API_KEY` ortam değişkeninin ayarlandığını varsayıyoruz. + +Context7 MCP sunucunu kullanmak için isteklerinize `use context7` ekleyin. + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +Alternatif olarak [AGENTS.md](/docs/rules/)'a buna benzer bir şey ekleyebilirsiniz. + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Grep by Vercel + +GitHub'daki kod parçacıkları arasında arama yapmak için [Grep by Vercel](https://grep.app) MCP sunucusunu ekleyin. + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +MCP sunucumuzu `gh_grep` olarak adlandırdığımız için, aracının onu kullanmasını sağlamak için istemlerinize `use the gh_grep tool` ekleyebilirsiniz. + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +Alternatif olarak [AGENTS.md](/docs/rules/)'a buna benzer bir şey ekleyebilirsiniz. + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/tr/models.mdx b/packages/web/src/content/docs/tr/models.mdx new file mode 100644 index 000000000..6404b99ce --- /dev/null +++ b/packages/web/src/content/docs/tr/models.mdx @@ -0,0 +1,223 @@ +--- +title: Modelci +description: LLM sağlayıcısını ve modelinin adı. +--- + +OpenCode, **75+ LLM sağlayıcısını** desteklemek için [AI SDK](https://ai-sdk.dev/) ve [Models.dev](https://models.dev) kullanır ve yerel modellerin çalıştırılmasını destekler. + +--- + +## Providers + +Çoğu popüler sağlayıcı varsayılan olarak önceden yüklenmiştir. Bir sağlayıcının kimlik bilgilerini `/connect` komutu aracılığıyla eklediyseniz, bunlar OpenCode'u başlattığınızda kullanılabilir olacaktır. + +[providers](/docs/providers) hakkında daha fazla bilgi edinin. + +--- + +## Bir model seçin + +Sağlayıcınızı yapılandırdıktan sonra aşağıdaki komutu yazarak istediğiniz modeli seçebilirsiniz: + +```bash frame="none" +/models +``` + +--- + +## Recommended models + +Piyasada pek çok model var ve her hafta yeni modeller çıkıyor. + +:::tip +Önerdiğimiz modellerden birini kullanmayı düşünün. +::: + +Ancak, hem kod oluşturmada hem de araç çağırmada iyi olan yalnızca birkaçı var. + +Burada, OpenCode ile belirli bir sıraya göre iyi çalışan birkaç model yer almaktadır. (Bu kapsamlı bir liste değildir ve mutlaka güncel olması da gerekmez): + +- GPT 5.2 +- GPT 5.1 Codex +- Claude Opus 4.5 +- Claude Sonnet 4.5 +- Minimax M2.1 +- Gemini 3 Pro + +--- + +## Varsayılanı ayarla + +Bunlardan birini varsayılan model olarak ayarlamak için `model` anahtarınızı telefonunuzudan ayarlayabilirsiniz. +OpenCode yapılandırması + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Burada tam kimlik `provider_id/model_id`'dir. Örneğin, [OpenCode Zen](/docs/zen) kullanıyorsanız, GPT 5.1 Codex için `opencode/gpt-5.1-codex` kullanırsınız. + +Bir [custom provider](/docs/providers#custom) yapılandırılmışsa, `provider_id`, performansınızın `provider` bölümünden gelen anahtardır ve `model_id`, `provider.models`'den gelen anahtardır. + +--- + +## Modelleri yapılandırın + +Bir modelin seçeneklerini genel olarak yapılandırma aracılığıyla yapılandırabilirsiniz. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Burada iki yerleşik model için genel ayarları yapılandırıyoruz: `openai` sağlayıcısı aracılığıyla erişildiğinde `gpt-5` ve `anthropic` sağlayıcısı aracılığıyla erişildiğinde `claude-sonnet-4-20250514`. +Yerleşik sağlayıcı ve model adları [Models.dev](https://models.dev) adresinde bulunabilir. + +Bu seçenekleri kullandığınız tüm aracılar için de yapılandırabilirsiniz. Aracı yapılandırması burada tüm genel seçenekleri geçersiz kılar. [Learn more](/docs/agents/#additional). + +Ayrıca yerleşik çeşitleri genişleten özel varyantlar da tanımlayabilirsiniz. Varyantlar, yinelenen girişler oluşturmadan aynı model için farklı ayarları yapılandırmanıza olanak tanır: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## Varyantlar + +Birçok model, farklı konfigürasyonlara sahip birden fazla kapasiteye sahip. OpenCode, popüler sağlayıcılar için sunulan değişkenlerle birlikte gelir. + +### Yerleşik çeşitler + +OpenCode birçok sağlayıcı için varsayılan değişkenlerle birlikte gelir: + +**Antropik**: + +- `high` - Yüksek düşünme bütçesi (varsayılan) +- `max` - Maksimum düşünme bütçesi + +**OpenAI**: + +Modele göre değişir ancak kabaca: + +- `none` - Gerekçe yok +- `minimal` - Minimum akıl yürütme çabası +- `low` - Düşük muhakeme çabası +- `medium` - Orta düzey muhakeme çabası +- `high` - Yüksek akıl yürütme çabası +- `xhigh` - Ekstra yüksek muhakeme çabası + +**Google**: + +- `low` - Daha düşük effort/token bütçesi +- `high` - Daha yüksek effort/token bütçesi + +:::tip +Bu liste kapsamlı değildir. Diğer birçok sağlayıcının da yerleşik varsayılanları vardır. +::: + +### Özel çeşitler + +Mevcut varyantları geçersiz kılabilir veya kendinizinkini ekleyebilirsiniz: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### Döngü çeşitleri + +Çeşitler arasında hızlı geçiş yapmak için `variant_cycle` tuş atamasını kullanın. [Learn more](/docs/keybinds). + +--- + +## Loading models + +OpenCode başlatıldığında modelleri aşağıdaki öncelik sırasına göre kontrol eder: + +1. `--model` veya `-m` komut satırı bayrağı. Biçim, yapılandırma dosyasındakiyle aynıdır: `provider_id/model_id`. + +2. OpenCode yapılandırmasındaki model listesi. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + Buradaki format `provider/model`'dır. + +3. En son kullanılan model. + +4. Dahili öncelik kullanan ilk model. diff --git a/packages/web/src/content/docs/tr/modes.mdx b/packages/web/src/content/docs/tr/modes.mdx new file mode 100644 index 000000000..b32358d02 --- /dev/null +++ b/packages/web/src/content/docs/tr/modes.mdx @@ -0,0 +1,331 @@ +--- +title: Modlar +description: farklı kullanım durumları için farklı modlar. +--- + +:::caution +Modlar artık açık kod yapılandırmasındaki `agent` seçeneği aracılığıyla yapılandırılıyor. +`mode` seçeneği artık kullanımdan kaldırıldı. [Learn more](/docs/agents). +::: + +Açık koddaki modlar, farklı kullanım durumları için davranışı, araçları ve istemleri özelleştirmenize olanak tanır. + +İki yerleşik modla birlikte gelir: **build** ve **plan**. Kişiselleştirebilirsiniz +bunları veya açık kod yapılandırması aracılığıyla kendinizinkini yapılandırın. + +Bir oturum sırasında modlar arasında geçiş yapabilir veya bunları yapılandırma dosyanızda yapılandırabilirsiniz. + +--- + +## Built-in + +opencode iki yerleşik modla birlikte gelir. + +--- + +### İnşa etmek + +Derleme, tüm araçların etkin olduğu **varsayılan** moddur. Bu, dosya işlemlerine ve sistem komutlarına tam erişime ihtiyaç duyduğunuz geliştirme çalışmaları için standart moddur. + +--- + +### Plan + +Planlama ve analiz için tasarlanmış sınırlı bir mod. Plan modunda aşağıdaki araçlar varsayılan olarak devre dışıdır: + +- `write` - Yeni dosyalar oluşturulamıyor +- `edit` - Planın kendisini detaylandırmak için `.opencode/plans/*.md` adresinde bulunan dosyalar dışında mevcut dosyalar değiştirilemez +- `patch` - Cannot apply patches +- `bash` - Kabuk komutları yürütülemiyor + +Bu mod, yapay zekanın kod tabanınızda herhangi bir gerçek değişiklik yapmadan kodu analiz etmesini, değişiklik önermesini veya plan oluşturmasını istediğinizde kullanışlıdır. + +--- + +## Anahtarlama + +Bir oturum sırasında _Tab_ tuşunu kullanarak modlar arasında geçiş yapabilirsiniz. Veya yapılandırılmış `switch_mode` tuş bağlantınız. + +Ayrıca bkz.: Kod biçimlendirme yapılandırması hakkında bilgi için [Formatters](/docs/formatters). + +--- + +## Yapılandır + +Yerleşik modları özelleştirebilir veya yapılandırma aracılığıyla kendinizinkini oluşturabilirsiniz. Modlar iki şekilde yapılandırılabilir: + +### JSON Configuration + +`opencode.json` yapılandırma dosyanızdaki modları yapılandırın: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Markdown Configuration + +Markdown dosyalarını kullanarak modları da tanımlayabilirsiniz. Bunları şuraya yerleştirin: + +- Global: `~/.config/opencode/modes/` +- Project: `.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Markdown dosyası adı mod adı olur (örneğin, `review.md` bir `review` modu oluşturur). + +Let's look at these configuration options in detail. + +--- + +### Modeli + +Bu modun varsayılan standardı geçersiz için `model` kontrolünü kullanın. Farklı bölümler için optimize edilmiş farklı modelleri kullanmak için kullanışlıdır. Örneğin planlama için daha hızlı bir model, uygulama için daha yetenekli bir model. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Temperature + +`temperature` yapılandırmasıyla yapay zekanın yanıtlarının rastgeleliğini ve yaratıcılığını kontrol edin. Düşük değerler yanıtları daha odaklı ve belirleyici hale getirirken, yüksek değerler yaratıcılığı ve değişkenliği artırır. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Sıcaklık değerleri tipik olarak 0,0 ila 1,0 arasındadır: + +- **0,0-0,2**: Çok odaklı ve belirleyici yanıtlar, kod analizi ve planlaması için idealdir +- **0,3-0,5**: Biraz yaratıcılık içeren dengeli yanıtlar, genel gelişim görevleri için iyi +- **0,6-1,0**: Daha yaratıcı ve çeşitli yanıtlar, beyin fırtınası ve keşif için yararlı + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +Sıcaklık belirtilmezse, açık kod modele özgü varsayılanları kullanır (çoğu model için genellikle 0, Qwen modelleri için 0,55). + +--- + +### Çabuk + +`prompt` analiziyle bu mod için özel bir sistem bilgi istemi dosyası destekleniyor. Bilgi istemi şeması, modun amacına özel talimatlar içermelidir. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +Bu yol, yapılandırma dosyasının bulunduğu yere göredir. Yani bu işe yarıyor +hem global açık kod yapılandırması hem de projeye özel yapılandırma. + +--- + +### Tools + +`tools` yapılandırmasıyla bu modda hangi araçların kullanılabileceğini kontrol edin. Belirli araçları `true` veya `false` olarak ayarlayarak etkinleştirebilir veya devre dışı bırakabilirsiniz. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +Hiçbir araç belirtilmezse tüm araçlar varsayılan olarak etkindir. + +--- + +#### Mevcut araçlar + +İşte mod yapılandırması aracılığıyla kontrol edilebilecek tüm araçlar. + +| Alet | Tanım | +| ----------- | ------------------------------- | +| `bash` | Kabuk komutlarını yürütün | +| `edit` | Mevcut dosyaları değiştirin | +| `write` | Yeni dosyalar oluştur | +| `read` | Dosya içeriğini oku | +| `grep` | Dosya içeriğini arayın | +| `glob` | Dosyaları desene göre bulun | +| `list` | Dizinin içeriği listele | +| `patch` | Dosyalara yama uygulama | +| `todowrite` | Yapılacaklar listelerini yönet | +| `todoread` | Yapılacaklar listelerini okuyun | +| `webfetch` | Web içeriğini getir | + +--- + +## Custom modes + +Yapılandırmaya ekleyerek kendi özel modlarınızı oluşturabilirsiniz. Her iki yaklaşımın kullanıldığı örnekler aşağıda verilmiştir: + +### JSON yapılandırmasını kullanma + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Markdown dosyalarını kullanma + +Projeye özel modlar için `.opencode/modes/` veya genel modlar için `~/.config/opencode/modes/`'de mod dosyaları oluşturun: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### Kullanım durumları + +Farklı modlar için bazı yaygın kullanım durumları aşağıda verilmiştir. + +- **Derleme modu**: Tüm araçların etkinleştirildiği tam geliştirme çalışması +- **Plan modu**: Değişiklik yapmadan analiz ve planlama +- **İnceleme modu**: Salt okunur erişim ve belgeleme araçlarıyla kod incelemesi +- **Hata ayıklama modu**: Bash ve okuma araçları etkinken araştırmaya odaklanıldı +- **Belgeler modu**: Dosya işlemleriyle ancak sistem komutları olmadan belge yazma + +Ayrıca farklı modellerin farklı kullanım durumları için iyi olduğunu da görebilirsiniz. diff --git a/packages/web/src/content/docs/tr/network.mdx b/packages/web/src/content/docs/tr/network.mdx new file mode 100644 index 000000000..0a9771fc2 --- /dev/null +++ b/packages/web/src/content/docs/tr/network.mdx @@ -0,0 +1,57 @@ +--- +title: Ağ +description: Proxy'leri ve özel sertifikaları yapılandırın. +--- + +OpenCode, kurumsal ağ ortamları için standart proxy ortam değişkenlerini ve özel sertifikaları destekler. + +--- + +## Proxy + +OpenCode respects standard proxy environment variables. + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::caution +TUI yerel bir HTTP sunucusuyla iletişim kurar. Yönlendirme döngülerini önlemek için bu bağlantının proxy'sini atlamanız gerekir. +::: + +[CLI flags](/docs/cli#run) kullanarak sunucunun bağlantı noktasını ve ana bilgisayar adını yapılandırabilirsiniz. + +--- + +### Kimlik doğrulama + +Proxy'niz temel kimlik doğrulama gerektiriyorsa, kimlik bilgilerini URL dosyasına ekleyin. + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::caution +Şifreleri sabit kodlamaktan kaçının. Ortam değişkenlerini veya güvenli kimlik bilgileri deposunu kullanın. +::: + +NTLM veya Kerberos gibi gelişmiş kimlik doğrulaması gerektiren proxy'ler için, kimlik doğrulama yönteminizi destekleyen bir LLM Ağ Geçidi kullanmayı düşünün. + +--- + +## Custom certificates + +Kuruluşunuz HTTPS bağlantıları için özel CA'lar kullanıyorsa, OpenCode'u bunlara güvenecek şekilde yapılandırın. + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +Bu hem proxy bağlantıları hem de doğrudan API erişimi için işe yarar. diff --git a/packages/web/src/content/docs/tr/permissions.mdx b/packages/web/src/content/docs/tr/permissions.mdx new file mode 100644 index 000000000..f87099201 --- /dev/null +++ b/packages/web/src/content/docs/tr/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: İzinler +description: Hangi işlemlerin çalıştırılması için onay işlemini kontrol edin. +--- + +OpenCode, belirli bir eylemin otomatik olarak mı çalıştırılacağına, size sorulacağına veya engelleneceğine karar vermek için `permission` yapılandırmasını kullanır. + +`v1.1.1` itibarıyla eski `tools` boolean yapılandırması kullanımdan kaldırıldı ve `permission` ile birleştirildi. Eski `tools` yapılandırması geriye dönük uyumluluk açısından hâlâ desteklenmektedir. + +--- + +## Actions + +Each permission rule resolves to one of: + +- `"allow"` — onay olmadan çalıştır +- `"ask"` — onay istemi +- `"deny"` — eylemi engelle + +--- + +## Yapılandırma + +İzinleri genel olarak (`*` ile) ayarlayabilir ve belirli araçları geçersiz kılabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +Ayrıca tüm izinleri aynı anda ayarlayabilirsiniz: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## Granular Rules (Object Syntax) + +Çoğu izin için, araç girişine bağlı olarak farklı eylemleri uygulamak için bir nesneyi kullanabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +Kurallar, **son eşleşen kuralın kazanması** ile kalıp eşleşmesine göre değerlendirilir. Yaygın bir model, tümünü yakala `"*"` kuralını ilk sıraya koymak ve daha spesifik kuralları ondan sonra koymaktır. + +### Wildcards + +İzin kalıpları basit joker karakter eşleştirmesini kullanır: + +- `*` herhangi bir karakterin sıfır veya daha fazlasıyla eşleşir +- `?` matches exactly one character +- All other characters match literally + +### Ana Dizin Genişletme + +Ana dizininize referans vermek için bir modelin başlangıcında `~` veya `$HOME` kullanabilirsiniz. Bu özellikle [`external_directory`](#external-directories) kuralları için kullanışlıdır. + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### Dış Dizinler + +OpenCode'un başlatıldığı çalışma dizini dışındaki yollara dokunan araç çağrılarına izin vermek için `external_directory` kullanın. Bu, girdi olarak bir yolu alan tüm araçlar için geçerlidir (örneğin `read`, `edit`, `list`, `glob`, `grep` ve birçok `bash` komutu). + +Ana sayfa genişletmesi (`~/...` gibi) yalnızca bir kalıbın nasıl yazıldığını etkiler. Geçerli çalışma alanının harici bir yolunu oluşturmaz, dolayısıyla çalışma dizini dışındaki yollara yine de `external_directory` aracılığıyla izin verilmesi gerekir. + +Örneğin bu, `~/projects/personal/` altındaki her şeye erişime izin verir: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +Burada izin verilen herhangi bir dizin, geçerli çalışma alanıyla aynı varsayılanları devralır. [`read` defaults to `allow`](#defaults)'dan bu yana, geçersiz kılınmadığı sürece `external_directory` altındaki girişler için okumalara da izin verilir. Bir aracın bu yollarda kısıtlanması gerektiğinde (okumaları tutarken düzenlemeleri engellemek gibi) açık kurallar ekleyin: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +Listeyi güvenilir yollara odaklı tutun ve diğer araçlar için gereken ekstra izin verme veya reddetme kurallarını katmanlayın (örneğin `bash`). + +--- + +## Mevcut İzinler + +OpenCode izinleri araç adına ve birkaç güvenlik görevlisine göre anahtarlanır: + +- `read` — bir dosyayı okumak (dosya yoluyla eşleşir) +- `edit` — tüm dosya değişiklikleri (`edit`, `write`, `patch`, `multiedit`'yi kapsar) +- `glob` — dosya genellemesi (glob düzeniyle eşleşir) +- `grep` — içerik arama (regex modeliyle eşleşir) +- `list` — bir dizideki dosyaları listeleme (dizin yoluyla eşleşir) +- `bash` — kabuk komutlarını çalıştırma (`git status --porcelain` gibi ayrıştırılmış komutlarla eşleşir) +- `task` — alt aracıların başlatılması (alt aracı türüyle eşleşir) +- `skill` — bir beceri yükleniyor (beceri adıyla eşleşir) +- `lsp` — LSP sorgularını çalıştırıyor (şu anda ayrıntılı değil) +- `todoread`, `todowrite` — reading/updating yapılacaklar listesi +- `webfetch` — URL getiriliyor (URL ile eşleşiyor) +- `websearch`, `codesearch` — web/code arama (sorguyla eşleşir) +- `external_directory` — bir araç proje çalışma dizini dışındaki yollara dokunduğunda tetiklenir +- `doom_loop` — aynı araç çağrısı aynı girdiyle 3 kez tekrarlandığında tetiklenir + +--- + +## Defaults + +Hiçbir şey belirtmezseniz OpenCode izin verilen varsayılanlardan başlar: + +- Çoğu izin varsayılan olarak `"allow"` şeklindedir. +- `doom_loop` ve `external_directory` varsayılan olarak `"ask"`'dir. +- `read`, `"allow"`'dir, ancak `.env` dosyaları varsayılan olarak reddedilir: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## “Sor” Ne Yapar? + +OpenCode onay istediğinde kullanıcı arayüzü üç sonuç sunar: + +- `once` — yalnızca bu isteği onayla +- `always` — önerilen kalıplarla eşleşen gelecekteki istekleri onaylayın (geçerli OpenCode oturumunun geri kalanı için) +- `reject` — isteği reddet + +`always`'ın onaylayacağı kalıp seti araç tarafından sağlanır (örneğin, bash onayları genellikle `git status*` gibi güvenli bir komut önekini beyaz listeye alır). + +--- + +## Agents + +Aracı başına izinleri geçersiz kılabilirsiniz. Aracı izinleri genel yapılandırmayla birleştirilir ve aracı kuralları öncelikli olur. [Learn more](/docs/agents#permissions) temsilci izinleri hakkında. + +:::note +Daha ayrıntılı desen eşleştirme örnekleri için yukarıdaki [Granular Rules (Object Syntax)](#granular-rules-object-syntax) bölümüne bakın. +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +Aracı izinlerini Markdown'da da yapılandırabilirsiniz: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tip +Bağımsız değişken içeren komutlar için kalıp eşleştirmeyi kullanın. `"grep *"`, `grep pattern file.txt`'ye izin verir, ancak `"grep"` tek başına onu engeller. `git status` gibi komutlar varsayılan davranış için çalışır ancak argümanlar aktarıldığında açık izin (`"git status *"` gibi) gerektirir. +::: diff --git a/packages/web/src/content/docs/tr/plugins.mdx b/packages/web/src/content/docs/tr/plugins.mdx new file mode 100644 index 000000000..0b089ad85 --- /dev/null +++ b/packages/web/src/content/docs/tr/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: Eklentiler +description: OpenCode'u genişletmek için kendi eklentilerinizi yazın. +--- + +Eklentiler, çeşitli olaylara bağlanarak ve davranışı özelleştirerek OpenCode'u genişletmenize olanak tanır. Yeni özellikler eklemek, harici hizmetlerle entegrasyon sağlamak veya OpenCode'un varsayılan davranışını değiştirmek için eklentiler oluşturabilirsiniz. + +Örnekler için topluluk tarafından oluşturulan [plugins](/docs/ecosystem#plugins)'a göz atın. + +--- + +## Bir eklenti kullanın + +There are two ways to load plugins. + +--- + +### Yerel dosyalardan + +JavaScript veya TypeScript dosyalarını eklenti dizinine yerleştirin. + +- `.opencode/plugins/` - Proje düzeyinde eklentiler +- `~/.config/opencode/plugins/` - Genel eklentiler + +Bu dizinlerdeki dosyalar başlangıçta otomatik olarak yüklenir. + +--- + +### npm'den + +Yapılandırma dosyanızda npm paketlerini belirtin. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +Hem normal hem de kapsamlı npm paketleri desteklenir. + +[ecosystem](/docs/ecosystem#plugins)'daki mevcut eklentilere göz atın. + +--- + +### Eklentiler nasıl kurulur? + +**npm eklentileri** başlangıçta Bun kullanılarak otomatik olarak yüklenir. Paketler ve bağımlılıkları `~/.cache/opencode/node_modules/`'da önbelleğe alınır. + +**Yerel eklentiler** doğrudan eklenti dizininden yüklenir. Harici paketleri kullanmak için, sisteminizin dizininde bir `package.json` oluşturmanız (bkz. [Dependencies](#dependencies)) veya eklentiyi npm ve [add it to your config](/docs/config#plugins)'de yayınlamanız gerekir. + +--- + +### Load order + +Eklentiler tüm kaynaklardan yüklenir ve tüm kancalar sırayla çalışır. Yükleme sırası şöyledir: + +1. Global config (`~/.config/opencode/opencode.json`) +2. Project config (`opencode.json`) +3. Global eklenti dizini (`~/.config/opencode/plugins/`) +4. Proje eklenti dizini (`.opencode/plugins/`) + +Aynı ad ve sürüme sahip yinelenen npm paketleri bir kez yüklenir. Ancak benzer adlara sahip bir yerel eklenti ve bir npm eklentisinin her ikisi de ayrı ayrı yüklenir. + +--- + +## Eklenti oluştur + +Eklenti, bir veya daha fazla eklentiyi dışa aktaran bir **JavaScript/TypeScript modülüdür** +işlevler. Her işlev bir bağlam nesnesi alır ve bir kanca nesnesi döndürür. + +--- + +### Dependencies + +Yerel eklentiler ve özel araçlar harici npm paketlerini kullanabilir. İhtiyacınız olan bağımlılıkları içeren config dizininize bir `package.json` ekleyin. + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode bunları yüklemek için başlangıçta `bun install` komutunu çalıştırır. Eklentileriniz ve araçlarınız daha sonra bunları içe aktarabilir. + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### Temel yapı + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +Eklenti işlevi şunları alır: + +- `project`: Mevcut proje bilgisi. +- `directory`: güncel çalışma dizini. +- `worktree`: Git çalışma ağacı yolu. +- `client`: Yapay zeka ile etkileşime geçmek için açık kodlu bir SDK istemcisi. +- `$`: Bun'un komutları yürütmek için kullandığı [shell API](https://bun.com/docs/runtime/shell). + +--- + +### TypeScript desteği + +TypeScript eklentileri için türleri eklenti paketinden içe aktarabilirsiniz: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### Olaylar + +Eklentiler aşağıdaki Örnekler bölümünde görüldüğü gibi etkinliklere abone olabilirler. Burada mevcut farklı etkinliklerin bir listesi bulunmaktadır. + +#### Komut Olayları + +- `command.executed` + +#### Dosya Olayları + +- `file.edited` +- `file.watcher.updated` + +#### Kurulum Etkinlikleri + +- `installation.updated` + +#### LSP Etkinlikler + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### Mesaj Etkinlikleri + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### İzin Etkinlikleri + +- `permission.asked` +- `permission.replied` + +#### Sunucu Etkinlikleri + +- `server.connected` + +#### Oturum Etkinlikleri + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### Yapılacak Etkinlikler + +- `todo.updated` + +#### Kabuk Etkinlikleri + +- `shell.env` + +#### Araç Olayları + +- `tool.execute.after` +- `tool.execute.before` + +#### TUI Etkinlikler + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## Examples + +Açık kodu genişletmek için kullanabileceğiniz bazı eklenti örneklerini burada bulabilirsiniz. + +--- + +### Bildirim gönder + +Belirli olaylar meydana geldiğinde bildirim gönderin: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +MacOS'ta AppleScript'i çalıştırmak için `osascript` kullanıyoruz. Burada bildirim göndermek için kullanıyoruz. + +:::note +OpenCode masaüstü uygulamasını kullanıyorsanız yanıt hazır olduğunda veya oturum hataları oluştuğunda otomatik olarak sistem bildirimleri gönderebilir. +::: + +--- + +### .env protection + +Açık kodun `.env` dosyalarını okumasını önleyin: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### Ortam değişkenlerini enjekte etme + +Ortam değişkenlerini tüm kabuk yürütmeye (AI araçları ve kullanıcı terminalleri) enjekte edin: + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### Custom tools + +Eklentiler ayrıca opencode'a özel araçlar da ekleyebilir: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +`tool` yardımcısı, opencode'un çağırabileceği özel bir araç oluşturur. Bir Zod şeması işlevini alır ve aşağıdakileri içeren bir araç tanımı döndürür: + +- `description`: Araç ne yapar? +- `args`: Aracın argümanları için Zod şeması +- `execute`: Araç çağrıldığında çalışan fonksiyon + +Özel araçlarınız, yerleşik araçların yanı sıra kod açmaya da hazır olacaktır. + +--- + +### Günlüğe kaydetme + +Yapılandırılmış günlük kaydı için `console.log` yerine `client.app.log()` kullanın: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +Seviyeler: `debug`, `info`, `warn`, `error`. Ayrıntılar için [SDK documentation](https://opencode.ai/docs/sdk)'e bakın. + +--- + +### Compaction hooks + +Bir oturum sıkıştırıldığında içerilen bağlamı özelleştirin: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +`experimental.session.compacting` kancası, LLM bir devam özeti oluşturmadan önce tetiklenir. Varsayılan sıkıştırma isteminin kaçıracağı etki alanına özgü bağlamı enjekte etmek için bunu kullanın. + +Ayrıca `output.prompt` ayarını yaparak sıkıştırma istemini tamamen değiştirebilirsiniz: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +`output.prompt` ayarlandığında, varsayılan sıkıştırma isteminin tamamen yerini alır. Bu durumda `output.context` dizisi dikkate alınmaz. diff --git a/packages/web/src/content/docs/tr/providers.mdx b/packages/web/src/content/docs/tr/providers.mdx new file mode 100644 index 000000000..14bd43f28 --- /dev/null +++ b/packages/web/src/content/docs/tr/providers.mdx @@ -0,0 +1,1888 @@ +--- +title: Sağlayıcılar +description: OpenCode'da herhangi bir LLM sağlayıcısını kullanma. +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode, **75'ten fazla LLM sağlayıcısını** desteklemek için [AI SDK](https://ai-sdk.dev/) ve [Models.dev](https://models.dev) kullanır ve yerel modellerin çalıştırılmasını destekler. + +Bir sağlayıcı eklemek için şunları yapmanız gerekir: + +1. `/connect` komutunu kullanarak sağlayıcı için API anahtarlarını ekleyin. +2. Sağlayıcıyı OpenCode yapılandırmanızda yapılandırın. + +--- + +### Credentials + +Bir sağlayıcının API anahtarlarını `/connect` komutuyla eklediğinizde, bunlar saklanır +`~/.local/share/opencode/auth.json` içinde. + +--- + +### Config + +Sağlayıcıları OpenCode'unuzdaki `provider` bölümü aracılığıyla özelleştirebilirsiniz. +config. + +--- + +#### Base URL + +`baseURL` seçeneğini ayarlayarak URL tabanını herhangi bir sağlayıcı için özelleştirebilirsiniz. Bu, proxy hizmetlerini veya özel uç noktaları kullanırken kullanışlıdır. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode Zen + +OpenCode Zen, OpenCode ekibi tarafından sağlanan modellerin bir listesidir. +OpenCode ile iyi çalıştığı test edildi ve doğrulandı. [Learn more](/docs/zen). + +:::tip +Yeniyseniz OpenCode Zen ile başlamanızı öneririz. +::: + +1. TUI'de `/connect` komutunu çalıştırın, açık kodu seçin ve [opencode.ai/auth](https://opencode.ai/auth)'ye gidin. + + ```txt + /connect + ``` + +2. Oturum açın, fatura ayrıntılarınızı ekleyin ve API anahtarınızı kopyalayın. + +3. API anahtarınızı yapıştırın. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Önerdiğimiz modellerin listesini görmek için TUI'de `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +OpenCode'daki diğer sağlayıcılar gibi çalışır ve kullanımı tamamen isteğe bağlıdır. + +--- + +## Dizin + +Sağlayıcılardan bazılarına ayrıntılı olarak bakalım. Bir sağlayıcı eklemek istiyorsanız +liste, bir PR açmaktan çekinmeyin. + +:::note +Burada bir sağlayıcı göremiyor musunuz? Bir PR gönderin. +::: + +--- + +### 302.AI + +1. [302.AI console](https://302.ai/) adresine gidin, bir hesap oluşturun ve bir API anahtarı oluşturun. + +2. `/connect` komutunu çalıştırın ve **302.AI**'yi arayın. + + ```txt + /connect + ``` + +3. 302.AI API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Amazon Bedrock + +Amazon Bedrock'u OpenCode ile kullanmak için: + +1. Amazon Bedrock konsolundaki **Model kataloğuna** gidin ve istekte bulunun + Dilediğiniz modellere ulaşabilirsiniz. + + :::tip + Amazon Bedrock'ta istediğiniz modele erişiminizin olması gerekiyor. + ::: + +2. **Kimlik doğrulamayı yapılandırın**: Aşağıdaki yöntemlerden birini kullanın: + + #### Ortam Değişkenleri (Hızlı Başlangıç) + + Set one of these environment variables while running opencode: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + Veya bunları bash profilinize ekleyin: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### Yapılandırma Dosyası (Önerilen) + + Projeye özel veya kalıcı yapılandırma için `opencode.json` kullanın: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **Mevcut seçenekler:** + - `region` - AWS region (e.g., `us-east-1`, `eu-west-1`) + - `profile` - `~/.aws/credentials`'den AWS adlı profil + - `endpoint` - VPC uç noktaları için özel uç nokta URL (genel `baseURL` seçeneğinin takma adı) + + :::tip + Yapılandırma dosyası seçenekleri ortam değişkenlerine göre önceliklidir. + ::: + + #### Advanced: VPC Endpoints + + Bedrock için VPC uç noktaları kullanıyorsanız: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::note + `endpoint` seçeneği, AWS'ye özgü terminolojiyi kullanan genel `baseURL` seçeneğinin takma adıdır. Hem `endpoint` hem de `baseURL` belirtilirse, `endpoint` öncelikli olur. + ::: + + #### Authentication Methods + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: Bir IAM kullanıcısı oluşturun ve AWS Konsolunda erişim anahtarları oluşturun + - **`AWS_PROFILE`**: `~/.aws/credentials`'den adlandırılmış profilleri kullanın. İlk önce `aws configure --profile my-profile` veya `aws sso login` ile yapılandırın + - **`AWS_BEARER_TOKEN_BEDROCK`**: Amazon Bedrock konsolundan uzun vadeli API anahtarları oluşturun + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: EKS IRSA (IAM Hizmet Hesapları için Roller) veya OIDC federasyonuna sahip diğer Kubernetes ortamları için. Bu ortam değişkenleri, hizmet hesabı ek açıklamaları kullanılırken Kubernetes tarafından otomatik olarak eklenir. + + #### Authentication Precedence + + Amazon Bedrock aşağıdaki kimlik doğrulama önceliğini kullanır: + 1. **Taşıyıcı Belirteç** - `AWS_BEARER_TOKEN_BEDROCK` ortam değişkeni veya `/connect` komutundan belirteç + 2. **AWS Credential Chain** - Profile, access keys, shared credentials, IAM roles, Web Identity Tokens (EKS IRSA), instance metadata + + :::note + When a bearer token is set (via `/connect` or `AWS_BEARER_TOKEN_BEDROCK`), it takes precedence over all AWS credential methods including configured profiles. + ::: + +3. İstediğiniz modeli seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +:::note +Özel çıkarım profilleri için anahtardaki modeli ve sağlayıcı adını kullanın ve `id` özelliğini arn olarak ayarlayın. Bu, doğru önbelleğe almayı sağlar: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### Anthropic + +1. Kaydolduktan sonra `/connect` komutunu çalıştırın ve Anthropic'i seçin. + + ```txt + /connect + ``` + +2. Burada **Claude Pro/Max** seçeneğini seçebilirsiniz; tarayıcınız açılacaktır. + ve sizden kimlik doğrulamanızı isteyeceğiz. + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. Artık `/models` komutunu kullandığınızda tüm Antropik modeller mevcut olmalıdır. + + ```txt + /models + ``` + +:::info +Claude Pro/Max aboneliğinizi OpenCode'da kullanmak [Anthropic](https://anthropic.com) tarafından resmi olarak desteklenmemektedir. +::: + +##### API tuşlarını kullanma + +Pro/Max aboneliğiniz yoksa **API Anahtarı Oluştur** seçeneğini de seçebilirsiniz. Ayrıca tarayıcınızı açacak ve Anthropic'te oturum açmanızı isteyecek ve terminalinize yapıştırabileceğiniz bir kod verecektir. + +Veya zaten bir API anahtarınız varsa **API Anahtarını Manuel Olarak Girin** seçeneğini seçip terminalinize yapıştırabilirsiniz. + +--- + +### Azure OpenAI + +:::note +"Üzgünüm ama bu isteğe yardımcı olamıyorum" hatalarıyla karşılaşırsanız Azure kaynağınızda içerik filtresini **DefaultV2** yerine **Default** olarak değiştirmeyi deneyin. +::: + +1. [Azure portal](https://portal.azure.com/)'a gidin ve bir **Azure OpenAI** kaynağı oluşturun. İhtiyacınız olacak: + - **Kaynak adı**: Bu, API bitiş noktanızın (`https://RESOURCE_NAME.openai.azure.com/`) parçası olur + - **API anahtarı**: Kaynağınızdan `KEY 1` veya `KEY 2` + +2. [Azure AI Foundry](https://ai.azure.com/)'a gidin ve bir model dağıtın. + + :::note + Açık kodun düzgün çalışması için dağıtım adının model adıyla eşleşmesi gerekir. + ::: + +3. `/connect` komutunu çalıştırın ve **Azure**'u arayın. + + ```txt + /connect + ``` + +4. API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Kaynak adınızı ortam değişkeni olarak ayarlayın: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + Veya bash profilinize ekleyin: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. Dağıtılan modelinizi seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Azure Cognitive Services + +1. [Azure portal](https://portal.azure.com/)'a gidin ve bir **Azure OpenAI** kaynağı oluşturun. İhtiyacınız olacak: + - **Kaynak adı**: Bu, API bitiş noktanızın (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) parçası olur + - **API anahtarı**: Kaynağınızdan `KEY 1` veya `KEY 2` + +2. [Azure AI Foundry](https://ai.azure.com/)'a gidin ve bir model dağıtın. + + :::note + Açık kodun düzgün çalışması için dağıtım adının model adıyla eşleşmesi gerekir. + ::: + +3. `/connect` komutunu çalıştırın ve **Azure Bilişsel Hizmetler**'i arayın. + + ```txt + /connect + ``` + +4. API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. Kaynak adınızı ortam değişkeni olarak ayarlayın: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + Veya bash profilinize ekleyin: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. Dağıtılan modelinizi seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Baseten + +1. [Baseten](https://app.baseten.co/) adresine gidin, bir hesap oluşturun ve bir API anahtarı oluşturun. + +2. `/connect` komutunu çalıştırın ve **Baseten**'i arayın. + + ```txt + /connect + ``` + +3. Baseten API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Cerebras + +1. [Cerebras console](https://inference.cerebras.ai/) adresine gidin, bir hesap oluşturun ve bir API anahtarı oluşturun. + +2. `/connect` komutunu çalıştırın ve **Cerebras**'ı arayın. + + ```txt + /connect + ``` + +3. Cerebras API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _Qwen 3 Coder 480B_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Cloudflare AI Gateway + +Cloudflare AI Gateway, OpenAI, Anthropic, Workers AI ve daha fazlasındaki modellere birleşik bir uç nokta aracılığıyla erişmenizi sağlar. [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) ile her sağlayıcı için ayrı API anahtarlarına ihtiyacınız yoktur. + +1. [Cloudflare dashboard](https://dash.cloudflare.com/)'a gidin, **AI** > **AI Ağ Geçidi**'ne gidin ve yeni bir ağ geçidi oluşturun. + +2. Hesap Kimliğinizi ve Ağ Geçidi Kimliğinizi ortam değişkenleri olarak ayarlayın. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. `/connect` komutunu çalıştırın ve **Cloudflare AI Gateway**'i arayın. + + ```txt + /connect + ``` + +4. Cloudflare API jetonunuzu girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + Or set it as an environment variable. + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. Bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + + Opencode yapılandırmanız aracılığıyla da modeller ekleyebilirsiniz. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### Cortecs + +1. [Cortecs console](https://cortecs.ai/) adresine gidin, bir hesap oluşturun ve bir API anahtarı oluşturun. + +2. `/connect` komutunu çalıştırın ve **Cortecs**'i arayın. + + ```txt + /connect + ``` + +3. Cortecs API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _Kimi K2 Instruct_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### DeepSeek + +1. [DeepSeek console](https://platform.deepseek.com/)'a gidin, bir hesap oluşturun ve **Yeni API anahtarı oluştur**'a tıklayın. + +2. `/connect` komutunu çalıştırın ve **DeepSeek**'i arayın. + + ```txt + /connect + ``` + +3. DeepSeek API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _DeepSeek Reasoner_ gibi bir DeepSeek modeli seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Deep Infra + +1. [Deep Infra dashboard](https://deepinfra.com/dash) adresine gidin, bir hesap oluşturun ve bir API anahtarı oluşturun. + +2. `/connect` komutunu çalıştırın ve **Deep Infra**'yı arayın. + + ```txt + /connect + ``` + +3. Deep Infra API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Firmware + +1. [Firmware dashboard](https://app.firmware.ai/signup) adresine gidin, bir hesap oluşturun ve bir API anahtarı oluşturun. + +2. `/connect` komutunu çalıştırın ve **Firmware**'i arayın. + + ```txt + /connect + ``` + +3. Firmware API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Fireworks AI + +1. [Fireworks AI console](https://app.fireworks.ai/)'a gidin, bir hesap oluşturun ve **API Anahtarı Oluştur**'a tıklayın. + +2. `/connect` komutunu çalıştırın ve **Fireworks AI**'yi arayın. + + ```txt + /connect + ``` + +3. Fireworks AI API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _Kimi K2 Instruct_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### GitLab Duo + +GitLab Duo, GitLab'ın Anthropic proxy'si aracılığıyla yerel araç çağırma yetenekleriyle yapay zeka destekli aracılı sohbet sağlar. + +1. `/connect` komutunu çalıştırın ve GitLab'ı seçin. + + ```txt + /connect + ``` + +2. Kimlik doğrulama yönteminizi seçin: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### OAuth Kullanımı (Önerilen) + + **OAuth**'u seçtiğinizde tarayıcınız yetkilendirme için açılacaktır. + + #### Kişisel Erişim Simgesini Kullanma + 1. Go to [GitLab User Settings > Access Tokens](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. Click **Add new token** + 3. Name: `OpenCode`, Scopes: `api` + 4. Belirteci kopyalayın (`glpat-` ile başlar) + 5. Terminale girin + +3. Mevcut modelleri görmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + + Üç Claude tabanlı model mevcuttur: + - **duo-chat-haiku-4-5** (Varsayılan) - Hızlı görevler için hızlı yanıtlar + - **duo-chat-sonnet-4-5** - Çoğu iş akışı için dengeli performans + - **duo-chat-opus-4-5** - Karmaşık analizler için en yeteneklisi + +:::note +İstemiyorsanız 'GITLAB_TOKEN' ortam değişkenini de belirtebilirsiniz. +to store token in opencode auth storage. +::: + +##### Self-Hosted GitLab + +:::note[compliance note] +OpenCode, oturum başlığını oluşturmak gibi bazı AI görevleri için küçük bir model kullanır. +Varsayılan olarak Zen tarafından barındırılan gpt-5-nano'yu kullanacak şekilde yapılandırılmıştır. OpenCode'u kilitlemek için +yalnızca kendi GitLab tarafından barındırılan örneğinizi kullanmak için aşağıdakileri ekleyin: +`opencode.json` dosyası. Ayrıca oturum paylaşımını devre dışı bırakmanız da önerilir. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +Şirket içinde barındırılan GitLab örnekleri için: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +Örneğiniz özel bir AI Ağ Geçidi çalıştırıyorsa: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +Veya bash profilinize ekleyin: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +GitLab yöneticiniz aşağıdakileri etkinleştirmelidir: + +1. Kullanıcı, grup veya örnek için [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) +2. Feature flags (via Rails console): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### Kendi Kendine Barındırılan örnekler için OAuth + +Oauth'un kendi kendine barındırılan örneğiniz için çalışmasını sağlamak amacıyla +yeni bir uygulama (Ayarlar → Uygulamalar) ile +geri arama URL `http://127.0.0.1:8080/callback` ve aşağıdaki kapsamlar: + +- api (Sizin adınıza API'a erişin) +- read_user (Kişisel bilgilerinizi okuyun) +- read_repository (Depoya salt okunur erişime izin verir) + +Then expose application ID as environment variable: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +Daha fazla belge [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth) ana sayfasında. + +##### Configuration + +Customize through `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API Tools (Optional, but highly recommended) + +To access GitLab tools (merge requests, issues, pipelines, CI/CD, etc.): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +Bu eklenti, MR incelemeleri, sorun izleme, işlem hattı izleme ve daha fazlasını içeren kapsamlı GitLab veri havuzu yönetimi yetenekleri sağlar. + +--- + +### GitHub Copilot + +GitHub Copilot aboneliğinizi açık kodla kullanmak için: + +:::note +Bazı modelleri kullanmak için [Pro+ aboneliği](https://github.com/features/copilot/plans) gerekebilir. + +Bazı modellerin [GitHub Copilot settings](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use)'da manuel olarak etkinleştirilmesi gerekir. +::: + +1. `/connect` komutunu çalıştırın ve GitHub Copilot'u arayın. + + ```txt + /connect + ``` + +2. [github.com/login/device](https://github.com/login/device)'a gidin ve kodu girin. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. Şimdi istediğiniz modeli seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Google Vertex AI + +Google Vertex AI'yi OpenCode ile kullanmak için: + +1. Google Cloud Console'daki **Model Bahçesi**'ne gidin ve şunları kontrol edin: + Bölgenizde mevcut modeller. + + :::note + Vertex AI API etkinleştirilmiş bir Google Cloud projenizin olması gerekir. + ::: + +2. Gerekli ortam değişkenlerini ayarlayın: + - `GOOGLE_CLOUD_PROJECT`: Google Cloud proje kimliğiniz + - `VERTEX_LOCATION` (isteğe bağlı): Vertex AI bölgesi (varsayılanı `global`'dir) + - Authentication (choose one): + - `GOOGLE_APPLICATION_CREDENTIALS`: Hizmet hesabınızın yolu JSON anahtar dosyası + - gcloud kullanarak kimlik doğrulaması yapın CLI: `gcloud auth application-default login` + + Set them while running opencode. + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + Veya bunları bash profilinize ekleyin. + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::tip +`global` bölgesi, hiçbir ekstra maliyet olmaksızın kullanılabilirliği artırır ve hataları azaltır. Veri yerleşimi gereksinimleri için bölgesel uç noktaları (ör. `us-central1`) kullanın. [Learn more](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. İstediğiniz modeli seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Groq + +1. [Groq console](https://console.groq.com/)'a gidin, **API Anahtarı Oluştur**'a tıklayın ve anahtarı kopyalayın. + +2. `/connect` komutunu çalıştırın ve Groq'u arayın. + + ```txt + /connect + ``` + +3. Sağlayıcının API anahtarını girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. İstediğinizi seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Hugging Face + +[Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers) 17'den fazla sağlayıcı tarafından desteklenen açık modellere erişim sağlar. + +1. Çıkarım Sağlayıcılara çağrı yapma iznine sahip bir belirteç oluşturmak için [Hugging Face settings](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) adresine gidin. + +2. `/connect` komutunu çalıştırın ve **Sarılma Yüzünü** arayın. + + ```txt + /connect + ``` + +3. Hugging Face jetonunuzu girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _Kimi-K2-Instruct_ veya _GLM-4.6_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Helicone + +[Helicone](https://helicone.ai), AI uygulamalarınız için günlük kaydı, izleme ve analiz sağlayan bir LLM gözlemlenebilirlik platformudur. Helicone AI Gateway, taleplerinizi modele göre otomatik olarak uygun sağlayıcıya yönlendirir. + +1. [Helicone](https://helicone.ai) adresine gidin, bir hesap oluşturun ve kontrol panelinizden bir API anahtarı oluşturun. + +2. `/connect` komutunu çalıştırın ve **Helicone**'yu arayın. + + ```txt + /connect + ``` + +3. Helicone API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +Daha fazla sağlayıcı ve önbelleğe alma ve hız sınırlama gibi gelişmiş özellikler için [Helicone documentation](https://docs.helicone.ai)'yi kontrol edin. + +#### Optional Configs + +Helicone'un açık kod aracılığıyla otomatik olarak yapılandırılmayan bir özelliği veya modelini görmeniz durumunda bunu her zaman kendiniz yapılandırabilirsiniz. + +İşte [Helicone's Model Directory](https://helicone.ai/models), eklemek istediğiniz modellerin kimliklerini almak için buna ihtiyacınız olacak. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### Custom Headers + +Helicone, önbelleğe alma, kullanıcı izleme ve oturum yönetimi gibi özellikler için özel başlıkları destekler. `options.headers` kullanarak bunları sağlayıcınızın yapılandırmasına ekleyin: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### Oturum izleme + +Helicone'un [Sessions](https://docs.helicone.ai/features/sessions) özelliği, ilgili LLM isteklerini birlikte gruplandırmanıza olanak tanır. Her OpenCode görüşmesini Helicone'da bir oturum olarak otomatik olarak kaydetmek için [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) eklentisini kullanın. + +```bash +npm install -g opencode-helicone-session +``` + +Yapılandırmanıza ekleyin. + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +Eklenti isteklerinize `Helicone-Session-Id` ve `Helicone-Session-Name` başlıklarını enjekte eder. Helicone'un Oturumlar sayfasında her OpenCode görüşmesinin ayrı bir oturum olarak listelendiğini göreceksiniz. + +##### Common Helicone headers + +| Başlık | Açıklama | +| -------------------------- | ------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | Enable response caching (`true`/`false`) | +| `Helicone-User-Id` | Track metrics by user | +| `Helicone-Property-[Name]` | Add custom properties (e.g., `Helicone-Property-Environment`) | +| `Helicone-Prompt-Id` | İstekleri bilgi istemi sürümleriyle ilişkilendirin | + +Mevcut tüm başlıklar için [Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory)'a bakın. + +--- + +### llama.cpp + +Açık kodu yerel modelleri kullanacak şekilde [llama.cpp's](https://github.com/ggml-org/llama.cpp) lama-server yardımcı programını kullanarak yapılandırabilirsiniz. + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +Bu örnekte: + +- `llama.cpp` özel sağlayıcı kimliğidir. Bu istediğiniz herhangi bir dize olabilir. +- `npm` bu sağlayıcı için kullanılacak paketi belirtir. Burada `@ai-sdk/openai-compatible`, herhangi bir OpenAI uyumlu API için kullanılır. +- `name` sağlayıcının kullanıcı arayüzündeki görünen adıdır. +- `options.baseURL` yerel sunucunun uç noktasıdır. +- `models` model kimliklerinin konfigürasyonlarına ait bir haritasıdır. Model adı, model seçim listesinde görüntülenecektir. + +--- + +### IO.NET + +IO.NET, çeşitli kullanım durumları için optimize edilmiş 17 model sunar: + +1. [IO.NET console](https://ai.io.net/) adresine gidin, bir hesap oluşturun ve bir API anahtarı oluşturun. + +2. `/connect` komutunu çalıştırın ve **IO.NET** öğesini arayın. + + ```txt + /connect + ``` + +3. IO.NET API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### LM Studio + +LM Studio aracılığıyla açık kodu yerel modelleri kullanacak şekilde yapılandırabilirsiniz. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +Bu örnekte: + +- `lmstudio` özel sağlayıcı kimliğidir. Bu istediğiniz herhangi bir dize olabilir. +- `npm` bu sağlayıcı için kullanılacak paketi belirtir. Burada `@ai-sdk/openai-compatible`, herhangi bir OpenAI uyumlu API için kullanılır. +- `name` sağlayıcının kullanıcı arayüzündeki görünen adıdır. +- `options.baseURL` yerel sunucunun uç noktasıdır. +- `models` model kimliklerinin konfigürasyonlarına ait bir haritasıdır. Model adı, model seçim listesinde görüntülenecektir. + +--- + +### Moonshot AI + +Moonshot AI'dan Kimi K2'yi kullanmak için: + +1. [Moonshot AI console](https://platform.moonshot.ai/console)'a gidin, bir hesap oluşturun ve **API anahtarı oluştur**'a tıklayın. + +2. `/connect` komutunu çalıştırın ve **Moonshot AI**'yi arayın. + + ```txt + /connect + ``` + +3. Moonshot API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _Kimi K2_ seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### MiniMax + +1. [MiniMax API Console](https://platform.minimax.io/login) adresine gidin, bir hesap oluşturun ve bir API anahtarı oluşturun. + +2. `/connect` komutunu çalıştırın ve **MiniMax**'ı arayın. + + ```txt + /connect + ``` + +3. MiniMax API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _M2.1_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Nebius Token Factory + +1. [Nebius Token Factory console](https://tokenfactory.nebius.com/)'a gidin, bir hesap oluşturun ve **Anahtar Ekle**'ye tıklayın. + +2. `/connect` komutunu çalıştırın ve **Nebius Token Factory**'yi arayın. + + ```txt + /connect + ``` + +3. Nebius Token Factory API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _Kimi K2 Instruct_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Ollama + +Ollama aracılığıyla açık kodu yerel modelleri kullanacak şekilde yapılandırabilirsiniz. + +:::tip +Ollama kendisini OpenCode için otomatik olarak yapılandırabilir. Ayrıntılar için [Ollama integration docs](https://docs.ollama.com/integrations/opencode)'a bakın. +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +Bu örnekte: + +- `ollama` özel sağlayıcı kimliğidir. Bu istediğiniz herhangi bir dize olabilir. +- `npm` bu sağlayıcı için kullanılacak paketi belirtir. Burada `@ai-sdk/openai-compatible`, herhangi bir OpenAI uyumlu API için kullanılır. +- `name` sağlayıcının kullanıcı arayüzündeki görünen adıdır. +- `options.baseURL` yerel sunucunun uç noktasıdır. +- `models` model kimliklerinin konfigürasyonlarına ait bir haritasıdır. Model adı, model seçim listesinde görüntülenecektir. + +:::tip +Araç çağrıları çalışmıyorsa Ollama'da `num_ctx` değerini artırmayı deneyin. 16k - 32k civarında başlayın. +::: + +--- + +### Ollama Cloud + +Ollama Cloud'u OpenCode ile kullanmak için: + +1. [https://ollama.com/](https://ollama.com/) adresine gidin ve oturum açın veya bir hesap oluşturun. + +2. **Ayarlar** > **Anahtarlar**'a gidin ve yeni bir API anahtarı oluşturmak için **API Anahtarı Ekle**'yi tıklayın. + +3. OpenCode'da kullanmak için API anahtarını kopyalayın. + +4. `/connect` komutunu çalıştırın ve **Ollama Cloud**'u arayın. + + ```txt + /connect + ``` + +5. Ollama Cloud API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **Önemli**: OpenCode'da bulut modellerini kullanmadan önce model bilgilerini yerel olarak almanız gerekir: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. Ollama Cloud modelinizi seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### OpenAI + +[ChatGPT Plus or Pro](https://chatgpt.com/pricing)'a kaydolmanızı öneririz. + +1. Kaydolduktan sonra `/connect` komutunu çalıştırın ve OpenAI'yi seçin. + + ```txt + /connect + ``` + +2. Burada **ChatGPT Plus/Pro** seçeneğini seçebilirsiniz, tarayıcınız açılacaktır. + ve sizden kimlik doğrulamanızı isteyeceğiz. + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. Artık `/models` komutunu kullandığınızda tüm OpenAI modelleri mevcut olmalıdır. + + ```txt + /models + ``` + +##### API tuşlarını kullanma + +Zaten bir API anahtarınız varsa, **API Anahtarını Manuel Olarak Girin** seçeneğini seçip terminalinize yapıştırabilirsiniz. + +--- + +### OpenCode Zen + +OpenCode Zen, OpenCode ekibi tarafından sağlanan test edilmiş ve doğrulanmış modellerin bir listesidir. [Learn more](/docs/zen). + +1. **OpenCode Zen**'de oturum açın ve **API Anahtarı Oluştur**'u tıklayın. + +2. `/connect` komutunu çalıştırın ve **OpenCode Zen**'i arayın. + + ```txt + /connect + ``` + +3. OpenCode API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _Qwen 3 Coder 480B_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### OpenRouter + +1. [OpenRouter dashboard](https://openrouter.ai/settings/keys)'a gidin, **API Anahtarı Oluştur**'a tıklayın ve anahtarı kopyalayın. + +2. `/connect` komutunu çalıştırın ve OpenRouter'ı arayın. + + ```txt + /connect + ``` + +3. Sağlayıcının API anahtarını girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Birçok OpenRouter modeli varsayılan olarak önceden yüklenmiştir; istediğiniz modeli seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + + Açık kod yapılandırmanız aracılığıyla ek modeller de ekleyebilirsiniz. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. Bunları ayrıca açık kod yapılandırmanız aracılığıyla da özelleştirebilirsiniz. Burada bir sağlayıcı belirtmeye ilişkin bir örnek verilmiştir + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP AI Core + +SAP AI Core, birleşik bir platform aracılığıyla OpenAI, Anthropic, Google, Amazon, Meta, Mistral ve AI21'den 40'tan fazla modele erişim sağlar. + +1. [SAP BTP Cockpit](https://account.hana.ondemand.com/) sunucunuza gidin, SAP AI Core hizmet örneğinize gidin ve bir hizmet anahtarı oluşturun. + + :::tip + Hizmet anahtarı, `clientid`, `clientsecret`, `url` ve `serviceurls.AI_API_URL` içeren bir JSON nesnesidir. AI Core örneğinizi BTP Kokpitinde **Hizmetler** > **Örnekler ve Abonelikler** altında bulabilirsiniz. + ::: + +2. Run the `/connect` command and search for **SAP AI Core**. + + ```txt + /connect + ``` + +3. Servis anahtarınızı JSON girin. + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + Veya `AICORE_SERVICE_KEY` ortam değişkenini ayarlayın: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + Veya bash profilinize ekleyin: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. İsteğe bağlı olarak dağıtım kimliğini ve kaynak grubunu ayarlayın: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::note + Bu ayarlar isteğe bağlıdır ve SAP AI Core kurulumunuza göre yapılandırılmalıdır. + ::: + +5. 40'tan fazla mevcut model arasından seçim yapmak için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### OVHcloud AI Endpoints + +1. [OVHcloud panel](https://ovh.com/manager)'a gidin. `Public Cloud` bölümüne gidin, `AI & Machine Learning` > `AI Endpoints` ve `API Keys` sekmesinde **Yeni bir API anahtarı oluştur**'u tıklayın. + +2. `/connect` komutunu çalıştırın ve **OVHcloud AI Endpoints**'i arayın. + + ```txt + /connect + ``` + +3. OVHcloud AI Uç Noktaları API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _gpt-oss-120b_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Scaleway + +[Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/)'yi Opencode ile kullanmak için: + +1. Yeni bir API anahtarı oluşturmak için [Scaleway Console IAM settings](https://console.scaleway.com/iam/api-keys)'a gidin. + +2. `/connect` komutunu çalıştırın ve **Scaleway**'i arayın. + + ```txt + /connect + ``` + +3. Scaleway API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _devstral-2-123b-instruct-2512_ veya _gpt-oss-120b_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Together AI + +1. [Together AI console](https://api.together.ai)'a gidin, bir hesap oluşturun ve **Anahtar Ekle**'ye tıklayın. + +2. `/connect` komutunu çalıştırın ve **Together AI**'yi arayın. + + ```txt + /connect + ``` + +3. Together AI API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _Kimi K2 Instruct_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Venice AI + +1. [Venice AI console](https://venice.ai) adresine gidin, bir hesap oluşturun ve bir API anahtarı oluşturun. + +2. `/connect` komutunu çalıştırın ve **Venice AI**'yi arayın. + + ```txt + /connect + ``` + +3. Venice AI API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _Llama 3.3 70B_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Vercel AI Gateway + +Vercel AI Gateway, OpenAI, Anthropic, Google, xAI ve daha fazlasındaki modellere birleşik bir uç nokta aracılığıyla erişmenizi sağlar. Modeller herhangi bir fark olmadan liste fiyatıyla sunulmaktadır. + +1. [Vercel dashboard](https://vercel.com/)'a gidin, **AI Ağ Geçidi** sekmesine gidin ve yeni bir API anahtarı oluşturmak için **API anahtarlarına** tıklayın. + +2. `/connect` komutunu çalıştırın ve **Vercel AI Gateway**'i arayın. + + ```txt + /connect + ``` + +3. Vercel AI Gateway API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +Modelleri açık kod yapılandırmanız aracılığıyla da özelleştirebilirsiniz. Sağlayıcı yönlendirme sırasını belirtmeye ilişkin bir örneği burada bulabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +Some useful routing options: + +| Seçenek | Açıklama | +| ------------------- | --------------------------------------------------------------------- | +| `order` | Denenecek sağlayıcı sırası | +| `only` | Restrict to specific providers | +| `zeroDataRetention` | Yalnızca sıfır veri saklama politikasına sahip sağlayıcıları kullanın | + +--- + +### xAI + +1. [xAI console](https://console.x.ai/) adresine gidin, bir hesap oluşturun ve bir API anahtarı oluşturun. + +2. `/connect` komutunu çalıştırın ve **xAI**'yi arayın. + + ```txt + /connect + ``` + +3. xAI API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _Grok Beta_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### Z.AI + +1. [Z.AI API console](https://z.ai/manage-apikey/apikey-list)'a gidin, bir hesap oluşturun ve **Yeni bir API anahtarı oluştur**'a tıklayın. + +2. `/connect` komutunu çalıştırın ve **Z.AI**'yi arayın. + + ```txt + /connect + ``` + + **GLM Kodlama Planı**'na aboneyseniz **Z.AI Kodlama Planı**'nı seçin. + +3. Z.AI API anahtarınızı girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. _GLM-4.7_ gibi bir model seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + +--- + +### ZenMux + +1. [ZenMux dashboard](https://zenmux.ai/settings/keys)'a gidin, **API Anahtarı Oluştur**'a tıklayın ve anahtarı kopyalayın. + +2. `/connect` komutunu çalıştırın ve ZenMux'u arayın. + + ```txt + /connect + ``` + +3. Sağlayıcının API anahtarını girin. + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. Çoğu ZenMux modeli varsayılan olarak önceden yüklenmiştir; istediğinizi seçmek için `/models` komutunu çalıştırın. + + ```txt + /models + ``` + + Açık kod yapılandırmanız aracılığıyla ek modeller de ekleyebilirsiniz. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## Özel sağlayıcı + +`/connect` komutunda listelenmeyen herhangi bir **OpenAI uyumlu** sağlayıcıyı eklemek için: + +:::tip +OpenAI uyumlu herhangi bir sağlayıcıyı opencode ile kullanabilirsiniz. Çoğu modern yapay zeka sağlayıcısı OpenAI uyumlu API'ler sunar. +::: + +1. `/connect` komutunu çalıştırın ve **Diğer** seçeneğine ilerleyin. + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. Sağlayıcı için benzersiz bir kimlik girin. + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note + Unutulmaz bir kimlik seçin, bunu yapılandırma dosyanızda kullanacaksınız. + ::: + +3. Sağlayıcı için API anahtarınızı girin. + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. Proje dizininizde `opencode.json` dosyanızı oluşturun veya güncelleyin: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + Yapılandırma seçenekleri şunlardır: + - **npm**: Kullanılacak AI SDK paketi, OpenAI uyumlu sağlayıcılar için `@ai-sdk/openai-compatible` + - **name**: Display name in UI. + - **modeller**: Mevcut modeller. + - **options.baseURL**: API endpoint URL. + - **options.apiKey**: Kimlik doğrulama kullanılmıyorsa isteğe bağlı olarak API anahtarını ayarlayın. + - **options.headers**: Optionally set custom headers. + + Aşağıdaki örnekte gelişmiş seçenekler hakkında daha fazla bilgi bulabilirsiniz. + +5. `/models` komutunu çalıştırın; özel sağlayıcınız ve modelleriniz seçim listesinde görünecektir. + +--- + +##### Example + +Burada `apiKey`, `headers` ve model `limit` seçeneklerini ayarlayan bir örnek verilmiştir. + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +Configuration details: + +- **apiKey**: `env` değişken söz dizimini kullanarak ayarlayın, [learn more](/docs/config#env-vars). +- **başlıklar**: Her istekle birlikte gönderilen özel başlıklar. +- **limit.context**: Modelin kabul ettiği maksimum giriş jetonları. +- **limit.output**: Modelin üretebileceği maksimum jeton sayısı. + +`limit` alanları OpenCode'un ne kadar bağlamınız kaldığını anlamasını sağlar. Standart sağlayıcılar bunları models.dev'den otomatik olarak alır. + +--- + +## Troubleshooting + +Sağlayıcıyı yapılandırma konusunda sorun yaşıyorsanız aşağıdakileri kontrol edin: + +1. **Kimlik doğrulama kurulumunu kontrol edin**: Kimlik bilgilerinin geçerli olup olmadığını görmek için `opencode auth list` komutunu çalıştırın. + sağlayıcı için yapılandırmanıza eklenir. + + Bu, kimlik doğrulaması için ortam değişkenlerine güvenen Amazon Bedrock gibi sağlayıcılar için geçerli değildir. + +2. Özel sağlayıcılar için açık kod yapılandırmasını kontrol edin ve: + - `/connect` komutunda kullanılan sağlayıcı kimliğinin, açık kod yapılandırmanızdaki kimlikle eşleştiğinden emin olun. + - Sağlayıcı için doğru npm paketi kullanılıyor. Örneğin Cerebras için `@ai-sdk/cerebras` kullanın. Diğer tüm OpenAI uyumlu sağlayıcılar için `@ai-sdk/openai-compatible` kullanın. + - `options.baseURL` alanında doğru API bitiş noktasının kullanıldığını kontrol edin. diff --git a/packages/web/src/content/docs/tr/rules.mdx b/packages/web/src/content/docs/tr/rules.mdx new file mode 100644 index 000000000..8036707f6 --- /dev/null +++ b/packages/web/src/content/docs/tr/rules.mdx @@ -0,0 +1,180 @@ +--- +title: Kurallar +description: Açık kod için özel talimatları ayarlayın. +--- + +Bir `AGENTS.md` dosyası oluşturarak kod açmaya özel talimatlar sağlayabilirsiniz. Bu, İmlecin kurallarına benzer. Özel projeniz için davranışını özelleştirmek amacıyla LLM'in içeriğine dahil edilecek talimatları içerir. + +--- + +## Initialize + +Yeni bir `AGENTS.md` dosyası oluşturmak için `/init` komutunu açık kodda çalıştırabilirsiniz. + +:::tip +Projenizin `AGENTS.md` dosyasını Git'e göndermelisiniz. +::: + +Bu, projenin neyle ilgili olduğunu anlamak için projenizi ve tüm içeriğini tarayacak ve onunla bir `AGENTS.md` dosyası oluşturacaktır. Bu, açık kodun projede daha iyi gezinmesine yardımcı olur. + +Mevcut bir `AGENTS.md` dosyanız varsa, bu dosyaya eklemeye çalışacaktır. + +--- + +## Example + +Bu dosyayı manuel olarak da oluşturabilirsiniz. İşte bir `AGENTS.md` dosyasına koyabileceğiniz bazı şeylere bir örnek. + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +Buraya projeye özel talimatlar ekliyoruz ve bu, ekibiniz arasında paylaşılacaktır. + +--- + +## Types + +opencode ayrıca `AGENTS.md` dosyasının birden fazla konumdan okunmasını da destekler. Ve bu farklı amaçlara hizmet ediyor. + +### Project + +Projeye özel kurallar için proje kökünüze bir `AGENTS.md` yerleştirin. Bunlar yalnızca bu dizinde veya alt dizinlerinde çalışırken geçerlidir. + +### Global + +Ayrıca `~/.config/opencode/AGENTS.md` dosyasında genel kurallara sahip olabilirsiniz. Bu, tüm açık kod oturumlarına uygulanır. + +Bu Git'e kaydedilmediği veya ekibinizle paylaşılmadığı için, LLM'ın uyması gereken kişisel kuralları belirtmek için bunu kullanmanızı öneririz. + +### Claude Code Compatibility + +OpenCode, Claude Code'dan geçiş yapan kullanıcılar için yedek olarak Claude Code'un dosya kurallarını destekler: + +- **Proje kuralları**: Proje dizininizdeki `CLAUDE.md` (`AGENTS.md` yoksa kullanılır) +- **Global rules**: `~/.claude/CLAUDE.md` (used if no `~/.config/opencode/AGENTS.md` exists) +- **Beceriler**: `~/.claude/skills/` — ayrıntılar için [Agent Skills](/docs/skills/)'e bakın + +To disable Claude Code compatibility, set one of these environment variables: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## Precedence + +Opencode başlatıldığında kural dosyalarını şu sırayla arar: + +1. **Yerel dosyalar** geçerli dizinden yukarıya doğru giderek (`AGENTS.md`, `CLAUDE.md`) +2. **Global dosya** `~/.config/opencode/AGENTS.md` adresinde +3. `~/.claude/CLAUDE.md` adresindeki **Claude Kod dosyası** (devre dışı bırakılmadığı sürece) + +Her kategoride ilk eşleşen dosya kazanır. Örneğin, hem `AGENTS.md` hem de `CLAUDE.md` varsa yalnızca `AGENTS.md` kullanılır. Benzer şekilde, `~/.config/opencode/AGENTS.md`, `~/.claude/CLAUDE.md`'ye göre önceliklidir. + +--- + +## Custom Instructions + +Özel talimat dosyalarını `opencode.json` veya global `~/.config/opencode/opencode.json`'de belirtebilirsiniz. Bu, sizin ve ekibinizin, mevcut kuralları AGENTS.md'ye kopyalamak yerine yeniden kullanmasına olanak tanır. + +Example: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +Web'den talimatlar yüklemek için uzak URL'leri de kullanabilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +Uzaktan talimatlar 5 saniyelik bir zaman aşımı ile getirilir. + +Tüm talimat dosyaları `AGENTS.md` dosyalarınızla birleştirilir. + +--- + +## Harici Dosyalara Referans Verme + +Opencode, `AGENTS.md`'daki dosya referanslarını otomatik olarak ayrıştırmasa da, benzer işlevleri iki şekilde elde edebilirsiniz: + +### opencode.json'u kullanma + +Önerilen yaklaşım, `opencode.json`'deki `instructions` alanını kullanmaktır: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Manual Instructions in AGENTS.md + +`AGENTS.md`'nizde açık talimatlar sağlayarak açık kodu harici dosyaları okumayı öğretebilirsiniz. İşte pratik bir örnek: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +Bu yaklaşım şunları yapmanızı sağlar: + +- Modüler, yeniden kullanılabilir kural dosyaları oluşturun +- Sembolik bağlantılar veya git alt modülleri aracılığıyla kuralları projeler arasında paylaşın +- Keep AGENTS.md concise while referencing detailed guidelines +- Açık kodun dosyaları yalnızca belirli bir görev için gerektiğinde yüklediğinden emin olun + +:::tip +Monorepo'lar veya ortak standartlara sahip projeler için, `opencode.json`'yi glob desenleriyle (`packages/*/AGENTS.md` gibi) kullanmak, manuel talimatlara göre daha sürdürülebilirdir. +::: diff --git a/packages/web/src/content/docs/tr/sdk.mdx b/packages/web/src/content/docs/tr/sdk.mdx new file mode 100644 index 000000000..6e9e1054e --- /dev/null +++ b/packages/web/src/content/docs/tr/sdk.mdx @@ -0,0 +1,22 @@ +--- +title: SDK +description: opencode serveri icin type-safe JS istemcisi. +--- + +OpenCode JS/TS SDK, sunucu ile etkilesmek icin type-safe bir istemci saglar. + +[Sunucu](/docs/server) sayfasinda mimariyi gorebilir, topluluk ornekleri icin [projects](/docs/ecosystem#projects) bolumune bakabilirsiniz. + +## Kurulum + +```bash +npm install @opencode-ai/sdk +``` + +## Baslangic + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` diff --git a/packages/web/src/content/docs/tr/server.mdx b/packages/web/src/content/docs/tr/server.mdx new file mode 100644 index 000000000..94a36d4f1 --- /dev/null +++ b/packages/web/src/content/docs/tr/server.mdx @@ -0,0 +1,285 @@ +--- +title: Sunucu +description: opencode sunucusuyla HTTP uzerinden etkilesin. +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +`opencode serve` komutu, opencode istemcisinin kullanabilecegi bir OpenAPI endpoint'i acan headless bir HTTP sunucusu calistirir. + +--- + +### Kullanim + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### Secenekler + +| Flag | Description | Default | +| --------------- | ----------------------------------- | ---------------- | +| `--port` | Port to listen on | `4096` | +| `--hostname` | Hostname to listen on | `127.0.0.1` | +| `--mdns` | Enable mDNS discovery | `false` | +| `--mdns-domain` | Custom domain name for mDNS service | `opencode.local` | +| `--cors` | Additional browser origins to allow | `[]` | + +`--cors` birden fazla kez gecilebilir: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### Kimlik dogrulama + +Sunucuyu HTTP basic auth ile korumak icin `OPENCODE_SERVER_PASSWORD` ayarlayin. Kullanici adi varsayilan olarak `opencode` degeridir; degistirmek isterseniz `OPENCODE_SERVER_USERNAME` ayarlayabilirsiniz. Bu ayar hem `opencode serve` hem de `opencode web` icin gecerlidir. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### Nasil calisir + +`opencode` calistirdiginizda hem TUI hem de sunucu baslar. TUI, sunucuyla konusan istemci tarafidir. +Sunucu bir OpenAPI 3.1 spec endpoint'i acar. Bu endpoint [SDK](/docs/sdk) uretiminde de kullanilir. + +:::tip +opencode ile programatik etkilesim icin opencode sunucusunu kullanin. +::: + +Bu mimari, opencode'un birden fazla istemciyi desteklemesini ve programatik kullanimlari mumkun kilmasini saglar. + +`opencode serve` ile bagimsiz bir sunucu baslatabilirsiniz. opencode TUI aciksa, `opencode serve` yeni bir sunucu baslatir. + +--- + +#### Mevcut sunucuya baglanin + +TUI baslarken rastgele bir port ve hostname atanir. Bunun yerine `--hostname` ve `--port` [bayraklarini](/docs/cli) verebilirsiniz. + +[`/tui`](#tui) endpoint'i sunucu uzerinden TUI'yi surmek icin kullanilabilir. Ornegin bir istemi onceden doldurabilir veya calistirabilirsiniz. Bu kurulum OpenCode [IDE](/docs/ide) eklentileri tarafindan kullanilir. + +--- + +## Spesifikasyon + +Sunucu, su adreste gorulebilen bir OpenAPI 3.1 spec yayinlar: + +``` +http://:/doc +``` + +Ornegin `http://localhost:4096/doc`. Istemci olusturmak, istek/yanit tiplerini incelemek veya Swagger gezgininde acmak icin bu spec'i kullanin. + +--- + +## API'ler + +opencode sunucusu asagidaki API'leri sunar. + +--- + +### Global + +| Method | Path | Description | Response | +| ------ | ---------------- | ------------------------------ | ------------------------------------ | +| `GET` | `/global/health` | Get server health and version | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | Get global events (SSE stream) | Event stream | + +--- + +### Project + +| Method | Path | Description | Response | +| ------ | ------------------ | ----------------------- | --------------------------------------------- | +| `GET` | `/project` | List all projects | Project[] | +| `GET` | `/project/current` | Get the current project | Project | + +--- + +### Path & VCS + +| Method | Path | Description | Response | +| ------ | ------- | ------------------------------------ | ------------------------------------------- | +| `GET` | `/path` | Get the current path | Path | +| `GET` | `/vcs` | Get VCS info for the current project | VcsInfo | + +--- + +### Instance + +| Method | Path | Description | Response | +| ------ | ------------------- | ---------------------------- | --------- | +| `POST` | `/instance/dispose` | Dispose the current instance | `boolean` | + +--- + +### Config + +| Method | Path | Description | Response | +| ------- | ------------------- | --------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` | Get config info | Config | +| `PATCH` | `/config` | Update config | Config | +| `GET` | `/config/providers` | List providers and default models | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +### Provider + +| Method | Path | Description | Response | +| ------ | -------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` | List all providers | `{ all: `Provider[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | Get provider authentication methods | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | Authorize a provider using OAuth | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | Handle OAuth callback for a provider | `boolean` | + +--- + +### Sessions + +| Method | Path | Description | Notes | +| -------- | ---------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------- | +| `GET` | `/session` | List all sessions | Returns Session[] | +| `POST` | `/session` | Create a new session | body: `{ parentID?, title? }`, returns Session | +| `GET` | `/session/status` | Get session status for all sessions | Returns `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | Get session details | Returns Session | +| `DELETE` | `/session/:id` | Delete a session and all its data | Returns `boolean` | +| `PATCH` | `/session/:id` | Update session properties | body: `{ title? }`, returns Session | +| `GET` | `/session/:id/children` | Get a session's child sessions | Returns Session[] | +| `GET` | `/session/:id/todo` | Get the todo list for a session | Returns Todo[] | +| `POST` | `/session/:id/init` | Analyze app and create `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returns `boolean` | +| `POST` | `/session/:id/fork` | Fork an existing session at a message | body: `{ messageID? }`, returns Session | +| `POST` | `/session/:id/abort` | Abort a running session | Returns `boolean` | +| `POST` | `/session/:id/share` | Share a session | Returns Session | +| `DELETE` | `/session/:id/share` | Unshare a session | Returns Session | +| `GET` | `/session/:id/diff` | Get the diff for this session | query: `messageID?`, returns FileDiff[] | +| `POST` | `/session/:id/summarize` | Summarize the session | body: `{ providerID, modelID }`, returns `boolean` | +| `POST` | `/session/:id/revert` | Revert a message | body: `{ messageID, partID? }`, returns `boolean` | +| `POST` | `/session/:id/unrevert` | Restore all reverted messages | Returns `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | Respond to a permission request | body: `{ response, remember? }`, returns `boolean` | + +--- + +### Messages + +| Method | Path | Description | Notes | +| ------ | --------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` | List messages in a session | query: `limit?`, returns `{ info: `Message`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` | Send a message and wait for response | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, returns `{ info: `Message`, parts: `Part[]`}` | +| `GET` | `/session/:id/message/:messageID` | Get message details | Returns `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/prompt_async` | Send a message asynchronously (no wait) | body: same as `/session/:id/message`, returns `204 No Content` | +| `POST` | `/session/:id/command` | Execute a slash command | body: `{ messageID?, agent?, model?, command, arguments }`, returns `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/shell` | Run a shell command | body: `{ agent, model?, command }`, returns `{ info: `Message`, parts: `Part[]`}` | + +--- + +### Commands + +| Method | Path | Description | Response | +| ------ | ---------- | ----------------- | --------------------------------------------- | +| `GET` | `/command` | List all commands | Command[] | + +--- + +### Files + +| Method | Path | Description | Response | +| ------ | ------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | Search for text in files | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | Find files and directories by name | `string[]` (paths) | +| `GET` | `/find/symbol?query=` | Find workspace symbols | Symbol[] | +| `GET` | `/file?path=` | List files and directories | FileNode[] | +| `GET` | `/file/content?path=

` | Read a file | FileContent | +| `GET` | `/file/status` | Get status for tracked files | File[] | + +#### `/find/file` query parametreleri + +- `query` (required) - arama metni (fuzzy match) +- `type` (optional) - sonuclari `"file"` veya `"directory"` ile sinirlama +- `directory` (optional) - arama icin proje kokunu gecersiz kilma +- `limit` (optional) - en fazla sonuc (1-200) +- `dirs` (optional) - eski bayrak (`"false"` sadece dosyalari dondurur) + +--- + +### Tools (Deneysel) + +| Method | Path | Description | Response | +| ------ | ------------------------------------------- | ---------------------------------------- | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` | List all tool IDs | ToolIDs | +| `GET` | `/experimental/tool?provider=

&model=` | List tools with JSON schemas for a model | ToolList | + +--- + +### LSP, Formatters & MCP + +| Method | Path | Description | Response | +| ------ | ------------ | -------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` | Get LSP server status | LSPStatus[] | +| `GET` | `/formatter` | Get formatter status | FormatterStatus[] | +| `GET` | `/mcp` | Get MCP server status | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` | Add MCP server dynamically | body: `{ name, config }`, returns MCP status object | + +--- + +### Agents + +| Method | Path | Description | Response | +| ------ | -------- | ------------------------- | ------------------------------------------- | +| `GET` | `/agent` | List all available agents | Agent[] | + +--- + +### Logging + +| Method | Path | Description | Response | +| ------ | ------ | ------------------------------------------------------------ | --------- | +| `POST` | `/log` | Write log entry. Body: `{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +| Method | Path | Description | Response | +| ------ | ----------------------- | ------------------------------------------- | ---------------------- | +| `POST` | `/tui/append-prompt` | Append text to the prompt | `boolean` | +| `POST` | `/tui/open-help` | Open the help dialog | `boolean` | +| `POST` | `/tui/open-sessions` | Open the session selector | `boolean` | +| `POST` | `/tui/open-themes` | Open the theme selector | `boolean` | +| `POST` | `/tui/open-models` | Open the model selector | `boolean` | +| `POST` | `/tui/submit-prompt` | Submit the current prompt | `boolean` | +| `POST` | `/tui/clear-prompt` | Clear the prompt | `boolean` | +| `POST` | `/tui/execute-command` | Execute a command (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | Show toast (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | Wait for the next control request | Control request object | +| `POST` | `/tui/control/response` | Respond to a control request (`{ body }`) | `boolean` | + +--- + +### Auth + +| Method | Path | Description | Response | +| ------ | ----------- | --------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | Set authentication credentials. Body must match provider schema | `boolean` | + +--- + +### Events + +| Method | Path | Description | Response | +| ------ | -------- | ----------------------------------------------------------------------------- | ------------------------- | +| `GET` | `/event` | Server-sent events stream. First event is `server.connected`, then bus events | Server-sent events stream | + +--- + +### Docs + +| Method | Path | Description | Response | +| ------ | ------ | ------------------------- | --------------------------- | +| `GET` | `/doc` | OpenAPI 3.1 specification | HTML page with OpenAPI spec | diff --git a/packages/web/src/content/docs/tr/share.mdx b/packages/web/src/content/docs/tr/share.mdx new file mode 100644 index 000000000..55744856d --- /dev/null +++ b/packages/web/src/content/docs/tr/share.mdx @@ -0,0 +1,127 @@ +--- +title: Paylasim +description: OpenCode konusmalarini genel baglantilarla paylasin. +--- + +OpenCode'un paylasim ozelligi, konusmalariniz icin genel baglantilar olusturmanizi saglar. Boylece ekip arkadaslarinizla birlikte calisabilir veya diger kisilerden yardim alabilirsiniz. + +:::note +Paylasilan konusmalar, baglantiya sahip herkes tarafindan gorulebilir. +::: + +--- + +## Nasil calisir + +Bir konusmayi paylastiginizda OpenCode: + +1. Oturumunuz icin benzersiz bir genel URL olusturur +2. Konusma gecmisinizi sunucularimiza senkronize eder +3. Konusmayi paylasim baglantisiyla erisilebilir hale getirir - `opncd.ai/s/` + +--- + +## Paylasim + +OpenCode, konusmalarin nasil paylasilacagini kontrol eden uc farkli paylasim modu sunar: + +--- + +### Manuel (varsayilan) + +Varsayilan olarak OpenCode manuel paylasim modunu kullanir. Oturumlar otomatik paylasilmaz, ancak `/share` komutuyla manuel olarak paylasabilirsiniz: + +``` +/share +``` + +Bu komut benzersiz bir URL uretir ve panoya kopyalar. + +Manuel modu acikca ayarlamak icin [config dosyaniza](/docs/config) sunu ekleyin: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### Otomatik paylasim + +Tum yeni konusmalar icin otomatik paylasimi acmak isterseniz, [config dosyanizda](/docs/config) `share` degerini `"auto"` yapin: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +Otomatik paylasim acikken her yeni konusma otomatik olarak paylasilir ve bir baglanti olusturulur. + +--- + +### Devre disi + +Paylasimi tamamen kapatmak icin [config dosyanizda](/docs/config) `share` degerini `"disabled"` yapin: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +Bunu belirli bir projede tum ekip icin zorunlu kilmak icin proje icindeki `opencode.json` dosyasina ekleyip Git'e commit edin. + +--- + +## Paylasimi kaldirma + +Bir konusmanin paylasimini durdurmak ve genel erisimi kaldirmak icin: + +``` +/unshare +``` + +Bu komut paylasim baglantisini kaldirir ve konusmaya ait verileri siler. + +--- + +## Gizlilik + +Bir konusmayi paylasirken akilda tutulmasi gereken bazi noktalar vardir. + +--- + +### Veri saklama + +Paylasilan konusmalar, siz acikca paylasimi kaldirana kadar erisilebilir kalir. Buna sunlar dahildir: + +- Tum konusma gecmisi +- Tum mesajlar ve yanitlar +- Oturum metaverisi + +--- + +### Oneriler + +- Hassas bilgi icermeyen konusmalari paylasin. +- Paylasmadan once konusma icerigini gozden gecirin. +- Is birligi bittiginde paylasimi kaldirin. +- Tescilli kod veya gizli veri iceren konusmalari paylasmayin. +- Hassas projelerde paylasimi tamamen kapatin. + +--- + +## Kurumsal kullanim + +Kurumsal kurulumlarda paylasim ozelligi su sekillerde yapilandirilabilir: + +- Guvenlik uyumu icin tamamen **devre disi** birakilabilir +- Sadece SSO ile dogrulanan kullanicilarla **sinirlandirilabilir** +- Kendi altyapinizda **self-hosted** olarak calistirilabilir + +Kurulusunuzda opencode kullanimi icin [daha fazla bilgi alin](/docs/enterprise). diff --git a/packages/web/src/content/docs/tr/skills.mdx b/packages/web/src/content/docs/tr/skills.mdx new file mode 100644 index 000000000..5d6a65ace --- /dev/null +++ b/packages/web/src/content/docs/tr/skills.mdx @@ -0,0 +1,222 @@ +--- +title: "Ajan becerileri" +description: "SKILL.md ile tekrar kullanilabilir davranis tanimlayin" +--- + +Ajan becerileri, OpenCode'un deponuzdan veya ev dizininizden tekrar kullanilabilir talimatlari kesfetmesini saglar. +Beceriler, yerel `skill` araci uzerinden ihtiyac aninda yuklenir; ajanlar mevcut becerileri gorur ve gerektiginde tam icerigi yukler. + +--- + +## Dosyalari yerlestirin + +Her beceri adi icin bir klasor olusturun ve icine bir `SKILL.md` koyun. +OpenCode su konumlari tarar: + +- Proje konfigurasyonu: `.opencode/skills//SKILL.md` +- Genel konfigurasyon: `~/.config/opencode/skills//SKILL.md` +- Proje Claude uyumlu: `.claude/skills//SKILL.md` +- Genel Claude uyumlu: `~/.claude/skills//SKILL.md` +- Proje agent uyumlu: `.agents/skills//SKILL.md` +- Genel agent uyumlu: `~/.agents/skills//SKILL.md` + +--- + +## Kesfi anlayin + +Proje yerel yollarinda OpenCode, mevcut calisma dizininizden baslayip git worktree kokune kadar yukari cikar. +Bu sirada `.opencode/` altindaki eslesen `skills/*/SKILL.md` dosyalarini ve `.claude/skills/*/SKILL.md` ya da `.agents/skills/*/SKILL.md` dosyalarini yukler. + +Genel tanimlar da `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` ve `~/.agents/skills/*/SKILL.md` yollarindan yuklenir. + +--- + +## Frontmatter yazin + +Her `SKILL.md`, YAML frontmatter ile baslamalidir. +Sadece su alanlar taninir: + +- `name` (zorunlu) +- `description` (zorunlu) +- `license` (istege bagli) +- `compatibility` (istege bagli) +- `metadata` (istege bagli, string-to-string map) + +Bilinmeyen frontmatter alanlari yok sayilir. + +--- + +## Adlari dogrulayin + +`name` su kurallari saglamalidir: + +- 1-64 karakter olmali +- Kucuk harf alfanumerik ve tekli tire ayirici kullanmali +- `-` ile baslamamali veya bitmemeli +- Ardisik `--` icermemeli +- `SKILL.md` dosyasini barindiran klasor adi ile ayni olmali + +Esdeger regex: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## Uzunluk kurallarina uyun + +`description` 1-1024 karakter arasinda olmali. +Ajanin dogru secim yapmasi icin yeterince acik yazin. + +--- + +## Ornek kullanin + +`.opencode/skills/git-release/SKILL.md` dosyasini soyle olusturun: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## Arac aciklamasini taniyin + +OpenCode, `skill` araci aciklamasinda mevcut becerileri listeler. +Her kayitta beceri adi ve aciklamasi yer alir: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +Ajan, araci cagirarak beceri yukler: + +``` +skill({ name: "git-release" }) +``` + +--- + +## Izinleri yapilandirin + +`opencode.json` icinde pattern tabanli izinlerle ajanlarin hangi becerilere erisecegini kontrol edin: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Permission | Behavior | +| ---------- | ------------------------------------------ | +| `allow` | Beceri hemen yuklenir | +| `deny` | Beceri ajandan gizlenir, erisim reddedilir | +| `ask` | Yukleme oncesi kullanicidan onay istenir | + +Pattern'lar wildcard destekler: `internal-*`, `internal-docs`, `internal-tools` vb. adlarla eslesir. + +--- + +## Ajan bazinda gecersiz kilin + +Belirli ajanlara genel varsayimlardan farkli izinler verebilirsiniz. + +**Ozel ajanlar icin** (agent frontmatter icinde): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**Yerlesik ajanlar icin** (`opencode.json` icinde): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## Skill aracini kapatin + +Beceri kullanmamasi gereken ajanlar icin skill aracini tamamen kapatabilirsiniz: + +**Ozel ajanlar icin**: + +```yaml +--- +tools: + skill: false +--- +``` + +**Yerlesik ajanlar icin**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +Devre disi oldugunda `` bolumu tamamen kaldirilir. + +--- + +## Yukleme sorunlarini giderin + +Bir beceri listede gorunmuyorsa: + +1. `SKILL.md` adinin tamamen buyuk harfle yazildigini dogrulayin +2. Frontmatter icinde `name` ve `description` oldugunu kontrol edin +3. Tum konumlarda beceri adlarinin benzersiz oldugundan emin olun +4. Izinleri kontrol edin - `deny` olan beceriler ajanlardan gizlenir diff --git a/packages/web/src/content/docs/tr/themes.mdx b/packages/web/src/content/docs/tr/themes.mdx new file mode 100644 index 000000000..2c77bedbb --- /dev/null +++ b/packages/web/src/content/docs/tr/themes.mdx @@ -0,0 +1,369 @@ +--- +title: Temalar +description: Yerlesik bir tema secin veya kendiniz olusturun. +--- + +OpenCode ile birden fazla yerlesik tema arasindan secim yapabilir, terminal temaniza uyum saglayan bir tema kullanabilir veya kendi ozel temanizi tanimlayabilirsiniz. + +Varsayilan olarak OpenCode kendi `opencode` temasini kullanir. + +--- + +## Terminal gereksinimleri + +Temalarin tum renk paletiyle dogru gorunmesi icin terminalinizin **truecolor** (24-bit renk) desteklemesi gerekir. Cogu modern terminal bunu varsayilan olarak destekler, ancak gerekirse etkinlestirmeniz gerekebilir: + +- **Destegi kontrol edin**: `echo $COLORTERM` calistirin - cikti `truecolor` veya `24bit` olmalidir +- **Truecolor etkinlestirin**: kabuk profilinizde `COLORTERM=truecolor` ortam degiskenini ayarlayin +- **Terminal uyumlulugu**: terminal emulatorunuzun 24-bit rengi desteklediginden emin olun (iTerm2, Alacritty, Kitty, Windows Terminal ve GNOME Terminal'in yeni surumleri gibi modern terminaller genelde destekler) + +Truecolor destegi yoksa temalar daha dusuk renk dogrulugu ile gorunebilir veya en yakin 256 renk yaklasimina dusebilir. + +--- + +## Yerlesik temalar + +OpenCode birden fazla yerlesik temayla gelir. + +| Ad | Aciklama | +| ---------------------- | ----------------------------------------------------------------------------- | +| `system` | Terminalinizin arka plan rengine uyum saglar | +| `tokyonight` | [Tokyonight](https://github.com/folke/tokyonight.nvim) temasini temel alir | +| `everforest` | [Everforest](https://github.com/sainnhe/everforest) temasini temel alir | +| `ayu` | [Ayu](https://github.com/ayu-theme) koyu temasini temel alir | +| `catppuccin` | [Catppuccin](https://github.com/catppuccin) temasini temel alir | +| `catppuccin-macchiato` | [Catppuccin](https://github.com/catppuccin) temasini temel alir | +| `gruvbox` | [Gruvbox](https://github.com/morhetz/gruvbox) temasini temel alir | +| `kanagawa` | [Kanagawa](https://github.com/rebelot/kanagawa.nvim) temasini temel alir | +| `nord` | [Nord](https://github.com/nordtheme/nord) temasini temel alir | +| `matrix` | Hacker tarzi yesil uzerine siyah tema | +| `one-dark` | [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) Dark temasini temel alir | + +Ve daha fazlasi; surekli yeni temalar ekliyoruz. + +--- + +## Sistem temasi + +`system` temasi, terminalinizin renk duzenine otomatik uyum saglamak icin tasarlanmistir. Sabit renk kullanan klasik temalardan farkli olarak _system_ temasi: + +- **Gri olcegi uretir**: En iyi kontrast icin terminal arka planina gore ozel gri tonlari olusturur +- **ANSI renkleri kullanir**: 0-15 arasi standart ANSI renklerini syntax highlighting ve UI ogelerinde kullanir, boylece terminal paletinize uyar +- **Terminal varsayilanlarini korur**: Metin ve arka plan renklerinde `none` kullanarak terminalin yerel gorunumunu korur + +Sistem temasi su kullanicilar icin idealdir: + +- OpenCode'un terminal gorunumuyle birebir uyumlu olmasini isteyenler +- Ozel terminal renk semalari kullananlar +- Tum terminal uygulamalarinda tutarli bir gorunum tercih edenler + +--- + +## Tema kullanin + +`/theme` komutuyla tema secicisini acip tema secebilirsiniz. Isterseniz [config](/docs/config) dosyanizda da belirtebilirsiniz. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Ozel temalar + +OpenCode, kullanicilarin kolayca tema olusturup ozellestirebilmesi icin esnek bir JSON tabanli tema sistemi sunar. + +--- + +### Hiyerarsi + +Temalar birden fazla dizinden su sirayla yuklenir; daha sonra gelen dizin oncekini ezer: + +1. **Yerlesik temalar** - Binary icine gomuludur +2. **Kullanici config dizini** - `~/.config/opencode/themes/*.json` veya `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Proje kok dizini** - `/.opencode/themes/*.json` +4. **Gecerli calisma dizini** - `./.opencode/themes/*.json` + +Birden fazla dizinde ayni adli tema varsa, onceligi daha yuksek dizindeki tema kullanilir. + +--- + +### Tema olusturun + +Ozel tema olusturmak icin tema dizinlerinden birinde bir JSON dosyasi olusturun. + +Kullanici geneli temalar icin: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +Proje ozel temalar icin: + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON formati + +Temalar asagidaki ozellikleri destekleyen esnek bir JSON formati kullanir: + +- **Hex renkler**: `"#ffffff"` +- **ANSI renkler**: `3` (0-255) +- **Renk referanslari**: `"primary"` veya ozel tanimlar +- **Koyu/acik varyantlar**: `{"dark": "#000", "light": "#fff"}` +- **Renk yok**: `"none"` - Terminal varsayilan rengi veya seffaflik kullanilir + +--- + +### Renk tanimlari + +`defs` bolumu istege baglidir ve tema icinde tekrar kullanilabilir renkler tanimlamanizi saglar. + +--- + +### Terminal varsayilanlari + +Ozel `"none"` degeri, terminalin varsayilan rengini miras almak icin herhangi bir renkte kullanilabilir. Bu, terminalinizin renk semasiyla dogal sekilde butunlesen temalar olustururken ozellikle faydalidir: + +- `"text": "none"` - Terminalin varsayilan on plan rengini kullanir +- `"background": "none"` - Terminalin varsayilan arka plan rengini kullanir + +--- + +### Ornek + +Asagida ozel bir tema ornegi var: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/tr/tools.mdx b/packages/web/src/content/docs/tr/tools.mdx new file mode 100644 index 000000000..a9ca97088 --- /dev/null +++ b/packages/web/src/content/docs/tr/tools.mdx @@ -0,0 +1,379 @@ +--- +title: Araclar +description: LLM'in kullanabilecegi araclari yonetin. +--- + +Araclar, LLM'in kod tabaninizda eylem gerceklestirmesini saglar. OpenCode yerlesik bir arac setiyle gelir, ancak bunu [ozel araclarla](/docs/custom-tools) veya [MCP sunuculariyla](/docs/mcp-servers) genisletebilirsiniz. + +Varsayilan olarak tum araclar **etkindir** ve calismak icin izin istemez. Arac davranisini [izinler](/docs/permissions) uzerinden kontrol edebilirsiniz. + +--- + +## Yapilandirin + +Arac davranisini kontrol etmek icin `permission` alanini kullanin. Her arac icin izin verebilir, reddedebilir veya onay isteyebilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +Birden fazla araci ayni anda kontrol etmek icin wildcard da kullanabilirsiniz. Ornegin, bir MCP sunucusundan gelen tum araclar icin onay istemek: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +Izin yapilandirmasi icin [daha fazla bilgi alin](/docs/permissions). + +--- + +## Yerlesik + +OpenCode icinde bulunan tum yerlesik araclar asagidadir. + +--- + +### bash + +Proje ortaminizda kabuk komutlari calistirir. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +Bu arac LLM'in `npm install`, `git status` gibi terminal komutlarini veya diger kabuk komutlarini calistirmasini saglar. + +--- + +### edit + +Birebir metin degistirme ile mevcut dosyalari duzenler. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Bu arac dosyalarda kesin metin eslesmelerini degistirerek hassas duzenleme yapar. LLM'in kodu degistirmek icin kullandigi temel yontemdir. + +--- + +### write + +Yeni dosyalar olusturur veya mevcut dosyalari uzerine yazar. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +LLM'in yeni dosya olusturmasina izin vermek icin bunu kullanin. Dosya zaten varsa uzerine yazar. + +:::note +`write` araci `edit` izniyle kontrol edilir; bu izin tum dosya degisikliklerini kapsar (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### read + +Kod tabaninizdan dosya icerigi okur. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +Bu arac dosyalari okur ve iceriklerini dondurur. Buyuk dosyalar icin belirli satir araliklarini okuma destegi vardir. + +--- + +### grep + +Duzensiz ifadelerle dosya iceriginde arama yapar. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +Kod tabaninda hizli icerik aramasi sunar. Tam regex sozdizimini ve dosya desen filtrelerini destekler. + +--- + +### glob + +Desen eslestirme ile dosya bulur. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +`**/*.js` veya `src/**/*.ts` gibi glob desenleriyle dosya arar. Eslesen dosya yollarini degisim zamanina gore siralar. + +--- + +### list + +Verilen yoldaki dosya ve dizinleri listeler. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +Bu arac dizin icerigini listeler. Sonuclari filtrelemek icin glob desenlerini kabul eder. + +--- + +### lsp (deneysel) + +Tanim, referans, hover bilgisi ve cagrilar hiyerarsisi gibi kod zekasi ozellikleri icin yapilandirdiginiz LSP sunuculariyla etkilesir. + +:::note +Bu arac yalnizca `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (veya `OPENCODE_EXPERIMENTAL=true`) oldugunda kullanilabilir. +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +Desteklenen islemler: `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls`, `outgoingCalls`. + +Projeniz icin kullanilabilir LSP sunucularini ayarlamak icin [LSP Servers](/docs/lsp) sayfasina bakin. + +--- + +### patch + +Dosyalara patch uygular. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +Bu arac patch dosyalarini kod tabaniniza uygular. Farkli kaynaklardan gelen diff ve patch'leri uygulamak icin kullanislidir. + +:::note +`patch` araci `edit` izniyle kontrol edilir; bu izin tum dosya degisikliklerini kapsar (`edit`, `write`, `patch`, `multiedit`). +::: + +--- + +### skill + +Bir [skill](/docs/skills) (`SKILL.md` dosyasi) yukler ve icerigini konusmaya dondurur. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todowrite + +Kodlama oturumlarinda yapilacaklar listesini yonetir. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +Karmasik islemlerde ilerlemeyi takip etmek icin gorev listeleri olusturur ve gunceller. LLM bunu cok adimli gorevleri duzenlemek icin kullanir. + +:::note +Bu arac alt ajanlar icin varsayilan olarak devre disidir, ama manuel etkinlestirebilirsiniz. [Daha fazla bilgi](/docs/agents/#permissions) +::: + +--- + +### todoread + +Mevcut yapilacaklar listesini okur. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +Guncel todo listesi durumunu okur. LLM bunu hangi gorevlerin bekledigini veya tamamlandigini takip etmek icin kullanir. + +:::note +Bu arac alt ajanlar icin varsayilan olarak devre disidir, ama manuel etkinlestirebilirsiniz. [Daha fazla bilgi](/docs/agents/#permissions) +::: + +--- + +### webfetch + +Web icerigi getirir. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +LLM'in web sayfalarini getirip okumasini saglar. Dokumantasyon aramak veya cevrimici kaynaklari incelemek icin kullanislidir. + +--- + +### websearch + +Web'de bilgi arar. + +:::note +Bu arac yalnizca OpenCode provider kullanilirken veya `OPENCODE_ENABLE_EXA` ortam degiskeni dogru degerlerden birine ayarlandiginda (ornegin `true` ya da `1`) kullanilabilir. + +OpenCode baslatirken etkinlestirmek icin: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +Exa AI ile web aramasi yaparak ilgili bilgileri bulur. Egitim verisi kesim tarihinin otesindeki konulari arastirmak, guncel olaylari bulmak veya genel arastirma yapmak icin kullanislidir. + +API anahtari gerekmez - arac Exa AI'nin barindirilan MCP hizmetine dogrudan kimlik dogrulamasi olmadan baglanir. + +:::tip +Bilgi kesfetmeniz gerekiyorsa `websearch`, belirli bir URL'den icerik cekmeniz gerekiyorsa `webfetch` kullanin. +::: + +--- + +### question + +Calisma sirasinda kullaniciya soru sorar. + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +Bu arac LLM'in gorev sirasinda kullaniciya soru sormasini saglar. Sunlar icin kullanislidir: + +- Kullanici tercihleri veya gereksinimleri toplamak +- Belirsiz talimatlari netlestirmek +- Uygulama seceneklerinde karar almak +- Hangi yone gidilecegine dair secenek sunmak + +Her soru bir baslik, soru metni ve secenek listesi icerir. Kullanicilar seceneklerden birini secebilir veya ozel yanit yazabilir. Birden fazla soru varsa tum yanitlari gondermeden once sorular arasinda gezebilirler. + +--- + +## Ozel araclar + +Ozel araclar, LLM'in cagirabilecegi kendi fonksiyonlarinizi tanimlamanizi saglar. Bunlar config dosyanizda tanimlanir ve keyfi kod calistirabilir. + +Ozel arac olusturma icin [daha fazla bilgi alin](/docs/custom-tools). + +--- + +## MCP sunuculari + +MCP (Model Context Protocol) sunuculari, harici araclari ve servisleri entegre etmenizi saglar. Buna veritabani erisimi, API entegrasyonlari ve ucuncu taraf servisler dahildir. + +MCP sunucularini yapilandirma icin [daha fazla bilgi alin](/docs/mcp-servers). + +--- + +## Dahili detaylar + +Dahilde `grep`, `glob` ve `list` gibi araclar [ripgrep](https://github.com/BurntSushi/ripgrep) kullanir. Varsayilan olarak ripgrep `.gitignore` desenlerine uyar; yani `.gitignore` icindeki dosya ve dizinler arama ve listeleme sonucuna dahil edilmez. + +--- + +### Ignore desenleri + +Normalde yok sayilan dosyalari dahil etmek icin proje kokunde bir `.ignore` dosyasi olusturun. Bu dosya belirli yollari acikca izinli yapabilir. + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +Ornegin bu `.ignore` dosyasi, `.gitignore` icinde olsalar bile ripgrep'in `node_modules/`, `dist/` ve `build/` dizinlerinde arama yapmasina izin verir. diff --git a/packages/web/src/content/docs/tr/troubleshooting.mdx b/packages/web/src/content/docs/tr/troubleshooting.mdx new file mode 100644 index 000000000..b6dadc724 --- /dev/null +++ b/packages/web/src/content/docs/tr/troubleshooting.mdx @@ -0,0 +1,299 @@ +--- +title: Sorun giderme +description: Yaygin sorunlar ve cozum adimlari. +--- + +OpenCode ile ilgili bir sorunu ayiklamak icin once loglari ve diskte tuttugu yerel verileri kontrol edin. + +--- + +## Loglar + +Log dosyalari su konuma yazilir: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: `WIN+R` tuslayip `%USERPROFILE%\.local\share\opencode\log` yapistirin + +Log dosyalari zaman damgasiyla adlandirilir (ornegin `2025-01-09T123456.log`) ve en yeni 10 log dosyasi tutulur. + +Daha ayrintili ayiklama bilgisi icin `--log-level` komut satiri secenegini kullanabilirsiniz. Ornek: `opencode --log-level DEBUG`. + +--- + +## Depolama + +opencode, oturum verilerini ve diger uygulama verilerini diskte su konumda saklar: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: `WIN+R` tuslayip `%USERPROFILE%\.local\share\opencode` yapistirin + +Bu dizin sunlari icerir: + +- `auth.json` - API anahtarlari, OAuth tokenlari gibi kimlik dogrulama verileri +- `log/` - Uygulama loglari +- `project/` - Oturum ve mesaj verileri gibi projeye ozel veriler + - Proje bir Git deposundaysa `.//storage/` altinda saklanir + - Git deposu degilse `./global/storage/` altinda saklanir + +--- + +## Masaustu uygulamasi + +OpenCode Desktop arka planda yerel bir OpenCode sunucusu (`opencode-cli` sidecar) calistirir. Sorunlarin cogu bozuk bir plugin, hasarli cache veya hatali sunucu ayarindan kaynaklanir. + +### Hizli kontroller + +- Uygulamayi tamamen kapatip yeniden acin +- Uygulama hata ekrani gosteriyorsa **Restart**'a tiklayip hata detaylarini kopyalayin +- Yalnizca macOS: `OpenCode` menusu -> **Reload Webview** (arayuz bos/donukse yardimci olur) + +--- + +### Pluginleri devre disi birakin + +Desktop uygulamasi acilista cokuyorsa, takiliyorsa veya garip davranislar gosteriyorsa once pluginleri devre disi birakin. + +#### Global config'i kontrol edin + +Global config dosyanizi acin ve `plugin` anahtarini arayin. + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (veya `~/.config/opencode/opencode.json`) +- **macOS/Linux** (eski kurulumlar): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: `WIN+R` tuslayip `%USERPROFILE%\.config\opencode\opencode.jsonc` yapistirin + +Plugin tanimliysa anahtari kaldirarak veya bos bir diziye cekerek gecici olarak devre disi birakin: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### Plugin dizinlerini kontrol edin + +OpenCode diskten yerel plugin de yukleyebilir. Bu dizinleri gecici olarak tasiyin (veya klasoru yeniden adlandirin) ve uygulamayi yeniden baslatin: + +- **Global plugins** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: `WIN+R` tuslayip `%USERPROFILE%\.config\opencode\plugins` yapistirin +- **Project plugins** (sadece proje bazli config kullaniyorsaniz) + - `/.opencode/plugins/` + +Uygulama duzelirse soruna neden olan plugini bulmak icin pluginleri tek tek yeniden etkinlestirin. + +--- + +### Cache'i temizleyin + +Pluginleri kapatmak ise yaramazsa (veya plugin kurulumu takili kaldiysa), OpenCode'un cache'i yeniden olusturmasi icin cache'i temizleyin. + +1. OpenCode Desktop'u tamamen kapatin +2. Cache dizinini silin: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/.cache/opencode` +- **Linux**: `~/.cache/opencode` dizinini silin (veya `rm -rf ~/.cache/opencode` calistirin) +- **Windows**: `WIN+R` tuslayip `%USERPROFILE%\.cache\opencode` yapistirin + +3. OpenCode Desktop'u yeniden baslatin + +--- + +### Sunucu baglanti sorunlarini duzeltin + +OpenCode Desktop ya kendi yerel sunucusunu baslatir (varsayilan) ya da sizin tanimladiginiz bir sunucu URL'sine baglanir. + +**"Connection Failed"** penceresi goruyorsaniz (veya uygulama acilis ekranini gecemiyorsa), ozel bir sunucu URL'si olup olmadigini kontrol edin. + +#### Desktop varsayilan sunucu URL'sini temizleyin + +Ana ekranda sunucu adina (durum noktali) tiklayarak Server secicisini acin. **Default server** bolumunde **Clear**'a tiklayin. + +#### Config'ten `server.port` / `server.hostname` kaldirin + +`opencode.json(c)` dosyanizda `server` bolumu varsa gecici olarak kaldirin ve desktop uygulamasini yeniden baslatin. + +#### Ortam degiskenlerini kontrol edin + +Ortamda `OPENCODE_PORT` ayarliysa desktop uygulamasi yerel sunucu icin o portu kullanmaya calisir. + +- `OPENCODE_PORT` degerini kaldirin (veya bos bir port secin) ve yeniden baslatin + +--- + +### Linux: Wayland / X11 sorunlari + +Linux'ta bazi Wayland kurulumlari bos pencere veya compositor hatalarina yol acabilir. + +- Wayland kullaniyorsaniz ve uygulama bos/acilmiyorsa `OC_ALLOW_WAYLAND=1` ile baslatin +- Bu daha kotu olursa kaldirip X11 oturumunda baslatmayi deneyin + +--- + +### Windows: WebView2 runtime + +Windows'ta OpenCode Desktop, Microsoft Edge **WebView2 Runtime** gerektirir. Uygulama bos pencereyle aciliyorsa veya hic baslamiyorsa WebView2'yi kurup/guncelleyip tekrar deneyin. + +--- + +### Windows: Genel performans sorunlari + +Windows'ta yavaslik, dosya erisim sorunlari veya terminal problemleri yasiyorsaniz [WSL (Windows Subsystem for Linux)](/docs/windows-wsl) kullanmayi deneyin. WSL, OpenCode ozellikleriyle daha sorunsuz calisan bir Linux ortami saglar. + +--- + +### Bildirimler gorunmuyor + +OpenCode Desktop sistem bildirimlerini yalnizca su durumlarda gosterir: + +- Isletim sistemi ayarlarinizda OpenCode icin bildirimler etkinse +- Uygulama penceresi odakta degilse + +--- + +### Desktop depolamasini sifirlayin (son care) + +Uygulama acilmiyorsa ve ayarlari arayuz icinden temizleyemiyorsaniz, desktop uygulamasinin kayitli durumunu sifirlayin. + +1. OpenCode Desktop'u kapatin +2. Su dosyalari bulun ve silin (OpenCode Desktop uygulama veri dizininde yer alirlar): + +- `opencode.settings.dat` (desktop varsayilan sunucu URL'si) +- `opencode.global.dat` ve `opencode.workspace.*.dat` (son sunucular/projeler gibi UI durumu) + +Dizini hizlica bulmak icin: + +- **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (ardindan yukaridaki dosya adlarini aratin) +- **Linux**: `~/.local/share` altinda bu dosya adlarini aratin +- **Windows**: `WIN+R` -> `%APPDATA%` (ardindan bu dosya adlarini aratin) + +--- + +## Yardim alin + +OpenCode ile ilgili bir sorun yasiyorsaniz: + +1. **GitHub'da issue acin** + + Hata bildirmek veya ozellik talep etmek icin en iyi yol GitHub depomuzdur: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + Yeni issue acmadan once sorununuzun daha once raporlanip raporlanmadigini kontrol edin. + +2. **Discord'a katilin** + + Gercek zamanli yardim ve topluluk sohbeti icin Discord sunucumuza katilin: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Yaygin sorunlar + +Asagida yaygin sorunlar ve cozumleri yer aliyor. + +--- + +### OpenCode baslamiyor + +1. Hata mesaji icin loglari kontrol edin +2. Terminalde cikti gormek icin `--print-logs` ile calistirin +3. `opencode upgrade` ile en guncel surumu kullandiginizdan emin olun + +--- + +### Kimlik dogrulama sorunlari + +1. TUI'da `/connect` komutuyla yeniden kimlik dogrulamasi yapin +2. API anahtarlarinizin gecerli oldugunu kontrol edin +3. Aginizin provider API baglantilarina izin verdiginden emin olun + +--- + +### Model kullanilamiyor + +1. Provider ile kimlik dogrulamasi yaptiginizi kontrol edin +2. Config'teki model adinin dogru oldugunu dogrulayin +3. Bazi modeller ozel erisim veya abonelik gerektirebilir + +`ProviderModelNotFoundError` aliyorsaniz buyuk olasilikla bir yerde model referansi yanlistir. +Model referansi su formatta olmalidir: `/` + +Ornekler: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +Erisiminiz olan modelleri gormek icin `opencode models` calistirin. + +--- + +### ProviderInitError + +`ProviderInitError` aliyorsaniz buyuk olasilikla config'iniz gecersiz veya bozulmustur. + +Cozum adimlari: + +1. Once [providers rehberini](/docs/providers) izleyerek provider kurulumunun dogru oldugunu dogrulayin +2. Sorun surerse kayitli konfigurasyonu temizlemeyi deneyin: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + Windows'ta `WIN+R` tuslayip su konumu silin: `%USERPROFILE%\.local\share\opencode` + +3. TUI'da `/connect` komutuyla provider kimlik dogrulamasini tekrar yapin + +--- + +### AI_APICallError ve provider paket sorunlari + +API cagrisi hatalari aliyorsaniz bunun nedeni guncel olmayan provider paketleri olabilir. opencode, provider paketlerini (OpenAI, Anthropic, Google vb.) gerektikce dinamik yukler ve yerelde onbellekler. + +Provider paket sorunlarini gidermek icin: + +1. Provider paket cache'ini temizleyin: + + ```bash + rm -rf ~/.cache/opencode + ``` + + Windows'ta `WIN+R` tuslayip su konumu silin: `%USERPROFILE%\.cache\opencode` + +2. En guncel provider paketlerini yeniden kurmak icin opencode'u yeniden baslatin + +Bu, opencode'un en yeni provider paket surumlerini indirmesini zorlar ve model parametresi/API degisikliklerinden kaynakli uyumsuzluklari cogu zaman cozer. + +--- + +### Linux'ta kopyala/yapistir calismiyor + +Linux kullanicilarinin kopyala/yapistir ozelliginin calismasi icin asagidaki pano araclarindan en az birini kurmasi gerekir: + +**X11 sistemleri icin:** + +```bash +apt install -y xclip +# veya +apt install -y xsel +``` + +**Wayland sistemleri icin:** + +```bash +apt install -y wl-clipboard +``` + +**Headless ortamlar icin:** + +```bash +apt install -y xvfb +# ve su komutlari calistirin: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode, Wayland kullandiginizi algilarsa `wl-clipboard` tercihi yapar. Aksi halde sirayla `xclip` ve `xsel` araclarini arar. diff --git a/packages/web/src/content/docs/tr/tui.mdx b/packages/web/src/content/docs/tr/tui.mdx new file mode 100644 index 000000000..c1af2d46f --- /dev/null +++ b/packages/web/src/content/docs/tr/tui.mdx @@ -0,0 +1,387 @@ +--- +title: TUI +description: OpenCode terminal arayuzunu kullanin. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode, projelerinizde LLM ile calismak icin etkilesimli bir terminal arayuzu (TUI) sunar. + +OpenCode'u calistirdiginizda mevcut dizin icin TUI baslar. + +```bash +opencode +``` + +Isterseniz belirli bir calisma dizini icin de baslatabilirsiniz. + +```bash +opencode /path/to/project +``` + +TUI icinde bir mesaj yazarak istem gonderebilirsiniz. + +```text +Kod tabani icin hizli bir ozet ver. +``` + +--- + +## Dosya referanslari + +Mesajlarinizda `@` kullanarak dosyalara referans verebilirsiniz. Bu, mevcut calisma dizininde bulanik dosya aramasi yapar. + +:::tip +Mesajlarinizda dosyalara referans vermek icin `@` kullanabilirsiniz. +::: + +```text "@packages/functions/src/api/index.ts" +@packages/functions/src/api/index.ts dosyasinda kimlik dogrulama nasil ele alinmis? +``` + +Dosya icerigi otomatik olarak konusmaya eklenir. + +--- + +## Bash komutlari + +Bir mesaji `!` ile baslatarak kabuk komutu calistirin. + +```bash frame="none" +!ls -la +``` + +Komut ciktiisi bir arac sonucu olarak konusmaya eklenir. + +--- + +## Komutlar + +OpenCode TUI kullanirken `/` ve komut adini yazarak hizli eylemler calistirabilirsiniz. Ornek: + +```bash frame="none" +/help +``` + +Komutlarin cogu, lider tusu `ctrl+x` olan bir kisayola da sahiptir. [Daha fazla bilgi](/docs/keybinds). + +Mevcut slash komutlarinin tam listesi: + +--- + +### connect + +OpenCode'a bir provider ekler. Mevcut provider'lari secip API anahtarlari eklemenizi saglar. + +```bash frame="none" +/connect +``` + +--- + +### compact + +Guncel oturumu sikistirir. _Takma ad_: `/summarize` + +```bash frame="none" +/compact +``` + +**Kisayol:** `ctrl+x c` + +--- + +### details + +Arac calistirma detaylarini goster/gizle yapar. + +```bash frame="none" +/details +``` + +**Kisayol:** `ctrl+x d` + +--- + +### editor + +Mesaj yazmak icin harici editor acar. `EDITOR` ortam degiskeninde ayarli editoru kullanir. [Daha fazla bilgi](#editor-setup). + +```bash frame="none" +/editor +``` + +**Kisayol:** `ctrl+x e` + +--- + +### exit + +OpenCode'dan cikar. _Takma adlar_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Kisayol:** `ctrl+x q` + +--- + +### export + +Mevcut konusmayi Markdown olarak disa aktarir ve varsayilan editorunuzde acar. `EDITOR` ortam degiskenindeki editoru kullanir. [Daha fazla bilgi](#editor-setup). + +```bash frame="none" +/export +``` + +**Kisayol:** `ctrl+x x` + +--- + +### help + +Yardim penceresini gosterir. + +```bash frame="none" +/help +``` + +**Kisayol:** `ctrl+x h` + +--- + +### init + +`AGENTS.md` dosyasini olusturur veya gunceller. [Daha fazla bilgi](/docs/rules). + +```bash frame="none" +/init +``` + +**Kisayol:** `ctrl+x i` + +--- + +### models + +Kullanilabilir modelleri listeler. + +```bash frame="none" +/models +``` + +**Kisayol:** `ctrl+x m` + +--- + +### new + +Yeni bir oturum baslatir. _Takma ad_: `/clear` + +```bash frame="none" +/new +``` + +**Kisayol:** `ctrl+x n` + +--- + +### redo + +Geri alinan bir mesaji tekrar uygular. Yalnizca `/undo` kullanildiktan sonra kullanilabilir. + +:::tip +Dosya degisiklikleri de geri yuklenir. +::: + +Dahilde bu islem dosya degisikliklerini yonetmek icin Git kullanir. Bu nedenle projenizin **bir Git deposu olmasi gerekir**. + +```bash frame="none" +/redo +``` + +**Kisayol:** `ctrl+x r` + +--- + +### sessions + +Oturumlari listeler ve aralarinda gecis yapar. _Takma adlar_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Kisayol:** `ctrl+x l` + +--- + +### share + +Mevcut oturumu paylasir. [Daha fazla bilgi](/docs/share). + +```bash frame="none" +/share +``` + +**Kisayol:** `ctrl+x s` + +--- + +### themes + +Kullanilabilir temalari listeler. + +```bash frame="none" +/theme +``` + +**Kisayol:** `ctrl+x t` + +--- + +### thinking + +Konusmadaki thinking/reasoning bloklarinin gorunurlugunu degistirir. Etkin oldugunda, genisletilmis dusunmeyi destekleyen modellerin akil yurutmelerini gorebilirsiniz. + +:::note +Bu komut sadece thinking bloklarinin **gosterimini** kontrol eder, modelin gercek akil yurutmelerini acip kapatmaz. Gercek akil yurutme yetenegini degistirmek icin `ctrl+t` ile model varyantlari arasinda gecis yapin. +::: + +```bash frame="none" +/thinking +``` + +--- + +### undo + +Konusmadaki son mesaji geri alir. En son kullanici mesaji, sonraki tum yanitlar ve dosya degisiklikleri kaldirilir. + +:::tip +Yapilan dosya degisiklikleri de geri cevrilir. +::: + +Dahilde bu islem dosya degisikliklerini yonetmek icin Git kullanir. Bu nedenle projenizin **bir Git deposu olmasi gerekir**. + +```bash frame="none" +/undo +``` + +**Kisayol:** `ctrl+x u` + +--- + +### unshare + +Mevcut oturumun paylasimini kaldirir. [Daha fazla bilgi](/docs/share#paylasimi-kaldirma). + +```bash frame="none" +/unshare +``` + +--- + +## Editor kurulumu + +`/editor` ve `/export` komutlari, `EDITOR` ortam degiskeninde tanimli editoru kullanir. + + + + ```bash + # nano veya vim ornegi + export EDITOR=nano + export EDITOR=vim + + # VS Code, Cursor, VSCodium, Windsurf, Zed vb. GUI editorler icin + # --wait ekleyin + export EDITOR="code --wait" + ``` + + Kalici yapmak icin bunu kabuk profilinize ekleyin: + `~/.bashrc`, `~/.zshrc` vb. + + + + + ```bash + set EDITOR=notepad + + # VS Code, Cursor, VSCodium, Windsurf, Zed vb. GUI editorler icin + # --wait ekleyin + set EDITOR=code --wait + ``` + + Kalici yapmak icin **System Properties** > **Environment Variables** yolunu kullanin. + + + + + ```powershell + $env:EDITOR = "notepad" + + # VS Code, Cursor, VSCodium, Windsurf, Zed vb. GUI editorler icin + # --wait ekleyin + $env:EDITOR = "code --wait" + ``` + + Kalici yapmak icin bunu PowerShell profilinize ekleyin. + + + + +Yaygin editor secenekleri: + +- `code` - Visual Studio Code +- `cursor` - Cursor +- `windsurf` - Windsurf +- `nvim` - Neovim editoru +- `vim` - Vim editoru +- `nano` - Nano editoru +- `notepad` - Windows Notepad +- `subl` - Sublime Text + +:::note +VS Code gibi bazi editorlerin `--wait` parametresiyle baslatilmasi gerekir. +::: + +Bazi editorler bloklayici modda calismak icin komut satiri argumanlari ister. `--wait` bayragi editor surecinin kapanana kadar beklemesini saglar. + +--- + +## Yapilandirin + +TUI davranisini OpenCode config dosyanizdan ozellestirebilirsiniz. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### Secenekler + +- `scroll_acceleration` - Daha akici ve dogal kaydirma icin macOS tarzı hizlanmayi acar. Etkin oldugunda hizli kaydirma hareketlerinde hiz artar, yavas hareketlerde hassas kalir. **Bu ayar etkin oldugunda `scroll_speed` degerini gecersiz kilar.** +- `scroll_speed` - Kaydirma komutlariyla TUI'nin ne kadar hizli kayacagini belirler (minimum: `1`). Varsayilan `3` degeridir. **Not: `scroll_acceleration.enabled` `true` ise yok sayilir.** + +--- + +## Ozellestirme + +TUI gorunumunun cesitli kisimlarini komut paletiyle (`ctrl+x h` veya `/help`) ozellestirebilirsiniz. Bu ayarlar yeniden baslatmalar arasinda korunur. + +--- + +#### Kullanici adi gorunumu + +Sohbet mesajlarinda kullanici adinizin gosterilip gosterilmeyecegini degistirir. Sunlardan erisebilirsiniz: + +- Komut paleti: "username" veya "hide username" aratin +- Ayar otomatik saklanir ve TUI oturumlarinda hatirlanir diff --git a/packages/web/src/content/docs/tr/web.mdx b/packages/web/src/content/docs/tr/web.mdx new file mode 100644 index 000000000..a8ae97ea8 --- /dev/null +++ b/packages/web/src/content/docs/tr/web.mdx @@ -0,0 +1,142 @@ +--- +title: Web +description: Tarayıcınızda OpenCode'u kullanma. +--- + +OpenCode, tarayıcınızda bir web uygulaması olarak çalışabilir ve bir terminale ihtiyaç duymadan aynı güçlü AI kodlama deneyimini sağlayabilir. + +![OpenCode Web - Yeni Oturum](../../../assets/web/web-homepage-new-session.png) + +## Başlarken + +Aşağıdakileri çalıştırarak web arayüzünü başlatın: + +```bash +opencode web +``` + +Bu, `127.0.0.1` üzerinde rastgele kullanılabilir bir bağlantı noktasına sahip yerel bir sunucuyu başlatır ve OpenCode'u varsayılan tarayıcınızda otomatik olarak açar. + +:::caution +`OPENCODE_SERVER_PASSWORD` ayarlanmadıysa sunucunun güvenliği kaldırılacaktır. Bu, yerel kullanım için iyidir ancak ağ erişimi için ayarlanmalıdır. +::: + +:::tip[Windows Users] +En iyi deneyim için PowerShell yerine `opencode web`'yi [WSL](/docs/windows-wsl)'den çalıştırın. Bu, uygun dosya sistemi erişimini ve terminal entegrasyonunu sağlar. +::: + +--- + +## Yapılandırma + +Web sunucusunu komut satırı bayraklarıyla veya [config dosyanızda](/docs/config) yapılandırabilirsiniz. + +### Port + +OpenCode varsayılan olarak kullanılabilir bir bağlantı noktasını seçer. Bir bağlantı noktası belirtebilirsiniz: + +```bash +opencode web --port 4096 +``` + +### Ana makine adı + +Varsayılan olarak sunucu `127.0.0.1` (yalnızca localhost) öğesine bağlanır. OpenCode'u ağınızda erişilebilir kılmak için: + +```bash +opencode web --hostname 0.0.0.0 +``` + +`0.0.0.0` kullanıldığında, OpenCode hem yerel hem de ağ adreslerini gösterecektir: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### mDNS Keşfi + +Sunucunuzun yerel ağda bulunabilir olmasını sağlamak için mDNS'yi etkinleştirin: + +```bash +opencode web --mdns +``` + +Bu, ana bilgisayar adını otomatik olarak `0.0.0.0` olarak ayarlar ve sunucuyu `opencode.local` olarak tanıtır. + +Aynı ağ üzerinde birden fazla örneği çalıştıracak şekilde mDNS alan adını özelleştirebilirsiniz: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +CORS'a yönelik ek alan adlarına izin vermek için (özel ön uçlar için kullanışlıdır): + +```bash +opencode web --cors https://example.com +``` + +### Kimlik Doğrulaması + +Erişimi korumak için `OPENCODE_SERVER_PASSWORD` ortam değişkenini kullanarak bir parola ayarlayın: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +Kullanıcı adı varsayılan olarak `opencode` şeklindedir ancak `OPENCODE_SERVER_USERNAME` ile değiştirilebilir. + +--- + +## Web Arayüzünü Kullanma + +Web arayüzü başlatıldığında OpenCode oturumlarınıza erişim sağlar. + +### Oturum + +Oturumlarınızı ana sayfadan görüntüleyin ve yönetin. Aktif oturumları görebilir ve yenilerini başlatabilirsiniz. + +![OpenCode Web - Etkin Oturum](../../../assets/web/web-homepage-active-session.png) + +### Sunucu Durumu + +Bağlı sunucuları ve durumlarını görüntülemek için "Sunucuları Gör" seçeneğini tıklayın. + +![OpenCode Web - Sunuculara bakın](../../../assets/web/web-homepage-see-servers.png) + +--- + +## Terminal Takma + +Çalışan bir web sunucusuna bir terminal TUI'si ekleyebilirsiniz: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +Bu, aynı oturumları ve durumu paylaşarak hem web arayüzünü hem de terminali aynı anda kullanmanıza olanak tanır. + +--- + +## Yapılandırma Dosyası + +Sunucu ayarlarını `opencode.json` yapılandırma dosyanızda da yapılandırabilirsiniz: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +Komut satırı bayrakları yapılandırma dosyası ayarlarından önceliklidir. diff --git a/packages/web/src/content/docs/tr/windows-wsl.mdx b/packages/web/src/content/docs/tr/windows-wsl.mdx new file mode 100644 index 000000000..cd80ce203 --- /dev/null +++ b/packages/web/src/content/docs/tr/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: En iyi deneyim icin OpenCode'u WSL'de calistirin. +--- + +import { Steps } from "@astrojs/starlight/components" + +OpenCode Windows'ta dogrudan calisabilir, ancak en iyi deneyim icin [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) kullanmanizi oneriyoruz. WSL, OpenCode ozellikleriyle sorunsuz calisan bir Linux ortami saglar. + +:::tip[Why WSL?] +WSL, daha iyi dosya sistemi performansi, tam terminal destegi ve OpenCode'un dayandigi gelistirme araclariyla uyumluluk sunar. +::: + +--- + +## Kurulum + + + +1. **WSL'i yukleyin** + + Henuz yuklemediyseniz resmi Microsoft rehberini kullanarak [WSL kurulumunu](https://learn.microsoft.com/en-us/windows/wsl/install) yapin. + +2. **OpenCode'u WSL icine yukleyin** + + WSL hazir olduktan sonra WSL terminalini acin ve OpenCode'u [kurulum yontemlerinden](/docs/) biriyle yukleyin. + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **OpenCode'u WSL icinden kullanin** + + Proje dizininize gidin (`/mnt/c/`, `/mnt/d/` vb. ile Windows dosyalarina erisebilirsiniz) ve OpenCode'u calistirin. + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## Desktop uygulamasi + WSL sunucusu + +OpenCode Desktop kullanmak isteyip sunucuyu WSL'de calistirmak istiyorsaniz: + +1. **Sunucuyu WSL'de baslatin** ve dis baglantilara izin vermek icin `--hostname 0.0.0.0` kullanin: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **Desktop uygulamasini** `http://localhost:4096` adresine baglayin + +:::note +Kurulumunuzda `localhost` calismiyorsa bunun yerine WSL IP adresini kullanin (WSL icinde: `hostname -I`) ve `http://:4096` adresine baglanin. +::: + +:::caution +`--hostname 0.0.0.0` kullaniyorsaniz sunucuyu guvene almak icin `OPENCODE_SERVER_PASSWORD` ayarlayin. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Web istemcisi + WSL + +Windows'ta en iyi web deneyimi icin: + +1. **`opencode web` komutunu PowerShell yerine WSL terminalinde calistirin**: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **Windows tarayicinizdan** `http://localhost:` adresini acin (OpenCode URL'yi yazdirir) + +`opencode web` komutunu WSL'den calistirmak, dosya sistemi erisimi ve terminal entegrasyonunu daha tutarli hale getirirken tarayicidan erisimi korur. + +--- + +## Windows dosyalarina erisin + +WSL, tum Windows dosyalariniza `/mnt/` dizini uzerinden erisebilir: + +- `C:` surucusu -> `/mnt/c/` +- `D:` surucusu -> `/mnt/d/` +- Ve digerleri... + +Ornek: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +En sorunsuz deneyim icin deponuzu WSL dosya sistemine (ornegin `~/code/` altina) klonlayip OpenCode'u orada calistirmayi dusunun. +::: + +--- + +## Ipuclari + +- Windows suruculerinde duran projelerde OpenCode'u WSL icinde calistirin - dosya erisimi daha sorunsuz olur +- Butunlesik bir gelistirme akisi icin OpenCode ile birlikte VS Code [WSL eklentisini](https://code.visualstudio.com/docs/remote/wsl) kullanin +- OpenCode konfigurasyonunuz ve oturumlariniz WSL ortaminda `~/.local/share/opencode/` konumunda saklanir diff --git a/packages/web/src/content/docs/tr/zen.mdx b/packages/web/src/content/docs/tr/zen.mdx new file mode 100644 index 000000000..a66fe8c0b --- /dev/null +++ b/packages/web/src/content/docs/tr/zen.mdx @@ -0,0 +1,238 @@ +--- +title: Zen +description: OpenCode ekibinin sundugu secili model listesi. +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen, OpenCode ekibi tarafindan test edilip dogrulanmis modellerin listesidir. + +:::note +OpenCode Zen su anda beta asamasindadir. +::: + +Zen, OpenCode'daki diger provider'lar gibi calisir. OpenCode Zen'e giris yapar ve API anahtarinizi alirsiniz. +Tamamen istege baglidir; OpenCode kullanmak icin Zen kullanmak zorunda degilsiniz. + +--- + +## Arka plan + +Piyasada cok sayida model var, ancak bunlarin sadece bir kismi kodlama ajani olarak iyi calisir. Ayrica provider'larin cogu birbirinden cok farkli sekilde ayarlanir; bu da performans ve kaliteyi ciddi bicimde degistirir. + +:::tip +OpenCode ile iyi calisan belirli model/provider kombinasyonlarini test ettik. +::: + +Bu nedenle OpenRouter benzeri bir servis uzerinden model kullaniyorsaniz, istediginiz modelin en iyi surumunu alip almadiginizdan her zaman emin olamazsiniz. + +Bunu cozmeye yonelik olarak sunlari yaptik: + +1. Secili bir model grubunu test ettik ve ekipleriyle en iyi calisma sekli uzerine gorustuk +2. Daha sonra bazi provider'larla bu modellerin dogru sekilde sunuldugunu dogruladik +3. Son olarak model/provider kombinasyonlarini benchmark ederek guvenle onerebilecegimiz bir liste olusturduk + +OpenCode Zen, bu modellere erisim saglayan bir AI gateway'dir. + +--- + +## Nasil calisir + +OpenCode Zen, OpenCode'daki diger provider'lar gibi calisir. + +1. **OpenCode Zen** hesabina giris yapin, odeme bilgilerinizi ekleyin ve API anahtarinizi kopyalayin +2. TUI'da `/connect` komutunu calistirin, OpenCode Zen'i secin ve API anahtarinizi yapistirin +3. Onerdigimiz model listesini gormek icin TUI'da `/models` calistirin + +Ucretlendirme istek basina yapilir ve hesabiniza kredi yukleyebilirsiniz. + +--- + +## Endpoint'ler + +Modellerimize asagidaki API endpoint'leri uzerinden de erisebilirsiniz. + +| Model | Model ID | Endpoint | AI SDK Package | +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Free | minimax-m2.1-free | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Free | glm-4.7-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Free | kimi-k2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +OpenCode config'inizdeki [model id](/docs/config/#models), `opencode/` formatini kullanir. +Ornegin GPT 5.2 Codex icin config'te `opencode/gpt-5.2-codex` kullanirsiniz. + +--- + +### Modeller + +Mevcut modellerin tam listesini ve metadatasini su adresten cekebilirsiniz: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## Fiyatlandirma + +Kullandikca ode modelini destekliyoruz. Asagidaki fiyatlar **1M token basina** verilmistir. + +| Model | Input | Output | Cached Read | Cached Write | +| --------------------------------- | ------ | ------ | ----------- | ------------ | +| Big Pickle | Free | Free | Free | - | +| MiniMax M2.1 Free | Free | Free | Free | - | +| MiniMax M2.1 | $0.30 | $1.20 | $0.10 | - | +| GLM 4.7 Free | Free | Free | Free | - | +| GLM 4.7 | $0.60 | $2.20 | $0.10 | - | +| GLM 4.6 | $0.60 | $2.20 | $0.10 | - | +| Kimi K2.5 Free | Free | Free | Free | - | +| Kimi K2.5 | $0.60 | $3.00 | $0.08 | - | +| Kimi K2 Thinking | $0.40 | $2.50 | - | - | +| Kimi K2 | $0.40 | $2.50 | - | - | +| Qwen3 Coder 480B | $0.45 | $1.50 | - | - | +| Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | +| Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | +| Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | +| Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | +| Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | +| Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | +| Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | +| Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | - | +| Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | - | +| Gemini 3 Flash | $0.50 | $3.00 | $0.05 | - | +| GPT 5.2 | $1.75 | $14.00 | $0.175 | - | +| GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | - | +| GPT 5.1 | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | - | +| GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | - | +| GPT 5 | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Codex | $1.07 | $8.50 | $0.107 | - | +| GPT 5 Nano | Free | Free | Free | - | + +Kullanim gecmisinizde _Claude Haiku 3.5_ gorebilirsiniz. Bu, oturum basliklarini olusturmak icin kullanilan [dusuk maliyetli bir modeldir](/docs/config/#models). + +:::note +Kredi karti ucretleri maliyetine yansitilir (islem basina %4.4 + $0.30); bunun disinda ek ucret almiyoruz. +::: + +Ucretsiz modeller: + +- GLM 4.7 Free, sinirli bir sure icin OpenCode'da ucretsizdir. Ekip bu surede geri bildirim toplayip modeli iyilestiriyor +- Kimi K2.5 Free, sinirli bir sure icin OpenCode'da ucretsizdir. Ekip bu surede geri bildirim toplayip modeli iyilestiriyor +- MiniMax M2.1 Free, sinirli bir sure icin OpenCode'da ucretsizdir. Ekip bu surede geri bildirim toplayip modeli iyilestiriyor +- Big Pickle, sinirli bir sure icin OpenCode'da ucretsiz olan gizli bir modeldir. Ekip bu surede geri bildirim toplayip modeli iyilestiriyor + +Sorunuz varsa bize ulasin. + +--- + +### Otomatik yukleme + +Bakiyeniz $5'in altina dustugunde Zen otomatik olarak $20 yukler. + +Otomatik yukleme tutarini degistirebilir veya bu ozelligi tamamen kapatabilirsiniz. + +--- + +### Aylik limitler + +Tum calisma alani ve ekip uyeleri icin aylik kullanim limiti belirleyebilirsiniz. + +Ornegin aylik limiti $20 yaptiysaniz Zen bir ayda $20'den fazla kullandirtmaz. Ancak otomatik yukleme aciksa bakiye $5 altina dustugunde toplam odemeniz $20'nin uzerine cikabilir. + +--- + +## Gizlilik + +Tum modellerimiz ABD'de barindiriliyor. Provider'larimiz sifir saklama politikasini izler ve verilerinizi model egitimi icin kullanmaz; asagidaki istisnalar haric: + +- Big Pickle: Ucretsiz donemde toplanan veriler modeli iyilestirmek icin kullanilabilir +- GLM 4.7 Free: Ucretsiz donemde toplanan veriler modeli iyilestirmek icin kullanilabilir +- Kimi K2.5 Free: Ucretsiz donemde toplanan veriler modeli iyilestirmek icin kullanilabilir +- MiniMax M2.1 Free: Ucretsiz donemde toplanan veriler modeli iyilestirmek icin kullanilabilir +- OpenAI API'leri: Istekler [OpenAI veri politikalari](https://platform.openai.com/docs/guides/your-data) kapsaminda 30 gun saklanir +- Anthropic API'leri: Istekler [Anthropic veri politikalari](https://docs.anthropic.com/en/docs/claude-code/data-usage) kapsaminda 30 gun saklanir + +--- + +## Ekipler icin + +Zen ekipler icin de guclu bir cozumdur. Ekip arkadaslarini davet edebilir, roller atayabilir, kullanilacak modelleri yonetebilir ve daha fazlasini yapabilirsiniz. + +:::note +Calisma alanlari beta kapsaminda su anda ekipler icin ucretsizdir. +::: + +Calisma alani yonetimi su anda beta kapsaminda ucretsizdir. Fiyatlandirma detaylarini yakinda paylasacagiz. + +--- + +### Roller + +Calisma alaniniza ekip arkadaslarini davet edip rol atayabilirsiniz: + +- **Admin**: Modelleri, uyeleri, API anahtarlarini ve faturalandirmayi yonetir +- **Member**: Yalnizca kendi API anahtarlarini yonetir + +Admin'ler maliyet kontrolu icin uye bazinda aylik harcama limitleri de ayarlayabilir. + +--- + +### Model erisimi + +Admin'ler calisma alani icin belirli modelleri acip kapatabilir. Devre disi bir modele yapilan istekler hata dondurur. + +Bu, veri toplayan bir modelin kullanimini kapatmak istediginiz durumlarda kullanislidir. + +--- + +### Kendi anahtarinizi kullanin + +Zen'deki diger modellere erisirken kendi OpenAI veya Anthropic API anahtarlarinizi da kullanabilirsiniz. + +Kendi anahtarinizi kullandiginizda token ucreti Zen yerine dogrudan provider tarafindan faturalandirilir. + +Ornegin kurulusunuzun zaten OpenAI veya Anthropic anahtari varsa Zen'in sagladigi anahtar yerine onu kullanabilirsiniz. + +--- + +## Hedefler + +OpenCode Zen'i su amaclarla olusturduk: + +1. Kodlama ajanlari icin en iyi model/provider kombinasyonlarini **benchmark etmek** +2. Performansi dusurmeden veya daha ucuz provider'a yonlendirmeden **en yuksek kaliteye** erismek +3. Maliyetine satarak fiyat dususlerini kullaniciya yansitmak ve yalnizca islem ucretlerini kapsayan pay birakmak +4. Herhangi bir kodlama ajaniyla kullanima izin vererek **kilitlenmeyi onlemek** ve OpenCode'da diger provider'lari her zaman acik tutmak diff --git a/packages/web/src/content/docs/zh-cn/1-0.mdx b/packages/web/src/content/docs/zh-cn/1-0.mdx new file mode 100644 index 000000000..b45625dad --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: 遷移到 1.0 +description: OpenCode 1.0 中的新增内容。 +--- + +OpenCode 1.0完全重写了TUI。 + +我们从存在的性能和功能问题的基于 go+bubbletea 的 TUI 迁移到使用 zig+solidjs 编写的内部框架 (OpenTUI)。 + +新的 TUI 的工作方式与旧的 TUI 类似,因为它连接到相同的开放代码服务器。 + +--- + +## 升級中 + +如果您當前正在使用以前的版本,則不應自動升級到 1.0 +版本。然而,一些旧版本的 OpenCode 总是获取最新版本。 + +要手動升級,請運行 + +```bash +$ opencode upgrade 1.0.0 +``` + +要降级回0.x,请运行 + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## 用戶體驗變化 + +会话历史记录更加压缩,仅显示编辑和 bash 工具的完整详细信息。 + +我们添加了一个命令栏,几乎所有内容都通过了它。按 ctrl+p 可以在任意上下文中调出它并查看您可以执行的所有操作。 + +添加了包含有用信息的會話側邊欄(可以切換)。 + +我們刪除了一些我們不確定是否有人實際使用的功能。如果缺少重要內容,請提出問題,我們會盡快將其添加回來。 + +--- + +## 重大變化 + +### 按鍵綁定已重命名 + +- messages_revert -> messages_undo +- switch_agent -> agent_cycle +- switch_agent_reverse -> agent_cycle_reverse +- switch_mode -> agent_cycle +- switch_mode_reverse -> agent_cycle_reverse + +### 按鍵綁定已移除 + +- 消息佈局切換 +- 下一條消息 +- 上一條消息 +- 文件差異切換 +- 文件搜索 +- 文件關閉 +- 文件列表 +- 應用程序幫助 +- 項目初始化 +- 工具詳細信息 +- 思維塊 diff --git a/packages/web/src/content/docs/zh-cn/acp.mdx b/packages/web/src/content/docs/zh-cn/acp.mdx new file mode 100644 index 000000000..9bcc0faad --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACP 支持 +description: 在任何 ACP 兼容编辑器中使用 OpenCode。 +--- + +OpenCode 支持[代理客户端协议](https://agentclientprotocol.com) 或 (ACP),允许您直接在兼容的编辑器和 IDE 中使用它。 + +:::提示 +有关支持 ACP 的编辑器和工具的列表,请查看[非加太进度进度报告](https://zed.dev/blog/acp-progress-report#available-now)。 +::: + +ACP 是一种开放协议,用于标准化代码编辑器和 AI 编码代理之间的通信。 + +--- + +## 配置 + +要通过 ACP 使用 OpenCode,须编辑器配置为运行 `opencode acp` 命令。 + +该命令将 OpenCode 作为 ACP 兼容的子进程启动,通过 stdio 通过 JSON-RPC 与您的编辑器进行通信。 + +以下是支持 ACP 的流行编辑器的示例。 + +--- + +### 澤德 + +添加到您的[泽德](https://zed.dev)配置(`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +要打开它,请使用 **命令面板** 中的 `agent: new thread` 操作。 + +您还可以通过编辑`keymap.json`来绑定键盘快捷键: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### JetBrains IDE + +根据[文件](https://www.jetbrains.com/help/ai-assistant/acp.html)添加到你的[JetBrains IDE](https://www.jetbrains.com/) acp.json]: + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +要打开它,请在 AI Chat 代理选择器中使用新的“OpenCode”代理。 + +--- + +### 前衛 + +添加到您的[前卫](https://github.com/yetone/avante.nvim)配置: + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +如果需要傳遞環境變量: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### 代码合作者.nvim + +相当于 OpenCode 网关 [代码伙伴.nvim](https://github.com/olimorris/codecompanion.nvim) 中的 ACP 代理,接下来将以下内容添加到 Neovim 配置中: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +此配置将 CodeCompanion 设置为使用 OpenCode 作为聊天的 ACP 代理。 + +如果您需要交付环境变量(如 `OPENCODE_API_KEY`),请参阅 CodeCompanion.nvim 文档中的 [配置充电器:环境变量Z](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) 了解完整信息。 + +## 支持 + +OpenCode 通过 ACP 的工作方式与在终端中的工作方式相同。支持所有功能: + +:::笔记 +目前不支持某些内置斜杠命令,例如 `/undo` 和 `/redo`。 +::: + +- 內置工具(文件操作、終端命令等) +- 自定義工具和斜杠命令 +- 在 OpenCode 配置中配置的 MCP 服务器 +- `AGENTS.md` 的项目特定规则 +- 自定义程序和 linter +- 代理和權限系統 diff --git a/packages/web/src/content/docs/zh-cn/agents.mdx b/packages/web/src/content/docs/zh-cn/agents.mdx new file mode 100644 index 000000000..75142d0cc --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/agents.mdx @@ -0,0 +1,747 @@ +--- +title: 代理商 +description: 配置和使用專門的代理。 +--- + +代理是專門的人工智能助手,可以針對特定任務和工作流程進行配置。它們允許您創建具有自定義提示、模型和工具訪問權限的專用工具。 + +:::提示 +使用計劃代理來分析代碼並審查建議,而無需進行任何代碼更改。 +::: + +您可以在會話期間在代理之間切換,或使用 `@` 提及來調用它們。 + +--- + +## 類型 + +OpenCode有两种类型的代理;主代理和次代理。 + +--- + +### 主要代理 + +主要代理是与您直接交互的主要助手。您可以使用 **Tab** 键或您配置的 `switch_agent` 键绑定循环浏览它们。这些代理处理您的主要对话。工具访问是通过权限配置的 - 例如,“构建”启用了所有工具,而“计划”则受到限制。 + +:::提示 +您可以在会话期间使用 **Tab** 键在主要代理之间进行切换。 +::: + +OpenCode附带两个内置的主要代理:**Build** 和 **Plan**。地 +看看下面這些。 + +--- + +### 子代理 + +子代理是主要代理可以調用​​來執行特定任務的專業助手。您還可以通過在消息中**@提及**它們來手動調用它們。 + +OpenCode附带两个内置子代理:**General** 和 **Explore**。我们将在下面看看这个。 + +--- + +## 內建 + +OpenCode附带两个内置主代理和两个内置子代理。 + +--- + +### 使用構建 + +_模式_:`primary` + +構建是啟用所有工具的**默認**主要代理。這是用於需要完全訪問文件操作和系統命令的開發工作的標準代理。 + +--- + +### 使用計劃 + +_模式_:`primary` + +專為規劃和分析而設計的受限代理。我們使用權限系統為您提供更多控制並防止意外更改。 +默认情况下,以下所有项均设置为`ask`: + +- `file edits`:所有书写、修复和编辑 +- `bash`:所有 bash 命令 + +当您希望 LLM 分析代码、建议更改或创建计划而不是对代码库进行任何实际修改时,此代理非常有用。 + +--- + +### 使用一般 + +_模式_:`subagent` + +用於研究複雜問題和執行多步驟任務的通用代理。具有完整的工具訪問權限(待辦事項除外),因此可以在需要時更改文件。使用它可以並行運行多個工作單元。 + +--- + +### 使用探索 + +_模式_:`subagent` + +用於探索代碼庫的快速只讀代理。無法修改文件。當您需要按模式快速查找文件、搜索代碼中的關鍵字或回答有關代碼庫的問題時,請使用此功能。 + +--- + +### 使用壓實 + +_模式_:`primary` + +隐藏的系统代理,将长上下文压缩为更小的抽象。它会在需要时自动运行,并且无法在 UI 中选择。 + +--- + +### 使用標題 + +_模式_:`primary` + +生成短会话标题的隐藏系统代理。它会自动运行,并且无法在 UI 中选择。 + +--- + +### 使用總結 + +_模式_:`primary` + +创建会话摘要的系统代理。它会自动运行,并且无法在 UI 中选择。 + +--- + +## 用法 + +1. 对于主要代理,请在会话期间使用 **Tab** 键循环浏览它们。您还可以使用配置的 `switch_agent` 键绑定。 + +2. 可以調用子代理: + - **自動**由主要代理根據其描述執行專門任務。 + - 通過在消息中**@提及**子代理手動進行。例如。 + + ```txt frame="none" + @general help me search for this function + ``` + +3. **會話之間導航**:當子代理創建自己的子會話時,您可以使用以下命令在父會話和所有子會話之間導航: + - **\+Right**(或您配置的 `session_child_cycle` 鍵綁定)向前循環父級 → 子級 1 → 子級 2 → ... → 父級 + - **\+Left**(或您配置的 `session_child_cycle_reverse` 鍵綁定)向後循環父級 ← 子級 1 ← 子級 2 ← ... ← 父級 + + 這使您可以在主要對話和專門的子代理工作之間無縫切換。 + +--- + +## 配置 + +您可以自定義內置代理或通過配置創建您自己的代理。可以通過兩種方式配置代理: + +--- + +### JSON + +在 `opencode.json` 配置文件中配置代理: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### 降價 + +您还可以使用 Markdown 文件定义代理。将它们放入: + +- 全球:`~/.config/opencode/agents/` +- 每个项目:`.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Markdown 文件名成为代理名称。例如,`review.md` 创建`review` 代理。 + +--- + +## 選項 + +讓我們詳細看看這些配置選項。 + +--- + +### 描述 + +使用 `description` 选项提供代理的作用以及使用时的简要描述。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +這是一個**必需的**配置選項。 + +--- + +### 溫度 + +使用 `temperature` 配置控制 LLM 响应的随机性和创意。 + +較低的值使響應更加集中和確定,而較高的值則增加創造力和可變性。 + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +溫度值的範圍通常為 0.0 到 1.0: + +- **0.0-0.2**:非常集中且確定的響應,非常適合代碼分析和規劃 +- **0.3-0.5**:具有一定創造力的平衡響應,適合一般開發任務 +- **0.6-1.0**:更有創意和多樣化的反應,有助於頭腦風暴和探索 + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +如果未指定温度,OpenCode 将使用特定于型号的默认值;大多数型号通常为 0,Qwen 型号为 0.55。 + +--- + +### 最大步數 + +控制代理在被迫僅使用文本響應之前可以執行的最大代理迭代次數。這允許希望控製成本的用戶對代理操作設置限制。 + +如果未設置,代理將繼續迭代,直到模型選擇停止或用戶中斷會話。 + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +當達到限制時,代理會收到特殊的系統提示,指示其響應其工作摘要和建議的剩餘任務。 + +:::警告 +旧版 `maxSteps` 字段已废弃。请改用`steps`。 +::: + +--- + +### 禁用 + +设置为`true`以取消代理。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### 迅速的 + +使用 `prompt` 配置为代理指定自定义系统提示文件。提示文件应包含特定于代理目的的说明。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +该路径相对于文件所在位置的配置。因此,这适用于全局 OpenCode 配置和项目特定配置。 + +--- + +### 模型 + +使用 `model` 配置此代理的模型。对于使用针对不同任务优化的不同模型很有用。例如,更快的规划模型、更强大的实施模型。 + +:::提示 +如果您不指定模型,主代理将使用[全局配置的模型](/docs/config#models),而子代理将使用调用子代理的主代理的模型。 +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +OpenCode配置中的模型ID使用格式`provider/model-id`。例如,如果您使用[开放代码禅](/docs/zen),则您将使用`opencode/gpt-5.1-codex`来表示GPT 5.1 Codex。 + +--- + +### 工具 + +使用 `tools` 配置控制此代理中可用的工具。您可以通过将特定工具设置为 `true` 或 `false` 来启用或禁用特定工具。 + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::笔记 +特定於代理的配置會覆蓋全局配置。 +::: + +您还可以使用通配符同时控制多个工具。例如,要禁用 MCP 服务器中的所有工具: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[了解有关工具的更多信息](/docs/tools)。 + +--- + +### 權限 + +您可以配置权限来管理代理可以执行的操作。 目前,`edit`、`bash` 和 `webfetch` 工具的权限可以配置为: + +- `"ask"` — 运行工具提示批准之前 +- `"allow"` — 尚未批准所有操作 +- `"deny"` — 取消该工具 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +您可以覆蓋每個代理的這些權限。 + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +您还可以在 Markdown 代理中设置权限。 + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +您可以设置特定的 bash 命令的权限。 + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +這可以採用全局模式。 + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +您還可以使用`*`通配符來管理所有命令的權限。 +由於最後一個匹配規則優先,因此將 `*` 通配符放在前面,將特定規則放在後面。 + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[了解有关权限的更多信息](/docs/permissions)。 + +--- + +### 模式 + +使用`mode` 配置控制代理的模式。 `mode` 选项用于确定如何使用代理。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +`mode` 选项可设置为`primary`、`subagent` 或`all`。如果未指定`mode`,则默认为`all`。 + +--- + +### 隱 + +使用`hidden: true`从`@`自动完成菜单隐藏子代理。对于只能由其他代理通过任务工具以编程方式调用的内部子代理很有用。 + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +這僅影響自動完成菜單中的用戶可見性。如果權限允許,模型仍然可以通過任務工具調用隱藏代理。 + +:::笔记 +仅适用于`mode: subagent`代理。 +::: + +--- + +### 任務權限 + +使用`permission.task`控制代理可以通过任务工具调用哪些子代理。使用glob模式进行灵活匹配。 + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +当设置为`deny`时,子代理社区任务工具描述中因此完全删除,模型不会尝试调用它。 + +:::提示 +规则按顺序评估,**最后匹配的规则触发**。在上面的示例中,`orchestrator-planner` 匹配`*`(拒绝)和`orchestrator-*`(允许),但由于`orchestrator-*` 位于`*` 之后,因此结果为`allow`。 +::: + +:::提示 +用戶始終可以通過 `@` 自動完成菜單直接調用任何子代理,即使代理的任務權限會拒絕它。 +::: + +--- + +### 顏色 + +在UI中的界面外观中使用`color`选项自定义代理。这会影响代理在界面中的显示方式。 + +使用有效的十六进制颜色(例如`#FF5733`)或主题颜色:`primary`、`secondary`、`accent`、`success`、`warning`、`error`、`info`。 + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### 顶P + +使用 `top_p` 选项控制响应多样性。控制随机性的温度替代方案。 + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +值範圍從 0.0 到 1.0。較低的值更加集中,較高的值更加多樣化。 + +--- + +### 額外的 + +您在代理配置中指定的任何其他選項都將作為模型選項**直接**傳遞給提供程序。這允許您使用特定於提供商的功能和參數。 + +例如,使用 OpenAI 的推理模型,您可以控制推理工作: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +這些附加選項是特定於型號和提供商的。檢查提供商的文檔以獲取可用參數。 + +:::提示 +运行 `opencode models` 查看可用模型的列表。 +::: + +--- + +## 創建代理 + +您可以使用以下命令創建新代理: + +```bash +opencode agent create +``` + +此交互式命令將: + +1. 詢問代理保存在哪裡;全局或特定項目。 +2. 描述代理應該做什麼。 +3. 生成適當的系統提示和標識符。 +4. 讓您選擇代理可以訪問哪些工具。 +5. 最后,使用代理配置创建一个markdown文件。 + +--- + +## 使用案例 + +以下是不同代理的一些常見用例。 + +- **構建代理**:啟用所有工具的完整開發工作 +- **規劃代理**:分析規劃,不做改動 +- **審查代理**:具有隻讀訪問權限和文檔工具的代碼審查 +- **调试代理**:专注于启用bash和读取工具的调查 +- **文檔代理**:使用文件操作但不使用系統命令的文檔編寫 + +--- + +## 示例 + +以下是一些您可能會覺得有用的示例代理。 + +:::提示 +您有想要分享的经纪人吗? [提交 PR](https://github.com/anomalyco/opencode)。 +::: + +--- + +### 文件代理 + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### 安全審核員 + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/zh-cn/cli.mdx b/packages/web/src/content/docs/zh-cn/cli.mdx new file mode 100644 index 000000000..5fa2eedf7 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/cli.mdx @@ -0,0 +1,601 @@ +--- +title: 命令行界面 +description: OpenCode CLI 选项和命令。 +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +默认情况下,OpenCode CLI 在不带任何参数运行时启动[途径易](/docs/tui)。 + +```bash +opencode +``` + +但它也接受允许本页记录的命令。这您以Smashing方式与OpenCode交互。 + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### 推 + +启动OpenCode用户终端界面。 + +```bash +opencode [project] +``` + +#### 旗幟 + +|旗幟|短|描述 | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | 继续上期 | +| `--session` | `-s` | 会话 ID 继续 | +| `--prompt` | |提示使用| +| `--model` | `-m` |以提供者/模型形式使用的模型 | +| `--agent` | |代理使用| +| `--port` | | 监听端口 | +| `--hostname` | | 监听的主机名 | + +--- + +## 命令 + +OpenCode CLI 还具有以下命令。 + +--- + +### 代理人 + +管理 OpenCode 代理。 + +```bash +opencode agent [command] +``` + +--- + +### 附 + +将终端通过 `serve` 或 `web` 命令启动已运行的 OpenCode 耳机服务器。 + +```bash +opencode attach [url] +``` + +这允许将 TUI 与远程 OpenCode 钱包一起使用。例如: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### 旗幟 + +|旗幟|短|描述 | +| ----------- | ----- | --------------------------------- | +| `--dir` | |启动 TUI 的工作目录 | +| `--session` | `-s` | 会话 ID 继续 | + +--- + +#### 創造 + +使用自定義配置創建新代理。 + +```bash +opencode agent create +``` + +此命令將指導您使用自定義系統提示和工具配置創建新代理。 + +--- + +#### 列表 + +列出所有可用的代理。 + +```bash +opencode agent list +``` + +--- + +### 授權 + +用於管理提供商的憑據和登錄的命令。 + +```bash +opencode auth [command] +``` + +--- + +#### 登入 + +OpenCode 由 [模型.dev](https://models.dev) 上的型号列表提供支持,因此您可以使用 `opencode auth login` 来为您想要使用的任何型号配置 API 按键。它存储在 `~/.local/share/opencode/auth.json` 中。 + +```bash +opencode auth login +``` + +当OpenCode启动时,它会从会计文件加载提供程序。如果您的环境中定义了任何按键或项目中的`.env`文件。 + +--- + +#### 列表 + +列出憑證文件中存儲的所有經過身份驗證的提供程序。 + +```bash +opencode auth list +``` + +或者簡短的版本。 + +```bash +opencode auth ls +``` + +--- + +#### 註銷 + +通過從憑據文件中清除提供程序,將您從提供程序中註銷。 + +```bash +opencode auth logout +``` + +--- + +### github + +管理 GitHub 代理以实现存储库自动化。 + +```bash +opencode github [command] +``` + +--- + +#### 安裝 + +在您的存储库中安装 GitHub 代理。 + +```bash +opencode github install +``` + +这将设置必要的 GitHub Actions 工作流程并指导您完成配置过程。 [了解更多](/docs/github)。 + +--- + +#### 跑步 + +运行 GitHub 代理。这通常用在 GitHub Actions 中。 + +```bash +opencode github run +``` + +##### 旗幟 + +|旗幟|描述 | +| --------- | -------------------------------------- | +| `--event` | 用于运行代理的 GitHub 模拟事件 | +| `--token` | GitHub 个人访问令牌 | + +--- + +### MCP + +管理模型上下文協議服務器。 + +```bash +opencode mcp [command] +``` + +--- + +#### 添加 + +将 MCP 服务器添加到您的配置中。 + +```bash +opencode mcp add +``` + +此命令将指导您添加本地或远程 MCP 服务器。 + +--- + +#### 列表 + +列出所有已配置的 MCP 服务器及其连接状态。 + +```bash +opencode mcp list +``` + +或者使用簡短版本。 + +```bash +opencode mcp ls +``` + +--- + +#### 授權 + +使用启用 OAuth 的 MCP 服务器进行身份验证。 + +```bash +opencode mcp auth [name] +``` + +如果您不提供服务器名称,系统将提示您从可用的支持 OAuth 的服务器中进行选择。 + +您还可以开始支持 OAuth 的及其服务器身份验证状态。 + +```bash +opencode mcp auth list +``` + +或者使用簡短版本。 + +```bash +opencode mcp auth ls +``` + +--- + +#### 註銷 + +删除 MCP 服务器的 OAuth 工具。 + +```bash +opencode mcp logout [name] +``` + +--- + +#### 偵錯 + +调试MCP服务器的OAuth连接问题。 + +```bash +opencode mcp debug +``` + +--- + +### 型號 + +列出已配置提供商的所有可用模型。 + +```bash +opencode models [provider] +``` + +此命令以 `provider/model` 格式显示您配置的提供程序中可用的所有模型。 + +这对于确定[你的配置](/docs/config/)中使用的意图模型名称很有用。 + +您可以选择提供项目ID并按该提供项目筛选模型。 + +```bash +opencode models anthropic +``` + +#### 旗幟 + +|旗幟|描述 | +| ----------- | ------------------------------------------------------------ | +| `--refresh` |来自 models.dev | 刷新模型存储 +| `--verbose` |使用更详细的模型输出(包括成本等元数据)| + +使用`--refresh`标志来更新服务器的模型列表。当新模型已添加到提供程序并且您希望在OpenCode中查看它们时,这非常有用。 + +```bash +opencode models --refresh +``` + +--- + +### 跑步 + +通过直接传递提示以非交互模式运行 opencode。 + +```bash +opencode run [message..] +``` + +这对于编写脚本、自动化,或者当您想要快速获得答案而不是完整的 TUI 时非常有用。例如。 + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +您还可以添加到正在运行的`opencode serve`实例,会员每次运行时MCP服务器冷启动时间: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### 旗幟 + +|旗幟|短|描述 | +| ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | | 要运行的命令,使用消息作为参数 | +| `--continue` | `-c` | 继续上期 | +| `--session` | `-s` | 会话 ID 继续 | +| `--share` | |分享会议| +| `--model` | `-m` |以提供者/模型形式使用的模型 | +| `--agent` | |代理使用| +| `--file` | `-f` |要附加到消息的文件 | +| `--format` | |格式:默认(格式化)或json(原始JSON事件)| +| `--title` | |会话标题(如果未提供值,则使用断断的提示)| +| `--attach` | | 连接到正在运行的 opencode 服务器(例如,http://localhost:4096)| +| `--port` | |本地服务器的端口(默认为随机端口) | + +--- + +### 服務 + +启动无头OpenCode服务器以进行API访问。查看[服务器文档](/docs/server)以获取完整的HTTP 接口。 + +```bash +opencode serve +``` + +这将启动一个 HTTP 服务器,该服务器提供对 opencode 功能的 API 访问,并占用 TUI 接口。设置 `OPENCODE_SERVER_PASSWORD` 以启用 HTTP 基本身份验证(用户名默认为 `opencode`)。 + +#### 旗幟 + +|旗幟|描述 | +| ------------ | ------------------------------------------ | +| `--port` |监听端口| +| `--hostname` | 监听的主机名 | +| `--mdns` | 启用 mDNS 发现 | +| `--cors` | 允许 CORS 的其他浏览器源 | + +--- + +### 會議 + +管理 OpenCode 会话。 + +```bash +opencode session [command] +``` + +--- + +#### 列表 + +列出所有 OpenCode 会话。 + +```bash +opencode session list +``` + +##### 旗幟 + +|旗幟|短|描述 | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` | 限制为最近的 N 个会话 | +| `--format` | | 输出格式:table 或 json(table) | + +--- + +### 統計數據 + +显示OpenCode会话的令牌使用情况和成本统计信息。 + +```bash +opencode stats +``` + +#### 旗幟 + +|旗幟|描述 | +| ----------- | --------------------------------------------------------------------------- | +| `--days` | 显示过去N天(所有时间)的统计数据| +| `--tools` | 显示工具数量(全部)| +| `--models` | 隐藏显示模型使用情况解读(默认)。输入一个数字来显示前 N | +| `--project` |按项目过滤(所有项目,空字符串:当前项目)| + +--- + +### 出口 + +将会话数据导出为JSON。 + +```bash +opencode export [sessionID] +``` + +如果您不提供会话 ID,系统将提示您从可用的会话中进行选择。 + +--- + +### 進口 + +从 JSON 文件或 OpenCode 共享 URL 导入会话数据。 + +```bash +opencode import +``` + +您可以从本地文件或 OpenCode 共享 URL 导入。 + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### 網絡 + +使用Web界面启动无头OpenCode服务器。 + +```bash +opencode web +``` + +这将启动HTTP服务器并打开Web浏览器以通过Web界面访问OpenCode。设置`OPENCODE_SERVER_PASSWORD`以启用HTTP基本身份验证(用户名默认为`opencode`)。 + +#### 旗幟 + +|旗幟|描述 | +| ------------ | ------------------------------------------ | +| `--port` |监听端口| +| `--hostname` | 监听的主机名 | +| `--mdns` | 启用 mDNS 发现 | +| `--cors` | 允许 CORS 的其他浏览器源 | + +--- + +### 丙烯酰胺 + +启动ACP(代理客户端协议)服务器。 + +```bash +opencode acp +``` + +此启动一个ACP服务器,该服务器使用nd-JSON通过stdin/stdout进行通信命令。 + +#### 旗幟 + +|旗幟|描述 | +| ------------ | --------------------- | +| `--cwd` |工作目录 | +| `--port` |监听端口| +| `--hostname` | 监听的主机名 | + +--- + +### 解除安裝 + +卸载OpenCode并删除所有相关文件。 + +```bash +opencode uninstall +``` + +#### 旗幟 + +|旗幟|短|描述 | +| --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` |保留配置文件| +| `--keep-data` | `-d` | 保留会话数据和快照| +| `--dry-run` | |在显示不删除的情况下将删除的内容 | +| `--force` | `-f` | 跳过确认提示 | + +--- + +### 升級 + +将 opencode 更新到最新版本或特定版本。 + +```bash +opencode upgrade [target] +``` + +升級到最新版本。 + +```bash +opencode upgrade +``` + +升級到特定版本。 + +```bash +opencode upgrade v0.1.48 +``` + +#### 旗幟 + +|旗幟|短|描述 | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` |使用的安装方法;卷曲、npm、pnpm、bun、brew | + +--- + +## 全球旗幟 + +opencode CLI采用以下全局标志。 + +|旗幟|短|描述 | +| -------------- | ----- | ------------------------------------ | +| `--help` | `-h` | 显示帮助| +| `--version` | `-v` | 打印版本号 | +| `--print-logs` | |将日志打印到stderr | +| `--log-level` | |日志级别(调试、信息、警告、错误)| + +--- + +## 環境變量 + +可以使用环境变量配置OpenCode。 + +|變量|類型 |描述 | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` | 布尔 | 自动共享会话 | +| `OPENCODE_GIT_BASH_PATH` |字符串| Windows 上 Git Bash 可执行文件的路径 | +| `OPENCODE_CONFIG` |字符串|配置文件路径 | +| `OPENCODE_CONFIG_DIR` |字符串|配置目录的路径 | +| `OPENCODE_CONFIG_CONTENT` |字符串|内联 json 配置内容 | +| `OPENCODE_DISABLE_AUTOUPDATE` | 布尔 | 取消自动更新检查 | +| `OPENCODE_DISABLE_PRUNE` | 布尔 | 取消数据的裁剪 | +| `OPENCODE_DISABLE_TERMINAL_TITLE` | 布尔 | 取消自动终端标题更新 | +| `OPENCODE_PERMISSION` |字符串|内联 json 权限配置 | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` | 布尔 | 取消默认插件 | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` | 布尔 | 禁用自动 LSP 服务器下载 | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` | 布尔 | 制作实验模型 | +| `OPENCODE_DISABLE_AUTOCOMPACT` |布尔|取消自动上下文压缩| +| `OPENCODE_DISABLE_CLAUDE_CODE` | 布尔 | 禁止从 `.claude` 读取(提示+技巧)| +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` | 布尔 | 禁用读取`~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` | 布尔 | 禁用加载`.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` | 布尔 | 禁止从远程源获取模型 | +| `OPENCODE_FAKE_VCS` |字符串|用于测试目的的假 VCS 成立 | +| `OPENCODE_DISABLE_FILETIME_CHECK` |布尔|取消文件时间检查以进行优化| +| `OPENCODE_CLIENT` |字符串|客户端标识符(默认为`cli`)| +| `OPENCODE_ENABLE_EXA` | 布尔 | 启用 Exa 网络搜索工具 | +| `OPENCODE_SERVER_PASSWORD` |字符串|为 `serve`/`web` 赠送基本身份验证 | +| `OPENCODE_SERVER_USERNAME` |字符串|覆盖基本身份验证用户名(默认`opencode`)| +| `OPENCODE_MODELS_URL` |字符串|用于获取模型配置的自定义 URL | + +--- + +### 實驗性的 + +這些環境變量啟用可能會更改或刪除的實驗性功能。 + +|變量|類型 |描述 | +| ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` | 布尔 | 实现所有实验性功能 | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` | 布尔 | 新增图标发现 | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` | 布尔 | 在 TUI 中禁用选择时复制 | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` | 数量 | bash 命令的默认超时(以毫秒为单位) | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` | 数量 | LLM 响应的最大输出令牌 | LLM +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` | 布尔 | 为整个目录启用文件观察器 | +| `OPENCODE_EXPERIMENTAL_OXFMT` |布尔 | 启用 oxfmt 清理程序 | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` | 布尔 | 实现实验性 LSP 工具 | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` | 布尔 | 禁用文件观察器 | +| `OPENCODE_EXPERIMENTAL_EXA` |布尔 | 实现实验性Exa功能 | +| `OPENCODE_EXPERIMENTAL_LSP_TY` |布尔 | 实现实验性 LSP 类型检查 | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` | 布尔 | 实现实验性 Markdown 功能 | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` |布尔 |启用计划模式 | diff --git a/packages/web/src/content/docs/zh-cn/commands.mdx b/packages/web/src/content/docs/zh-cn/commands.mdx new file mode 100644 index 000000000..a80aa9258 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/commands.mdx @@ -0,0 +1,323 @@ +--- +title: 命令 +description: 為重複任務創建自定義命令。 +--- + +自定义命令允许您指定在 TUI 中执行该命令时要运行的提示。 + +```bash frame="none" +/my-command +``` + +除了`/init`、`/undo`、`/redo`、`/share`、`/help`等内置命令之外,还有自定义命令。 [了解更多](/docs/tui#commands)。 + +--- + +## 創建命令文件 + +在`commands/`目录中创建markdown文件来定义自定义命令。 + +创建`.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +frontmatter 定义命令属性。内容成为模板。 + +通過鍵入 `/` 後跟命令名稱來使用該命令。 + +```bash frame="none" +"/test" +``` + +--- + +## 配置 + +您可以通过 OpenCode 配置或通过在 `commands/` 目录中创建 markdown 文件来添加自定义命令。 + +--- + +### JSON + +在 OpenCode [配置](/docs/config) 中使用 `command` 选项: + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +现在您可以在 TUI 中运行这个命令: + +```bash frame="none" +/test +``` + +--- + +### 降價 + +您还可以使用 Markdown 文件定义命令。将它们放入: + +- 全球:`~/.config/opencode/commands/` +- 每个项目:`.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Markdown 文件名成为命令名。例如,`test.md` 让 +你運行: + +```bash frame="none" +/test +``` + +--- + +## 提示配置 + +自定義命令的提示支持幾個特殊的佔位符和語法。 + +--- + +### 論據 + +使用`$ARGUMENTS`占位符将参数提交给命令。 + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +使用參數運行命令: + +```bash frame="none" +/component Button +``` + +`$ARGUMENTS` 将替换为 `Button`。 + +您還可以使用位置參數訪問各個參數: + +- `$1` - 第一個參數 +- `$2` - 第二個參數 +- `$3` - 第三個參數 +- 等等... + +例如: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +運行命令: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +這取代了: + +- `$1` 与 `config.json` +- `$2` 与 `src` +- `$3` 与 `{ "key": "value" }` + +--- + +### 外殼輸出 + +使用 _!`command`_ 将 [bash命令](/docs/tui#bash-commands) 输出注入到提示符中。 + +例如,要創建分析測試覆蓋率的自定義命令: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +或者查看最近的更改: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +命令在項目的根目錄中運行,其輸出成為提示的一部分。 + +--- + +### 文件參考 + +使用 `@` 後跟文件名將文件包含在命令中。 + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +文件內容會自動包含在提示中。 + +--- + +## 選項 + +讓我們詳細看看配置選項。 + +--- + +### 模板 + +`template` 选项定义执行命令时将发送到 LLM 的提示。 + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +這是一個**必需的**配置選項。 + +--- + +### 描述 + +使用 `description` 选项提供命令功能的简要描述。 + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +当您输入命令时,这将在 TUI 中显示为描述。 + +--- + +### 代理人 + +使用`agent`配置选择指定哪个[代理人](/docs/agents)应执行此命令。 +如果是 [子代理](/docs/agents/#subagents) 该命令将默认触发子代理调用。 +要取消此行为,则将`subtask`设置为`false`。 + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +這是一個**可選**配置選項。如果未指定,則默認為您當前的代理。 + +--- + +### 子任務 + +使用`subtask`布尔值强制命令触发[子代理](/docs/agents/#subagents)调用。 +如果您希望命令不污染您的主要上下文並且將**強制**代理充當子代理,那麼這非常有用, +即使`mode`在[代理人](/docs/agents)配置上设置为`primary`。 + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +這是一個**可選**配置選項。 + +--- + +### 模型 + +使用 `model` 配置覆盖此命令的默认模型。 + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +這是一個**可選**配置選項。 + +--- + +## 內建 + +opencode包含`/init`、`/undo`、`/redo`、`/share`、`/help`等内置命令;【了解更多](/docs/tui#commands)。 + +:::笔记 +自定義命令可以覆蓋內置命令。 +::: + +如果您定義同名的自定義命令,它將覆蓋內置命令。 diff --git a/packages/web/src/content/docs/zh-cn/config.mdx b/packages/web/src/content/docs/zh-cn/config.mdx new file mode 100644 index 000000000..12322a569 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/config.mdx @@ -0,0 +1,685 @@ +--- +title: 配置 +description: 使用 OpenCode JSON 配置。 +--- + +您可以使用 JSON 配置文件配置 OpenCode。 + +--- + +## 格式 + +OpenCode 支持 **JSON** 和 **JSONC**(带注释的 JSON)格式。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## 地點 + +您可以將配置放置在幾個不同的位置,它們有一個 +不同的優先順序。 + +:::笔记 +配置文件**合併在一起**,而不是替換。 +::: + +配置文件被合併在一起,而不是被替換。以下配置位置的設置被合併。僅當密鑰衝突時,後面的配置才會覆蓋前面的配置。保留所有配置中的非衝突設置。 + +例如,如果您的全局配置设置`theme: "opencode"`和`autoupdate: true`,并且您的项目配置设置ZZPH最终2ZZ,则配置将包括所有三个设置。 + +--- + +### 優先順序 + +配置源按以下順序加載(後面的源覆蓋前面的源): + +1. **远程配置**(来自`.well-known/opencode`)-组织默认值 +2. **全局配置** (`~/.config/opencode/opencode.json`) - 用户首选项 +3. **自定义配置** (`OPENCODE_CONFIG` env var) - 自定义覆盖 +4. **项目配置**(项目中的`opencode.json`)- 项目特定的设置 +5. **`.opencode` 目录** - 代理、命令、插件 +6. **内联配置** (`OPENCODE_CONFIG_CONTENT` env var) - 运行时覆盖 + +這意味著項目配置可以覆蓋全局默認值,全局配置可以覆蓋遠程組織默認值。 + +:::笔记 +`.opencode` 和`~/.config/opencode` 目录对子目录使用**复数名称**:`agents/`、`commands/`、`modes/`、`plugins/`、`skills/`、`tools/` 和`themes/`。为了坚固兼容,还支持单数名称(例如`agent/`)。 +::: + +--- + +### 偏僻的 + +组织可以通过 `.well-known/opencode` 端点提供默认配置。当您向支持的成功进行身份验证时,会自动获取该信息。 + +首先加載遠程配置,作為基礎層。所有其他配置源(全局、項目)都可以覆蓋這些默認值。 + +例如,如果您的组织提供默认取消的 MCP 服务器: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +您可以在本地配置中啟用特定服務器: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### 全球的 + +将全局 OpenCode 配置放在 `~/.config/opencode/opencode.json` 中。使用全局配置来实现用户范围的首选项,例如主题、提供程序或按键绑定。 + +全局配置覆蓋遠程組織默認值。 + +--- + +### 每個項目 + +在项目根目录中添加`opencode.json`。项目配置在标准配置文件中具有最高优先级 - 它覆盖全局配置和远程配置。 + +:::提示 +將項目特定配置放在項目的根目錄中。 +::: + +当OpenCode启动时,它会在当前目录中查找配置文件或打开到最近的Git目录。 + +这也可以安全地签入 Git 并使用与全局模式相同的模式。 + +--- + +### 自定義路徑 + +使用 `OPENCODE_CONFIG` 环境变量指定自定义配置文件路径。 + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +自定義配置按優先順序在全局配置和項目配置之間加載。 + +--- + +### 自定義目錄 + +使用`OPENCODE_CONFIG_DIR`指定自定义配置目录 +環境變量。將在該目錄中搜索代理、命令、 +模式和插件类似于标准`.opencode`目录一样,并且应该 +遵循相同的結構。 + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +自定义目录在全局配置和`.opencode`目录加载后,因此**可以覆盖**它们的设置。 + +--- + +## 模式 + +配置文件具有在 [**`opencode.ai/config.json`**](https://opencode.ai/config.json) 中配置的架构。 + +您的編輯器應該能夠根據架構進行驗證和自動完成。 + +--- + +### 途易 + +您可以通过 `tui` 选项配置特定于 TUI 的设置。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +可用選項: + +- `scroll_acceleration.enabled` - 启用 macOS 风格的滚动加速。 **优先于`scroll_speed`。 ** +- `scroll_speed` - 自定义滚动速度倍增(默认值:`3`,简单:`1`)。如果`scroll_acceleration.enabled`是`true`,则忽略。 +- `diff_style` - 控制差异渲染。 `"auto"` 适应宽度,`"stacked"` 始终显示单列。 + +[在此处了解有关使用 TUI 的更多信息](/docs/tui)。 + +--- + +### 伺服器 + +您可以通过`server` 选项为`opencode serve` 和`opencode web` 命令配置服务器设置。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +可用選項: + +- Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. +- Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. +- `mdns` - 启用 mDNS 服务发现。这允许网络上的其他设备发现您的 OpenCode 服务器。 +- `mdnsDomain` - mDNS 服务的自定义域名。默认为 `opencode.local`。对于在同一个网络上运行多个实例很有用。 +- `cors` - 从基于浏览器的客户端使用 HTTP 服务器时允许 CORS 的其他来源。值必须是完整来源(方案+主机+任选端口),例如 `https://app.example.com`。 + +[在此处了解有关服务器的更多信息](/docs/server)。 + +--- + +### 工具 + +您可以通过 `tools` 选项管理法学硕士可以使用的工具。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[在此处了解有关工具的更多信息](/docs/tools)。 + +--- + +### 型號 + +您可以通过 `provider`、`model` 和 `small_model` 选项来配置要在 OpenCode 配置中使用的提供的程序和模型。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +`small_model` 选项为标题生成等轻量级任务配置单独的模型。默认情况下,如果您的成功可以提供更便宜的模型,OpenCode 会尝试使用更便宜的模型,否则它会退回到您的主模型。 + +Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - 请求超时以毫秒为单位(默认值:300000)。设置为 `false` 以禁用。 +- `setCacheKey` -确保始终为指定的提供者设置存储硬盘。 + +您还可以配置[本地模型](/docs/models#local)。[了解更多](/docs/models)。 + +--- + +#### 特定於提供商的選項 + +有些提供程序支持除通用 `timeout` 和 `apiKey` 之外的其他配置选项。 + +##### 亞馬遜基岩 + +Amazon Bedrock 支持 AWS 特定配置: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. +- `profile` - 来自 `~/.aws/credentials` 的 AWS 命名配置文件(默认为 `AWS_PROFILE` env var) +- `endpoint` - VPC 终端节点的自定义节点 URL。这是使用 AWS 特定术语的通用 `baseURL` 选项的别名。如果两者都指定,`endpoint` 优先。 + +:::笔记 +承载令牌(`AWS_BEARER_TOKEN_BEDROCK` 或`/connect`)优先于基于配置文件的身份验证。详情请参见【认证优先级](/docs/providers#authentication-precedence)。 +::: + +[了解有关 Amazon Bedrock 配置的更多信息](/docs/providers#amazon-bedrock)。 + +--- + +### 主題 + +您可以通过 OpenCode 配置中配置中的 `theme` 选项要使用的主题。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[在这里了解更多](/docs/themes)。 + +--- + +### 代理商 + +您可以通过 `agent` 选项为特定任务配置专用代理。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +您还可以使用 `~/.config/opencode/agents/` 或 `.opencode/agents/` 中的 markdown 文件定义代理。 [在这里了解更多](/docs/agents)。 + +--- + +### 默認代理 + +您可以使用 `default_agent` 选项默认设置代理。当没有明确指定时,这将确定使用哪个代理。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + +此设置适用于所有界面:TUI、CLI (`opencode run`)、桌面应用程序和 GitHub Action。 + +--- + +### 分享 + +您可以通过`share`选项配置[分享](/docs/share)功能。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +這需要: + +- Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. +- `"auto"` - 自动分享新对话 +- `"disabled"` - 完全禁用共享 + +默认情况下,共享设置为手动模式,您需要使用 `/share` 命令显式共享对话。 + +--- + +### 命令 + +您可以通过`command`选项为重复任务配置自定义命令。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +您还可以使用 `~/.config/opencode/commands/` 或 `.opencode/commands/` 中的 Markdown 文件定义命令。 [在这里了解更多](/docs/commands)。 + +--- + +### 按鍵綁定 + +您可以通过 `keybinds` 选项自定义您的按键绑定。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[在这里了解更多](/docs/keybinds)。 + +--- + +### 自動更新 + +OpenCode 将在启动时自动下载任何新的更新。您可以使用 `autoupdate` 选项取消此功能。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +如果您不想更新但希望在新版本可用时收到通知,则需将`autoupdate`设置为`"notify"`。 +请注意,这仅在未使用 Homebrew 等包管理器安装时才有效。 + +--- + +### 格式化程序 + +您可以通过`formatter`选项配置代码初始化程序。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + +--- + +### 權限 + +默认情况下,opencode **允许所有操作**,无需明确批准。您可以使用 `permission` 选项更改此设置。 + +例如,要确保 `edit` 和 `bash` 工具需要用户批准: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[在此处了解有关权限的更多信息](/docs/permissions)。 + +--- + +### 壓實 + +您可以通过 `compaction` 选项控制上下文压缩行为。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. +- `prune` - 删除旧工具以输出保存令牌(默认值:`true`)。 + +--- + +### 守望者 + +您可以通过`watcher`选项配置文件观察器忽略模式。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +模式遵循 glob 语法。使用它可以从文件监视中排除杂的目录。 + +--- + +### MCP服务器 + +您可以通过 `mcp` 选项配置要使用的 MCP 服务器。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[在这里了解更多](/docs/mcp-servers)。 + +--- + +### 插件 + +[插件](/docs/plugins) 使用自定义工具、挂钩和集成扩展 OpenCode。 + +将插件文件放置在`.opencode/plugins/` 或`~/.config/opencode/plugins/` 中。您还可以通过 `plugin` 选项从 npm 加载插件。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[在这里了解更多](/docs/plugins)。 + +--- + +### 指示 + +您可以通过 `instructions` 选项配置您正在使用的型号的说明。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +這需要指令文件的路徑和全局模式數組。 [了解更多 +关于规则在这里](/docs/rules)。 + +--- + +### 殘疾服務提供者 + +您可以通过 `disabled_providers` 选项取消自动加载的提供程序。当您想要阻止加载某些提供程序(即使其可用)时,这非常有用。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::笔记 +`disabled_providers` 优先于`enabled_providers`。 +::: + +`disabled_providers` 选项接受提供者 ID 内存。当提供者被取消时: + +- 即使設置了環境變量也不會加載。 +- 即使通过`/connect`命令配置API钥匙,也不会加载它。 +- 提供商的型號不會出現在型號選擇列表中。 + +--- + +### 啟用的提供商 + +Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +当您想要限制 OpenCode 仅使用特定的提供程序而不是一一禁止它们时,这非常有用。 + +:::笔记 +`disabled_providers` 优先于`enabled_providers`。 +::: + +如果有人提供程序同时出现在`enabled_providers`和`disabled_providers`中,则`disabled_providers`优先考虑一致性。 + +--- + +### 實驗性的 + +`experimental` 键包含正在积极开发的选项。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::警告 +實驗選項不穩定。它們可能會更改或被刪除,恕不另行通知。 +::: + +--- + +## 變量 + +您可以在配置文件中使用變量替換來引用環境變量和文件內容。 + +--- + +### 環境變量 + +使用`{env:VARIABLE_NAME}`替换环境变量: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +如果未設置環境變量,它將被替換為空字符串。 + +--- + +### 文件 + +Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +文件路徑可以是: + +- 相對於配置文件目錄 +- 或者以 `/` 或 `~` 開頭的絕對路徑 + +這些對於: + +- 将API等敏感数据保存在单独的文件中。 +- 包含大型指令文件,而不會弄亂您的配置。 +- 跨多個配置文件共享通用配置片段。 diff --git a/packages/web/src/content/docs/zh-cn/custom-tools.mdx b/packages/web/src/content/docs/zh-cn/custom-tools.mdx new file mode 100644 index 000000000..6e47a81df --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: 定制工具 +description: 創建法學碩士可以在開放代碼中調用的工具。 +--- + +自定义工具是您创建的函数,LLM 可以在对话期间调用。它们与 opencode 的[内置工具](/docs/tools) 一起工作,例如 `read`、`write` 和 `bash`。 + +--- + +## 創建工具 + +工具定义为 **TypeScript** 或 **JavaScript** 文件。但是,工具定义调用可以使用 **任何语言** 编写的脚本 - TypeScript 或 JavaScript 仅用于工具定义本身。 + +--- + +### 地點 + +它們可以定義為: + +- 通过将它们放在项目的 `.opencode/tools/` 目录中来本地进行。 +- Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + +--- + +### 結構 + +创建工具最简单的方法是使用 `tool()` 帮助程序,它提供类型安全和验证。 + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +**文件名**成为**工具名称**。以上创建了一个 `database` 工具。 + +--- + +#### 每個文件多個工具 + +您還可以從單個文件導出多個工具。每個導出都會成為**一個單獨的工具**,名稱為**`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +这将创建两个工具:`math_add` 和 `math_multiply`。 + +--- + +### 論據 + +您可以使用`tool.schema`(即[佐德](https://zod.dev))来定义参数类型。 + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +您还可以直接导入[佐德](https://zod.dev)并返回一个普通对象: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### 情境 + +工具接收有關當前會話的上下文: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +使用 `context.directory` 作为会话工作目录。 +使用 `context.worktree` 作为 git 工作树根。 + +--- + +## 示例 + +### 用Python编写一个工具 + +您可以使用任何您想要的语言编写工具。下面是一个使用 Python 将两个数字相加的示例。 + +首先,使用创建 Python 脚本的工具: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +然後創建調用它的工具定義: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +这里我们使用 [`Bun.$`](https://bun.com/docs/runtime/shell) 实用程序来运行 Python 脚本。 diff --git a/packages/web/src/content/docs/zh-cn/ecosystem.mdx b/packages/web/src/content/docs/zh-cn/ecosystem.mdx new file mode 100644 index 000000000..8d440ef97 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: 生態系統 +description: 使用 OpenCode 构建的项目和集成。 +--- + +基于 OpenCode 的社区项目集合。 + +:::笔记 +想要将您的 OpenCode 相关项目添加到此列表中吗?提交 PR。 +::: + +您还可以查看[很棒的开放代码](https://github.com/awesome-opencode/awesome-opencode)和[开放代码缓存](https://opencode.cafe),这是一个聚合生态系统和社区的社区。 + +--- + +## 插件 + +|名稱 |描述 | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [Opencode-Daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) | 在隔离的 Daytona 沙箱中自动运行 OpenCode 会话 | 使用 git 同步和实时预览 +| [opencode-helicone-会话](https://github.com/H2Shami/opencode-helicone-session) |自动注入 Helicone 会话标头以进行请求包 | +| [打开代码类型注入](https://github.com/nick-vi/opencode-type-inject) |使用查找工具将 TypeScript/Svelte 类型自动注入到文件读取中 | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | 使用您的 ChatGPT Plus/Pro 订阅而不是 API 积分 | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) |使用您现有的 Gemini 计划而不是 API 设备 | +| [opencode-反重力-auth](https://github.com/NoeFabris/opencode-antigravity-auth) |使用反重力的免费模型代替API | +| [opencode-devcontainers 开放代码开发容器](https://github.com/athal7/opencode-devcontainers) | 具有浅克隆和自动分配端口的多分支开发容器隔离 | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Antigravity OAuth 插件,支持 Google 搜索和更强大的 API 处理 | +| [opencode-动态宽度修剪](https://github.com/Tarquinen/opencode-dynamic-context-pruning) |通过修剪过时的工具输出来优化代币使用| +| [opencode-websearch-引用](https://github.com/ghoulr/opencode-websearch-cited.git) | 为具有Google接地风格的受支持增加本机网络搜索支持| +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) |使AI代理能够在PTY中运行后台进程,末端发送其交互输入。 +| [opencode-shell-策略](https://github.com/JRedeker/opencode-shell-strategy) |非吸引力 shell 命令说明 - 阻止依赖 TTY 的操作挂起 +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) |使用 Wakatime 跟踪 OpenCode 使用情况 | +| [opencode-md-表清理程序](https://github.com/franlol/opencode-md-table-formatter/tree/main) |清理法学大师生成的降价表| +| [开放代码变形快速应用](https://github.com/JRedeker/opencode-morph-fast-apply) | 使用Morph Fast Apply API和取消编辑标记将代码编辑速度提高10倍 | +| [哦我的开放代码](https://github.com/code-yeongyu/oh-my-opencode) | 后台代理、预构建的LSP/AST/MCP工具、精选代理、兼容Claude代码| +| [开放代码通知器](https://github.com/panta82/opencode-notificator) | OpenCode 会话的桌面通知和声音警报 | OpenCode 会话的桌面通知和声音警报 +| [开放代码通知程序](https://github.com/mohak34/opencode-notifier) | 针对权限、完成和错误事件的桌面通知和声音警报 | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | 基于 OpenCode 上下文的 AI 支持的自动 Zellij 会话命名 | +| [开放代码技巧](https://github.com/zenobi-us/opencode-skillful) | 允许OpenCode代理通过技能发现和注入失败延迟加载提示 | +| [开放代码超级内存](https://github.com/supermemoryai/opencode-supermemory) | 使用超级内存跨会话持久内存| +| [@ZZ​​PH0ZZ](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) |具有視覺註釋和私人/離線共享的交互式計劃審查| +| [@ZZ​​PH0ZZ](https://github.com/spoons-and-mirrors/subtask2) |將開放代碼/命令擴展為具有精細流程控制的強大編排系統 | +| [开放代码调度程序](https://github.com/different-ai/opencode-scheduler) | 使用带 cron 语法的 launchd (Mac) 或 systemd (Linux) 安排重复作业 | +| [微码](https://github.com/vtemian/micode) | 塑造头脑风暴 → 计划 → 实施具有会议连续性的工作流程 | +| [奥克托](https://github.com/vtemian/octto) |用于通过多问题形式进行AI头痛风暴的交互式浏览器UI +| [opencode-后台代理](https://github.com/kdcokenny/opencode-background-agents) | 具有异步委托和上下文持久性的Claude Code风格后台代理 | +| [打开代码通知](https://github.com/kdcokenny/opencode-notify) | OpenCode 的本机操作系统通知 – 了解任务何时完成 | +| [开放代码工作区](https://github.com/kdcokenny/opencode-workspace) | 一堆多代理编排工具 – 16个,组件一次安装 | +| [开放代码工作树](https://github.com/kdcokenny/opencode-worktree) | OpenCode 的零难度 git 工作树 | + +--- + +## 專案 + +|名稱 |描述 | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [木牧](https://github.com/remorses/kimaki) |用于控制 OpenCode 会话的 Discord 机器人,基于 SDK 构建 | +| [开放代码.nvim](https://github.com/NickvanDyke/opencode.nvim) | Neovim 插件,用于编辑器采集提示,基于 API 构建 | +| [门户网站](https://github.com/hosenur/portal) |通过Tailscale/VPN实现OpenCode的移动优先Web UI | +| [打开代码插件模板](https://github.com/zenobi-us/opencode-plugin-template/) |用于构建 OpenCode 插件的模板 | +| [开放代码.nvim](https://github.com/sudo-tee/opencode.nvim) | Neovim opencode 前端 - 基于终端的 AI 编码代理 | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Vercel AI SDK 提供程序,用于通过 @opencode-ai/sdk 使用 OpenCode | +| [开放室](https://github.com/btriapitsyn/openchamber) | OpenCode 的 Web/桌面應用程序和 VS Code 扩展 | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) |在 Obsidian 的 UI 中嵌入 OpenCode 的 Obsidian 插件 | +| [开放式工作](https://github.com/different-ai/openwork) | Claude Cowork 的替代开源方案,由 OpenCode 提供支持 | +| [奥克斯](https://github.com/kdcokenny/ocx) | OpenCode扩展管理器具有可移植、隔离的配置文件。 +| [代码游牧者](https://github.com/NeuralNomadsAI/CodeNomad) | OpenCode 的桌面、Web、移动和远程客户端应用程序 | + +--- + +## 代理商 + +|名稱 |描述 | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [代理](https://github.com/Cluster444/agentic) |用于格式化开发的定价人工智能代理和命令] +| [开放代码代理](https://github.com/darrenhinde/opencode-agents) |用于增强工作流程的配置、提示、代理和插件 | diff --git a/packages/web/src/content/docs/zh-cn/enterprise.mdx b/packages/web/src/content/docs/zh-cn/enterprise.mdx new file mode 100644 index 000000000..eb28c3897 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: 企業 +description: 在您的组织中安全地使用 OpenCode。 +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise 适用于希望确保其代码和数据永远不会离开其基础设施的组织。它可以通过使用与 SSO 和内部 AI 网关集成的集中方式配置来实现此目的。 + +:::笔记 +OpenCode 不存储您的任何代码或上下文数据。 +::: + +要开始使用OpenCode Enterprise: + +1. 與您的團隊進行內部試驗。 +2. **聯繫我們**討論定價和實施選項。 + +--- + +## 審判 + +OpenCode 是开源的,不存储您的任何代码或上下文数据,因此您的开发人员只需 [开始吧](/docs/) 并进行试用。 + +--- + +### 數據處理 + +**OpenCode 不会存储您的代码或上下文数据。 **所有处理都在本地进行或通过直接 API 调用您的 AI 成功。 + +這意味著只要您使用您信任的提供商或內部提供商 +AI网关,您可以安全使用OpenCode。 + +这里唯一需要注意的是可选的 `/share` 功能。 + +--- + +#### 分享對話 + +如果启用用户 `/share` 功能,对话和关联的数据将被发送到我们用于在 opencode.ai 上托管这些共享页面的服务。 + +数据当前通过我们的CDN边缘网络提供服务,并缓存在用户附近的边缘。 + +我們建議您在試用時禁用此功能。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[了解更多关于分享的信息](/docs/share)。 + +--- + +### 代碼所有權 + +**您拥有 OpenCode 生成的所有代码。 ** 没有许可限制或语音报表。 + +--- + +## 定價 + +我們對 OpenCode Enterprise 使用單機模型。如果您有自己的 LLM 網關,我們不會對使用的令牌收取費用。有關定價和實施選項的更多詳細信息,請**聯繫我們**。 + +--- + +## 部署 + +完成试验并准备好使用 OpenCode 后,请访问: +您的組織,您可以**聯繫我們**進行討論 +定價和實施選項。 + +--- + +### 中央配置 + +我们可以将 OpenCode 设置为您的整个组织使用单一的中央配置。 + +这种集中式配置可以与您的 SSO 成功集成,并确保所有用户仅访问您的内部 AI 网关。 + +--- + +### 單點登錄集成 + +通过中央配置,OpenCode 可以与您组织的 SSO 成功集成以进行身份​​​​验证。 + +这使得 OpenCode 能够通过现有的身份管理系统获取内部 AI 网关的凭据。 + +--- + +### 内部AI网关 + +通过中央配置,OpenCode 还可以配置为仅使用您的内部 AI 网关。 + +您还可以取消所有其他人工智能启动,确保所有请求都通过组织批准的基础设施。 + +--- + +### 自託管 + +雖然我們建議禁用共享頁面以確保您的數據永遠不會離開 +您的組織,我們還可以幫助您在您的基礎設施上自行託管它們。 + +目前這已在我們的路線圖上。如果您有興趣,**讓我們知道**。 + +--- + +## 常問問題 + +

+什麼是 OpenCode Enterprise? + +OpenCode Enterprise 适用于希望确保其代码和数据永远不会离开其基础设施的组织。它可以通过使用与 SSO 和内部 AI 网关集成的集中方式配置来实现此目的。 + +
+ +
+如何開始使用 OpenCode Enterprise? + +与您的团队进行内部实验即可。OpenCode 默认情况下不存储您的代码或上下文数据,可以轻松上手。 + +然後**聯繫我們**討論定價和實施選項。 + +
+ +
+企業定價如何運作? + +我們提供按席位企業定價。如果您有自己的 LLM 網關,我們不會對使用的令牌收取費用。如需了解更多詳情,請**聯繫我們**,獲取根據您組織的需求定制的報價。 + +
+ +
+OpenCode Enterprise 保證我的數據安全嗎? + +OpenCode 不存储您的代码或上下文数据。所有处理都在本地进行或通过直接 API 调用您的 AI 工作。通过中央配置和 SSO 集成,您的数据在组织的基础架构中保持安全。 + +
+ +
+我們可以使用自己的私有 NPM 註冊表嗎? + +OpenCode 通过 Bun 的本机 `.npmrc` 文件支持来支持香蕉 npm 肥料。如果您的组织使用了花生,例如 JFrog Artifactory、Nexus 或类似的肥料,请确保开发人员在运行 OpenCode 之前经过身份验证。 + +要使用您的私有註冊表設置身份驗證: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +这将创建带有身份验证详细信息的 `~/.npmrc`。 OpenCode 会自动 +拿起這個。 + +:::警告 +在运行 OpenCode 之前,您必须登录灌木丛。 +::: + +或者,您可以手动配置`.npmrc`文件: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +开发人员必须在运行OpenCode之前登录棉花,以确保从企业种植樱桃。 + +
diff --git a/packages/web/src/content/docs/zh-cn/formatters.mdx b/packages/web/src/content/docs/zh-cn/formatters.mdx new file mode 100644 index 000000000..1f75edc0c --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: 格式化程序 +description: OpenCode 使用特定于语言的清理程序。 +--- + +使用在语言的格式化程序编写或编辑文件后,OpenCode会自动格式化文件。这可以确保生成的代码遵循项目的代码风格。 + +--- + +## 內建 + +OpenCode附带了多个适用于流行语言和框架的内置初始化程序。下面是格式化程序、支持的文件扩展名以及所需的命令或配置选项的列表。 + +|格式化程序|擴展 |要求| +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +|政府| .go | `gofmt` 命令可用 | +|混合| .ex、.exs、.eex、.heex、.leex、.neex、.sface | `mix` 命令可用 | +|更漂亮| .js、.jsx、.ts、.tsx、.html、.css、.md、.json、.yaml 和 [更多的](https://prettier.io/docs/en/index.html) | `package.json` | `prettier` 依赖关系 +|生物群系 | .js、.jsx、.ts、.tsx、.html、.css、.md、.json、.yaml 和 [更多的](https://biomejs.dev/) | `biome.json(c)` 配置文件 | +|之字形 | .zig、.zon | `zig` 命令可用 | +| clang 格式 | .c、.cpp、.h、.hpp、.ino 和 [更多的](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` 配置文件 | +|克特林特 | .kt、.kts | `ktlint` 命令可用 | +|领子 | .py, .pyi | `ruff` 命令可通过配置 | +|生锈 | .rs | `rustfmt` 命令可用 | +| 货物运输 | .rs | `cargo fmt` 命令可用 | +|美丽| .py, .pyi | `uv` 命令可用 | +|鲁博科普 | .rb、.rake、.gemspec、.ru | `rubocop` 命令可用 | +|标准rb | .rb、.rake、.gemspec、.ru | `standardrb` 命令可用 | +| html美化器 | .erb、.html.erb | `htmlbeautifier` 命令可用 | +|空气| .R | `air` 命令可用 | +|飞镖 | .dart | `dart` 命令可用 | +| ocaml 格式 | .ml、.mli | `ocamlformat` 可用命令和 `.ocamlformat` 配置文件 | +|地形 | .tf、.tfvars | `terraform` 命令可用 | +|微光| .gleam | `gleam` 命令可用 | +|尼克斯夫MTT | .nix | `nixfmt` 命令可用 | +| sfmt| .sh、.bash | `shfmt` 命令可用 | +|品脱| .php | `composer.json` | `laravel/pint` 依赖关系 +| oxfmt(实验)| .js、.jsx、.ts、.tsx | `package.json` 和[实验环境指标](/docs/cli/#experimental) | `oxfmt` 依赖关系 +| 奥尔莫鲁 | .hs | `ormolu` 命令可用 | + +因此,如果您的项目的`package.json`或`prettier`,OpenCode将自动使用它。 + +--- + +## 它是如何運作的 + +当OpenCode写入或编辑文件时,它: + +1. 根據所有啟用的格式化程序檢查文件擴展名。 +2. 對文件運行適當的格式化程序命令。 +3. 自動應用格式更改。 + +此過程在後台進行,確保無需任何手動步驟即可維護您的代碼樣式。 + +--- + +## 配置 + +您可以通过 OpenCode 配置中的 `formatter` 部分自定义程序。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +每個格式化程序配置支持以下內容: + +|物業 |類型 |描述 | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` | 布尔 | 将其设置为 `true` 以取消删除程序 | +| `command` |字符串[] | 格式化运行的命令 | +| `environment` |对象|运行格式化程序时要设置的环境变量 | +| `extensions` |字符串[] |此整理程序应处理的文件扩展名 | + +讓我們看一些例子。 + +--- + +### 禁用格式化程序 + +要全局取消**所有**清理程序,然后`formatter`设置为`false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +要取消**特定**删除程序,则`disabled`设置为`true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### 自定義格式化程序 + +您可以覆蓋內置格式化程序或通過指定命令、環境變量和文件擴展名添加新格式化程序: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +命令中的 **`$FILE` 占位符** 将替换为正在格式化的文件的路径。 diff --git a/packages/web/src/content/docs/zh-cn/github.mdx b/packages/web/src/content/docs/zh-cn/github.mdx new file mode 100644 index 000000000..69e8ff443 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: 在 GitHub 问题和拉取请求中使用 OpenCode。 +--- + +OpenCode 与您的 GitHub 工作流程集成。在评论中提及 `/opencode` 或 `/oc`,OpenCode 将在您的 GitHub Actions 运行器中执行任务。 + +--- + +## 特徵 + +- **分类问题**:要求 OpenCode 调查问题并向您解释。 +- **修复和实施**:要求 OpenCode 修复问题或实施功能。将在一个新的分支中工作并提交包含所有更改的 PR。 +- **安全**:OpenCode 在 GitHub 的运行器中运行。 + +--- + +## 安裝 + +在 GitHub 存储库中的项目中运行以下命令: + +```bash +opencode github install +``` + +这将引导您完成安装 GitHub 应用程序、创建工作流程和设置机密。 + +--- + +### 手動設置 + +或者您可以手動設置。 + +1. 错误 500(服务器错误)!!1500。这是一个错误。出现错误。请稍后重试。我们只知道这些。 + + 前往[**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent)。确保它​​已安装在目标存储库上。 + +2. **添加工作流程** + + 将以下工作流程文件添加到存储库中的`.github/workflows/opencode.yml`中。确保在`env`中设置适当的`model`和所需的API按键。 + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. 错误 500(服务器错误)!!1500。这是一个错误。出现错误。请稍后重试。我们只知道这些。 + + 在您的组织或项目的**设置**中,展开左侧的**秘密和变量**,然后选择**操作**。并添加所需的API钥匙。 + +--- + +## 配置 + +- `model`:与 OpenCode 一起使用的模型。采用 `provider/model` 格式。这是**必需的**。 +- `agent`:要使用的代理。必须是一级代理。如果未找到,则从配置回退到 `default_agent` 或 `"build"`。 +- `share`:是否共享OpenCode会话。对于公共存储库,默认为**true**。 +- `prompt`:可选的自定义提示以覆盖默认行为。使用它来自定义 OpenCode 处理请求的方式。 +- `token`:可选的 GitHub 访问令牌,用于执行创建评论、提交更改和打开拉取请求等操作。默认情况下,OpenCode 使用来自 OpenCode GitHub 应用程序的安装访问令牌,因此提交、评论和拉取请求显示为来自应用。 + + 或者,您可以使用 GitHub Action 运行程序的[内置`GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token),而无需安装 OpenCode GitHub 应用程序。只需确保在您的工作流程中所需的权限: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + 错误 500(服务器错误)!!1500。这是一个错误。出现错误。请稍后重试。我们只知道这些。 + +--- + +## 支持的活動 + +OpenCode 可以由以下 GitHub 事件触发: + +|事件類型 |觸發者 |詳情 | +| ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` |对问题或 PR 发表评论 |在评论中提及 `/opencode` 或 `/oc`。 OpenCode 读取上下文并可以创建分支、打开 PR 或回复。 +| `pull_request_review_comment` |对 PR 中的特定代码行进行评论 |在检查代码时提及`/opencode` 或`/oc`。 OpenCode 接收文件路径、行号和 diff 上下文。 | +| `issues` |问题已打开或已编辑|创建或修改问题时自动触发OpenCode。需要`prompt` 输入。 +| `pull_request` | PR 已开启或已更新 |当 PR 打开、同步或重新打开时自动触发 OpenCode。对于自动评论很有用。 +| `schedule` | 基于 Cron 的计划 | 按计划运行 OpenCode。需要 `prompt` 输入。输出进入日志和 PR(没有可评论的问题)。 +| `workflow_dispatch` | 从 GitHub UI 手动触发 |通过“操作”选项卡触发 OpenCode。需要 `prompt` 输入。输出进入日志和 PR。 | + +### 時間表示例 + +按计划运行OpenCode以执行自动化任务: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +对于计划事件,`prompt` 输入是**必需的**,因为没有注释可以从中提取指令。希望计划工作流在没有用户上下文的情况下运行并进行权限检查,因此如果您 OpenCode 创建分支或 PR,工作流必须支持 `contents: write` 和 `pull-requests: write`。 + +--- + +### 拉取請求示例 + +或更新公关时间自动审核: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +对于`pull_request`事件,如果未提供`prompt`,OpenCode将默认审核拉取请求。 + +--- + +### 問題分類示例 + +自動分類新問題。此示例過濾超過 30 天的帳戶以減少垃圾郵件: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +对于 `issues` 事件,`prompt` 输入是**必需的**,因为没有注释可足以提取指令。 + +--- + +## 自定義提示 + +覆盖默认提示,为您的工作流程自定义 OpenCode 的行为。 + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +這對於執行與您的項目相關的特定審查標準、編碼標准或重點領域非常有用。 + +--- + +## 示例 + +以下是如何在 GitHub 中使用 OpenCode 的一些示例。 + +- **解釋一個問題** + + 在 GitHub 问题中添加此评论。 + + ``` + /opencode explain this issue + ``` + + OpenCode 将阅读整个线程,包括所有评论,并回复并提供语音解释。 + +- **解決問題** + + 在 GitHub 问题中,说: + + ``` + /opencode fix this + ``` + + OpenCode 将创建一个新分支,实施更改,并使用更改打开 PR。 + +- **审查 PR 并进行更改** + + 在 GitHub PR 上留下以下评论。 + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + 错误 500(服务器错误)!!1500。这是一个错误。出现错误。请稍后重试。我们只知道这些。 + +- **查看特定代碼行** + + 直接在PR的“文件”选项卡中的代码行上留下评论。OpenCode自动检测文件、行号和差异上下文以提供准确的响应。 + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + 错误 500(服务器错误)!!1500。这是一个错误。出现错误。请稍后重试。我们只知道这些。 + - 正在審查的確切文件 + - 具體代碼行 + - 周围的差异上下文 + - 行號信息 + + 這允許更有針對性的請求,而無需手動指定文件路徑或行號。 diff --git a/packages/web/src/content/docs/zh-cn/gitlab.mdx b/packages/web/src/content/docs/zh-cn/gitlab.mdx new file mode 100644 index 000000000..1fb235b3e --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: 在 GitLab 问题和合并请求中使用 OpenCode。 +--- + +OpenCode 通过 GitLab CI/CD 管道或与 GitLab Duo 与您的 GitLab 工作流程集成。 + +在这两种情况下,OpenCode 都会在您的 GitLab 运行器上运行。 + +--- + +## GitLab。 + +OpenCode 在常规 GitLab 管道中工作。您可以将其构建为管道 [CI](https://docs.gitlab.com/ee/ci/components/) + +在这里,我们使用社区创建的 OpenCode CI/CD 组件 — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode)。 + +--- + +### 特徵 + +- **每个作业使用每个自定义配置**:使用自定义配置目录配置OpenCode,例如`./config/#custom-directory`以启用或禁用OpenCode调用的功能。 +- 错误 500(服务器错误)!!1500。这是一个错误。出现错误。请稍后重试。我们只知道这些。 +- **灵活**:CI 组件支持多种输入来自定义其行为 + +--- + +### 設定 + +1. 将 OpenCode 身份验证 JSON 作为文件类型 CI 环境变量存储在 **设置** > **CI/CD** > **变量** 下。确保将它们标记为“隐藏和隐藏”。 +2. 将以下内容添加到您的 `.gitlab-ci.yml` 文件中。 + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +有关此组件的更多输入和示例[查看文档](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode)。 + +--- + +## 亚搏体育app二人组 + +OpenCode 与您的 GitLab 工作流程集成。 +在评论中提及`@opencode`,OpenCode 将在您的 GitLab CI 管道中执行任务。 + +--- + +### 特徵 + +- **分类问题**:要求 OpenCode 调查问题并向您解释。 +- **修复和实施**:要求OpenCode修复问题或实施功能。 + 它將創建一個新分支並提出包含更改的合併請求。 +- **安全**:OpenCode 在您的 GitLab 运行器上运行。 + +--- + +### 設定 + +OpenCode 在您的 GitLab CI/CD 管道中运行,您需要进行以下设置: + +:::提示 +查看[**GitLab 文档**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) 获取最新说明。 +::: + +1. 配置您的 GitLab 环境 +2. 安装CI/CD +3. 获取AI模型成功 API键 +4. 創建服務帳戶 +5. 配置 CI/CD 变量 +6. 創建一個流配置文件,這是一個示例: + +
+ + Flow configuration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +详细说明可以参考[GitLab CLI 代理文档](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/)。 + +--- + +### 示例 + +以下是如何在 GitLab 中使用 OpenCode 的一些示例。 + +:::提示 +您可以配置使用 `@opencode` 不同的触发主板。 +::: + +- **解釋一個問題** + + 在 GitLab 问题中添加此评论。 + + ``` + @opencode explain this issue + ``` + + OpenCode 将阅读该问题并回复并提供清晰的解释。 + +- **解決問題** + + 在 GitLab 问题中,说: + + ``` + @opencode fix this + ``` + + OpenCode 将创建一个新分支,实施更改,并打开包含更改的合并请求。 + +- **審查合併請求** + + 对 GitLab 合并请求留下以下评论。 + + ``` + @opencode review this merge request + ``` + + OpenCode 将审核合并请求并提供反馈。 diff --git a/packages/web/src/content/docs/zh-cn/ide.mdx b/packages/web/src/content/docs/zh-cn/ide.mdx new file mode 100644 index 000000000..4a2a21e82 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/ide.mdx @@ -0,0 +1,48 @@ +--- +title: 集成開發環境 +description: VS Code、Cursor 等 IDE 的 OpenCode 扩展 +--- + +OpenCode 与 VS Code、Cursor 或任何支持终端的 IDE 集成。只需在终端中运行 `opencode` 即可开始。 + +--- + +## 用法 + +- **快速启动**:使用 `Cmd+Esc` (Mac) 或 `Ctrl+Esc` (Windows/Linux) 在分割终端视图中打开 OpenCode,或者聚焦现有终端会话(如果现有终端会话正在运行)。 +- **新会话**:使用 `Cmd+Shift+Esc` (Mac) 或 `Ctrl+Shift+Esc` (Windows/Linux) 启动新的 OpenCode 终端会话,即使该会话已打开。您还可以单击 UI 中的 OpenCode 按钮。 +- **上下文获取**:自动与OpenCode共享您当前的选择或选项卡。 +- **文件引用快捷方式**:使用`Cmd+Option+K` (Mac) 或`Alt+Ctrl+K` (Linux/Windows) 插入文件引用。例如,`@File#L37-42`。 + +--- + +## 安裝 + +要在 VS Code 和 Cursor、Windsurf、VSCodium 等流行分支上安装 OpenCode: + +1. 打开VS代码 +2. 打開集成終端 +3. 运行 `opencode` - 扩展会自动安装 + +另一方面,如果您想在从 TUI 运行 `/editor` 或 `/export` 时使用自己的 IDE,则需要设置 `export EDITOR="code --wait"`。 [了解更多](/docs/tui/#editor-setup)。 + +--- + +### 手動安裝 + +在扩展市场中搜索**OpenCode**,然后单击**安装**。 + +--- + +### 故障排除 + +如果擴展無法自動安裝: + +- 确定您在集成终止中运行`opencode`。 +- 确认您的 IDE 和 CLI 已安装: + - 对于 VS 代码:`code` 命令 + - 适用字体:`cursor` 命令 + - 对于风帆冲浪:`windsurf` 命令 + - 对于 VSCodium:`codium` 命令 + - 如果,请运行 `Cmd+Shift+P` (Mac) 或 `Ctrl+Shift+P` (Windows/Linux) 并搜索“Shell Command: Install 'code' command in PATH”(或适用于您的 IDE 的没有对应命令) +- 确保 VS Code 能够安装扩展 diff --git a/packages/web/src/content/docs/zh-cn/index.mdx b/packages/web/src/content/docs/zh-cn/index.mdx new file mode 100644 index 000000000..49f3ce4de --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/index.mdx @@ -0,0 +1,359 @@ +--- +title: 簡介 +description: 开始使用OpenCode。 +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**开放代码**](/)是一个开源人工智能编码代理。它可用于基于终端的界面、桌面应用程序或IDE扩展。 + +![具有opencode主题的OpenCode TUI](../../../assets/lander/screenshot.png) + +讓我們開始吧。 + +--- + +#### 先決條件 + +要在终端中使用OpenCode,您需要: + +1. 現代終端模擬器,例如: + - [韦兹术语](https://wezterm.org),跨平台 + - [阿拉克里蒂](https://alacritty.org),跨平台 + - [幽灵般的](https://ghostty.org),Linux 和 macOS + - [ 猫咪](https://sw.kovidgoyal.net/kitty/),Linux 和 macOS + +2. 您想要使用的 LLM 强大的 API 钥匙。 + +--- + +## 安裝 + +安装 OpenCode 最简单的方法是通过安装脚本。 + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +您還可以使用以下命令安裝它: + +- **使用 Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **在 macOS 和 Linux 上使用 Homebrew** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > 我们使用 OpenCode Tap 来获取最新版本。官方 `brew install opencode` 公式由 Homebrew 团队建议,维护频率较低。 + +- **在 Arch Linux 上使用 Paru** + + ```bash + paru -S opencode-bin + ``` + +#### 視窗 + +:::tip[Recommended: 使用 WSL] +为了在 Windows 上获得最佳体验,我们建议使用[适用于 Linux 的 Windows 子系统 (WSL)](/docs/windows-wsl)。它提供了更好的性能并与 OpenCode 的功能完全兼容。 +::: + +- **使用巧克力** + + ```bash + choco install opencode + ``` + +- **使用勺子** + + ```bash + scoop install opencode + ``` + +- **使用 NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **使用米塞** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **使用 Docker** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +目前正在支持在 Windows 上安装 OpenCode 时使用 Bun。 + +您还可以从[发布](https://github.com/anomalyco/opencode/releases) 获取二进制文件。 + +--- + +## 配置 + +借助 OpenCode,您可以通过配置 API 来使用任何 LLM 成功。 + +如果您不熟悉使用 LLM 成功,我们建议使用[开放代码禅](/docs/zen)。 +这是经过 OpenCode 测试和验证的精选模型列表 +團隊。 + +1. 在 TUI 中运行 `/connect` 命令,选择 opencode,然后前往 [opencode.ai/auth](https://opencode.ai/auth)。 + + ```txt + /connect + ``` + +2. 登录,添加您的账单信息,然后复制您的详细 API 密钥。 + +3. 粘贴您的 API 钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +或者,您可以选择其他巨头之一。 [了解更多](/docs/providers#directory)。 + +--- + +## 初始化 + +現在您已經配置了提供程序,您可以導航到一個項目 +你想繼續工作。 + +```bash +cd /path/to/project +``` + +并运行OpenCode。 + +```bash +opencode +``` + +接下来,通过运行以下命令来初始化项目的 OpenCode。 + +```bash frame="none" +/init +``` + +这涉及 OpenCode 分析您的项目并在以下位置创建 `AGENTS.md` 文件 +項目根。 + +:::提示 +您应该将项目的 `AGENTS.md` 文件提交到 Git。 +::: + +这有助于 OpenCode 理解项目结构和编码模式 +用過的。 + +--- + +## 用法 + +您现在已准备好使用 OpenCode 来处理您的项目。请轻松询问 +任何事物! + +如果您不熟悉使用 AI 编码代理,以下是一些可能会有所帮助的示例 +幫助。 + +--- + +### 提出問題 + +您可以要求 OpenCode 向您解释代码库。 + +:::提示 +使用`@`鍵模糊搜索工程中的文件。 +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +如果您沒有處理代碼庫的一部分,這會很有幫助。 + +--- + +### 添加功能 + +您可以要求 OpenCode 向您的项目添加新功能。但是我们首先建议要求它制定一个计划。 + +1. **制定計劃** + + OpenCode 有一个*计划模式*,该模式禁止其进行更改和 + 相反,建議*如何*實現該功能。 + + 使用 **Tab** 键切换到它。您会在右下角有一个指示符。 + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + 現在讓我們描述一下我們想要它做什麼。 + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + 您需要为 OpenCode 提供足够的详细信息才能了解您想要的内容。它有帮助 + 就像與團隊中的初級開發人員交談一樣與它交談。 + + :::提示 + 为 OpenCode 提供大量上下文和示例,以帮助其理解您的内容 + 想。 + ::: + +2. **迭代計劃** + + 一旦它為您提供了計劃,您就可以提供反饋或添加更多詳細信息。 + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::提示 + 將圖像拖放到終端中以將其添加到提示中。 + ::: + + OpenCode 可以扫描您提供的任何图像并将其添加到提示中。您可以 + 通過將圖像拖放到終端中來完成此操作。 + +3. **構建功能** + + 一旦您對計劃感到滿意,請切換回*構建模式* + 再次按 **Tab** 键。 + + ```bash frame="none" + + ``` + + 並要求它做出改變。 + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### 做出改變 + +对于更直接的更改,您可以要求 OpenCode 直接构建它 +無需先審查計劃。 + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +您需要确保提供大量详细信息,以便 OpenCode 做出正确的决定 +變化。 + +--- + +### 撤消更改 + +假设您要求 OpenCode 进行一些更改。 + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +但你意識到這不是你想要的。您**可以撤消**更改 +使用 `/undo` 命令。 + +```bash frame="none" +/undo +``` + +OpenCode 现在将恢复您所做的更改并显示您的原始消息 +再次。 + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +您可以从这里调整提示并要求 OpenCode 重试。 + +:::提示 +您可以多次运行 `/undo` 以取消消减更改。 +::: + +或者您**可以使用 `/redo` 命令重做**更改。 + +```bash frame="none" +/redo +``` + +--- + +## 分享 + +您与 OpenCode 的对话可以[与您的 +團隊](/docs/分享)。 + +```bash frame="none" +/share +``` + +這將創建當前對話的鏈接並將其複製到剪貼板。 + +:::笔记 +默認情況下不共享對話。 +::: + +这是带有 OpenCode 的[示例对话](https://opencode.ai/s/4XP1fce5)。 + +--- + +## 定制 + +就是这样!您现在已经是使用 OpenCode 的专家了。 + +要让您成为自己的,我们建议[选择一个主题](/docs/themes)、[自定义交互绑定](/docs/keybinds)、[配置代码整理程序](/docs/formatters)、[创建自定义命令](/docs/commands)或使用[开放代码配置](/docs/config)。 diff --git a/packages/web/src/content/docs/zh-cn/keybinds.mdx b/packages/web/src/content/docs/zh-cn/keybinds.mdx new file mode 100644 index 000000000..b0720c168 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: 按鍵綁定 +description: 自定義您的按鍵綁定。 +--- + +OpenCode 有一个按键绑定列表,您可以通过 OpenCode 配置进行自定义。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## 領袖鑰匙 + +OpenCode 对大多数按键绑定使用 `leader` 键。这可以避免终端中的冲突。 + +默认情况下,`ctrl+x` 是主键,大多数操作要求您先按主键,再按键盘。例如,要开始新会话,请先按 `ctrl+x`,然后按 `n`。 + +您不需要為鍵綁定使用主鍵,但我們建議您這樣做。 + +--- + +## 禁用按鍵綁定 + +您可以通过将按键添加到您的配置中并使用值“none”来取消按键绑定。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## 桌面提示快捷方式 + +OpenCode 桌面应用程序提示输入支持常见的 Readline/Emacs 风格的文本编辑快捷方式。这些是内置的,目前无法通过 `opencode.json` 进行配置。 + +|快捷方式 |行動| +| -------- | ---------------------------------------- | +| `ctrl+a` | 移至当前行起点 | +| `ctrl+e` | 移至当前行尾 | +| `ctrl+b` |将牙刷墨水移动一个字符| +| `ctrl+f` |将光标向前移动一个字符 | +| `alt+b` |将杭州墨水移动一个字| +| `alt+f` |将曼哈顿向前移动一个字 | +| `ctrl+d` |删除光标下的字符| +| `ctrl+k` |尾巴狂奔 | +| `ctrl+u` | 杀至行首 | +| `ctrl+w` |删除前一个单词| +| `alt+d` | 杀死下一个词 | +| `ctrl+t` | 转置字符 | +| `ctrl+g` |取消彈出窗口/中止運行響應 | + +--- + +## Shift+Enter + +默认情况下,某些终端不发送带有 Enter 的修饰配置键。您可能需要将终端发送 `Shift+Enter` 作为转义序列。 + +### Windows终端 + +打开您的`settings.json`: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +将其添加到根级`actions`数据库: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +将其添加到根级`keybindings`数据库: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +保存文件并重新启动Windows终端或打开新选项卡。 diff --git a/packages/web/src/content/docs/zh-cn/lsp.mdx b/packages/web/src/content/docs/zh-cn/lsp.mdx new file mode 100644 index 000000000..4ba61434a --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: LSP服务器 +description: OpenCode 与您的 LSP 服务器集成。 +--- + +OpenCode 与您的语言服务器协议 (LSP) 集成,以帮助 LLM 与您的代码库交互。它使用诊断向法学硕士提供反馈。 + +--- + +## 內建 + +OpenCode附带了多种适用于流行语言的内置LSP服务器: + +| LSP服务器|扩展|要求| +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +|天文 | .astro | Astro 项目自动安装 | +| bash | .sh、.bash、.zsh、.ksh | 自动安装bash-语言- 服务器 | +|叮叮| .c、.cpp、.cc、.cxx、.c++、.h、.hpp、.hh、.hxx、.h++ |自动安装 C/C++ 项目 | +|夏普| .cs | `.NET SDK` 已安装 | +| Clojure-lsp | 语言.clj、.cljs、.cljc、.edn | `clojure-lsp` 命令可用 | +|飞镖 | .dart | `dart` 命令可用 | +| 给定 | .ts、.tsx、.js、.jsx、.mjs | `deno`命令可用(自动检测deno.json/deno.jsonc)| +|长生不老药-LS | .ex、.exs | `elixir` 命令可用 | +|埃斯林特 | .ts、.tsx、.js、.jsx、.mjs、.cjs、.mts、.cts、.vue | `eslint` 项目中的依赖项 | +|锐利 | .fs、.fsi、.fsx、.fsscript | `.NET SDK` 已安装 | +|微光| .gleam | `gleam` 命令可用 | +|男生们| .go | `go` 命令可用 | +| HLS | .hs、.lhs | `haskell-language-server-wrapper` 命令可用 | +| jdtls| .java | `Java SDK (version 21+)` 已安装 | +| kotlin-ls | .kt、.kts | Kotlin 项目的自动安装 | +| lua-ls | .lua |自动安装 Lua 项目 | +|尼克斯 | .nix | `nixd` 命令可用 | +| ocaml-lsp | .ml、.mli | `ocamllsp` 命令可用 | +|奥克斯林特 | .ts、.tsx、.js、.jsx、.mjs、.cjs、.mts、.cts、.vue、.astro、.svelte | `oxlint` 项目中的依赖项 | +| php intelephense | php php .php | PHP 项目的自动安装 | +|棱镜| .prisma | `prisma` 命令可用 | +|皮赖特| .py, .pyi | `pyright` 依赖项已安装 | +| ruby​​-lsp(rubocop)| .rb、.rake、.gemspec、.ru | `ruby` 和 `gem` 命令可用 | +|生锈| .rs | `rust-analyzer` 命令可用 | +|源套件-lsp | .swift、.objc、.objcpp | `swift` 已安装(`xcode` 在 macOS 上)| +|苗条| .svelte | Svelte 项目的自动安装 | +| 立场 | .tf、.tfvars | 从 GitHub 版本自动安装 | +|微雾| .typ、.typc | 来自 GitHub 版本自动安装 | +| 稿件 | 稿件.ts、.tsx、.js、.jsx、.mjs、.cjs、.mts、.cts | `typescript` 项目中的依赖项 | +| 视图 | .vue | Vue 项目自动安装 | +| yaml-ls | .yaml、.yml |自动安装 Red Hat yaml-language-server | +|中立 | .zig、.zon | `zig` 命令可用 | + +当检测到上述文件扩展名之一并且满足要求时,LSP服务器将自动启用。 + +:::笔记 +您可以通过将`OPENCODE_DISABLE_LSP_DOWNLOAD`环境变量设置为`true`来取消自动LSP服务器下载。 +::: + +--- + +## 它是如何運作的 + +当opencode打开一个文件时,它: + +1. 根据所有启用的 LSP 服务器检查文件扩展名。 +2. 如果尚未运行,则启动相应的LSP服务器。 + +--- + +## 配置 + +您可以通过opencode配置中的`lsp`部分自定义LSP服务器。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +每个LSP服务器支持以下功能: + +|物業 |類型 |描述 | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` |布尔 |将其设置为`true`以禁用LSP服务器| +| `command` |字符串[] |启动LSP服务器的命令| +| `extensions` |字符串[] |此 LSP 服务器应处理的文件扩展名 | +| `env` |对象|启动服务器时设置的环境变量| +| `initialization` |对象|发送到LSP服务器的初始化选项| + +讓我們看一些例子。 + +--- + +### 環境變量 + +启动LSP服务器时使用`env`参数设置环境变量: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### 初始化選項 + +使用`initialization`属性将初始化选项传递给LSP服务器。这些是在LSP `initialize`请求发送期间的服务器特定设置: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::笔记 +初始化选项因 LSP 服务器而异。检查 LSP 服务器的文档以获得可用选项。 +::: + +--- + +### 取消LSP服务器 + +要全局取消**所有** LSP服务,其中`lsp`设置为`false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +要取消**特定** LSP服务器,使`disabled`设置为`true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### 自定义 LSP 服务器 + +您可以通过指定命令和文件扩展名来添加自定义LSP服务器: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## 附加信息 + +### PHP 英特尔芬斯 + +PHP Intelephense 通过许可证密钥提供高级功能。您可以通过将(仅)密钥挂钩位于以下位置的文本文件中来提供许可证密钥: + +- 在 macOS/Linux 上:`$HOME/intelephense/licence.txt` +- 在 Windows 上:`%USERPROFILE%/intelephense/licence.txt` + +該文件應僅包含許可證密鑰,不包含其他內容。 diff --git a/packages/web/src/content/docs/zh-cn/mcp-servers.mdx b/packages/web/src/content/docs/zh-cn/mcp-servers.mdx new file mode 100644 index 000000000..56fc8a6c9 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: MCP服务器 +description: 添加本地和远程MCP工具。 +--- + +您可以使用“模型上下文协议”或MCP将外部工具添加到OpenCode。OpenCode支持本地和远程服务器。 + +添加使用后,MCP工具将自动与内置工具一起供法学硕士。 + +--- + +#### 注意事項 + +当您使用 MCP 服务器时,它会添加到上下文中。如果您有很多工具,这会很快增加。因此,我们建议您选择使用哪些 MCP 服务器。 + +:::提示 +MCP服务器会添加到您的上下文中,因此您需要小心启用哪些服务器。 +::: + +某些MCP服务器(例如GitHub MCP服务器)往往会添加大量代币,并且很容易超出上下文限制。 + +--- + +## 使能夠 + +您可以在`mcp`下的[开放代码配置](https://opencode.ai/docs/config/)中定义MCP服务器。为每个MCP添加唯一的名称。当提示LLM时,您可以通过名称引用该MCP。 + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +您还可以通过将`enabled`设置为`false`来取消服务器。如果您想暂时取消服务器而不将其从配置中删除,这非常有用。 + +--- + +### 覆蓋遠程默認值 + +组织可以通过其 `.well-known/opencode` 端点提供默认的 MCP 服务器。这些服务器可能默认被禁用,允许用户选择他们需要的服务器。 + +要从组织的远程特定启用服务器,请使用配置 `enabled: true` 将其添加到本地配置: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +您的本地配置值会覆盖远程默认值。有关更多详细信息,请参阅[配置优先级](/docs/config#precedence-order)。 + +--- + +## 當地的 + +使用`type`将本地MCP服务器添加到MCP对像中的`"local"`。 + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +该命令是本地MCP服务器的启动方式。您还可以确定环境变量列表。 + +例如,以下是添加测试 [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP 服务器的方法。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +要使用它,我可以将 `use the mcp_everything tool` 添加到我的提示中。 + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### 選項 + +以下是配置本地 MCP 服务器的所有选项。 + +|選項|類型 |必填 |描述 | +| ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` |字符串|是| MCP 服务器连接类型,必须是`"local"`。 +| `command` | 数据库 | 是 | 运行 MCP 服务器的命令和参数。 +| `environment` |对象| |运行服务器时设置的环境变量。 +| `enabled` | 布尔 | |在启动时启用或禁用MCP 服务器。 +| `timeout` | 数量 | |从MCP服务器获取工具的超时(以毫秒为单位)。默认为5000(5秒)。 | + +--- + +## 偏僻的 + +通过将`type`设置为ZZPH1Z添加远程MCP服务器。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` 是远程MCP服务器的URL,使用`headers`选项您可以创建标头列表。 + +--- + +#### 選項 + +|選項|類型 |必填 |描述 | +| --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` |字符串|是| MCP 服务器连接类型,必须是`"remote"`。 +| | `url` |字符串|是|远程MCP服务器的URL。 +| `enabled` | 布尔 | |在启动时启用或禁用MCP 服务器。 +| `headers` |对象| |随请求一起发送的标头。 +| `oauth` |对象| | OAuth 身份验证。请参阅下面的配置[开放认证](#oauth) 部分。 | +| `timeout` | 数量 | |从MCP服务器获取工具的超时(以毫秒为单位)。默认为5000(5秒)。 | + +--- + +## 開放認證 + +OpenCode自动处理远程MCP服务器的OAuth身份验证。当服务器需要身份验证时,OpenCode将: + +1. 检测 401 响应并启动 OAuth 流程 +2. 如果服务器支持,请使用**动态客户端注册 (RFC 7591)** +3. 安全地存儲令牌以供將來的請求 + +--- + +### 自動的 + +对于大多数支持 OAuth 的 MCP 配置服务器,不需要特殊配置。只需远程服务器: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +如果服務器需要身份驗證,OpenCode 將在您第一次嘗試使用它時提示您進行身份驗證。如果沒有,您可以使用 `opencode mcp auth `[手動觸發流量](#authenticating)。 + +--- + +### 預登記 + +如果您有来自MCP服务器强大的客户端,则可以配置它们: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### 正在驗證 + +您可以手動觸發身份驗證或管理憑據。 + +使用特定MCP服务器进行身份验证: + +```bash +opencode mcp auth my-oauth-server +``` + +列出所有MCP服务器及其身份验证状态: + +```bash +opencode mcp list +``` + +刪除存儲的憑據: + +```bash +opencode mcp logout my-oauth-server +``` + +`mcp auth` 命令将打开您的浏览器进行授权。授权后,OpenCode 令牌安全地存储在 `~/.local/share/opencode/mcp-auth.json` 中。 + +--- + +#### 禁用 OAuth + +如果要禁用服务器的自动OAuth(例如,对于使用API密钥的服务器),则`oauth`设置为`false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### OAuth 选项 + +|選項|類型 |描述 | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` |对象\|假| OAuth 配置对象,或 `false` 以取消 OAuth 自动检测。 +| `clientId` |字符串| OAuth 客户端 ID。如果未提供,将尝试动态客户端注册。 | +| `clientSecret` |字符串| OAuth客户端密钥(如果需要授权服务器)。 +| `scope` |字符串|授权期间请求的 OAuth 范围。 + +#### 偵錯 + +如果远程MCP服务器无法进行身份验证,您可以通过以下方式诊断问题: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +`mcp debug`命令显示当前身份验证状态、测试HTTP连接并尝试OAuth发现流程。 + +--- + +## 管理 + +您的 MCP 可以作为 OpenCode 中的工具以及内置工具使用。,您可以像任何其他工具一样通过 OpenCode 配置来管理它们。 + +--- + +### 全球的 + +這意味著您可以全局啟用或禁用它們。 + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +我们还可以使用 glob 模式来取消所有匹配的 MCP。 + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +这里我们使用 glob 模式 `my-mcp*` 来取消所有 MCP。 + +--- + +### 每個代理人 + +如果您有大量 MCP 服务器,您可以选择为每个代理启用它们并全局取消它们。因此: + +1. 全局禁用它作為工具。 +2. 在您的[代理配置](/docs/agents#tools)中,启用MCP作为服务器工具。 + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### 全局模式 + +glob 模式使用简单的正则表达式 globbing 模式: + +- `*` 匹配零个或多个任意字符(例如,`"my-mcp*"` 匹配 `my-mcp_search`、`my-mcp_list` 等) +- `?` 恰好匹配一個字符 +- 所有其他字符均按字面意思匹配 + +:::笔记 +MCP服务器工具以名称服务器作为出口进行注册,要因此禁用服务器的所有工具,只需使用: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## 示例 + +以下是一些常见的 MCP 服务器的示例。如果您想记录其他服务器,您可以提交 PR。 + +--- + +### 哨兵 + +添加[哨兵MCP服务器](https://mcp.sentry.dev)以与您的Sentry项目和问题进行交互。 + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +添加配置后,使用Sentry进行身份验证: + +```bash +opencode mcp auth sentry +``` + +这将打开一个浏览器窗口以完成 OAuth 流程并将 OpenCode 连接到您的 Sentry 账户。 + +通过身份验证后,您可以在提示中使用Sentry工具来查询问题、项目和错误数据。 + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### 背景7 + +添加[Context7 MCP 服务器](https://github.com/upstash/context7) 以搜索文档。 + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +如果您注册了免费帐户,则可以使用 API 轴并获得更高的速率限制。 + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +这里我们假设您设置了 `CONTEXT7_API_KEY` 环境变量。 + +将 `use context7` 添加到提示中以使用 Context7 MCP 服务器。 + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +或者,您可以将类似的内容添加到您的[代理.md](/docs/rules/)。 + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Vercel 的 Grep + +添加 [Vercel 的 Grep](https://grep.app) MCP 服务器正在搜索 GitHub 上的代码片段。 + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +由于我们将 MCP 服务器命名为 `gh_grep`,因此您可以将 `use the gh_grep tool` 添加到提示中以便代理使用它。 + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +或者,您可以将类似的内容添加到您的[代理.md](/docs/rules/)。 + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/zh-cn/models.mdx b/packages/web/src/content/docs/zh-cn/models.mdx new file mode 100644 index 000000000..100091b45 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/models.mdx @@ -0,0 +1,223 @@ +--- +title: 型號 +description: 配置LLM提供者和模型。 +--- + +OpenCode 使用[人工智能软件开发工具包](https://ai-sdk.dev/) 和[模型.dev](https://models.dev) 来支持**75+ LLM 成功**,并且支持运行本地模型。 + +--- + +## 供應商 + +默认情况下会预加载大多数流行的提供程序。如果您已通过 `/connect` 命令添加了提供程序的辅助程序,那么它们将在您启动 OpenCode 时可用。 + +了解有关[提供者](/docs/providers) 的更多信息。 + +--- + +## 選擇型號 + +配置完提供商後,您可以通過輸入以下內容來選擇您想要的型號: + +```bash frame="none" +/models +``` + +--- + +## 推薦型號 + +那裡有很多型號,每週都會有新型號問世。 + +:::提示 +考慮使用我們推薦的模型之一。 +::: + +然而,既擅長生成代碼又擅長工具調用的只有少數。 + +以下是与 OpenCode 配合良好的几个模型,排名不分前面。(这不是好看的列表,也不一定是最新的): + +- GPT 5.2 +- GPT 5.1 法典 +- 近距離工作4.5 +- 克勞德十四行詩 4.5 +- 极小极M2.1 +- 雙子座 3 專業版 + +--- + +## 設置默認值 + +要將其中之一設置為默認模型,您可以在您的 +打開代碼配置。 + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +这里完整的ID是`provider_id/model_id`。例如,如果您使用[开放代码禅](/docs/zen),则您将使用`opencode/gpt-5.1-codex`来表示GPT 5.1 Codex。 + +如果您配置了[定制生产](/docs/providers#custom),则`provider_id` 是配​​置中`provider` 部分的按键,`model_id` 是`provider.models` 中的按键。 + +--- + +## 配置模型 + +您可以通过 config.json 全局配置模型的选项。 + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +在这里,我们为两个内置模型配置全局设置:`gpt-5`(通过 `openai` 提供程序访问时间)和 `claude-sonnet-4-20250514`(通过 `anthropic` 提供程序访问时间)。 +内置结构和型号名称可以在[模型.dev](https://models.dev) 上找到。 + +您还可以为您正在使用的任何代理配置这些选项。代理配置会覆盖此处的所有全局选项。 [了解更多](/docs/agents/#additional)。 + +您還可以定義擴展內置變體的自定義變體。變體允許您為同一模型配置不同的設置,而無需創建重複的條目: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## 變體 + +许多型号支持具有不同配置的多种变体。OpenCode附带了流行建设的内置默认变体。 + +### 內置變體 + +OpenCode 附带了许多重大的默认变体: + +**人擇**: + +- `high` - 高思维预算(默认) +- `max` - 最大预算规划 + +**開放人工智能**: + +因型號而異,但大致如下: + +- `none` - 没有推理 +- `minimal` - 最少的推理工作 +- `low` - 推理工作量低 +- `medium` - 中等推理努力 +- `high` - 高推理能力 +- `xhigh` - 极高的推理能力 + +**谷歌**: + +- `low` - 降低工作量/代幣預算 +- `high` - 更高的努力/代幣預算 + +:::提示 +該列表並不全面。許多其他提供商也有內置的默認值。 +::: + +### 定制變體 + +您可以覆蓋現有變體或添加您自己的變體: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### 循環變體 + +使用按键绑定`variant_cycle`在变体之间快速切换。 [了解更多](/docs/keybinds)。 + +--- + +## 加載模型 + +当OpenCode启动时,它会按以下优先顺序检查模型: + +1. `--model` 或 `-m` 配置命令行标志。格式与文件中的相同:`provider_id/model_id`。 + +2. OpenCode 配置中的模型列表。 + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + 这里的格式是`provider/model`。 + +3. 最後使用的型號。 + +4. 第一個模型使用內部優先級。 diff --git a/packages/web/src/content/docs/zh-cn/modes.mdx b/packages/web/src/content/docs/zh-cn/modes.mdx new file mode 100644 index 000000000..b9c5926d4 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/modes.mdx @@ -0,0 +1,331 @@ +--- +title: 模式 +description: 不同的模式適用於不同的用例。 +--- + +:::警告 +现在通过opencode配置中的`agent`选项配置模式。这 +`mode` 选项现已废弃。 [了解更多](/docs/agents)。 +::: + +opencode 中的模式允许自定义不同的示例行为、工具和提示。 + +它具有兩種內置模式:**構建**和**計劃**。您可以定制 +这些或通过 opencode 配置配置您自己的。 + +您可以在會話期間在模式之間切換或在配置文件中配置它們。 + +--- + +## 內建 + +opencode 有两种内置模式。 + +--- + +### 建造 + +構建是啟用所有工具的**默認**模式。這是開發工作的標準模式,您需要完全訪問文件操作和系統命令。 + +--- + +### 計劃 + +專為規劃和分析而設計的受限模式。在計劃模式下,默認情況下禁用以下工具: + +- `write` - 无法创建新文件 +- `edit` - 无法修改现有文件,位于 `.opencode/plans/*.md` 的用于详细说明计划本身的文件另外 +- `patch` - 无法应用补丁 +- `bash` - 无法执行 shell 命令 + +当您希望人工智能分析代码、建议更改或创建计划而不对代码库进行任何实际修改时,此模式非常有用。 + +--- + +## 交換 + +您可以在会话期间使用 _Tab_ 键在模式之间切换。或者您配置的 `switch_mode` 键绑定。 + +另请参见:[格式化程序](/docs/formatters)相关代码配置的信息。 + +--- + +## 配置 + +您可以自定義內置模式或通過配置創建自己的模式。可以通過兩種方式配置模式: + +### JSON 配置 + +在 `opencode.json` 配置文件中配置模式: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### 降價配置 + +您还可以使用 Markdown 文件定义模式。将它们放入: + +- 全球:`~/.config/opencode/modes/` +- 项目:`.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Markdown 文件名成为模式名称(例如,`review.md` 创建`review` 模式)。 + +讓我們詳細看看這些配置選項。 + +--- + +### 模型 + +使用`model`配置覆盖此模式的默认模型。对于使用针对不同任务优化的不同模型很有用。例如,更快的规划模型、更强大的实施模型。 + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### 溫度 + +使用`temperature`配置控制AI响应的随机性和创造。较低的值使响应更加集中和确定,而较高的值则增加创造力和可变性。 + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +溫度值的範圍通常為 0.0 到 1.0: + +- **0.0-0.2**:非常集中且確定的響應,非常適合代碼分析和規劃 +- **0.3-0.5**:具有一定創造力的平衡響應,適合一般開發任務 +- **0.6-1.0**:更有創意和多樣化的反應,有助於頭腦風暴和探索 + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +如果未指定温度,opencode将使用特定于模型的默认值(大多数模型通常为0,Qwen模型为0.55)。 + +--- + +### 迅速的 + +使用 `prompt` 配置为模式指定自定义系统提示文件。提示文件应包含特定于该模式用途的指令。 + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +該路徑是相對於配置文件所在位置的。所以這適用於 +全局开放代码配置和项目特定配置。 + +--- + +### 工具 + +使用 `tools` 配置控制模式下可用的工具。您可以通过将特定工具设置为 `true` 或 `false` 来启用或禁用特定工具。 + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +如果未指定任何工具,則默認啟用所有工具。 + +--- + +#### 可用工具 + +這裡是所有可以通過模式配置控制的工具。 + +|工具|描述 | +| ----------- | ----------------------- | +| `bash` | 执行shell命令 | +| `edit` | 修改现有文件 | +| `write` |创建新文件 | +| `read` | 读取文件内容 | +| `grep` |搜索文件内容 | +| `glob` |按模式查找文件 | +| `list` | 上市目录内容 | +| `patch` |对文件应用补丁 | +| `todowrite` | 管理待办事项列表 | +| `todoread` |阅读待办事项列表 | +| `webfetch` |获取网页内容 | + +--- + +## 自定義模式 + +您可以通過將自定義模式添加到配置來創建自己的自定義模式。以下是使用這兩種方法的示例: + +### 使用 JSON 配置 + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### 使用 Markdown 文件 + +在`.opencode/modes/`中为项目特定模式创建模式文件,在`~/.config/opencode/modes/`中为全局模式创建模式文件: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### 使用案例 + +以下是不同模式的一些常見用例。 + +- **構建模式**:啟用所有工具的完整開發工作 +- **計劃模式**:分析和計劃,無需更改 +- **審閱模式**:使用只讀訪問權限和文檔工具進行代碼審閱 +- **调试模式**:专注于启用bash和读取工具的调查 +- **文檔模式**:使用文件操作但不使用系統命令的文檔編寫 + +您可能還會發現不同的模型適用於不同的用例。 diff --git a/packages/web/src/content/docs/zh-cn/network.mdx b/packages/web/src/content/docs/zh-cn/network.mdx new file mode 100644 index 000000000..d00cfa5d6 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/network.mdx @@ -0,0 +1,57 @@ +--- +title: 網絡 +description: 配置代理和自定義證書。 +--- + +OpenCode支持企业网络环境的标准代理环境变量和自定义证书。 + +--- + +## 代理人 + +OpenCode 尊重标准代理环境变量。 + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::警告 +TUI 与本地 HTTP 服务器通信。您必须绕过此连接的代理以防止路由循环。 +::: + +您可以使用[CLI 标志](/docs/cli#run)配置服务器的端口和主机名。 + +--- + +### 認證 + +如果您的代理需要基本身份验证,请在 URL 中包含凭据。 + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::警告 +避免對密碼進行硬編碼。使用環境變量或安全憑證存儲。 +::: + +对于需要高级身份验证(例如 NTLM 或 Kerberos)的代理,请考虑使用支持您的身份验证方法的 LLM 网关。 + +--- + +## 定制證書 + +如果您的企业使用自定义 CA 进行 HTTPS 连接,请配置 OpenCode 以信任它们。 + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +这适用于代理连接和直接 API 访问。 diff --git a/packages/web/src/content/docs/zh-cn/permissions.mdx b/packages/web/src/content/docs/zh-cn/permissions.mdx new file mode 100644 index 000000000..c9dbd23a3 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: 權限 +description: 控制哪些操作需要批准才能運行。 +--- + +OpenCode 使用`permission` 配置来决定给定的操作是否应自动运行、提示您或被阻止。 + +从 `v1.1.1` 开始,旧版配置 `tools` 布尔已被废弃,并已合并到 `permission` 中。仍支持旧版的 `tools` 配置以实现平滑兼容。 + +--- + +## 行動 + +每個權限規則解析為以下之一: + +- `"allow"` — 尚未批准运行 +- `"ask"` — 提示批准 +- `"deny"` — 阻止该操作 + +--- + +## 配置 + +您可以全局設置權限(使用`*`),並覆蓋特定工具。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +您還可以一次設置所有權限: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## 粒度規則(對象語法) + +對於大多數權限,您可以使用對像根據工具輸入應用不同的操作。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +規則通過模式匹配進行評估,**最後匹配的規則獲勝**。常見的模式是將包羅萬象的 `"*"` 規則放在前面,然後再放置更具體的規則。 + +### 通配符 + +權限模式使用簡單的通配符匹配: + +- `*` 匹配零個或多個任意字符 +- `?` 恰好匹配一個字符 +- 所有其他字符均按字面意思匹配 + +### 主目錄擴展 + +您可以在模式目录中使用 `~` 或 `$HOME` 来引用您的主目录。这对于 [`external_directory`](#external-directories) 规则特别有用。 + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### 外部目錄 + +使用 `external_directory` 允许工具调用启动 OpenCode 的工作目录之外的路径。这适用于任何采用路径作为输入的工具(例如 `read`、`edit`、`list`、`glob`、`grep` 和许多Z`bash` 命令)。 + +主扩展(如`~/...`)仅影响模式的编写方式。它不会使外部路径成为当前工作空间的一部分,因此仍然必须通过 `external_directory` 允许工作目录之外的路径。 + +例如,这允许访问`~/projects/personal/`下的所有内容: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +这里允许的任何目录都会继承与当前工作空间默认相同的值。自[`read`默认为`allow`](#defaults)起,也允许读取`external_directory`下面的边界,除非被覆盖。当工具应在这些路径中时添加显式规则,例如在保留读取的同时阻止编辑: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +将列表重点放在受信任的路径上,并根据其他工具的需要分层额外的允许或拒绝规则(例如`bash`)。 + +--- + +## 可用權限 + +OpenCode权限由工具名称和一些安全防护措施决定: + +- `read` — 读取文件(与文件路径匹配) +- `edit` — 所有文件修改(头部`edit`、`write`、`patch`、`multiedit`) +- `glob` — 文件通配符(匹配通配符模式) +- `grep` — 内容搜索(匹配正则表达式模式) +- `list` — 上市目录中的文件(与目录路径匹配) +- `bash` — 运行 shell 命令(匹配 `git status --porcelain` 等解析命令) +- `task` — 启动子代理(与子代理类型匹配) +- `skill` — 加载技能(与技能名称匹配) +- `lsp` — 运行 LSP 查询(当前非粒度) +- `todoread`、`todowrite` — 讀取/更新待辦事項列表 +- `webfetch` — 获取 URL(与 URL 匹配) +- `websearch`、`codesearch` — 網頁/代碼搜索(与查询匹配) +- `external_directory` — 当工具访问项目工作目录外部的路径时触发 +- `doom_loop` — 当相同的工具调用相同的输入重复 3 次时触发 + +--- + +## 預設值 + +如果您未指定任何内容,OpenCode分散许可的默认值开始: + +- 大部分权限默认为`"allow"`。 +- `doom_loop`和`external_directory`默认为`"ask"`。 +- `read` 是 `"allow"`,但 `.env` 文件默认被拒绝: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## “問”的作用是什麼 + +当 OpenCode 提示批准时,UI 会提供清晰的结果: + +- `once` — 仅批准此请求 +- `always` — 批准与建议模式匹配的未来请求(对于当前 OpenCode 会话的其余部分) +- `reject` — 拒绝请求 + +`always` 将批准的模式集由该工具提供(例如,bash 批准通常将安全端口(如 `git status*`)列入白名单)。 + +--- + +## 代理商 + +您可以覆盖每个代理的权限。代理权限与全局​​配置合并,代理规则优先。 [了解更多](/docs/agents#permissions)关于代理权限。 + +:::笔记 +有关更详细的模式匹配示例,请参见上面的 [粒度规则(对象语法)](#granular-rules-object-syntax) 部分。 +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +您还可以在 Markdown 中配置代理权限: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::提示 +对参数的命令使用模式匹配。 `"grep *"` 允许 `grep pattern file.txt`,而 `"grep"` 单独会阻止它。像 `git status` 这样的命令适用于默认行为,但在传递参数时需要显式许可(如 `"git status *"`)。 +::: diff --git a/packages/web/src/content/docs/zh-cn/plugins.mdx b/packages/web/src/content/docs/zh-cn/plugins.mdx new file mode 100644 index 000000000..e61e18dca --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: 插件 +description: 编写您自己的插件来扩展 OpenCode。 +--- + +插件允许您通过挂钩各种事件和自定义行为来扩展 OpenCode。您可以创建插件来添加新功能、与外部服务集成或修改 OpenCode 的默认行为。 + +例如,查看社区创建的[插件](/docs/ecosystem#plugins)。 + +--- + +## 使用插件 + +有兩種加載插件的方法。 + +--- + +### 從本地文件 + +将 JavaScript 或 TypeScript 文件放置在插件目录中。 + +- `.opencode/plugins/` - 项目级插件 +- `~/.config/opencode/plugins/` - 全局插件 + +這些目錄中的文件會在啟動時自動加載。 + +--- + +### 来自 npm + +在配置文件中指定 npm 包。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +支持常规和范围的 npm 包。 + +浏览[生态系统](/docs/ecosystem#plugins)中的可用插件。 + +--- + +### 插件是如何安裝的 + +**npm 插件** 在启动时使用 Bun 自动安装。包及其依赖项缓存在 `~/.cache/opencode/node_modules/` 中。 + +**本地插件**直接从插件目录加载。要使用外部包,您必须在配置目录中创建`package.json`(请参阅[依赖关系](#dependencies)),或将插件发布到npm和[将其添加到您的配置中](/docs/config#plugins)。 + +--- + +### 加載順序 + +插件從所有源加載,所有掛鉤按順序運行。加載順序為: + +1. 全局配置 (`~/.config/opencode/opencode.json`) +2. 项目配置(`opencode.json`) +3. 插件全局目录 (`~/.config/opencode/plugins/`) +4. 项目插件目录(`.opencode/plugins/`) + +具有相同的名称和版本,但是重复的 npm 包将被加载一次。,本地插件和名称相似的 npm 插件都是分开加载的。 + +--- + +## 創建一個插件 + +插件是一个 **JavaScript/TypeScript 模块多个**,它导出一个或插件 +功能。每個函數接收一個上下文對象並返回一個鉤子對象。 + +--- + +### 依賴關係 + +本地插件和自定义工具可以使用外部 npm 包。将 `package.json` 添加到您的配置目录,其中包含您需要的依赖项。 + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode 在启动时运行 `bun install` 来安装这些。然后你的插件和工具就可以导入它们了。 + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### 基本結構 + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +插件函數接收: + +- `project`:当前项目信息。 +- `directory`:当前工作目录。 +- `worktree`:git 工作树路径。 +- `client`:用于与AI交互的开放代码SDK客户端。 +- `$`:Bun的[外壳API](https://bun.com/docs/runtime/shell)用于执行命令。 + +--- + +### TypeScript 支持 + +对于 TypeScript 插件,您可以从插件包中导入类型: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### 活動 + +插件可以訂閱事件,如下面的示例部分所示。以下是可用的不同事件的列表。 + +#### 命令事件 + +- `command.executed` + +#### 文件事件 + +- `file.edited` +- `file.watcher.updated` + +#### 安裝活動 + +- `installation.updated` + +#### LSP活动 + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### 消息事件 + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### 權限事件 + +- `permission.asked` +- `permission.replied` + +#### 服務器事件 + +- `server.connected` + +#### 會議活動 + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### 都都活動 + +- `todo.updated` + +#### 殼牌活動 + +- `shell.env` + +#### 工具事件 + +- `tool.execute.after` +- `tool.execute.before` + +#### 途易活動 + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## 示例 + +以下是一些可用于扩展 opencode 的插件示例。 + +--- + +### 發送通知 + +當某些事件發生時發送通知: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +我们在 macOS 上使用 `osascript` AppleScript。这里我们用它运行来发送通知。 + +:::笔记 +如果您使用 OpenCode 桌面应用程序,它可以在响应准备就绪或会话错误时自动发送系统通知。 +::: + +--- + +### .env 保护 + +阻止opencode读取`.env`文件: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### 注入環境變量 + +将环境变量注入所有shell执行(AI工具和用户终端): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### 定制工具 + +插件还可以向 opencode 添加自定义工具: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +`tool` 帮助器创建一个可以调用的自定义工具的开放代码。它采用 Zod 模式函数并返回一个工具定义: + +- `description`:该工具的作用 +- `args`:Zod 模式的工具参数 +- `execute`:调用工具时运行的函数 + +您的自定義工具將可與內置工具一起用於開放代碼。 + +--- + +### 記錄 + +使用 `client.app.log()` 而不是 `console.log` 进行成型日志记录: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +级别:`debug`、`info`、`warn`、`error`。详情请参见【SDK文档](https://opencode.ai/docs/sdk)。 + +--- + +### 壓實鉤 + +自定義壓縮會話時包含的上下文: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +`experimental.session.compacting`钩子在LLM生成驱动机之前触发。使用它来填充默认压缩提示会丢失的特定于域的上下文。 + +您还可以通过设置`output.prompt`来完全替换压缩提示: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +当设置`output.prompt`时,它会取代完全默认的压缩提示。在这种情况下,`output.context` 内存将被忽略。 diff --git a/packages/web/src/content/docs/zh-cn/providers.mdx b/packages/web/src/content/docs/zh-cn/providers.mdx new file mode 100644 index 000000000..ea4d40001 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/providers.mdx @@ -0,0 +1,1889 @@ +--- +title: 供應商 +description: 使用 OpenCode 中的任何 LLM 提供程式。 +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode uses the [AI SDK](https://ai-sdk.dev/) and [Models.dev](https://models.dev) to support **75+ LLM providers** and it supports running local models. + +要新增提供商,您需要: + +1. 使用 `/connect` 命令新增提供 API 程序金钥匙。 +2. 在您的 OpenCode 配置中配置提供程式。 + +--- + +### 證書 + +当您使用 `/connect` 命令再次成功的 API 时,它们会被存储 +in `~/.local/share/opencode/auth.json`. + +--- + +### 配置 + +您可以利用 OpenCode 中的 `provider` 部分自定义提供程序 +配置。 + +--- + +#### 基本網址 + +您可以通过设置 `baseURL` 选项来自定义任何提供程序的基本 URL。这在使用代理服务或自定义端点时非常有用。 + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## OpenCode 一代 + +OpenCode Zen 是OpenCode团队提供的模型列表,这些模型已被 +经测试和验证可与OpenCode良好配合。 [了解更多](/docs/zen)。 + +:::提示 +如果您是新手,我们建议您从 OpenCode Zen 开始。 +::: + +1. Run the `/connect` command in the TUI, select opencode, and head to [opencode.ai/auth](https://opencode.ai/auth). + + ```txt + /connect + ``` + +2. 登入,新增您的账单详细信息,然后复制您的 API 金钥匙。 + +3. 贴上您的 API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 在 TUI 中执行 `/models` 以检视我们推荐的型号列表。 + + ```txt + /models + ``` + +它的工作方式与 OpenCode 中的任何其他提供的程序相同,并且完全可以选择使用。 + +--- + +## 目錄 + +讓我們詳細瞭解一些提供商。如果您想將提供商新增到 +列表,请随时开启PR。 + +:::笔记 +在这里没有看到成功?提交 PR。 +::: + +--- + +### 302.艾伊 + +1. Head over to the [302.AI console](https://302.ai/), create an account, and generate an API key. + +2. 执行`/connect`命令并搜索**302.AI**。 + + ```txt + /connect + ``` + +3. 输入您的 302.AI API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择型号。 + + ```txt + /models + ``` + +--- + +### 亞馬遜基岩 + +相当于 Amazon Bedrock 与 OpenCode 结合使用: + +1. 前往 Amazon Bedrock 控制台中的 **模型目录** 并请求 + 訪問您想要的模型。 + + :::提示 + 您需要能够在 Amazon Bedrock 中访问所需的模型。 + ::: + +2. **使用以下方法之一配置身份驗證**: + + #### 環境變數(快速啟動) + + 执行 opencode 时设置以下环境变量之一: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + 或者将它们添加到您的 bash 配置文件中: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### 配置檔案(推薦) + + For project-specific or persistent configuration, use `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **可用選項:** + - `region` - AWS 区域(例如 `us-east-1`、`eu-west-1`) + - `profile` - 来自 `~/.aws/credentials` 的 AWS 命名配置档案 + - `endpoint` - VPC 节点节点的自定义节点 URL(通用 `baseURL` 选项的别名) + + :::提示 + 配置檔案選項優先於環境變數。 + ::: + + #### 高阶:VPC 端点 + + 如果您使用 Bedrock 的 VPC 终端节点: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::笔记 + `endpoint` 选项是通用 `baseURL` 选项的别名,使用 AWS 术语特定。如果同时指定了 `endpoint` 和 `baseURL`,则 `endpoint` 优先。 + ::: + + #### 認證方式 + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**:创建IAM用户并在AWS控制台中生成访问金币。 + - **`AWS_PROFILE`**:使用 `~/.aws/credentials` 中的命名配置文件。首先配置 `aws configure --profile my-profile` 或 `aws sso login` + - **`AWS_BEARER_TOKEN_BEDROCK`**:从 Amazon Bedrock 控制台生成长期 API 金钥匙 + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**:适用于 EKS IRSA(服务账户的 IAM 角色)或具有 OIDC 联合的其他 Kubernetes 环境。使用服务账户注释时,这些环境变量由 Kubernetes 自动注入。 + + #### 認證優先順序 + + Amazon Bedrock 使用以下身份验证优先顺序: + 1. **不记名令牌** - `AWS_BEARER_TOKEN_BEDROCK`环境变化数据或来自`/connect`令牌的令牌 + 2. **AWS 凭证链** - 配置档案、访问金钥、共享凭证、IAM 角色、Web 身份令牌 (EKS IRSA)、实例项后设置资料 + + :::笔记 + 设置不记名令牌(使用 `/connect` 或 `AWS_BEARER_TOKEN_BEDROCK`)时,其优先于所有 AWS 凭证方法(包括配置的配置文件)。 + ::: + +3. 执行`/models`命令选择所需的型号。 + + ```txt + /models + ``` + +:::笔记 +对于自定义推理配置文件,请在按键中使用模型并提供程序名称,并将 `id` 属性设置为 arn。这确保了正确的快取: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### 人择 + +1. 注册后,执行`/connect`命令并选择Anthropic。 + + ```txt + /connect + ``` + +2. 您可以在此处选择 **Claude Pro/Max** 选项,就会打开您的浏览器 + 並要求您進行身份驗證。 + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. 现在,当您使用 `/models` 命令时,所有人类模型都应该可用。 + + ```txt + /models + ``` + +:::信息 +Using your Claude Pro/Max subscription in OpenCode is not officially supported by [Anthropic](https://anthropic.com). +::: + +##### 使用 API 键 + +如果您没有 Pro/Max 订阅,您还可以选择 **建立 API 重要**。它还会开启您的浏览器并要求您登入 Anthropic 并为您提供一个可以粘贴到终端中的程序代码。 + +或者,如果您已安装 API 金钥匙,则可以选择 **手动输入 API 金钥匙** 将其贴到终端中。 + +--- + +### 天蓝色 OpenAI + +:::笔记 +如果遇到“抱歉,但我无法协助该请求”错误,请尝试将 Azure 资源中的内容筛选器从 **DefaultV2** 更改为 **Default**。 +::: + +1. Head over to the [Azure portal](https://portal.azure.com/) and create an **Azure OpenAI** resource. You'll need: + - **资源名称**:这将成为您的 API 端点 (`https://RESOURCE_NAME.openai.azure.com/`) 的一部分 + - **API 金钥匙**:来自您资源的 `KEY 1` 或 `KEY 2` + +2. Go to [Azure AI Foundry](https://ai.azure.com/) and deploy a model. + + :::笔记 + 部署名称必须与型号名称匹配,opencode才能正常工作。 + ::: + +3. 执行 `/connect` 命令并搜索 **Azure**。 + + ```txt + /connect + ``` + +4. 输入您的 API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. 將您的資源名稱設定為環境變數: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + 或者将其新增内容添加到您的 bash 配置文件中: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. 执行 `/models` 命令以选择您部署的模型。 + + ```txt + /models + ``` + +--- + +### Azure 认知服务 + +1. Head over to the [Azure portal](https://portal.azure.com/) and create an **Azure OpenAI** resource. You'll need: + - **资源名称**:这将成为您的 API 端点 (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) 的一部分 + - **API 金钥匙**:来自您资源的 `KEY 1` 或 `KEY 2` + +2. Go to [Azure AI Foundry](https://ai.azure.com/) and deploy a model. + + :::笔记 + 部署名称必须与型号名称匹配,opencode才能正常工作。 + ::: + +3. 执行 `/connect` 命令并搜索 **Azure 认知服务**。 + + ```txt + /connect + ``` + +4. 输入您的 API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. 將您的資源名稱設定為環境變數: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + 或者将其新增内容添加到您的 bash 配置文件中: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. 执行 `/models` 命令以选择您部署的模型。 + + ```txt + /models + ``` + +--- + +### 巴吉度獵犬 + +1. Head over to the [Baseten](https://app.baseten.co/), create an account, and generate an API key. + +2. 执行 `/connect` 命令并搜索 **Baseten**。 + + ```txt + /connect + ``` + +3. 输入您的 Baseten API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择型号。 + + ```txt + /models + ``` + +--- + +### 大腦 + +1. Head over to the [Cerebras console](https://inference.cerebras.ai/), create an account, and generate an API key. + +2. 执行 `/connect` 命令并搜索 **Cerebras**。 + + ```txt + /connect + ``` + +3. 输入您的 Cerebras API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择_Qwen 3 Coder 480B_等型号。 + + ```txt + /models + ``` + +--- + +### Cloudflare AI闸道器 + +Cloudflare AI Gateway lets you access models from OpenAI, Anthropic, Workers AI, and more through a unified endpoint. With [Unified Billing](https://developers.cloudflare.com/ai-gateway/features/unified-billing/) you don't need separate API keys for each provider. + +1. Head over to the [Cloudflare dashboard](https://dash.cloudflare.com/), navigate to **AI** > **AI Gateway**, and create a new gateway. + +2. 将您的账户ID和闸道器ID设定为环境变量。 + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. 执行 `/connect` 命令并搜索 **Cloudflare AI Gateway**。 + + ```txt + /connect + ``` + +4. 输入您的 Cloudflare API 令牌。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + 或者將其設定為環境變數。 + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. 执行`/models`命令选择型号。 + + ```txt + /models + ``` + + 您还可以使用开放代码配置新增模型。 + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### 皮質 + +1. Head over to the [Cortecs console](https://cortecs.ai/), create an account, and generate an API key. + +2. 执行 `/connect` 命令并搜索 **Cortecs**。 + + ```txt + /connect + ``` + +3. 输入您的 Cortecs API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行 `/models` 命令以选择类似 _Kimi K2 Instruct_ 的型号。 + + ```txt + /models + ``` + +--- + +### 深度搜尋 + +1. Head over to the [DeepSeek console](https://platform.deepseek.com/), create an account, and click **Create new API key**. + +2. 执行 `/connect` 命令并搜索 **DeepSeek**。 + + ```txt + /connect + ``` + +3. 输入您的 DeepSeek API 金钥。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令以选择DeepSeek模型,例如_DeepSeek Reasoner_。 + + ```txt + /models + ``` + +--- + +### 深層基礎設施 + +1. Head over to the [Deep Infra dashboard](https://deepinfra.com/dash), create an account, and generate an API key. + +2. 执行 `/connect` 命令并搜索 **Deep Infra**。 + + ```txt + /connect + ``` + +3. 输入您的深层基础设施 API 金钥。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择型号。 + + ```txt + /models + ``` + +--- + +### 韌體 + +1. Head over to the [Firmware dashboard](https://app.firmware.ai/signup), create an account, and generate an API key. + +2. 执行`/connect`命令并搜索**韧体**。 + + ```txt + /connect + ``` + +3. 输入您的韧体API金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择型号。 + + ```txt + /models + ``` + +--- + +### 煙花人工智慧 + +1. Head over to the [Fireworks AI console](https://app.fireworks.ai/), create an account, and click **Create API Key**. + +2. 执行 `/connect` 命令并搜索 **Fireworks AI**。 + + ```txt + /connect + ``` + +3. 输入您的 Fireworks AI API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行 `/models` 命令以选择类似 _Kimi K2 Instruct_ 的型号。 + + ```txt + /models + ``` + +--- + +### GitLab 二人组 + +GitLab Duo 通过 GitLab 的人工代理提供具有本机工具呼叫功能的人工智慧代理聊天。 + +1. 执行`/connect`命令并选择GitLab。 + + ```txt + /connect + ``` + +2. 選擇您的身份驗證方法: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### 使用OAuth(推荐) + + 选择**OAuth**,您的浏览器将开启并进行授权。 + + #### 使用個人訪問令牌 + 1. Go to [GitLab User Settings > Access Tokens](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. 單擊**新增新令牌** + 3. Name: `OpenCode`, Scopes: `api` + 4. 复制令牌(以 `glpat-` 发起人) + 5. 在終端中輸入 + +3. 执行 `/models` 命令检视可用模型。 + + ```txt + /models + ``` + + 提供基于 Claude 的模型: + - **duo-chat-haiku-4-5**(默认)- 快速任务的快速响应 + - **duo-chat-sonnet-4-5** - 大多数工作流程的平衡失败 + - **duo-chat-opus-4-5** - 最有能力进行复杂分析 + +:::笔记 +如果您不愿意,也可以指定“GITLAB_TOKEN”环境变量 +将令牌存储在opencode身份验证存储中。 +::: + +##### 自托管 GitLab + +:::note[合规笔记] +OpenCode 使用一个小模型来执行一些 AI 任务,例如生成会话标题。 +情况下,其配置为使用 gpt-5-nano,由 Zen 托管。默认 OpenCode +只需使用您自己的 GitLab 托管示例项,即可将以下内容添加到您的 +`opencode.json` file. It is also recommended to disable session sharing. + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +对于自托管 GitLab 示例项目: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +如果您的示例项执行自定义AI闸道器: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +或者添加到您的 bash 配置文件中: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::笔记 +您的 GitLab 管理员必须启用以下功能: + +1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) for the user, group, or instance +2. 功能标志(透过Rails控制台): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### 用于自托管项目的 OAuth + +为了使 Oauth 适用于您的自托管项目,您需要建立 +一個新的應用程式(設定→應用程式) +回拨 URL `http://127.0.0.1:8080/callback` 和以下范围: + +- api(您代表访问API) +- read_user(读取您的个人信息) +- read_repository(允许对存储库进行只读访问) + +然后将应用程序ID公开为环境变量: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +More documentation on [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth) homepage. + +##### 配置 + +Customize through `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API 工具(可选,但强烈推荐) + +要访问GitLab工具(合并请求、问题、管道、CI/CD等): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +该外挂提供全面的GitLab存储库管理功能,包括MR审查、问题跟踪、管道监控等。 + +--- + +### GitHub 副驾驶 + +相当于您的 GitHub Copilot 订阅与 opencode 一起使用: + +:::笔记 +某些型号可能需要 [Pro+ +订阅](https://github.com/features/copilot/plans)使用。 + +Some models need to be manually enabled in your [GitHub Copilot settings](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use). +::: + +1. 执行 `/connect` 命令并搜索 GitHub Copilot。 + + ```txt + /connect + ``` + +2. Navigate to [github.com/login/device](https://github.com/login/device) and enter the code. + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. 现在执行 `/models` 命令来选择您想要的型号。 + + ```txt + /models + ``` + +--- + +### 谷歌顶点人工智能 + +Google Vertex AI 与 OpenCode 结合使用: + +1. 前往 Google Cloud Console 中的 **模型花园** 并检查 + 您所在地區提供的型號。 + + :::笔记 + 您需要有一个启用了 Vertex AI API 的 Google Cloud 专案。 + ::: + +2. 設定所需的環境變數: + - `GOOGLE_CLOUD_PROJECT`:您的Google云专案ID + - `VERTEX_LOCATION`(可选):Vertex AI的区域(默认为`global`) + - 身份驗證(選擇一項): + - `GOOGLE_APPLICATION_CREDENTIALS`:服务帐户 JSON 密钥文件的路径 + - 使用 gcloud CLI 进行身份验证:`gcloud auth application-default login` + + 在执行 opencode 时设置它们。 + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + 或者将它们添加到您的 bash 配置文件中。 + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::提示 +The `global` region improves availability and reduces errors at no extra cost. Use regional endpoints (e.g., `us-central1`) for data residency requirements. [Learn more](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. 执行`/models`命令选择所需的型号。 + + ```txt + /models + ``` + +--- + +### 格羅克 + +1. Head over to the [Groq console](https://console.groq.com/), click **Create API Key**, and copy the key. + +2. 执行 `/connect` 命令并搜索 Groq。 + + ```txt + /connect + ``` + +3. 输入结构的API金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令来选择您想要的。 + + ```txt + /models + ``` + +--- + +### 抱臉 + +[Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers) provides access to open models supported by 17+ providers. + +1. Head over to [Hugging Face settings](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) to create a token with permission to make calls to Inference Providers. + +2. 执行 `/connect` 命令并搜索 **拥抱脸**。 + + ```txt + /connect + ``` + +3. 輸入您的擁抱臉標記。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择_Kimi-K2-Instruct_ 或 _GLM-4.6_ 等模型。 + + ```txt + /models + ``` + +--- + +### 螺旋錐 + +[Helicone](https://helicone.ai) is an LLM observability platform that provides logging, monitoring, and analytics for your AI applications. The Helicone AI Gateway routes your requests to the appropriate provider automatically based on the model. + +1. Head over to [Helicone](https://helicone.ai), create an account, and generate an API key from your dashboard. + +2. 执行 `/connect` 命令并搜索 **Helicone**。 + + ```txt + /connect + ``` + +3. 输入您的 Helicone API 金钥。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择型号。 + + ```txt + /models + ``` + +For more providers and advanced features like caching and rate limiting, check the [Helicone documentation](https://docs.helicone.ai). + +#### 可選配置 + +如果您发现Helicone的某些功能或型号未通过opencode自动配置,您始终可以自行配置。 + +Here's [Helicone's Model Directory](https://helicone.ai/models), you'll need this to grab the IDs of the models you want to add. + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### 自定義標頭 + +Helicone 支持快速获取、用户跟踪和会话管理等功能的自定义标头。使用 `options.headers` 将它们添加到您提供的方案配置中: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### 會話跟蹤 + +Helicone's [Sessions](https://docs.helicone.ai/features/sessions) feature lets you group related LLM requests together. Use the [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) plugin to automatically log each OpenCode conversation as a session in Helicone. + +```bash +npm install -g opencode-helicone-session +``` + +將其新增到您的配置中。 + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +该外挂将 `Helicone-Session-Id` 和 `Helicone-Session-Name` 标头注入您的请求中。在 Helicone 的会话页面中,您将看到每个 OpenCode 对话都是单独的会话。 + +##### 常见螺旋接头 + +|標題 |描述 | +| -------------------------- | ------------------------------------------------------------- | +| `Helicone-Cache-Enabled` | Enable response caching (`true`/`false`) | +| `Helicone-User-Id` | 点击用户跟踪指标 | +| `Helicone-Property-[Name]` | 新增自定义属性(例如`Helicone-Property-Environment`)| +| `Helicone-Prompt-Id` |将请求与提示版本相关联 | + +See the [Helicone Header Directory](https://docs.helicone.ai/helicone-headers/header-directory) for all available headers. + +--- + +### 呼叫.cpp + +You can configure opencode to use local models through [llama.cpp's](https://github.com/ggml-org/llama.cpp) llama-server utility + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +在這個例子中: + +- `llama.cpp` 是自定义创建 ID。这可以是您想要的任何字串。 +- `npm` specifies the package to use for this provider. Here, `@ai-sdk/openai-compatible` is used for any OpenAI-compatible API. +- `name` 是 UI 中提供程序的显示名称。 +- `options.baseURL` 是本地服务器器的端点。 +- `models` 是型号 ID 以及配置的对应映射。型号名称将显示在型号选择列表中。 + +--- + +### IO网路 + +IO.NET提供了17种针对各种例子进行优化的模型: + +1. Head over to the [IO.NET console](https://ai.io.net/), create an account, and generate an API key. + +2. 执行`/connect`命令并搜索**IO.NET**。 + + ```txt + /connect + ``` + +3. 输入您的 IO.NET API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择型号。 + + ```txt + /models + ``` + +--- + +### LM工作室 + +您可以通过使用本地模型来使用 LM Studio 配置开放代码。 + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +在這個例子中: + +- `lmstudio` 是自定义创建 ID。这可以是您想要的任何字串。 +- `npm` specifies the package to use for this provider. Here, `@ai-sdk/openai-compatible` is used for any OpenAI-compatible API. +- `name` 是 UI 中提供程序的显示名称。 +- `options.baseURL` 是本地服务器器的端点。 +- `models` 是型号 ID 以及配置的对应映射。型号名称将显示在型号选择列表中。 + +--- + +### 登月人工智慧 + +要使用 Moonshot AI 中的 Kimi K2: + +1. Head over to the [Moonshot AI console](https://platform.moonshot.ai/console), create an account, and click **Create API key**. + +2. 执行 `/connect` 命令并搜索 **Moonshot AI**。 + + ```txt + /connect + ``` + +3. 输入您的 Moonshot API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令以选择_Kimi K2_。 + + ```txt + /models + ``` + +--- + +### 最小最大 + +1. Head over to the [MiniMax API Console](https://platform.minimax.io/login), create an account, and generate an API key. + +2. 执行 `/connect` 命令并搜索 **MiniMax**。 + + ```txt + /connect + ``` + +3. 输入您的 MiniMax API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择_M2.1_等型号。 + + ```txt + /models + ``` + +--- + +### Nebius 代币工厂 + +1. Head over to the [Nebius Token Factory console](https://tokenfactory.nebius.com/), create an account, and click **Add Key**. + +2. 执行`/connect`命令并搜索**Nebius令牌工厂**。 + + ```txt + /connect + ``` + +3. 输入您的 Nebius 令牌工厂 API 金钥。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行 `/models` 命令以选择类似 _Kimi K2 Instruct_ 的型号。 + + ```txt + /models + ``` + +--- + +### 成為 + +您可以使用 Ollama 配置 opencode 本地模型。 + +:::提示 +Ollama can automatically configure itself for OpenCode. See the [Ollama integration docs](https://docs.ollama.com/integrations/opencode) for details. +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +在這個例子中: + +- `ollama` 是自定义创建 ID。这可以是您想要的任何字串。 +- `npm` specifies the package to use for this provider. Here, `@ai-sdk/openai-compatible` is used for any OpenAI-compatible API. +- `name` 是 UI 中提供程序的显示名称。 +- `options.baseURL` 是本地服务器器的端点。 +- `models` 是型号 ID 以及配置的对应映射。型号名称将显示在型号选择列表中。 + +:::提示 +如果工具暂停,请尝试增加 Ollama 中的 `num_ctx`。从 16k - 32k 左右开始。 +::: + +--- + +### 奧拉馬雲 + +相当于 Ollama Cloud 与 OpenCode 一起使用: + +1. 前往 [https://ollama.com/](https://ollama.com/) 并登入或建立账户。 + +2. 导航至**设置** > **金钥匙**,然后单击**添加API金钥匙**以生成新的API金钥匙。 + +3. 复制 API 金钥以在 OpenCode 中使用。 + +4. 执行 `/connect` 命令并搜索 **Ollama Cloud**。 + + ```txt + /connect + ``` + +5. 输入您的 Ollama Cloud API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **重要**:在OpenCode中使用云模型之前,必须将模型信息拉取到本地: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. 执行 `/models` 命令以选择您的 Ollama Cloud 模型。 + + ```txt + /models + ``` + +--- + +### 开放人工智能 + +We recommend signing up for [ChatGPT Plus or Pro](https://chatgpt.com/pricing). + +1. 注册后,执行`/connect`命令并选择OpenAI。 + + ```txt + /connect + ``` + +2. 您可以选择 **ChatGPT Plus/Pro** 选项,就会在这里开启您的浏览器 + 並要求您進行身份驗證。 + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. 现在,当您使用 `/models` 命令时,所有 OpenAI 模型都应该可用。 + + ```txt + /models + ``` + +##### 使用 API 键 + +如果您已安装 API 金钥匙,则可以选择 **手动输入 API 金钥匙** 将其贴到终端中。 + +--- + +### OpenCode 一代 + +OpenCode Zen 是 OpenCode 团队提供的经过测试和验证的模型列表。 [了解更多](/docs/zen)。 + +1. 登入 **OpenCode Zen** 並單擊 **建立 API 金鑰**。 + +2. 执行 `/connect` 命令并搜索 **OpenCode Zen**。 + + ```txt + /connect + ``` + +3. 输入您的 OpenCode API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择_Qwen 3 Coder 480B_等型号。 + + ```txt + /models + ``` + +--- + +### 開放路由器 + +1. Head over to the [OpenRouter dashboard](https://openrouter.ai/settings/keys), click **Create API Key**, and copy the key. + +2. 执行`/connect`命令并搜索OpenRouter。 + + ```txt + /connect + ``` + +3. 输入结构的API金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 默认情况下预加载了多个OpenRouter模型,执行`/models`命令选择您想要的模型。 + + ```txt + /models + ``` + + 您还可以通过开放代码配置添加其他模型。 + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. 您还可以使用开放代码配置自定义它们。这是指定的示例 + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP人工智慧核心 + +SAP AI Core跨统一平台提供对OpenAI、Anthropic、Google、Amazon、Meta、Mistral和AI21的40多个模型的访问。 + +1. Go to your [SAP BTP Cockpit](https://account.hana.ondemand.com/), navigate to your SAP AI Core service instance, and create a service key. + + :::提示 + The service key is a JSON object containing `clientid`, `clientsecret`, `url`, and `serviceurls.AI_API_URL`. You can find your AI Core instance under **Services** > **Instances and Subscriptions** in the BTP Cockpit. + ::: + +2. 执行`/connect`命令并搜索**SAP AI Core**。 + + ```txt + /connect + ``` + +3. 输入您的服务金号JSON。 + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + 或者设置`AICORE_SERVICE_KEY`环境变量: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + 或者将其新增内容添加到您的 bash 配置文件中: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. (可选)设置部署ID和资源组: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::笔记 + 这些设置是可选的,应根据 SAP AI Core 设置进行配置。 + ::: + +5. 执行 `/models` 命令从 40 个多个可用型号中进行选择。 + + ```txt + /models + ``` + +--- + +### OVHcloud AI 端点 + +1. Head over to the [OVHcloud panel](https://ovh.com/manager). Navigate to the `Public Cloud` section, `AI & Machine Learning` > `AI Endpoints` and in `API Keys` tab, click **Create a new API key**. + +2. 执行 `/connect` 命令并搜索 **OVHcloud AI 端点**。 + + ```txt + /connect + ``` + +3. 输入您的 OVHcloud AI 端点 API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择_gpt-oss-120b_等型号。 + + ```txt + /models + ``` + +--- + +### 斯卡威 + +To use [Scaleway Generative APIs](https://www.scaleway.com/en/docs/generative-apis/) with Opencode: + +1. Head over to the [Scaleway Console IAM settings](https://console.scaleway.com/iam/api-keys) to generate a new API key. + +2. 执行 `/connect` 命令并搜索 **Scaleway**。 + + ```txt + /connect + ``` + +3. 输入您的Scaleway API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行 `/models` 命令选择 _devstral-2-123b-instruct-2512_ 或 _gpt-oss-120b_ 等模型。 + + ```txt + /models + ``` + +--- + +### 一起人工智慧 + +1. Head over to the [Together AI console](https://api.together.ai), create an account, and click **Add Key**. + +2. 执行 `/connect` 命令并搜索 **Together AI**。 + + ```txt + /connect + ``` + +3. 输入您的Together AI API金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行 `/models` 命令以选择类似 _Kimi K2 Instruct_ 的型号。 + + ```txt + /models + ``` + +--- + +### 威尼斯人工智慧 + +1. Head over to the [Venice AI console](https://venice.ai), create an account, and generate an API key. + +2. 执行 `/connect` 命令并搜索 **Venice AI**。 + + ```txt + /connect + ``` + +3. 输入您的威尼斯 AI API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择_Llama 3.3 70B_等型号。 + + ```txt + /models + ``` + +--- + +### Vercel人工智慧闸道器 + +Vercel AI Gateway 可以让您跨统一端点访问来自 OpenAI、Anthropic、Google、xAI 等的模型。型号按标价提供,不加价。 + +1. Head over to the [Vercel dashboard](https://vercel.com/), navigate to the **AI Gateway** tab, and click **API keys** to create a new API key. + +2. 执行 `/connect` 命令并搜索 **Vercel AI Gateway**。 + + ```txt + /connect + ``` + +3. 输入您的 Vercel AI 网关 API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择型号。 + + ```txt + /models + ``` + +您还可以穿透 opencode 配置自定义模型。以下是指定提供者路由顺序的示例。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +一些有用的路由選項: + +|選項 |描述 | +| ------------------- | ---------------------------------------------------- | +| `order` |提供者尝试顺序| +| `only` |限制特定提供商 | +| `zeroDataRetention` |仅使用零资料保留的政策| + +--- + +### 人工智慧 + +1. Head over to the [xAI console](https://console.x.ai/), create an account, and generate an API key. + +2. 执行 `/connect` 命令并搜索 **xAI**。 + + ```txt + /connect + ``` + +3. 输入您的 xAI API 金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行 `/models` 命令来选择类似 _Grok Beta_ 的模型。 + + ```txt + /models + ``` + +--- + +### 扎艾 + +1. Head over to the [Z.AI API console](https://z.ai/manage-apikey/apikey-list), create an account, and click **Create a new API key**. + +2. 执行 `/connect` 命令并搜索 **Z.AI**。 + + ```txt + /connect + ``` + + 如果您订阅了**GLM编码计划**,请选择**Z.AI编码计划**。 + +3. 输入您的 Z.AI API 金钥。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 执行`/models`命令选择_GLM-4.7_等模型。 + + ```txt + /models + ``` + +--- + +### 多路復用器 + +1. Head over to the [ZenMux dashboard](https://zenmux.ai/settings/keys), click **Create API Key**, and copy the key. + +2. 执行 `/connect` 命令并搜索 ZenMux。 + + ```txt + /connect + ``` + +3. 输入结构的API金钥匙。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 默认情况下预加载了多个 ZenMux 模型,执行 `/models` 命令选择您想要的模型。 + + ```txt + /models + ``` + + 您还可以通过开放代码配置添加其他模型。 + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## 定製提供商 + +要新增 `/connect` 命令中未列出的任何 **OpenAI 相容**提供程式: + +:::提示 +您可以将任何 OpenAI 相容的提供方案与 opencode 一起使用。大多数人工现代智慧工厂都提供 OpenAI 相容 API。 +::: + +1. 执行`/connect`命令并逐步升级到**其他**。 + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. 输入企业的唯一ID。 + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::笔记 + 选择一个容易记住的 ID,您将在配置文件中使用它。 + ::: + +3. 输入您的事业的 API 金钥。 + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. Create or update your `opencode.json` file in your project directory: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + 以下是配置選項: + - **npm**:要使用AI的SDK包,`@ai-sdk/openai-compatible`用于OpenAI相容的事业 + - **名称**:UI中的显示名称。 + - **型號**:可用型號。 + - **options.baseURL**:API 端点 URL。 + - **options.apiKey**:如果不使用身份验证,可以选择设置API金钥匙。 + - **options.headers**:可选择设置自定义标头。 + + 有關高階選項的更多資訊,請參見下面的示例。 + +5. 执行 `/models` 命令,您提供的自定义程序和模型将出现在选择列表中。 + +--- + +##### 例子 + +以下是设置 `apiKey`、`headers` 和模型 `limit` 选项的示例。 + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +配置詳情: + +- **apiKey**:使用`env`变数语法[了解更多](/docs/config#env-vars)设置。 +- ** headers **:随每个请求传送的自定义标头。 +- **limit.context**:模型接受的最大输入标记。 +- **limit.output**:模型可以生成的最大令牌。 + +`limit` 栏位允许 OpenCode 了解您还剩下多少上下文。标准成功会自动从 models.dev 中提取这些内容。 + +--- + +## 故障排除 + +如果您在配置提供商時遇到問題,請檢查以下內容: + +1. **Check the auth setup**: Run `opencode auth list` to see if the credentials + 提供商的配置已新增到您的配置中。 + + 这并不利于 Amazon Bedrock 等依赖环境变数进行身份验证的工作。 + +2. 对于自定义提供的程序,请检查 opencode 配置并: + - 确保 `/connect` 命令中使用的提供方案 ID 与 opencode 配置中的 ID 匹配。 + - 正确的 npm 包用于提供程序。例如,对 Cerebras 使用 `@ai-sdk/cerebras`。对于所有其他 OpenAI 相内容的提供程序,请使用 `@ai-sdk/openai-compatible`。 + - 检查 `options.baseURL` 栏位中使用的 API 端点是否正确。 diff --git a/packages/web/src/content/docs/zh-cn/rules.mdx b/packages/web/src/content/docs/zh-cn/rules.mdx new file mode 100644 index 000000000..e4ae46a97 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/rules.mdx @@ -0,0 +1,180 @@ +--- +title: 規則 +description: 設置開放代碼的自定義指令。 +--- + +您可以通过 `AGENTS.md` 文件创建 opencode 的自定义指令。这和 Cursor 的规则类似。它包含将包含在 LLM 上下文中的说明,方便您的特定项目自定义其行为。 + +--- + +## 初始化 + +要创建新的`AGENTS.md`文件,您可以在opencode中运行`/init`命令。 + +:::提示 +您应该将项目的 `AGENTS.md` 文件提交到 Git。 +::: + +这将扫描您的项目及其所有内容,以了解该项目的内容并生成一个 `AGENTS.md` 文件。这有助于更好地打开代码导航项目。 + +如果您已有现有的 `AGENTS.md` 文件,将尝试添加到其中。 + +--- + +## 例子 + +您也可以手动创建此文件。以下是您可以导入 `AGENTS.md` 文件中的一些内容的示例。 + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +我們在此處添加特定於項目的說明,這將在您的團隊中共享。 + +--- + +## 類型 + +opencode 还支持从多个位置读取 `AGENTS.md` 文件。这有不同的目的。 + +### 專案 + +将 `AGENTS.md` 放置在项目根目录中以获取特定于项目的规则。这些仅适用于您在此目录或子目录中工作时。 + +### 全球的 + +您还可以在 `~/.config/opencode/AGENTS.md` 文件中包含全局规则。这适用于所有开放代码会话。 + +由于此未提交给 Git 或与您的团队共享,因此我们建议使用它来指定 LLM 应遵循的任何个人规则。 + +### 克勞德代碼兼容性 + +Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + +- **项目规则**:项目目录中的`CLAUDE.md`(如果`AGENTS.md`不存在则使用) +- **全局规则**:`~/.claude/CLAUDE.md`(如果不存在`~/.config/opencode/AGENTS.md`则使用) +- **技能**:`~/.claude/skills/` — 详情请参见[代理技巧](/docs/skills/) + +要取消Claude Code兼容性,请设置以下环境变量之一: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## 優先級 + +当opencode启动时,它会按以下顺序查找规则文件: + +1. **本地文件**,从当前目录向上浏览(`AGENTS.md`,`CLAUDE.md`) +2. **全局文件** `~/.config/opencode/AGENTS.md` +3. **克劳德代码文件**位于`~/.claude/CLAUDE.md`(禁用禁用) + +第一个匹配的文件每个在类别中触发。例如,如果您同时拥有`AGENTS.md`和`CLAUDE.md`,则仅使用`AGENTS.md`。同样,`~/.config/opencode/AGENTS.md`优先于`~/.claude/CLAUDE.md`。 + +--- + +## 定制說明 + +您可以在 `opencode.json` 或全局 `~/.config/opencode/opencode.json` 中指定自定义指令文件。这允许您和您的团队重用现有规则,而不必将它们复制到 AGENTS.md。 + +例子: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +您还可以使用远程URL从Web加载说明。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +遠程指令的獲取有 5 秒的超時時間。 + +所有说明文件均与您的`AGENTS.md`文件合并。 + +--- + +## 引用外部文件 + +虽然opencode不会自动解析`AGENTS.md`中的文件引用,但您可以通过两种方式实现类似的功能: + +### 使用 opencode.json + +推荐的方法是在`opencode.json`中使用`instructions`字段: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### AGENTS.md 中的手册说明 + +您可以通过在 `AGENTS.md` 中明确提供的指令来教 opencode 读取外部文件。这是一个实际的示例: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +這種方法允許您: + +- 創建模塊化、可重用的規則文件 +- 通过符号链接或git子模块在项目之间共享规则 +- 保持 AGENTS.md 简洁,同时参考详细指南 +- 确保opencode仅在特定任务需要时加载文件 + +:::提示 +对于 monorepos 或具有共享标准的项目,使用 `opencode.json` 和 glob 模式(如 `packages/*/AGENTS.md`)比手动指令更易于维护。 +::: diff --git a/packages/web/src/content/docs/zh-cn/sdk.mdx b/packages/web/src/content/docs/zh-cn/sdk.mdx new file mode 100644 index 000000000..4d2e33839 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: 軟體開發工具包 +description: opencode 服务器的类型不同于安全 JS 客户端。 +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +opencode JS/TS SDK 提供类型其他安全的客户端用于与服务器交互。 +使用它以程序设计方式构建集成和控制开放代码。 + +[了解更多关于服务器如何工作的](/docs/server)。例如,检视社区构建的[projects](/docs/ecosystem#projects)。 + +--- + +## 安裝 + +从npm安装SDK: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## 建立客戶端 + +创建opencode的示例项: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +這會同時啟動伺服器和客戶端 + +#### 選項 + +|選項|型別 |描述 |預設| +| ---------- | ------------- | ------------------------------ | ----------- | +| `hostname` | `string` | 服务器主机名 | `127.0.0.1` | +| `port` | `number` |伺服器埠 | `4096` | +| `signal` | `AbortSignal` | 取消的中止讯号 | `undefined` | +| `timeout` | `number` | 服务器启动超时(以毫秒为单位)| `5000` | +| `config` | `Config` |放置的财产 | `{}` | + +--- + +## 配置 + +You can pass a configuration object to customize behavior. The instance still picks up your `opencode.json`, but you can override or add configuration inline: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## 僅限客戶 + +如果您已经有 opencode 的正在执行示例项,则可以创建一个客户端示例项来连线到它: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### 選項 + +|選項|型別 |描述 |預設 | +| --------------- | ---------- | -------------------------------- | ----------------------- | +| `baseUrl` | `string` |伺服器的 URL | `http://localhost:4096` | +| `fetch` | `function` |习俗获取实现| `globalThis.fetch` | +| `parseAs` | `string` |响应解析方法| `auto` | +| `responseStyle` | `string` | 返回样式:`data` 或 `fields` | `fields` | +| `throwOnError` | `boolean` | 掷骰错误而不是返回 | `false` | + +--- + +## 型別 + +SDK 包括所有 API 型以外的 TypeScript 定义。直接汇入其中: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +所有型別均根據伺服器的 OpenAPI 規範生成,並可在 型別檔案 中找到。 + +--- + +## 錯誤 + +SDK 可能会丢掷错误,您可以捕获并处理这些错误: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## 蜜蜂 + +SDK跨越型别安全客户端公开所有服务器API。 + +--- + +### 全球的 + +|方法|描述 |回應 | +| ----------------- | ------------------------------- | ------------------------------------ | +| `global.health()` |检查服务器健康状况和版本 | `{ healthy: true, version: string }` | + +--- + +#### 示例 + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### 應用程式 + +|方法|描述 |回應 | +| -------------- | ------------------------- | ------------------------------------------- | +| `app.log()` | 登录日志 | `boolean` | +| `app.agents()` |列出所有可用的代理 | 代理[] | + +--- + +#### 示例 + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### 專案 + +|方法|描述 |回應 | +| ------------------- | ------------------- | --------------------------------------------- | +| `project.list()` |列出所有專案 | 專案[] | +| `project.current()` |獲取當前專案 | 專案 | + +--- + +#### 示例 + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### 小路 + +|方法|描述 |回應 | +| ------------ | ---------------- | ---------------------------------------- | +| `path.get()` |獲取當前路徑 | 路徑 | + +--- + +#### 示例 + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### 配置 + +|方法|描述 |回應 | +| -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` |獲取配置資訊 | 配置 | +| `config.providers()` |列出提供商和預設模型 | `{ providers: `提供商[]`, default: { [key: string]: string } }` | + +--- + +#### 示例 + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### 會議 + +|方法|描述 |筆記| +| ---------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` |列出會話 |返回 Session[] | +| `session.get({ path })` |獲取會話 |返回 會話 | +| `session.children({ path })` |列出子會話 |返回 Session[] | +| `session.create({ body })` |建立會話 |返回 會話 | +| `session.delete({ path })` | 离开会话 | 返回`boolean` | +| `session.update({ path, body })` |更新會話屬性 |返回 會話 | +| `session.init({ path, body })` | Analyze app and create `AGENTS.md` | Returns `boolean` | +| `session.abort({ path })` |中止正在执行的会话 |返回`boolean` | +| `session.share({ path })` |分享會 |返回 會話 | +| `session.unshare({ path })` |取消共享會話 |返回 會話 | +| `session.summarize({ path, body })` | 会议总结 |返回`boolean` | +| `session.messages({ path })` |列出會話中的訊息 |返回 `{ info: `訊息`, parts: `部分[]`}[]` | +| `session.message({ path })` |獲取訊息詳情 |返回 `{ info: `訊息`, parts: `部分[]`}` | +| `session.prompt({ path, body })` |傳送提示資訊 | `body.noReply: true` 返回 UserMessage(僅限上下文)。預設返回 AssistantMessage 以及 AI 響應 | +| `session.command({ path, body })` |向會話傳送命令 |返回 `{ info: `AssistantMessage`, parts: `部分[]`}` | +| `session.shell({ path, body })` |執行 shell 命令 |返回 AssistantMessage | +| `session.revert({ path, body })` |回覆訊息 |返回 會話 | +| `session.unrevert({ path })` |恢復已恢復的訊息 |返回 會話 | +| `postSessionByIdPermissionsByPermissionId({ path, body })` |回复许可权限请求 |返回`boolean` | + +--- + +#### 示例 + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### 檔案 + +|方法|描述 |回應 | +| ------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `find.text({ query })` |搜索档案中文字 | 含 `path`、`lines`、`line_number`、`absolute_offset`、`submatches` | 与像团队的匹配 | +| `find.files({ query })` |按名称查询档案和目录 | `string[]`(路径)| +| `find.symbols({ query })` |查詢工作區符號 | 符號[] | +| `file.read({ query })` | 读取档案 | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` |獲取跟蹤檔案的狀態 | 檔案[] | + +`find.files` 支持一些可选的查询栏位: + +- `type`:`"file"` 或 `"directory"` +- `directory`:覆盖搜索的专案根目录 +- `limit`:最大结果 (1–200) + +--- + +#### 示例 + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +|方法|描述 |回應 | +| ------------------------------ | ------------------------- | --------- | +| `tui.appendPrompt({ body })` |将文字附加到提示| `boolean` | +| `tui.openHelp()` | 开启帮助对话方块 | `boolean` | +| `tui.openSessions()` |开启会话选择器 | `boolean` | +| `tui.openThemes()` |开启主题选择器 | `boolean` | +| `tui.openModels()` | 开启模型选择器 | `boolean` | +| `tui.submitPrompt()` |提交当前提示| `boolean` | +| `tui.clearPrompt()` |清除提示| `boolean` | +| `tui.executeCommand({ body })` |执行命令| `boolean` | +| `tui.showToast({ body })` | 显示吐司通知 | `boolean` | + +--- + +#### 示例 + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### 授權 + +|方法|描述 |回應 | +| ------------------- | ------------------------------ | --------- | +| `auth.set({ ... })` |设定身份验证凭据| `boolean` | + +--- + +#### 示例 + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### 活動 + +|方法|描述 |回應 | +| ------------------- | ------------------------- | ------------------------- | +| `event.subscribe()` | 服务器传送的事件流 | 服务器传送的事件流 | + +--- + +#### 示例 + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/zh-cn/server.mdx b/packages/web/src/content/docs/zh-cn/server.mdx new file mode 100644 index 000000000..dcf521fe9 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/server.mdx @@ -0,0 +1,287 @@ +--- +title: 伺服器 +description: 通过 HTTP 与 opencode 服务器交互。 +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +The `opencode serve` command runs a headless HTTP server that exposes an OpenAPI endpoint that an opencode client can use. + +--- + +### 用法 + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### 選項 + +| 旗幟 | 描述 | 預設 | +| --------------- | --------------------- | ---------------- | +| `--port` | 监听音频 | `4096` | +| `--hostname` | 监听的主机名 | `127.0.0.1` | +| `--mdns` | 启用 mDNS 发现 | `false` | +| `--mdns-domain` | Custom domain name for mDNS service | `opencode.local` | +| `--cors` | 允许的其他浏览器来源 | `[]` | + +`--cors` 可以多次交付: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### 驗證 + +Set `OPENCODE_SERVER_PASSWORD` to protect the server with HTTP basic auth. The username defaults to `opencode`, or set `OPENCODE_SERVER_USERNAME` to override it. This applies to both `opencode serve` and `opencode web`. + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### 它是如何運作的 + +When you run `opencode` it starts a TUI and a server. Where the TUI is the +与服务器器对话的客户端。服务器器公开 OpenAPI 3.1 规范 +该端点还用于生成 [SDK](/docs/sdk)。 + +:::提示 +使用opencode服务器以程序设计方式与opencode交互。 +::: + +该架构让 opencode 支持客户端,并允许您以多种设计方式与 opencode 交互。 + +You can run `opencode serve` to start a standalone server. If you have the +opencode TUI running, `opencode serve` will start a new server. + +--- + +#### 連線到現有伺服器 + +当您启动 TUI 时,它会随机分配端口和主机名。您可以重新设置 `--hostname` 和 `--port` [flags](/docs/cli)。使用它连线到其服务器然后器。 + +[**_T2_**](#tui) 端点可用于跨境服务器驱动 TUI。例如,您可以预填充或执行提示。此设置由 OpenCode [IDE](/docs/ide) 外挂使用。 + +--- + +## 規格 + +服务器发布了OpenAPI 3.1规范,可以在以下位置检视: + +``` +http://:/doc +``` + +例如,`http://localhost:4096/doc`。使用规范生成客户端或检查请求和响应类型其他。或者在 Swagger 浏览器中查看它。 + +--- + +## 蜜蜂 + +opencode服务器公开以下API。 + +--- + +### 全球的 + +| 方法 | 路徑 | 描述 | 回應 | +| ----- | ---------------- | ------------------------ | ------------------------------------ | +| `GET` | `/global/health` | 获取服务器运行状况和版本 | `{ healthy: true, version: string }` | +| `GET` | `/global/event` | 获取全域性事件(SSE 流) | 事件流 | + +--- + +### 專案 + +| 方法 | 路徑 | 描述 | 回應 | +| ----- | ------------------ | ------------ | ------------------------------------------ | +| `GET` | `/project` | 列出所有專案 | 專案[] | +| `GET` | `/project/current` | 獲取當前專案 | 專案 | + +--- + +### 路径和VCS + +| 方法 | 路徑 | 描述 | 回應 | +| ----- | ------- | ----------------------- | ------------------------------------------- | +| `GET` | `/path` | 獲取當前路徑 | 路徑 | +| `GET` | `/vcs` | 獲取當前專案的 VCS 資訊 | VcsInfo | + +--- + +### 例項 + +| 方法 | 路徑 | 描述 | 回應 | +| ------ | ------------------- | -------------- | --------- | +| `POST` | `/instance/dispose` | 执行当前实例项 | `boolean` | + +--- + +### 配置 + +| 方法 | 路徑 | 描述 | 回應 | +| ------- | ------------------- | -------------------- | -------------------------------------------------------------------------------------- | +| `GET` | `/config` | 獲取配置資訊 | 配置 | +| `PATCH` | `/config` | 更新配置 | 配置 | +| `GET` | `/config/providers` | 列出提供商和預設模型 | `{ providers: `提供商[]`, default: { [key: string]: string } }` | + +--- + +### 提供者 + +| 方法 | 路徑 | 描述 | 回應 | +| ------ | -------------------------------- | ---------------------- | --------------------------------------------------------------------------------- | +| `GET` | `/provider` | 列出所有提供商 | `{ all: `提供商[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` | 獲取提供商身份驗證方法 | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` | 使用 OAuth 授權提供商 | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` | 处理成功的 OAuth 回拨 | `boolean` | + +--- + +### 會議 + +| 方法 | 路徑 | 描述 | 筆記 | +| -------- | ---------------------------------------- | ----------------------------- | -------------------------------------------------------------------------------- | +| `GET` | `/session` | 列出所有會話 | 返回 Session[] | +| `POST` | `/session` | 建立新會話 | 正文: `{ parentID?, title? }`,返回 Session | +| `GET` | `/session/status` | 獲取所有會話的會話狀態 | 返回 `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` | 獲取會話詳細資訊 | 返回會話 | +| `DELETE` | `/session/:id` | 删除会话及所有资料 | 返回`boolean` | +| `PATCH` | `/session/:id` | 更新會話屬性 | 正文: `{ title? }`,返回 Session | +| `GET` | `/session/:id/children` | 獲取會話的子會話 | 返回 Session[] | +| `GET` | `/session/:id/todo` | 獲取會話的待辦事項列表 | 返回 Todo[] | +| `POST` | `/session/:id/init` | Analyze app and create `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returns `boolean` | +| `POST` | `/session/:id/fork` | 在訊息中分叉現有會話 | 正文: `{ messageID? }`,返回 Session | +| `POST` | `/session/:id/abort` | 中止正在执行的会话 | 返回`boolean` | +| `POST` | `/session/:id/share` | 分享會議 | 返回會話 | +| `DELETE` | `/session/:id/share` | 取消共享會話 | 返回會話 | +| `GET` | `/session/:id/diff` | 獲取本次會話的差異 | 查詢:`messageID?`,返回 FileDiff[] | +| `POST` | `/session/:id/summarize` | 会议总结 | 正文:`{ providerID, modelID }`,返回 `boolean` | +| `POST` | `/session/:id/revert` | 回覆讯息 | 正文:`{ messageID, partID? }`,返回 `boolean` | +| `POST` | `/session/:id/unrevert` | 恢复所有已恢复的消息 | 返回`boolean` | +| `POST` | `/session/:id/permissions/:permissionID` | 回复许可权限请求 | 正文:`{ response, remember? }`,返回 `boolean` | + +--- + +### 留言 + +| 方法 | 路徑 | 描述 | 筆記 | +| ------ | --------------------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` | 列出會話中的訊息 | 查詢: `limit?`,返回 `{ info: `訊息`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` | 傳送訊息並等待回覆 | 正文: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`,返回 `{ info: `訊息`, parts: `部分[]`}` | +| `GET` | `/session/:id/message/:messageID` | 獲取訊息詳情 | 返回 `{ info: `訊息`, parts: `部分[]`}` | +| `POST` | `/session/:id/prompt_async` | 非同步传送消息(休眠等待) | 主体:与 `/session/:id/message` 相同,返回 `204 No Content` | +| `POST` | `/session/:id/command` | 執行斜槓命令 | 正文: `{ messageID?, agent?, model?, command, arguments }`,返回 `{ info: `訊息`, parts: `部分[]`}` | +| `POST` | `/session/:id/shell` | 執行 shell 命令 | 正文: `{ agent, model?, command }`,返回 `{ info: `訊息`, parts: `部分[]`}` | + +--- + +### 命令 + +| 方法 | 路徑 | 描述 | 回應 | +| ----- | ---------- | ------------ | ------------------------------------------ | +| `GET` | `/command` | 列出所有命令 | 命令[] | + +--- + +### 檔案 + +| 方法 | 路徑 | 描述 | 回應 | +| ----- | ------------------------ | -------------------- | ----------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | 搜尋檔案中的文字 | 具有 `path`、`lines`、`line_number`、`absolute_offset`、`submatches` 的匹配對像陣列 | +| `GET` | `/find/file?query=` | 按名稱查詢檔案和目錄 | `string[]`(路徑) | +| `GET` | `/find/symbol?query=` | 查詢工作區符號 | 符號[] | +| `GET` | `/file?path=` | 列出檔案和目錄 | FileNode[] | +| `GET` | `/file/content?path=

` | 讀取檔案 | 檔案內容 | +| `GET` | `/file/status` | 獲取跟蹤檔案的狀態 | 檔案[] | + +#### `/find/file` 查询引数 + +- `query`(必需)—搜寻字串(模糊匹配) +- `type`(可选)— 将结果限制为 `"file"` 或 `"directory"` +- `directory` (任选) — 覆盖搜索的专案根目录 +- `limit`(任选)— 最大结果 (1–200) +- `dirs`(任选)— 旧标志(`"false"`仅返回档案) + +--- + +### 工具(實驗) + +| 方法 | 路徑 | 描述 | 回應 | +| ----- | ------------------------------------------- | ---------------------------- | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` | 列出所有工具 ID | 工具ID | +| `GET` | `/experimental/tool?provider=

&model=` | 列出具有模型 JSON 模式的工具 | 工具列表 | + +--- + +### LSP、格式化程式和 MCP + +| 方法 | 路徑 | 描述 | 回應 | +| ------ | ------------ | ------------------- | ------------------------------------------------------ | +| `GET` | `/lsp` | 獲取 LSP 伺服器狀態 | LSPStatus[] | +| `GET` | `/formatter` | 獲取格式化程式狀態 | FormatterStatus[] | +| `GET` | `/mcp` | 獲取 MCP 伺服器狀態 | `{ [name: string]: `MCP狀態` }` | +| `POST` | `/mcp` | 动态添加 MCP 服务器 | 主体:`{ name, config }`,返回 MCP 状态对象 | + +--- + +### 代理商 + +| 方法 | 路徑 | 描述 | 回應 | +| ----- | -------- | ------------------ | ------------------------------------------ | +| `GET` | `/agent` | 列出所有可用的代理 | 代理[] | + +--- + +### 記錄 + +| 方法 | 路徑 | 描述 | 回應 | +| ------ | ------------------------------------------- | ------ | -------------------- | +| `POST` | 身体:`{ service, level, message, extra? }` | `/log` | 写入日志。 `boolean` | + +--- + +### TUI + +| 方法 | 路徑 | 描述 | 回應 | +| ------ | ----------------------- | ----------------------------------------- | ------------ | +| `POST` | `/tui/append-prompt` | 将文字附加到提示 | `boolean` | +| `POST` | `/tui/open-help` | 开启帮助对话方块 | `boolean` | +| `POST` | `/tui/open-sessions` | 开启会话选择器 | `boolean` | +| `POST` | `/tui/open-themes` | 开启主题选择器 | `boolean` | +| `POST` | `/tui/open-models` | 开启模型选择器 | `boolean` | +| `POST` | `/tui/submit-prompt` | 提交当前提示 | `boolean` | +| `POST` | `/tui/clear-prompt` | 清除提示 | `boolean` | +| `POST` | `/tui/execute-command` | 执行命令 (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | 显示祝酒 (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | 等待下一个控制请求 | 控制请求对象 | +| `POST` | `/tui/control/response` | 响应控制请求 (`{ body }`) | `boolean` | + +--- + +### 授權 + +| 方法 | 路徑 | 描述 | 回應 | +| ----- | ----------- | ------------------------------------------ | --------- | +| `PUT` | `/auth/:id` | 设置身份验证凭据。正文必须与提供者架构匹配 | `boolean` | + +--- + +### 活動 + +| 方法 | 路徑 | 描述 | 回應 | +| ----- | ---------------------------------------------- | ------------------ | -------- | -------------------- | +| `GET` | 第一个事件是`server.connected`,然后是巴士事件 | 服务器传送的事件流 | `/event` | 服务器传送的事件流。 | + +--- + +### 檔案 + +| 方法 | 路徑 | 描述 | 回應 | +| ----- | ------ | --------------- | ------------------------- | +| `GET` | `/doc` | 开启API 3.1规范 | 具有OpenAPI规范的HTML页面 | diff --git a/packages/web/src/content/docs/zh-cn/share.mdx b/packages/web/src/content/docs/zh-cn/share.mdx new file mode 100644 index 000000000..c3ce2acef --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/share.mdx @@ -0,0 +1,128 @@ +--- +title: 分享 +description: 分享您的 OpenCode 对话。 +--- + +OpenCode 的共享功能允许您建立指向 OpenCode 对话的公共链接,以便您可以与蓝牙进行战斗或从其他人那里获得帮助。 + +:::笔记 +任何知道連結的人都可以公開訪問共享對話。 +::: + +--- + +## 它是如何運作的 + +当您分享对话时,OpenCode: + +1. 为您的会话建立唯一的公共 URL +2. 將您的對話歷史記錄同步到我們的伺服器 +3. 透過可共享連結訪問對話 — `opncd.ai/s/` + +--- + +## 分享 + +OpenCode 支持清晰控制对话共享方式的共享模式: + +--- + +### 手動(預設) + +在默认情况下,OpenCode 使用手动共享模式。会话不会自动共享,但您可以使用 `/share` 命令手动共享它们: + +``` +/share +``` + +这将生成一个唯一的 URL,将其复制到您的剪贴簿中。 + +要在[配置文件](/docs/config) 中显式设置手动模式: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### 自動分享 + +您可以通过将 [config file](/docs/config) 中的 `share` 选项设置为 `"auto"` 来为所有新对话启用自动共享: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +啟用自動共享後,每個新對話都會自動共享並生成連結。 + +--- + +### 殘疾人 + +您可以通过将 [config file](/docs/config) 中的 `share` 选项设置为 `"disabled"` 来完全禁用共享: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +To enforce this across your team for a given project, add it to the `opencode.json` in your project and check into Git. + +--- + +## 取消共享 + +要停止共享對話並將其從公共訪問中刪除: + +``` +/unshare +``` + +這將刪除共享連結並刪除與對話相關的資料。 + +--- + +## 隱私 + +分享對話時需要記住一些事項。 + +--- + +### 資料保留 + +共享對話仍然可以訪問,直到您明確取消共享。這 +包括: + +- 完整的對話歷史記錄 +- 所有訊息和回覆 +- 會話後設資料 + +--- + +### 建議 + +- 僅共享不包含敏感資訊的對話。 +- 分享之前檢視對話內容。 +- 協作完成後取消共享對話。 +- 避免與專有程式碼或機密資料共享對話。 +- 對於敏感專案,完全禁用共享。 + +--- + +## 對於企業 + +對於企業部署,共享功能可以是: + +- **出於安全合規性完全禁用** +- **仅限** 仅透过 SSO 进行身份验证的用户 +- **在您自己的基礎設施上自行託管** + +[了解更多关于在您的组织中使用开放代码的](/docs/enterprise)。 diff --git a/packages/web/src/content/docs/zh-cn/skills.mdx b/packages/web/src/content/docs/zh-cn/skills.mdx new file mode 100644 index 000000000..ca5d2b568 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/skills.mdx @@ -0,0 +1,222 @@ +--- +title: 《代理技巧》 +description: “贯穿 SKILL.md 定义可重用行为” +--- + +代理让 OpenCode 技能从您的存储库或主目录中找到可重用的指令。 +技能贯穿本机 `skill` 工具输入导入 - 代理可以检视可用技能并可以在需要时加载完整内容。 + +--- + +## 放置檔案 + +为每个技能名称建立一个资料夹,并在其中放入`SKILL.md`。 +OpenCode 搜索这些位置: + +- Project config: `.opencode/skills//SKILL.md` +- Global config: `~/.config/opencode/skills//SKILL.md` +- 專案Claude相容:`.claude/skills//SKILL.md` +- 全域性 Claude 相容: `~/.claude/skills//SKILL.md` +- 專案代理相容:`.agents/skills//SKILL.md` +- 全球代理相容:`~/.agents/skills//SKILL.md` + +--- + +## 瞭解發現 + +对于专案本地路径, OpenCode 从当前工作目录向上走,直到到达 git 工作树。 +It loads any matching `skills/*/SKILL.md` in `.opencode/` and any matching `.claude/skills/*/SKILL.md` or `.agents/skills/*/SKILL.md` along the way. + +Global definitions are also loaded from `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md`, and `~/.agents/skills/*/SKILL.md`. + +--- + +## 寫前言 + +每个 `SKILL.md` 必须以 YAML frontmatter 。 +僅識別這些欄位: + +- `name`(必填) +- `description`(必填) +- `license`(任选) +- `compatibility`(任选) +- `metadata`(任选,字串到字串对映) + +未知的 frontmatter 栏位将被忽略。 + +--- + +## 驗證姓名 + +`name` 必须: + +- 長度為 1–64 個字元 +- 為小寫字母數字並帶有單個連字元分隔符 +- 不以 `-` 開始或結束 +- 不包含連續的 `--` +- 匹配包含 `SKILL.md` 的目录名 + +等效的正規表示式: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## 遵循長度規則 + +`description` 必须是 1-1024 个字元。 +保持足夠具體,以便代理能夠正確選擇。 + +--- + +## 使用一個例子 + +Create `.opencode/skills/git-release/SKILL.md` like this: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## 識別工具說明 + +OpenCode 列出了 `skill` 工具描述中的可用技能。 +每個條目都包含技能名稱和描述: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +代理透過呼叫工具來載入技能: + +``` +skill({ name: "git-release" }) +``` + +--- + +## 配置許可權 + +Control which skills agents can access using pattern-based permissions in `opencode.json`: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +|許可|行為 | +| ---------- | ----------------------------------------- | +| `allow` | 技能立即加载 | +| `deny` | 对特工隐藏技能,访问被拒绝 | +| `ask` | 加载前提示用户批准 | + +模式支持万用字元:`internal-*` 匹配 `internal-docs`、`internal-tools` 等。 + +--- + +## 覆蓋每個代理 + +為特定代理授予與全域性預設許可權不同的許可權。 + +**對於自定義代理**(在代理前言中): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**For built-in agents** (in `opencode.json`): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## 禁用技能工具 + +完全禁用不應該使用技能的特工: + +**對於定製代理**: + +```yaml +--- +tools: + skill: false +--- +``` + +**對於內建代理**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +禁用後,`` 部分將被完全省略。 + +--- + +## 解決載入問題 + +如果某項技能沒有顯示: + +1. 验证 `SKILL.md` 拼写为全部大写 +2. 检查 frontmatter 是否包括 `name` 和 `description` +3. 確保技能名稱在所有位置都是唯一的 +4. 查询权限——具有`deny`的代理隐藏技能 diff --git a/packages/web/src/content/docs/zh-cn/themes.mdx b/packages/web/src/content/docs/zh-cn/themes.mdx new file mode 100644 index 000000000..88e1b7923 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/themes.mdx @@ -0,0 +1,369 @@ +--- +title: 主題 +description: 選擇內建主題或定義您自己的主題。 +--- + +使用 OpenCode,您可以从多个内建主题中进行选择,使用适合您的终端主题的主题,或定义您自己的自定义主题。 + +By default, OpenCode uses our own `opencode` theme. + +--- + +## 終端要求 + +為了使主題能夠正確顯示完整的調色盤,您的終端必須支援**真彩色**(24 位顏色)。大多數現代終端預設支援此功能,但您可能需要啟用它: + +- **检查支持**:执行 `echo $COLORTERM` - 它应该输出 `truecolor` 或 `24bit` +- **启用真彩色**:在shell配置文件中设置环境变量`COLORTERM=truecolor` +- **您的终端相容性**:确保终端模拟器支持24位颜色(大多数现代终端,​​​​如iTerm2、Alacritty、Kitty、Windows终端和最新版本的GNOME终端都支持) + +如果沒有真彩色支援,主題的顏色精度可能會降低或回落到最接近的 256 色近似值。 + +--- + +## 內建主題 + +OpenCode 带有几个内建主题。 + +|名稱 |描述 | +| ---------------------- | ---------------------------------------------------------------------------- | +| `system` |适应您所处的背景颜色| +| `tokyonight` | Based on the [Tokyonight](https://github.com/folke/tokyonight.nvim) theme | +| `everforest` | Based on the [Everforest](https://github.com/sainnhe/everforest) theme | +| `ayu` | Based on the [Ayu](https://github.com/ayu-theme) dark theme | +| `catppuccin` | Based on the [Catppuccin](https://github.com/catppuccin) theme | +| `catppuccin-macchiato` | Based on the [Catppuccin](https://github.com/catppuccin) theme | +| `gruvbox` | Based on the [Gruvbox](https://github.com/morhetz/gruvbox) theme | +| `kanagawa` | Based on the [Kanagawa](https://github.com/rebelot/kanagawa.nvim) theme | +| `nord` | Based on the [Nord](https://github.com/nordtheme/nord) theme | +| `matrix` | 骇客风格黑底绿主题| +| `one-dark` | Based on the [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) Dark theme | + +此外,我們還在不斷新增新主題。 + +--- + +## 系統主題 + +`system` 主题旨在自动适应您的最终方案。与使用固定颜色的传统主题不同,_system_ 主题: + +- **生成灰度**:根據終端的背景顏色建立自定義灰度,確保最佳對比度。 +- **使用 ANSI 颜色**:使用标准 ANSI 颜色 (0-15) 进行语法突出显示和 UI 元素,尊重 Windows 的调色盘。 +- **保留默认设置**:使用 `none` 作为文字和背景颜色以保持本机的外观。 + +系統主題適合以下使用者: + +- 希望 OpenCode 与终端的外观相匹配 +- 使用自定義終端配色方案 +- 希望所有終端應用程式具有一致的外觀 + +--- + +## 使用主題 + +您可以通过使用 `/theme` 命令调出主题选择来选择主题。或者您可以在 [config](/docs/config) 中指定它。 + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## 自定義主題 + +OpenCode 支持灵活的基于 JSON 的主题系统,允许用户轻松创建和自定义主题。 + +--- + +### 等級制度 + +主題按以下順序從多個目錄載入,其中後面的目錄覆蓋前面的目錄: + +1. **內建主題** - 這些主題嵌入在二進製檔案中 +2. **User config directory** - Defined in `~/.config/opencode/themes/*.json` or `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Project root directory** - Defined in the `/.opencode/themes/*.json` +4. **Current working directory** - Defined in `./.opencode/themes/*.json` + +如果多個目錄包含同名主題,則將使用優先順序較高的目錄中的主題。 + +--- + +### 建立主題 + +要创建自定义主题,请在主题目录中创建 JSON 档案。 + +對於使用者範圍的主題: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +以及針對特定專案的主題。 + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON 格式 + +主题使用灵活的 JSON 格式,支持: + +- **十六进位制造颜色**: `"#ffffff"` +- **ANSI 颜色**: `3` (0-255) +- **颜色参考**: `"primary"` 或自定义定义 +- **深色/light 变体**: `{"dark": "#000", "light": "#fff"}` +- **无颜色**: `"none"` - 使用终端的默认颜色或透明 + +--- + +### 顏色定義 + +`defs` 部分是可选的,它允许您定义可在主题中引用的可重用颜色。 + +--- + +### 終端預設值 + +特殊值 `"none"` 可用于任何颜色以继承默认的默认颜色。这对于建立与终端方案无缝的融合主题特别有用: + +- `"text": "none"` - 使用遥控器的预设前景色 +- `"background": "none"` - 使用桌面的背景颜色 + +--- + +### 例子 + +以下是自定義主題的示例: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/zh-cn/tools.mdx b/packages/web/src/content/docs/zh-cn/tools.mdx new file mode 100644 index 000000000..1aee21cf6 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/tools.mdx @@ -0,0 +1,379 @@ +--- +title: 工具 +description: 管理 LLM 可以使用的工具。 +--- + +Tools allow the LLM to perform actions in your codebase. OpenCode comes with a set of built-in tools, but you can extend it with [custom tools](/docs/custom-tools) or [MCP servers](/docs/mcp-servers). + +默认情况下,所有工具都是**启用**并且不需要执行权限。您可以交叉[permissions](/docs/permissions) 控制工具行为。 + +--- + +## 配置 + +使用 `permission` 栏位控制工具行为。您可以允许、拒绝或要求批准每个工具。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +您还可以使用万用字元同时控制多个工具。例如,要求 MCP 服务器批准所有工具: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[了解更多](/docs/permissions)关于配置许可权。 + +--- + +## 內建 + +以下是 OpenCode 中可用的所有内置工具。 + +--- + +### 巴什 + +在专案环境中执行shell命令。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +This tool allows the LLM to run terminal commands like `npm install`, `git status`, or any other shell command. + +--- + +### 編輯 + +使用精確的字串替換修改現有檔案。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +该工具取消替换精确的文字来匹配对文件执行精确编辑。这是 LLM 修改程序代码的主要方式。 + +--- + +### 寫 + +建立新檔案或覆蓋現有檔案。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +使用它允许 LLM 创建新文件。如果现有文件已经存在,将会覆盖它们。 + +:::笔记 +`write`工具由`edit`许可权控制,该许可权主题所有文件修改(`edit`、`write`、`patch`、`multiedit`)。 +::: + +--- + +### 讀 + +從程式碼庫中讀取檔案內容。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +該工具讀取檔案並返回其內容。它支援讀取大檔案的特定行範圍。 + +--- + +### grep + +使用正規表示式搜尋檔案內容。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +在您的程式碼庫中快速進行內容搜尋。支援完整的正規表示式語法和檔案模式過濾。 + +--- + +### 全域性 + +透過模式匹配查詢檔案。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +使用 `**/*.js` 或 `src/**/*.ts` 等全域性模式搜索档案。返回按时间排序的匹配档案路径修改。 + +--- + +### 列表 + +列出給定路徑中的檔案和目錄。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +該工具列出目錄內容。它接受全域性模式來過濾結果。 + +--- + +### lsp(实验性) + +与您配置的LSP服务器交互,通知计划码智慧功能,例如定义、引用、悬停资讯和呼叫层次结构。 + +:::笔记 +This tool is only available when `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` (or `OPENCODE_EXPERIMENTAL=true`). +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +支援的操作包括 `goToDefinition`、`findReferences`、`hover`、`documentSymbol`、`workspaceSymbol`、`goToImplementation`、`prepareCallHierarchy`、`incomingCalls` 和 `outgoingCalls`。 + +To configure which LSP servers are available for your project, see [LSP Servers](/docs/lsp). + +--- + +### 修補 + +對檔案應用補丁。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +該工具將補丁檔案應用到您的程式碼庫。對於應用來自各種來源的差異和補丁很有用。 + +:::笔记 +`patch`工具由`edit`许可权控制,该许可权主题所有文件修改(`edit`、`write`、`patch`、`multiedit`)。 +::: + +--- + +### 技能 + +加载[skill](/docs/skills)(`SKILL.md` 档案)并在对话中返回其内容。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### 待辦寫入 + +在編碼會話期間管理待辦事項列表。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +建立和更新任务列表以跟踪复杂操作期间的详细信息。LLM 使用它来组织多步骤任务。 + +:::笔记 +默认情况下,子代理取消此工具,但您可以手动启用它。 [了解更多](/docs/agents/#permissions) +::: + +--- + +### 託多雷德 + +閱讀現有的待辦事項列表。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +读取当前完成待办事项列表状态。由 LLM 用于跟踪哪些任务待处理或已已。 + +:::笔记 +默认情况下,子代理取消此工具,但您可以手动启用它。 [了解更多](/docs/agents/#permissions) +::: + +--- + +### 網頁抓取 + +獲取網頁內容。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +允许 LLM 获取和读取网页。对于查询文件或研究线上资源很有用。 + +--- + +### 網路搜尋 + +在網路上搜尋資訊。 + +:::笔记 +仅当使用 OpenCode 提供或 `OPENCODE_ENABLE_EXA` 程序环境变量设置为任何真值(例如 `true` 或 `1`)时,此工具才可用。 + +要在启动 OpenCode 时启用: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +使用 Exa AI 执行网路搜索以线上查询相关资讯。对于研究主题、查询时事或收集训练超出数据范围的资讯很有用。 + +不需要 API 金钥匙 — 该工具消耗身份验证即可直接连线到 Exa AI 的托管 MCP 服务。 + +:::提示 +当您需要查询资讯(发现)时,请使用 `websearch`;当您需要从特定 URL 检索内容(搜索)时,请使用 `webfetch`。 +::: + +--- + +### 問題 + +在執行過程中詢問使用者問題。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +该工具允许 LLM 在任务期间询问用户问题。它适用于: + +- 收集使用者偏好或要求 +- 澄清不明確的指令 +- 就實施選擇做出決策 +- 提供選擇方向 + +每個問題都包含標題、問題文字和選項列表。使用者可以從提供的選項中進行選擇或輸入自定義答案。當存在多個問題時,使用者可以在提交所有答案之前在這些問題之間導航。 + +--- + +## 定製工具 + +自定义工具可以让您定义LLM可以调用自己的函式。这些是在您的配置文件中定义的并且可以执行任何程序代码。 + +[了解更多](/docs/custom-tools)关于创建自定义工具。 + +--- + +## MCP 伺服器 + +MCP(模型上下文协议)服务器允许您集成外部工具和服务。这包括数据库访问、API 集成和第三方服务。 + +[了解更多](/docs/mcp-servers)关于配置MCP服务器。 + +--- + +## 內部結構 + +Internally, tools like `grep`, `glob`, and `list` use [ripgrep](https://github.com/BurntSushi/ripgrep) under the hood. By default, ripgrep respects `.gitignore` patterns, which means files and directories listed in your `.gitignore` will be excluded from searches and listings. + +--- + +### 忽略模式 + +要包含通常会被忽略的文件,请在专案根目录中建立 `.ignore` 文件。该文件可以明确允许某些路径。 + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +例如,此 `.ignore` 档案允许 ripgrep 在 `node_modules/`、`dist/` 和 `build/` 目录中搜索,即使它们列在 `.gitignore` 中。 diff --git a/packages/web/src/content/docs/zh-cn/troubleshooting.mdx b/packages/web/src/content/docs/zh-cn/troubleshooting.mdx new file mode 100644 index 000000000..e23d3ef1f --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/troubleshooting.mdx @@ -0,0 +1,300 @@ +--- +title: 故障排除 +description: 常見問題以及如何解決它們。 +--- + +要排除 OpenCode 的问题,请首先检查其存储在磁碟上的日志和本地数据。 + +--- + +## 紀錄 + +日誌檔案寫入: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.local\share\opencode\log` + +日志档案以时间命名(例如`2025-01-09T123456.log`),并保留最近10个日志档案。 + +You can set the log level with the `--log-level` command-line option to get more detailed debug information. For example, `opencode --log-level DEBUG`. + +--- + +## 貯存 + +opencode程序将会话数据和其他应用程序数据存储在磁碟上: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.local\share\opencode` + +該目錄包含: + +- `auth.json` - 身份验证资料,例如API金密钥、OAuth令牌 +- `log/` - 应用日志 +- `project/` - 专案特定数据,例如会话和消息数据 + - 如果專案位於 Git 儲存庫中,則它儲存在 `.//storage/` 中 + - 如果不是 Git 存储库,则存储在 `./global/storage/` 中 + +--- + +## 桌面應用程式 + +OpenCode Desktop runs a local OpenCode server (the `opencode-cli` sidecar) in the background. Most issues are caused by a misbehaving plugin, a corrupted cache, or a bad server setting. + +### 快速檢查 + +- 完全退出並重新啟動應用程式。 +- 如果應用程式顯示錯誤螢幕,請單擊“**重新啟動**”並複制錯誤詳細資訊。 +- macOS only: `OpenCode` menu -> **Reload Webview** (helps if the UI is blank/frozen). + +--- + +### 禁用外掛 + +如果桌面應用程式在啟動時崩潰、掛起或行為異常,請首先禁用外掛。 + +#### 檢查全域性配置 + +开启全域性文件并查询`plugin`键。 + +- **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (or `~/.config/opencode/opencode.json`) +- **macOS/Linux** (older installs): `~/.local/share/opencode/opencode.jsonc` +- **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.config\opencode\opencode.jsonc` + +如果您配置了外掛,請透過刪除金鑰或將其設定為空陣列來暫時禁用它們: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### 檢查外掛目錄 + +OpenCode 还可以从磁碟加载本地外挂。暂时将它们移开(或重新命名资料夹)并重新启动桌面应用程序: + +- **全域性外掛** + - **macOS/Linux**: `~/.config/opencode/plugins/` + - **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.config\opencode\plugins` +- **專案外掛**(僅當您使用每個專案配置時) + - `/.opencode/plugins/` + +如果應用程式再次開始工作,請一次重新啟用一個外掛,以找出導致問題的外掛。 + +--- + +### 清除快取 + +如果取消外挂没有帮助(或者外挂安装被卡住),请清除快取,方便OpenCode可以重建它。 + +1. 完全退出 OpenCode 桌面。 +2. 刪除快取目錄: + +- **macOS**: Finder -> `Cmd+Shift+G` -> paste `~/.cache/opencode` +- **Linux**: delete `~/.cache/opencode` (or run `rm -rf ~/.cache/opencode`) +- **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.cache\opencode` + +3. 重新启动 OpenCode 桌面。 + +--- + +### 修復伺服器連線問題 + +OpenCode Desktop 可以启动自己的本地服务器(默认配置)或连线到您的服务器 URL。 + +如果您看到**“连线失败”**对话中断(或者应用程序永远无法穿透启动萤幕),请检查自定义服务器URL。 + +#### 清除桌面桌面服务器 URL + +在主螢幕中,單擊伺服器名稱(帶有狀態點)以開啟伺服器選擇器。在“**預設伺服器**”部分中,單擊“**清除**”。 + +#### 从配置中删除 `server.port` / `server.hostname` + +If your `opencode.json(c)` contains a `server` section, temporarily remove it and restart the desktop app. + +#### 檢查環境變數 + +如果您在环境中设置了 `OPENCODE_PORT`,桌面应用程序将尝试将交换机用于本地服务器。 + +- 取消设置`OPENCODE_PORT`(或选择一个休闲摊)并重新启动。 + +--- + +### Linux:Wayland / X11 问题 + +在 Linux 上,某些 Wayland 设置可能会导致空白视窗或合成器错误。 + +- 如果您在 Wayland 程序上并且应用的是 blank/crashing,请尝试使用 `OC_ALLOW_WAYLAND=1` 启动。 +- 如果这让事情变得更糟糕,请完成其删除并尝试在 X11 会话下启动。 + +--- + +### Windows:WebView2执行时 + +在 Windows 上,OpenCode 桌面需要 Microsoft Edge **WebView2 执行时**。如果应用程序打开为空白视窗或无法启动,请 install/update WebView2 并重试。 + +--- + +### Windows:一般问题 + +If you're experiencing slow performance, file access issues, or terminal problems on Windows, try using [WSL (Windows Subsystem for Linux)](/docs/windows-wsl). WSL provides a Linux environment that works more seamlessly with OpenCode's features. + +--- + +### 通知不顯示 + +OpenCode 桌面仅在以下情况下显示系统通知: + +- 在您的作业系统中设置为 OpenCode 启用了通知,并且 +- 應用程式視窗未聚焦。 + +--- + +### 重置桌面應用程式儲存(最後的手段) + +如果应用程序无法并且启动您无法从 UI 内部清除设置,请重置桌面应用程序的存储状态。 + +1. 退出 OpenCode 桌面。 +2. 查询并删除这些文件(它们位于 OpenCode 桌面应用程序数据目录中): + +- `opencode.settings.dat` (desktop default server URL) +- `opencode.global.dat` and `opencode.workspace.*.dat` (UI state like recent servers/projects) + +快速找到目錄: + +- **macOS**:Finder -> `Cmd+Shift+G` -> `~/Library/Application Support`(然后搜索上面的档名) +- **Linux**:在`~/.local/share`下搜索上述档名 +- **Windows**:按 `WIN+R` -> `%APPDATA%` (然后搜索上面的档名) + +--- + +## 尋求幫助 + +如果您遇到 OpenCode 问题: + +1. **报告 GitHub** 上的问题 + + 报告错误或请求功能的最佳方式是利用我们的 GitHub 存储库: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + 在建立新問題之前,請搜尋現有問題以檢視您的問題是否已被報告。 + +2. **加入我們的不和諧** + + 获得实时帮助和社群讨论,请加入我们的Discord服务器: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## 常見問題 + +以下是一些常見問題以及解決方法。 + +--- + +### OpenCode 无法启动 + +1. 檢查日誌中是否有錯誤訊息 +2. 尝试使用 `--print-logs` 执行以检视终端中的输出 +3. Ensure you have the latest version with `opencode upgrade` + +--- + +### 身份驗證問題 + +1. 尝试使用 TUI 中的 `/connect` 命令重新进行身份验证 +2. 检查您的API金钥匙是否有效 +3. 保证您的网路允许连线到达辉煌的API + +--- + +### 型號不可用 + +1. 檢查您是否已透過提供商的身份驗證 +2. 驗證配置中的型號名稱是否正確 +3. 某些型號可能需要特定的訪問許可權或訂閱 + +如果您遇到 `ProviderModelNotFoundError` 您很可能是错误的 +在某處引用模型。 +模型應該像這樣引用:`/` + +示例: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +To figure out what models you have access to, run `opencode models` + +--- + +### 提供者初始化錯誤 + +如果遇到 ProviderInitError,您的配置可能无效或损坏。 + +要解決這個問題: + +1. 首先,按照[提供商指南](/docs/providers) 验证您的事业是否已正确设置 +2. 如果問題仍然存在,請嘗試清除儲存的配置: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + On Windows, press `WIN+R` and delete: `%USERPROFILE%\.local\share\opencode` + +3. 使用 TUI 中的 `/connect` 命令指示您的企业重新进行身份验证。 + +--- + +### AI_API_CallError 和提供程序包问题 + +如果您遇到 API 呼叫错误,这可能是由于过去提供程序包造成的。 opencode 根据需要动态安装提供程序包(OpenAI、Anthropic、Google 等)将其快取放在本地。 + +要解決提供程式包問題: + +1. 清除提供程式包快取: + + ```bash + rm -rf ~/.cache/opencode + ``` + + On Windows, press `WIN+R` and delete: `%USERPROFILE%\.cache\opencode` + +2. 重新启动 opencode 以重新安装最新的提供程序包 + +这将需要 opencode 下载最新版本的提供程序包,这通常可以解决模型引数和 API 更改的相容性问题。 + +--- + +### 複製/paste 不适用 Linux + +Linux 用户需要安装以下剪贴簿实用程序之一才能使 copy/paste 功能正常工作: + +**对于X11系统:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +** 对于 Wayland 系统:** + +```bash +apt install -y wl-clipboard +``` + +**對於無頭環境:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode 将检测您是否正在使用 Wayland 并更喜欢 `wl-clipboard`,否则将尝试按以下顺序剪贴簿工具:`xclip` 和 `xsel`。 diff --git a/packages/web/src/content/docs/zh-cn/tui.mdx b/packages/web/src/content/docs/zh-cn/tui.mdx new file mode 100644 index 000000000..dcaa0444f --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/tui.mdx @@ -0,0 +1,390 @@ +--- +title: TUI +description: 使用 OpenCode 终端用户界面。 +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode 提供交互式终端介面或 TUI,以便使用 LLM 处理您的专案。 + +执行OpenCode启动当前目录的TUI。 + +```bash +opencode +``` + +或者您可以為特定的工作目錄啟動它。 + +```bash +opencode /path/to/project +``` + +进入TUI后,您可以查看消息进行提示。 + +```text +Give me a quick summary of the codebase. +``` + +--- + +## 檔案參考 + +您可以使用 `@` 在訊息中引用檔案。這會在當前工作目錄中進行模糊檔案搜尋。 + +:::提示 +您還可以使用 `@` 來引用訊息中的檔案。 +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +檔案的內容會自動新增到對話中。 + +--- + +## bash 命令 + +以`!`开始一条消息以执行shell命令。 + +```bash frame="none" +!ls -la +``` + +命令的輸出將作為工具結果新增到對話中。 + +--- + +## 命令 + +使用 OpenCode TUI 时,您可以输入 `/` 后跟命令名称来快速执行操作。例如: + +```bash frame="none" +/help +``` + +大多数命令还是以使用 `ctrl+x` 作为主键的键系结,其中 `ctrl+x` 是默认主键。 [了解更多](/docs/keybinds)。 + +以下是所有可用的斜槓命令: + +--- + +### 連線 + +将新增到 OpenCode。允许您从可用的成功中进行选择并新增他们的 API 重要。 + +```bash frame="none" +/connect +``` + +--- + +### 袖珍的 + +压缩当前会话。_别名_: `/summarize` + +```bash frame="none" +/compact +``` + +** 按键系结:** `ctrl+x c` + +--- + +### 細節 + +切換工具執行詳細資訊。 + +```bash frame="none" +/details +``` + +** 按键系结:** `ctrl+x d` + +--- + +### 編輯 + +开启外部编辑器来编写消息。使用`EDITOR`环境变量中设定的编辑器。 [了解更多](#editor-setup)。 + +```bash frame="none" +/editor +``` + +** 按键系结:** `ctrl+x e` + +--- + +### 出口 + +退出OpenCode。 _别名_:`/quit`、`/q` + +```bash frame="none" +/exit +``` + +** 按键系结:** `ctrl+x q` + +--- + +### 出口 + +将当前对话汇出到 Markdown 并在默认编辑器中开启。使用 `EDITOR` 环境变数中设定的编辑器。 [了解更多](#editor-setup)。 + +```bash frame="none" +/export +``` + +** 按键系结:** `ctrl+x x` + +--- + +### 幫助 + +顯示幫助對話方塊。 + +```bash frame="none" +/help +``` + +** 按键系结:** `ctrl+x h` + +--- + +### 初始化 + +Create or update `AGENTS.md` file. [Learn more](/docs/rules). + +```bash frame="none" +/init +``` + +** 按键系结:** `ctrl+x i` + +--- + +### 型號 + +列出可用型號。 + +```bash frame="none" +/models +``` + +** 按键系结:** `ctrl+x m` + +--- + +### 新的 + +开始新的会话。 _别名_: `/clear` + +```bash frame="none" +/new +``` + +** 按键系结:** `ctrl+x n` + +--- + +### 重做 + +删除之前重做消除的讯息。仅在使用`/undo`后可用。 + +:::提示 +任何檔案更改也將被恢復。 +::: + +在内部,这使用 Git 来管理文件更改。所以你的专案**需要 +是一个Git存储库**。 + +```bash frame="none" +/redo +``` + +** 按键系结:** `ctrl+x r` + +--- + +### 會議 + +上市会话并在会话之间切换。 _别名_:`/resume`、`/continue` + +```bash frame="none" +/sessions +``` + +** 按键系结:** `ctrl+x l` + +--- + +### 分享 + +共享当前会话。 [了解更多](/docs/share)。 + +```bash frame="none" +/share +``` + +** 按键系结:** `ctrl+x s` + +--- + +### 主題 + +列出可用的主題。 + +```bash frame="none" +/theme +``` + +** 按键系结:** `ctrl+x t` + +--- + +### 思維 + +切换对话中 thinking/reasoning 块的可视性。启用后,您可以看到支持增强套件思维的模型的推理过程。 + +:::笔记 +该命令仅控制是否**显示** - 不启用或取消模型的推理功能。要切换实际推理功能,请使用 `ctrl+t` 回圈切换模型变体。 +::: + +```bash frame="none" +/thinking +``` + +--- + +### 撤消 + +撤消對話中的最後一條訊息。刪除最近的使用者訊息、所有後續響應以及任何檔案更改。 + +:::提示 +所做的任何檔案更改也將被恢復。 +::: + +在内部,这使用 Git 来管理文件更改。所以你的专案**需要 +是一个Git存储库**。 + +```bash frame="none" +/undo +``` + +** 按键系结:** `ctrl+x u` + +--- + +### 取消共享 + +取消共享当前会话。 [了解更多](/docs/share#un-sharing)。 + +```bash frame="none" +/unshare +``` + +--- + +## 編輯器設定 + +`/editor` 和 `/export` 命令都使用 `EDITOR` 环境变量中指定的编辑器。 + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + + 要使其永久存在,请将其添加到您的 shell 配置文件中; + `~/.bashrc`、`~/.zshrc` 等 + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + + 要使其永久化,请使用 **系统属性** > **环境 + 变量**。 + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + + 要使其永久化,请将其添加到您的 PowerShell 配置文件中。 + + + + +流行的編輯器選項包括: + +- `code` - Visual Studio 程序代码 +- `cursor` - 游标 +- `windsurf` - 风帆冲浪 +- `nvim` - Neo 的编辑器 +- `vim` - Vim 编辑器 +- `nano` - 奈米编辑器 +- `notepad` - Windows 文章书 +- `subl` - 崇高文字 + +:::笔记 +一些编辑器如 VS Code 需要以 `--wait` 标志启动。 +::: + +某些编辑器需要命令列引数才能在阻止模式下执行。 `--wait` 标志使编辑器程序阻塞直至关闭。 + +--- + +## 配置 + +您可以使用 OpenCode 配置文件自定义 TUI 行为。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### 選項 + +- `scroll_acceleration` - 启用 macOS 式滚动加速以实现平滑、自然的滚动。启用后,滚动速度会随着快速滚动滚动而增加,并在较慢的移动时保持精确。 **此设定优先于 `scroll_speed` 并在启用时覆盖它。 ** +- `scroll_speed` - 控制使用滚动控制器时 TUI 滚动的速度(简单:`1`)。默认为 `3`。 **注意:如果 `scroll_acceleration.enabled` 设置为 `true`,则忽略此设置。 ** + +--- + +## 定製化 + +您可以使用命令选项板(`ctrl+x h` 或 `/help`)自定义 TUI 检视的各个方面。这些设置在重新启动后仍然存在。 + +--- + +#### 使用者名稱顯示 + +切換您的使用者名稱是否出現在聊天訊息中。透過以下方式訪問: + +- 命令面板:搜尋“使用者名稱”或“隱藏使用者名稱” +- 该设置会自动保留,放在 TUI 会话中被记住 diff --git a/packages/web/src/content/docs/zh-cn/web.mdx b/packages/web/src/content/docs/zh-cn/web.mdx new file mode 100644 index 000000000..3a0bb9c4a --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/web.mdx @@ -0,0 +1,142 @@ +--- +title: 網路 +description: 在浏览器中使用OpenCode。 +--- + +OpenCode 可以在浏览器中作为 Web 应用程序执行,消耗终端可以提供同样强大的 AI 编码体验。 + +![OpenCode Web - New Session](../../../assets/web/web-homepage-new-session.png) + +## 入門 + +绕过执行以下命令启动 Web 简介: + +```bash +opencode web +``` + +这将在 `127.0.0.1` 上启动一个具有随机可用端口的本地服务器,并自动在默认浏览器中开启 OpenCode。 + +:::警告 +如果未设置`OPENCODE_SERVER_PASSWORD`,服务器将不安全。这对于本地使用来说很好,但应该针对网路访问进行设置。 +::: + +:::tip[Windows 使用者] +For the best experience, run `opencode web` from [WSL](/docs/windows-wsl) rather than PowerShell. This ensures proper file system access and terminal integration. +::: + +--- + +## 配置 + +您可以使用命令列标志或在[config file](/docs/config).conf 中配置Web服务器。 + +### 港口 + +默认情况下,OpenCode 选择一个可用的端口。您可以指定一个端口: + +```bash +opencode web --port 4096 +``` + +### 主機名 + +情况默认下,服务器系结到`127.0.0.1`(仅限本地主机)。要使OpenCode在您的网路上可访问: + +```bash +opencode web --hostname 0.0.0.0 +``` + +使用`0.0.0.0`时,OpenCode将显示本地地址和网络地址: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### mDNS 发现 + +启用 mDNS 使您的服务器在本地网上可以发现: + +```bash +opencode web --mdns +``` + +This automatically sets the hostname to `0.0.0.0` and advertises the server as `opencode.local`. + +您可以自定义 mDNS 域名以在同一网路上执行多个示例: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +允许CORS使用其他域(对于自定义前缀有用): + +```bash +opencode web --cors https://example.com +``` + +### 驗證 + +要保护访问,请使用 `OPENCODE_SERVER_PASSWORD` 环境变数设置密码: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +The username defaults to `opencode` but can be changed with `OPENCODE_SERVER_USERNAME`. + +--- + +## 使用網路介面 + +启动后,网路界面将提供对您的 OpenCode 会话的访问。 + +### 會議 + +從主頁檢視和管理您的會話。您可以檢視活動會話並開始新會話。 + +![OpenCode Web - Active Session](../../../assets/web/web-homepage-active-session.png) + +### 伺服器狀態 + +單擊“檢視伺服器”可檢視連線的伺服器及其狀態。 + +![OpenCode Web - See Servers](../../../assets/web/web-homepage-see-servers.png) + +--- + +## 連線終端 + +您可以将终端 TUI 连线到正在执行的 Web 服务器: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +这允许您同时使用 Web 界面和终端,共享相同的会话和状态。 + +--- + +## 配置檔案 + +You can also configure server settings in your `opencode.json` config file: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +命令列標誌優先於配置檔案設定。 diff --git a/packages/web/src/content/docs/zh-cn/windows-wsl.mdx b/packages/web/src/content/docs/zh-cn/windows-wsl.mdx new file mode 100644 index 000000000..031ef2fef --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: 在 Windows 上通过 WSL 使用 OpenCode。 +--- + +import { Steps } from "@astrojs/starlight/components" + +虽然 OpenCode 可以直接在 Windows 上运行,但为了获得最佳体验,我们推荐使用 [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install)。WSL 提供了一个与 OpenCode 功能无缝协作的 Linux 环境。 + +:::tip[为什么使用 WSL?] +WSL 提供更好的文件系统性能、完整的终端支持,以及与 OpenCode 依赖的开发工具的兼容性。 +::: + +--- + +## 设置 + + + +1. **安装 WSL** + + 如果你还没有安装,请按照 Microsoft 官方指南 [安装 WSL](https://learn.microsoft.com/en-us/windows/wsl/install)。 + +2. **在 WSL 中安装 OpenCode** + + 完成 WSL 设置后,打开 WSL 终端并使用任一[安装方式](/docs/)安装 OpenCode。 + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **从 WSL 使用 OpenCode** + + 进入你的项目目录(可通过 `/mnt/c/`、`/mnt/d/` 等访问 Windows 文件)并运行 OpenCode。 + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## 桌面应用 + WSL 服务器 + +如果你想使用 OpenCode 桌面应用,但希望在 WSL 中运行服务器: + +1. **在 WSL 中启动服务器**,并使用 `--hostname 0.0.0.0` 以允许外部连接: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **将桌面应用连接到** `http://localhost:4096` + +:::note +如果你的环境中 `localhost` 不可用,请改用 WSL 的 IP 地址连接(在 WSL 中执行:`hostname -I`),并使用 `http://:4096`。 +::: + +:::caution +使用 `--hostname 0.0.0.0` 时,请设置 `OPENCODE_SERVER_PASSWORD` 来保护服务器。 + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Web 客户端 + WSL + +在 Windows 上获得最佳 Web 体验: + +1. **请在 WSL 终端中运行 `opencode web`**,而不是在 PowerShell 中运行: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **在 Windows 浏览器中访问** `http://localhost:`(OpenCode 会打印该 URL) + +从 WSL 运行 `opencode web` 可以确保正确的文件系统访问和终端集成,同时仍可在 Windows 浏览器中访问。 + +--- + +## 访问 Windows 文件 + +WSL 可以通过 `/mnt/` 目录访问你所有的 Windows 文件: + +- `C:` drive → `/mnt/c/` +- `D:` drive → `/mnt/d/` +- 其他盘符同理 + +示例: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +为了获得更流畅的体验,建议将仓库克隆或复制到 WSL 文件系统中(例如 `~/code/`),并在那里运行 OpenCode。 +::: + +--- + +## 提示 + +- 即使项目存放在 Windows 盘符中,也建议在 WSL 中运行 OpenCode,文件访问会更顺畅 +- 可将 OpenCode 与 VS Code 的 [WSL 扩展](https://code.visualstudio.com/docs/remote/wsl)配合使用,形成一体化开发流程 +- OpenCode 的配置和会话会保存在 WSL 环境中的 `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/zh-cn/zen.mdx b/packages/web/src/content/docs/zh-cn/zen.mdx new file mode 100644 index 000000000..fc3782279 --- /dev/null +++ b/packages/web/src/content/docs/zh-cn/zen.mdx @@ -0,0 +1,254 @@ +--- +title: 禪 +description: 由 OpenCode 提供的精选模型列表。 +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + +:::笔记 +OpenCode Zen 目前处于一个测试阶段。 +::: + +Zen 的工作方式与 OpenCode 中的任何其他提供程序相同。您登入 OpenCode Zen 并获得 +你的API钥匙。它是**完全可选的**,你不需要使用它即可使用 +开放代码。 + +--- + +## 背景 + +市面上有很多型號,但其中只有少數幾個 +這些模型可以很好地用作編碼代理。此外,大多數提供商都 +配置非常不同;所以你會得到截然不同的效能和質量。 + +:::提示 +我们测试了一组与 OpenCode 配合良好的模型并提供方案。 +::: + +因此,如果您使用 OpenRouter 之类的东西使用模型,您永远无法 +確定您是否獲得了您想要的模型的最佳版本。 + +為瞭解決這個問題,我們做了幾件事: + +1. 我們測試了一組選定的模型,並與他們的團隊討論瞭如何 + 最好執行它們。 +2. 然後我們與一些提供商合作以確保這些服務得到服務 + 正確。 +3. 最后,我们对 model/provider 的组合进行了基准测试,总结了 + 並附上一份我們覺得不錯的推薦清單。 + +OpenCode Zen 是一个AI闸道器,可以让您访问这些模型。 + +--- + +## 它是如何運作的 + +OpenCode Zen 的工作方式与 OpenCode 中的任何其他功能相同。 + +1. 您登入 **OpenCode Zen**,新增您的帳單 + 详细资讯,然后复制您的 API 金钥匙。 +2. 您在 TUI 中执行 `/connect` 命令,选择 OpenCode Zen,然后贴上 API 金钥匙。 +3. 在 TUI 中执行 `/models` 以检视我们推荐的型号列表。 + +您需要按請求付費,並且您可以將積分新增到您的帳戶中。 + +--- + +## 端點 + +您还可以通过以下 API 端点访问我们的模型。 + +|型号|型号ID |端点 |人工智慧SDK包| +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +| Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +| MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 Free | minimax-m2.1-free | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 Free | glm-4.7-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 Free | kimi-k2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +OpenCode 配置中的 [model id](/docs/config/#models) +uses the format `opencode/`. For example, for GPT 5.2 Codex, you would +use `opencode/gpt-5.2-codex` in your config. + +--- + +### 型號 + +您可以從以下位置獲取可用模型及其後設資料的完整列表: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## 定價 + +我們支援即用即付模式。以下是**每 100 萬代幣的價格**。 + +|型號|輸入 |輸出|快取讀取 |快取寫入| +| --------------------------------- | ------ | ------ | ----------- | ------------ | +|大泡菜|免費|免費|免費| - | +| MiniMax M2.1 免费 |免费|免费|免费| - | +|迷你最大M2.1 | 0.30 美元 | 1.20 美元 | 0.10 美元 | - | +| GLM 4.7 免费 |免费|免费|免费| - | +| GLM 4.7 | 0.60 美元 | 2.20 美元 | 0.10 美元 | - | +| GLM 4.6 | 0.60 美元 | 2.20 美元 | 0.10 美元 | - | +| Kimi K2.5 免费|免费|免费|免费| - | +|作为K2.5| 0.60 美元 | $3.00 | 0.08 美元 | - | +| Kimi K2 思考 | 0.40 美元 | 2.50 美元 | - | - | +|作为K2 | 0.40 美元 | 2.50 美元 | - | - | +| Qwen3 编码器 480B | 0.45 美元 | 1.50 美元 | - | - | +| Claude Sonnet 4.5(≤ 200K 令牌)| $3.00 | 15.00 美元 | 0.30 美元 | 3.75 美元 | +|克劳德十四行诗 4.5(> 200K 代币)| 6.00 美元 | 22.50 美元 | 0.60 美元 | 7.50 美元 | +| Claude Sonnet 4(≤ 200K 令牌)| $3.00 | 15.00 美元 | 0.30 美元 | 3.75 美元 | +| Claude Sonnet 4(> 200K 令牌)| 6.00 美元 | 22.50 美元 | 0.60 美元 | 7.50 美元 | +| Claude 俳句 4.5 | 1.00 美元 | 5.00 美元 | 0.10 美元 | 1.25 美元 | +| Claude 俳句 3.5 | 0.80 美元 | 4.00 美元 | 0.08 美元 | 1.00 美元 | +|克劳德作品4.6(≤ 200K 代币)| 5.00 美元 | 25.00 美元 | 0.50 美元 | 6.25 美元 | +| Claude Opus 4.6(> 200K 代幣)| 10.00 美元 | 37.50 美元 | 1.00 美元 | 12.50 美元 | +| Claude 工作 4.5 | 5.00 美元 | 25.00 美元 | 0.50 美元 | 6.25 美元 | +| Claude 工作 4.1 | 15.00 美元 | 75.00 美元 | 1.50 美元 | 18.75 美元 | +| Gemini 3 Pro(≤20万代币)| 2.00 美元 | 12.00 美元 | 0.20 美元 | - | +| Gemini 3 Pro(>20万代币)| 4.00 美元 | 18.00 美元 | 0.40 美元 | - | +|双子座 3 闪光 | 0.50 美元 | $3.00 | 0.05 美元 | - | +| GPT 5.2 | 1.75 美元 | 14.00 美元 | 0.175 美元 | - | +| GPT 5.2 法典 | 1.75 美元 | 14.00 美元 | 0.175 美元 | - | +| GPT 5.1 | 1.07 美元 | 8.50 美元 | 0.107 美元 | - | +| GPT 5.1 法典 | 1.07 美元 | 8.50 美元 | 0.107 美元 | - | +| GPT 5.1 法典最大 | 1.25 美元 | 10.00 美元 | 0.125 美元 | - | +| GPT 5.1 迷你版 | 0.25 美元 | 2.00 美元 | 0.025 美元 | - | +| GPT 5 | 1.07 美元 | 8.50 美元 | 0.107 美元 | - | +| GPT 5 法典 | 1.07 美元 | 8.50 美元 | 0.107 美元 | - | +| GPT 5 奈米 |免费|免费|免费| - | + +您可能会在您的使用历史记录中注意到_Claude Haiku 3.5_。这是一个[低成本模型](/docs/config/#models),用于生成会话标题。 + +:::笔记 +信用卡費用按成本轉嫁(4.4% + 每筆交易 0.30 美元);除此之外我們不收取任何費用。 +::: + +免費模型: + +- GLM 4.7 免费版本在 OpenCode 上限时提供。团队正在利用这段时间收集反馈并改进模型。 +- Kimi K2.5 在 OpenCode 限时免费发布。团队正在利用这段时间收集反馈并改进模型。 +- MiniMax M2.1 在 OpenCode 限时免费供应。团队正在利用这段时间收集反馈并改进模型。 +- Big Pickle 是一个隐形模型,在 OpenCode 上限时免费。团队正在利用这个临时收集反馈并改进模型。 + +如果您有任何疑問,請聯絡我們。 + +--- + +### 自動重新載入 + +如果您的余额低于 5 美元,Zen 将自动充值 20 美元。 + +您可以更改自動充值金額。您還可以完全禁用自動重新載入。 + +--- + +### 每月限額 + +您還可以為整個工作區和每個工作區設定每月使用限制 +你的團隊成員。 + +例如,假设您将每月使用中断设置为 20 美元,Zen 将不会使用 +一个月超过 20 美元。但如果你启用了自动重新加载,Zen 可能会结束 +如果您的餘額低於 5 美元,則向您收取超過 20 美元的費用。 + +--- + +## 隱私 + +我們所有的模型都在美國託管。我們的提供商遵循零保留政策,不會將您的資料用於模型訓練,但以下情況除外: + +- Big Pickle:在免费期间,收集可用于改进模型的数据。 +- GLM 4.7 免费:在免费期间,收集可用于改进模型的数据。 +- Kimi K2.5 免费:在免费期间,收集可用于改进模型的数据。 +- MiniMax M2.1 免费:在免费期间,收集可用于改进模型的数据。 +- OpenAI APIs: Requests are retained for 30 days in accordance with [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data). +- Anthropic APIs: Requests are retained for 30 days in accordance with [Anthropic's Data Policies](https://docs.anthropic.com/en/docs/claude-code/data-usage). + +--- + +## 對於團隊 + +Zen 对团队也很有效。您可以参与第三方、角色、策划 +您的團隊使用的模型等等。 + +:::笔记 +作為測試版的一部分,工作空間目前對團隊免費。 +::: + +作為測試版的一部分,管理工作空間目前對團隊免費。我們將會 +很快就會分享更多有關定價的細節。 + +--- + +### 角色 + +您可以邀請團隊成員到您的工作區並分配角色: + +- **管理员**:管理模型、成员、API 金钥匙和设备 +- **成员**:仅管理自己的API 金? + +管理員還可以為每個成員設定每月支出限額,以控製成本。 + +--- + +### 模型訪問 + +管理員可以啟用或禁用工作區的特定模型。對禁用模型發出的請求將返回錯誤。 + +這對於您想要禁用以下模型的情況很有用: +收集資料。 + +--- + +### 帶上你自己的鑰匙 + +您可以使用自己的 OpenAI 或 Anthropic API 键,同时仍然访问 Zen 中的其他模型。 + +当您使用自己的金密钥时,令牌将由强大的直接设备组成,而不是由 Zen。 + +例如,您的组织可能已经拥有 OpenAI 或 Anthropic 的金? +你想使用它而不是 Zen 提供的。 + +--- + +## 去寻找 + +我们建立OpenCode Zen是为了: + +1. **基准**编码代理的最佳models/providers。 +2. 可以使用**最高質量**選項,而不是降低效能或轉向更便宜的提供商。 +3. 透過按成本價銷售來傳遞任何**價格下跌**;所以唯一的加價就是支付我們的加工費。 +4. 通过允许您将其与任何其他编码代理一起使用,**无锁定**。并且始终允许您将任何其他成功与 OpenCode 一起使用。 diff --git a/packages/web/src/content/docs/zh-tw/1-0.mdx b/packages/web/src/content/docs/zh-tw/1-0.mdx new file mode 100644 index 000000000..a1148a8f7 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/1-0.mdx @@ -0,0 +1,67 @@ +--- +title: 遷移到 1.0 +description: OpenCode 1.0 中的新增內容。 +--- + +OpenCode 1.0 完全重寫了 TUI。 + +我們從存在性能和功能問題的基於 go+bubbletea 的 TUI 遷移到用 zig+solidjs 編寫的內部框架 (OpenTUI)。 + +新 TUI 的工作方式與舊 TUI 類似,因為它連接到相同的開放代碼服務器。 + +--- + +## 升級中 + +如果您當前正在使用以前的版本,則不應自動升級到 1.0 +版本。然而,一些舊版本的 OpenCode 總是獲取最新版本。 + +要手動升級,請運行 + +```bash +$ opencode upgrade 1.0.0 +``` + +要降級回 0.x,請運行 + +```bash +$ opencode upgrade 0.15.31 +``` + +--- + +## 用戶體驗變化 + +會話歷史記錄更加壓縮,僅顯示編輯和 bash 工具的完整詳細信息。 + +我們添加了一個命令欄,幾乎所有內容都經過它。按 ctrl+p 可在任何上下文中調出它並查看您可以執行的所有操作。 + +添加了包含有用信息的會話側邊欄(可以切換)。 + +我們刪除了一些我們不確定是否有人實際使用的功能。如果缺少重要內容,請提出問題,我們會盡快將其添加回來。 + +--- + +## 重大變化 + +### 按鍵綁定已重命名 + +- messages_revert -> messages_undo +- switch_agent -> agent_cycle +- switch_agent_reverse -> agent_cycle_reverse +- switch_mode -> agent_cycle +- switch_mode_reverse -> agent_cycle_reverse + +### 按鍵綁定已移除 + +- 消息佈局切換 +- 下一條消息 +- 上一條消息 +- 文件差異切換 +- 文件搜索 +- 文件關閉 +- 文件列表 +- 應用程序幫助 +- 項目初始化 +- 工具詳細信息 +- 思維塊 diff --git a/packages/web/src/content/docs/zh-tw/acp.mdx b/packages/web/src/content/docs/zh-tw/acp.mdx new file mode 100644 index 000000000..cf3baf86c --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/acp.mdx @@ -0,0 +1,156 @@ +--- +title: ACP 支持 +description: 在任何 ACP 兼容編輯器中使用 OpenCode。 +--- + +OpenCode 支持 [代理客戶端協議](https://agentclientprotocol.com) 或 (ACP),允許您直接在兼容的編輯器和 IDE 中使用它。 + +:::tip +有關支持 ACP 的編輯器和工具的列表,請查看[非加太進程進度報告](https://zed.dev/blog/acp-progress-report#available-now)。 +::: + +ACP 是一種開放協議,用於標準化代碼編輯器和 AI 編碼代理之間的通信。 + +--- + +## 配置 + +要通過 ACP 使用 OpenCode,請將編輯器配置為運行 `opencode acp` 命令。 + +該命令將 OpenCode 作為 ACP 兼容的子進程啟動,通過 stdio 通過 JSON-RPC 與您的編輯器進行通信。 + +以下是支持 ACP 的流行編輯器的示例。 + +--- + +### 澤德 + +添加到您的[澤德](https://zed.dev)配置(`~/.config/zed/settings.json`): + +```json title="~/.config/zed/settings.json" +{ + "agent_servers": { + "OpenCode": { + "command": "opencode", + "args": ["acp"] + } + } +} +``` + +要打開它,請使用 **命令面板** 中的 `agent: new thread` 操作。 + +您還可以通過編輯`keymap.json`來綁定鍵盤快捷鍵: + +```json title="keymap.json" +[ + { + "bindings": { + "cmd-alt-o": [ + "agent::NewExternalAgentThread", + { + "agent": { + "custom": { + "name": "OpenCode", + "command": { + "command": "opencode", + "args": ["acp"] + } + } + } + } + ] + } + } +] +``` + +--- + +### JetBrains IDE + +根據[文件](https://www.jetbrains.com/help/ai-assistant/acp.html)添加到你的[JetBrains IDE](https://www.jetbrains.com/) acp.json: + +```json title="acp.json" +{ + "agent_servers": { + "OpenCode": { + "command": "/absolute/path/bin/opencode", + "args": ["acp"] + } + } +} +``` + +要打開它,請在 AI Chat 代理選擇器中使用新的“OpenCode”代理。 + +--- + +### 前衛 + +添加到您的[前衛](https://github.com/yetone/avante.nvim)配置: + +```lua +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" } + } + } +} +``` + +如果需要傳遞環境變量: + +```lua {6-8} +{ + acp_providers = { + ["opencode"] = { + command = "opencode", + args = { "acp" }, + env = { + OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") + } + } + } +} +``` + +--- + +### 代碼伴侶.nvim + +要將 OpenCode 用作 [代碼伴侶.nvim](https://github.com/olimorris/codecompanion.nvim) 中的 ACP 代理,請將以下內容添加到 Neovim 配置中: + +```lua +require("codecompanion").setup({ + interactions = { + chat = { + adapter = { + name = "opencode", + model = "claude-sonnet-4", + }, + }, + }, +}) +``` + +此配置將 CodeCompanion 設置為使用 OpenCode 作為聊天的 ACP 代理。 + +如果您需要傳遞環境變量(如 `OPENCODE_API_KEY`),請參閱 CodeCompanion.nvim 文檔中的 [配置適配器:環境變量](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) 了解完整詳細信息。 + +## 支持 + +OpenCode 通過 ACP 的工作方式與在終端中的工作方式相同。支持所有功能: + +:::note +目前不支持某些內置斜杠命令,例如 `/undo` 和 `/redo`。 +::: + +- 內置工具(文件操作、終端命令等) +- 自定義工具和斜杠命令 +- 在 OpenCode 配置中配置的 MCP 服務器 +- `AGENTS.md` 的項目特定規則 +- 自定義格式化程序和 linter +- 代理和權限系統 diff --git a/packages/web/src/content/docs/zh-tw/agents.mdx b/packages/web/src/content/docs/zh-tw/agents.mdx new file mode 100644 index 000000000..598176e8b --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/agents.mdx @@ -0,0 +1,747 @@ +--- +title: 代理商 +description: 配置和使用專門的代理。 +--- + +代理是專門的人工智能助手,可以針對特定任務和工作流程進行配置。它們允許您創建具有自定義提示、模型和工具訪問權限的專用工具。 + +:::tip +使用計劃代理來分析代碼並審查建議,而無需進行任何代碼更改。 +::: + +您可以在會話期間在代理之間切換,或使用 `@` 提及來調用它們。 + +--- + +## 類型 + +OpenCode 中有兩種類型的代理;主要代理人和次代理人。 + +--- + +### 主要代理 + +主要代理是與您直接互動的主要助手。您可以使用 **Tab** 鍵或您配置的 `switch_agent` 鍵綁定循環瀏覽它們。這些代理處理您的主要對話。工具訪問是通過權限配置的 - 例如,“構建”啟用了所有工具,而“計劃”則受到限制。 + +:::tip +您可以在會話期間使用 **Tab** 鍵在主要代理之間切換。 +::: + +OpenCode 附帶兩個內置的主要代理:**Build** 和 **Plan**。出色地 +看看下面這些。 + +--- + +### 子代理 + +子代理是主要代理可以調用​​來執行特定任務的專業助手。您還可以通過在消息中**@提及**它們來手動調用它們。 + +OpenCode 附帶兩個內置子代理:**General** 和 **Explore**。我們將在下面看看這個。 + +--- + +## 內建 + +OpenCode 附帶兩個內置主代理和兩個內置子代理。 + +--- + +### 使用構建 + +_模式_:`primary` + +構建是啟用所有工具的**默認**主要代理。這是用於需要完全訪問文件操作和系統命令的開發工作的標準代理。 + +--- + +### 使用計劃 + +_模式_:`primary` + +專為規劃和分析而設計的受限代理。我們使用權限系統為您提供更多控制並防止意外更改。 +默認情況下,以下所有項均設置為`ask`: + +- `file edits`:所有寫入、修補和編輯 +- `bash`:所有 bash 命令 + +當您希望 LLM 分析代碼、建議更改或創建計劃而不對代碼庫進行任何實際修改時,此代理非常有用。 + +--- + +### 使用一般 + +_模式_:`subagent` + +用於研究複雜問題和執行多步驟任務的通用代理。具有完整的工具訪問權限(待辦事項除外),因此可以在需要時更改文件。使用它可以並行運行多個工作單元。 + +--- + +### 使用探索 + +_模式_:`subagent` + +用於探索代碼庫的快速只讀代理。無法修改文件。當您需要按模式快速查找文件、搜索代碼中的關鍵字或回答有關代碼庫的問題時,請使用此功能。 + +--- + +### 使用壓實 + +_模式_:`primary` + +隱藏的系統代理,將長上下文壓縮為較小的摘要。它會在需要時自動運行,並且無法在 UI 中選擇。 + +--- + +### 使用標題 + +_模式_:`primary` + +生成短會話標題的隱藏系統代理。它會自動運行,並且無法在 UI 中選擇。 + +--- + +### 使用總結 + +_模式_:`primary` + +創建會話摘要的隱藏系統代理。它會自動運行,並且無法在 UI 中選擇。 + +--- + +## 用法 + +1. 對於主要代理,請在會話期間使用 **Tab** 鍵循環瀏覽它們。您還可以使用配置的 `switch_agent` 鍵綁定。 + +2. 可以調用子代理: + - **自動**由主要代理根據其描述執行專門任務。 + - 通過在消息中**@提及**子代理手動進行。例如。 + + ```txt frame="none" + @general help me search for this function + ``` + +3. **會話之間導航**:當子代理創建自己的子會話時,您可以使用以下命令在父會話和所有子會話之間導航: + - **\+Right**(或您配置的 `session_child_cycle` 鍵綁定)向前循環父級 → 子級 1 → 子級 2 → ... → 父級 + - **\+Left**(或您配置的 `session_child_cycle_reverse` 鍵綁定)向後循環父級 ← 子級 1 ← 子級 2 ← ... ← 父級 + + 這使您可以在主要對話和專門的子代理工作之間無縫切換。 + +--- + +## 配置 + +您可以自定義內置代理或通過配置創建您自己的代理。可以通過兩種方式配置代理: + +--- + +### JSON + +在 `opencode.json` 配置文件中配置代理: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### 降價 + +您還可以使用 Markdown 文件定義代理。將它們放入: + +- 全球:`~/.config/opencode/agents/` +- 每個項目:`.opencode/agents/` + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Markdown 文件名成為代理名稱。例如,`review.md` 創建`review` 代理。 + +--- + +## 選項 + +讓我們詳細看看這些配置選項。 + +--- + +### 描述 + +使用 `description` 選項提供代理的作用以及何時使用它的簡要描述。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +這是一個**必需的**配置選項。 + +--- + +### 溫度 + +使用 `temperature` 配置控制 LLM 響應的隨機性和創造性。 + +較低的值使響應更加集中和確定,而較高的值則增加創造力和可變性。 + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +溫度值的範圍通常為 0.0 到 1.0: + +- **0.0-0.2**:非常集中且確定的響應,非常適合代碼分析和規劃 +- **0.3-0.5**:具有一定創造力的平衡響應,適合一般開發任務 +- **0.6-1.0**:更有創意和多樣化的反應,有助於頭腦風暴和探索 + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +如果未指定溫度,OpenCode 將使用特定於型號的默認值;大多數型號通常為 0,Qwen 型號為 0.55。 + +--- + +### 最大步數 + +控制代理在被迫僅使用文本響應之前可以執行的最大代理迭代次數。這允許希望控製成本的用戶對代理操作設置限制。 + +如果未設置,代理將繼續迭代,直到模型選擇停止或用戶中斷會話。 + +```json title="opencode.json" +{ + "agent": { + "quick-thinker": { + "description": "Fast reasoning with limited iterations", + "prompt": "You are a quick thinker. Solve problems with minimal steps.", + "steps": 5 + } + } +} +``` + +當達到限制時,代理會收到特殊的系統提示,指示其響應其工作摘要和建議的剩餘任務。 + +:::caution +舊版 `maxSteps` 字段已棄用。請改用`steps`。 +::: + +--- + +### 禁用 + +設置為 `true` 以禁用代理。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### 迅速的 + +使用 `prompt` 配置為此代理指定自定義系統提示文件。提示文件應包含特定於代理目的的說明。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +該路徑是相對於配置文件所在位置的。因此,這適用於全局 OpenCode 配置和項目特定配置。 + +--- + +### 模型 + +使用 `model` 配置覆蓋此代理的模型。對於使用針對不同任務優化的不同模型很有用。例如,更快的規劃模型、更強大的實施模型。 + +:::tip +如果您不指定模型,主代理將使用[全局配置的模型](/docs/config#models),而子代理將使用調用子代理的主代理的模型。 +::: + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +OpenCode 配置中的模型 ID 使用格式`provider/model-id`。例如,如果您使用 [開放代碼禪](/docs/zen),則您將使用 `opencode/gpt-5.1-codex` 來表示 GPT 5.1 Codex。 + +--- + +### 工具 + +使用 `tools` 配置控制此代理中可用的工具。您可以通過將特定工具設置為`true` 或`false` 來啟用或禁用特定工具。 + +```json title="opencode.json" {3-6,9-12} +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": true, + "bash": true + }, + "agent": { + "plan": { + "tools": { + "write": false, + "bash": false + } + } + } +} +``` + +:::note +特定於代理的配置會覆蓋全局配置。 +::: + +您還可以使用通配符同時控制多個工具。例如,要禁用 MCP 服務器中的所有工具: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +[了解有關工具的更多信息](/docs/tools)。 + +--- + +### 權限 + +您可以配置權限來管理代理可以執行的操作。目前,`edit`、`bash` 和`webfetch` 工具的權限可以配置為: + +- `"ask"` — 運行工具之前提示批准 +- `"allow"` — 未經批准允許所有操作 +- `"deny"` — 禁用該工具 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + } +} +``` + +您可以覆蓋每個代理的這些權限。 + +```json title="opencode.json" {3-5,8-10} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny" + }, + "agent": { + "build": { + "permission": { + "edit": "ask" + } + } + } +} +``` + +您還可以在 Markdown 代理中設置權限。 + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: + "*": ask + "git diff": allow + "git log*": allow + "grep *": allow + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +您可以設置特定 bash 命令的權限。 + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git push": "ask", + "grep *": "allow" + } + } + } + } +} +``` + +這可以採用全局模式。 + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "git *": "ask" + } + } + } + } +} +``` + +您還可以使用`*`通配符來管理所有命令的權限。 +由於最後一個匹配規則優先,因此將 `*` 通配符放在前面,將特定規則放在後面。 + +```json title="opencode.json" {8} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git status *": "allow" + } + } + } + } +} +``` + +[了解有關權限的更多信息](/docs/permissions)。 + +--- + +### 模式 + +使用`mode` 配置控制代理的模式。 `mode` 選項用於確定如何使用代理。 + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +`mode` 選項可設置為`primary`、`subagent` 或`all`。如果未指定`mode`,則默認為`all`。 + +--- + +### 隱 + +使用 `hidden: true` 從 `@` 自動完成菜單隱藏子代理。對於只能由其他代理通過任務工具以編程方式調用的內部子代理很有用。 + +```json title="opencode.json" +{ + "agent": { + "internal-helper": { + "mode": "subagent", + "hidden": true + } + } +} +``` + +這僅影響自動完成菜單中的用戶可見性。如果權限允許,模型仍然可以通過任務工具調用隱藏代理。 + +:::note +僅適用於`mode: subagent` 代理。 +::: + +--- + +### 任務權限 + +使用 `permission.task` 控制代理可以通過任務工具調用哪些子代理。使用 glob 模式進行靈活匹配。 + +```json title="opencode.json" +{ + "agent": { + "orchestrator": { + "mode": "primary", + "permission": { + "task": { + "*": "deny", + "orchestrator-*": "allow", + "code-reviewer": "ask" + } + } + } + } +} +``` + +當設置為 `deny` 時,子代理將從任務工具描述中完全刪除,因此模型不會嘗試調用它。 + +:::tip +規則按順序評估,**最後匹配的規則獲勝**。在上面的示例中,`orchestrator-planner` 匹配`*`(拒絕)和`orchestrator-*`(允許),但由於`orchestrator-*` 位於`*` 之後,因此結果為`allow`。 +::: + +:::tip +用戶始終可以通過 `@` 自動完成菜單直接調用任何子代理,即使代理的任務權限會拒絕它。 +::: + +--- + +### 顏色 + +使用 `color` 選項自定義代理在 UI 中的視覺外觀。這會影響代理在界面中的顯示方式。 + +使用有效的十六進制顏色(例如`#FF5733`)或主題顏色:`primary`、`secondary`、`accent`、`success`、`warning`、`error`、`info`。 + +```json title="opencode.json" +{ + "agent": { + "creative": { + "color": "#ff6b6b" + }, + "code-reviewer": { + "color": "accent" + } + } +} +``` + +--- + +### 頂P + +使用 `top_p` 選項控制響應多樣性。控制隨機性的溫度替代方案。 + +```json title="opencode.json" +{ + "agent": { + "brainstorm": { + "top_p": 0.9 + } + } +} +``` + +值範圍從 0.0 到 1.0。較低的值更加集中,較高的值更加多樣化。 + +--- + +### 額外的 + +您在代理配置中指定的任何其他選項都將作為模型選項**直接**傳遞給提供程序。這允許您使用特定於提供商的功能和參數。 + +例如,使用 OpenAI 的推理模型,您可以控制推理工作: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +這些附加選項是特定於型號和提供商的。檢查提供商的文檔以獲取可用參數。 + +:::tip +運行 `opencode models` 查看可用模型的列表。 +::: + +--- + +## 創建代理 + +您可以使用以下命令創建新代理: + +```bash +opencode agent create +``` + +此交互式命令將: + +1. 詢問代理保存在哪裡;全局或特定項目。 +2. 描述代理應該做什麼。 +3. 生成適當的系統提示和標識符。 +4. 讓您選擇代理可以訪問哪些工具。 +5. 最後,使用代理配置創建一個 markdown 文件。 + +--- + +## 使用案例 + +以下是不同代理的一些常見用例。 + +- **構建代理**:啟用所有工具的完整開發工作 +- **規劃代理**:分析規劃,不做改動 +- **審查代理**:具有隻讀訪問權限和文檔工具的代碼審查 +- **調試代理**:專注於啟用 bash 和讀取工具的調查 +- **文檔代理**:使用文件操作但不使用系統命令的文檔編寫 + +--- + +## 示例 + +以下是一些您可能會覺得有用的示例代理。 + +:::tip +您有想要分享的經紀人嗎? [提交 PR](https://github.com/anomalyco/opencode)。 +::: + +--- + +### 文件代理 + +```markdown title="~/.config/opencode/agents/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### 安全審核員 + +```markdown title="~/.config/opencode/agents/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/zh-tw/cli.mdx b/packages/web/src/content/docs/zh-tw/cli.mdx new file mode 100644 index 000000000..58380d741 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/cli.mdx @@ -0,0 +1,601 @@ +--- +title: 命令行界面 +description: OpenCode CLI 選項和命令。 +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +默認情況下,OpenCode CLI 在不帶任何參數運行時啟動[途易](/docs/tui)。 + +```bash +opencode +``` + +但它也接受本頁記錄的命令。這允許您以編程方式與 OpenCode 交互。 + +```bash +opencode run "Explain how closures work in JavaScript" +``` + +--- + +### tui + +啟動 OpenCode 終端用戶界面。 + +```bash +opencode [project] +``` + +#### 旗幟 + +|旗幟|短|描述 | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` |繼續上一期 | +| `--session` | `-s` |會話 ID 繼續 | +| `--prompt` | |提示使用| +| `--model` | `-m` |以提供者/模型形式使用的模型 | +| `--agent` | |代理使用| +| `--port` | |監聽端口 | +| `--hostname` | |監聽的主機名 | + +--- + +## 命令 + +OpenCode CLI 還具有以下命令。 + +--- + +### agent + +管理 OpenCode 代理。 + +```bash +opencode agent [command] +``` + +--- + +### attach + +將終端連接到通過 `serve` 或 `web` 命令啟動的已運行的 OpenCode 後端服務器。 + +```bash +opencode attach [url] +``` + +這允許將 TUI 與遠程 OpenCode 後端一起使用。例如: + +```bash +# Start the backend server for web/mobile access +opencode web --port 4096 --hostname 0.0.0.0 + +# In another terminal, attach the TUI to the running backend +opencode attach http://10.20.30.40:4096 +``` + +#### 旗幟 + +|旗幟|短|描述 | +| ----------- | ----- | --------------------------------- | +| `--dir` | |啟動 TUI 的工作目錄 | +| `--session` | `-s` |會話 ID 繼續 | + +--- + +#### create + +使用自定義配置創建新代理。 + +```bash +opencode agent create +``` + +此命令將指導您使用自定義系統提示和工具配置創建新代理。 + +--- + +#### list + +列出所有可用的代理。 + +```bash +opencode agent list +``` + +--- + +### auth + +用於管理提供商的憑據和登錄的命令。 + +```bash +opencode auth [command] +``` + +--- + +#### login + +OpenCode 由 [模型.dev](https://models.dev) 上的提供商列表提供支持,因此您可以使用 `opencode auth login` 為您想要使用的任何提供商配置 API 密鑰。它存儲在`~/.local/share/opencode/auth.json` 中。 + +```bash +opencode auth login +``` + +當 OpenCode 啟動時,它會從憑據文件加載提供程序。如果您的環境中定義了任何鍵或項目中的 `.env` 文件。 + +--- + +#### list + +列出憑證文件中存儲的所有經過身份驗證的提供程序。 + +```bash +opencode auth list +``` + +或者簡短的版本。 + +```bash +opencode auth ls +``` + +--- + +#### logout + +通過從憑據文件中清除提供程序,將您從提供程序中註銷。 + +```bash +opencode auth logout +``` + +--- + +### github + +管理 GitHub 代理以實現存儲庫自動化。 + +```bash +opencode github [command] +``` + +--- + +#### install + +在您的存儲庫中安裝 GitHub 代理。 + +```bash +opencode github install +``` + +這將設置必要的 GitHub Actions 工作流程並指導您完成配置過程。 [了解更多](/docs/github)。 + +--- + +#### run + +運行 GitHub 代理。這通常用在 GitHub Actions 中。 + +```bash +opencode github run +``` + +##### 旗幟 + +|旗幟|描述 | +| --------- | -------------------------------------- | +| `--event` |用於運行代理的 GitHub 模擬事件 | +| `--token` | GitHub 個人訪問令牌 | + +--- + +### mcp + +管理模型上下文協議服務器。 + +```bash +opencode mcp [command] +``` + +--- + +#### add + +將 MCP 服務器添加到您的配置中。 + +```bash +opencode mcp add +``` + +此命令將指導您添加本地或遠程 MCP 服務器。 + +--- + +#### list + +列出所有已配置的 MCP 服務器及其連接狀態。 + +```bash +opencode mcp list +``` + +或者使用簡短版本。 + +```bash +opencode mcp ls +``` + +--- + +#### auth + +使用啟用 OAuth 的 MCP 服務器進行身份驗證。 + +```bash +opencode mcp auth [name] +``` + +如果您不提供服務器名稱,系統將提示您從可用的支持 OAuth 的服務器中進行選擇。 + +您還可以列出支持 OAuth 的服務器及其身份驗證狀態。 + +```bash +opencode mcp auth list +``` + +或者使用簡短版本。 + +```bash +opencode mcp auth ls +``` + +--- + +#### logout + +刪除 MCP 服務器的 OAuth 憑據。 + +```bash +opencode mcp logout [name] +``` + +--- + +#### debug + +調試 MCP 服務器的 OAuth 連接問題。 + +```bash +opencode mcp debug +``` + +--- + +### models + +列出已配置提供商的所有可用模型。 + +```bash +opencode models [provider] +``` + +此命令以 `provider/model` 格式顯示您配置的提供程序中可用的所有模型。 + +這對於確定[你的配置](/docs/config/) 中使用的確切模型名稱很有用。 + +您可以選擇傳遞提供程序 ID 以按該提供程序篩選模型。 + +```bash +opencode models anthropic +``` + +#### 旗幟 + +|旗幟|描述 | +| ----------- | ------------------------------------------------------------ | +| `--refresh` |從 models.dev | 刷新模型緩存 +| `--verbose` |使用更詳細的模型輸出(包括成本等元數據)| + +使用`--refresh`標誌來更新緩存的模型列表。當新模型已添加到提供程序並且您希望在 OpenCode 中查看它們時,這非常有用。 + +```bash +opencode models --refresh +``` + +--- + +### run + +通過直接傳遞提示以非交互模式運行 opencode。 + +```bash +opencode run [message..] +``` + +這對於腳本編寫、自動化,或者當您想要快速得到答案而不啟動完整的 TUI 時非常有用。例如。 + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +您還可以附加到正在運行的 `opencode serve` 實例,以避免每次運行時 MCP 服務器冷啟動時間: + +```bash +# Start a headless server in one terminal +opencode serve + +# In another terminal, run commands that attach to it +opencode run --attach http://localhost:4096 "Explain async/await in JavaScript" +``` + +#### 旗幟 + +|旗幟|短|描述 | +| ------------ | ----- | ------------------------------------------------------------------ | +| `--command` | |要運行的命令,使用消息作為參數 | +| `--continue` | `-c` |繼續上一期 | +| `--session` | `-s` |會話 ID 繼續 | +| `--share` | |分享會議 | +| `--model` | `-m` |以提供者/模型形式使用的模型 | +| `--agent` | |代理使用| +| `--file` | `-f` |要附加到消息的文件 | +| `--format` | |格式:默認(格式化)或 json(原始 JSON 事件)| +| `--title` | |會話標題(如果未提供值,則使用截斷的提示)| +| `--attach` | |連接到正在運行的 opencode 服務器(例如,http://localhost:4096)| +| `--port` | |本地服務器的端口(默認為隨機端口) | + +--- + +### serve + +啟動無頭 OpenCode 服務器以進行 API 訪問。查看[服務器文檔](/docs/server) 以獲取完整的 HTTP 接口。 + +```bash +opencode serve +``` + +這將啟動一個 HTTP 服務器,該服務器提供對 opencode 功能的 API 訪問,而無需 TUI 接口。設置`OPENCODE_SERVER_PASSWORD`以啟用HTTP基本身份驗證(用戶名默認為`opencode`)。 + +#### 旗幟 + +|旗幟|描述 | +| ------------ | ------------------------------------------ | +| `--port` |監聽端口 | +| `--hostname` |監聽的主機名 | +| `--mdns` |啟用 mDNS 發現 | +| `--cors` |允許 CORS 的其他瀏覽器源 | + +--- + +### session + +管理 OpenCode 會話。 + +```bash +opencode session [command] +``` + +--- + +#### list + +列出所有 OpenCode 會話。 + +```bash +opencode session list +``` + +##### 旗幟 + +|旗幟|短|描述 | +| ------------- | ----- | ------------------------------------ | +| `--max-count` | `-n` |限制為最近 N 個會話 | +| `--format` | |輸出格式:table 或 json(table) | + +--- + +### stats + +顯示 OpenCode 會話的令牌使用情況和成本統計信息。 + +```bash +opencode stats +``` + +#### 旗幟 + +|旗幟|描述 | +| ----------- | --------------------------------------------------------------------------- | +| `--days` |顯示過去 N 天(所有時間)的統計數據 | +| `--tools` |顯示的工具數量(全部)| +| `--models` |顯示模型使用情況細分(默認隱藏)。傳遞一個數字來顯示前 N | +| `--project` |按項目過濾(所有項目,空字符串:當前項目)| + +--- + +### export + +將會話數據導出為 JSON。 + +```bash +opencode export [sessionID] +``` + +如果您不提供會話 ID,系統將提示您從可用會話中進行選擇。 + +--- + +### import + +從 JSON 文件或 OpenCode 共享 URL 導入會話數據。 + +```bash +opencode import +``` + +您可以從本地文件或 OpenCode 共享 URL 導入。 + +```bash +opencode import session.json +opencode import https://opncd.ai/s/abc123 +``` + +--- + +### web + +使用 Web 界面啟動無頭 OpenCode 服務器。 + +```bash +opencode web +``` + +這將啟動 HTTP 服務器並打開 Web 瀏覽器以通過 Web 界面訪問 OpenCode。設置`OPENCODE_SERVER_PASSWORD`以啟用HTTP基本身份驗證(用戶名默認為`opencode`)。 + +#### 旗幟 + +|旗幟|描述 | +| ------------ | ------------------------------------------ | +| `--port` |監聽端口 | +| `--hostname` |監聽的主機名 | +| `--mdns` |啟用 mDNS 發現 | +| `--cors` |允許 CORS 的其他瀏覽器源 | + +--- + +### acp + +啟動 ACP(代理客戶端協議)服務器。 + +```bash +opencode acp +``` + +此命令啟動一個 ACP 服務器,該服務器使用 nd-JSON 通過 stdin/stdout 進行通信。 + +#### 旗幟 + +|旗幟|描述 | +| ------------ | --------------------- | +| `--cwd` |工作目錄 | +| `--port` |監聽端口 | +| `--hostname` |監聽的主機名 | + +--- + +### uninstall + +卸載 OpenCode 並刪除所有相關文件。 + +```bash +opencode uninstall +``` + +#### 旗幟 + +|旗幟|短|描述 | +| --------------- | ----- | ------------------------------------------- | +| `--keep-config` | `-c` |保留配置文件| +| `--keep-data` | `-d` |保留會話數據和快照 | +| `--dry-run` | |顯示在不刪除的情況下將刪除的內容 | +| `--force` | `-f` |跳過確認提示 | + +--- + +### upgrade + +將 opencode 更新到最新版本或特定版本。 + +```bash +opencode upgrade [target] +``` + +升級到最新版本。 + +```bash +opencode upgrade +``` + +升級到特定版本。 + +```bash +opencode upgrade v0.1.48 +``` + +#### 旗幟 + +|旗幟|短|描述 | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` |使用的安裝方法;捲曲、npm、pnpm、bun、brew | + +--- + +## 全球旗幟 + +opencode CLI 採用以下全局標誌。 + +|旗幟|短|描述 | +| -------------- | ----- | ------------------------------------ | +| `--help` | `-h` |顯示幫助| +| `--version` | `-v` |打印版本號 | +| `--print-logs` | |將日誌打印到 stderr | +| `--log-level` | |日誌級別(調試、信息、警告、錯誤)| + +--- + +## 環境變量 + +可以使用環境變量配置 OpenCode。 + +|變量|類型 |描述 | +| ------------------------------------- | ------- | ------------------------------------------------- | +| `OPENCODE_AUTO_SHARE` |布爾 |自動共享會話 | +| `OPENCODE_GIT_BASH_PATH` |字符串| Windows 上 Git Bash 可執行文件的路徑 | +| `OPENCODE_CONFIG` |字符串|配置文件路徑 | +| `OPENCODE_CONFIG_DIR` |字符串|配置目錄的路徑 | +| `OPENCODE_CONFIG_CONTENT` |字符串|內聯 json 配置內容 | +| `OPENCODE_DISABLE_AUTOUPDATE` |布爾 |禁用自動更新檢查 | +| `OPENCODE_DISABLE_PRUNE` |布爾 |禁用舊數據的修剪 | +| `OPENCODE_DISABLE_TERMINAL_TITLE` |布爾 |禁用自動終端標題更新 | +| `OPENCODE_PERMISSION` |字符串|內聯 json 權限配置 | +| `OPENCODE_DISABLE_DEFAULT_PLUGINS` |布爾 |禁用默認插件 | +| `OPENCODE_DISABLE_LSP_DOWNLOAD` |布爾 |禁用自動 LSP 服務器下載 | +| `OPENCODE_ENABLE_EXPERIMENTAL_MODELS` |布爾 |啟用實驗模型 | +| `OPENCODE_DISABLE_AUTOCOMPACT` |布爾 |禁用自動上下文壓縮 | +| `OPENCODE_DISABLE_CLAUDE_CODE` |布爾 |禁止從`.claude`讀取(提示+技巧)| +| `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` |布爾 |禁用讀取`~/.claude/CLAUDE.md` | +| `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` |布爾 |禁用加載`.claude/skills` | +| `OPENCODE_DISABLE_MODELS_FETCH` |布爾 |禁用從遠程源獲取模型 | +| `OPENCODE_FAKE_VCS` |字符串|用於測試目的的假 VCS 提供商 | +| `OPENCODE_DISABLE_FILETIME_CHECK` |布爾 |禁用文件時間檢查以進行優化 | +| `OPENCODE_CLIENT` |字符串|客戶端標識符(默認為`cli`)| +| `OPENCODE_ENABLE_EXA` |布爾 |啟用 Exa 網絡搜索工具 | +| `OPENCODE_SERVER_PASSWORD` |字符串|為 `serve`/`web` 啟用基本身份驗證 | +| `OPENCODE_SERVER_USERNAME` |字符串|覆蓋基本身份驗證用戶名(默認`opencode`)| +| `OPENCODE_MODELS_URL` |字符串|用於獲取模型配置的自定義 URL | + +--- + +### 實驗性的 + +這些環境變量啟用可能會更改或刪除的實驗性功能。 + +|變量|類型 |描述 | +| ----------------------------------------------- | ------- | --------------------------------------- | +| `OPENCODE_EXPERIMENTAL` |布爾 |啟用所有實驗性功能 | +| `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY` |布爾 |啟用圖標發現 | +| `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT` |布爾 |在 TUI 中禁用選擇時復制 | +| `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS` |數量 | bash 命令的默認超時(以毫秒為單位) | +| `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX` |數量 | LLM 響應的最大輸出令牌 | +| `OPENCODE_EXPERIMENTAL_FILEWATCHER` |布爾 |為整個目錄啟用文件觀察器 | +| `OPENCODE_EXPERIMENTAL_OXFMT` |布爾 |啟用 oxfmt 格式化程序 | +| `OPENCODE_EXPERIMENTAL_LSP_TOOL` |布爾 |啟用實驗性 LSP 工具 | +| `OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER` |布爾 |禁用文件觀察器 | +| `OPENCODE_EXPERIMENTAL_EXA` |布爾 |啟用實驗性 Exa 功能 | +| `OPENCODE_EXPERIMENTAL_LSP_TY` |布爾 |啟用實驗性 LSP 類型檢查 | +| `OPENCODE_EXPERIMENTAL_MARKDOWN` |布爾 |啟用實驗性 Markdown 功能 | +| `OPENCODE_EXPERIMENTAL_PLAN_MODE` |布爾 |啟用計劃模式 | diff --git a/packages/web/src/content/docs/zh-tw/commands.mdx b/packages/web/src/content/docs/zh-tw/commands.mdx new file mode 100644 index 000000000..06786bf98 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/commands.mdx @@ -0,0 +1,323 @@ +--- +title: 命令 +description: 為重複任務創建自定義命令。 +--- + +自定義命令允許您指定在 TUI 中執行該命令時要運行的提示。 + +```bash frame="none" +/my-command +``` + +除了`/init`、`/undo`、`/redo`、`/share`、`/help` 等內置命令之外,還有自定義命令。 [了解更多](/docs/tui#commands)。 + +--- + +## 創建命令文件 + +在`commands/`目錄中創建markdown文件來定義自定義命令。 + +創建`.opencode/commands/test.md`: + +```md title=".opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +frontmatter 定義命令屬性。內容成為模板。 + +通過鍵入 `/` 後跟命令名稱來使用該命令。 + +```bash frame="none" +"/test" +``` + +--- + +## 配置 + +您可以通過 OpenCode 配置或通過在 `commands/` 目錄中創建 markdown 文件來添加自定義命令。 + +--- + +### JSON + +在 OpenCode [配置](/docs/config) 中使用 `command` 選項: + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is shown as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +現在您可以在 TUI 中運行此命令: + +```bash frame="none" +/test +``` + +--- + +### 降價 + +您還可以使用 Markdown 文件定義命令。將它們放入: + +- 全球:`~/.config/opencode/commands/` +- 每個項目:`.opencode/commands/` + +```markdown title="~/.config/opencode/commands/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +Markdown 文件名成為命令名。例如,`test.md` 讓 +你運行: + +```bash frame="none" +/test +``` + +--- + +## 提示配置 + +自定義命令的提示支持幾個特殊的佔位符和語法。 + +--- + +### 論據 + +使用 `$ARGUMENTS` 佔位符將參數傳遞給命令。 + +```md title=".opencode/commands/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +使用參數運行命令: + +```bash frame="none" +/component Button +``` + +`$ARGUMENTS` 將替換為 `Button`。 + +您還可以使用位置參數訪問各個參數: + +- `$1` - 第一個參數 +- `$2` - 第二個參數 +- `$3` - 第三個參數 +- 等等... + +例如: + +```md title=".opencode/commands/create-file.md" +--- +description: Create a new file with content +--- + +Create a file named $1 in the directory $2 +with the following content: $3 +``` + +運行命令: + +```bash frame="none" +/create-file config.json src "{ \"key\": \"value\" }" +``` + +這取代了: + +- `$1` 與`config.json` +- `$2` 與`src` +- `$3` 與`{ "key": "value" }` + +--- + +### 外殼輸出 + +使用 _!`command`_ 將 [bash命令](/docs/tui#bash-commands) 輸出注入到提示符中。 + +例如,要創建分析測試覆蓋率的自定義命令: + +```md title=".opencode/commands/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +或者查看最近的更改: + +```md title=".opencode/commands/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +命令在項目的根目錄中運行,其輸出成為提示的一部分。 + +--- + +### 文件參考 + +使用 `@` 後跟文件名將文件包含在命令中。 + +```md title=".opencode/commands/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +文件內容會自動包含在提示中。 + +--- + +## 選項 + +讓我們詳細看看配置選項。 + +--- + +### 模板 + +`template` 選項定義執行命令時將發送到 LLM 的提示。 + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +這是一個**必需的**配置選項。 + +--- + +### 描述 + +使用 `description` 選項提供命令功能的簡要描述。 + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +當您鍵入命令時,這將在 TUI 中顯示為描述。 + +--- + +### 代理人 + +使用`agent` 配置可選擇指定哪個[代理人](/docs/agents) 應執行此命令。 +如果這是 [子代理](/docs/agents/#subagents) 該命令將默認觸發子代理調用。 +要禁用此行為,請將`subtask` 設置為`false`。 + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +這是一個**可選**配置選項。如果未指定,則默認為您當前的代理。 + +--- + +### 子任務 + +使用`subtask` 布爾值強制命令觸發[子代理](/docs/agents/#subagents) 調用。 +如果您希望命令不污染您的主要上下文並且將**強制**代理充當子代理,那麼這非常有用, +即使`mode` 在[代理人](/docs/agents) 配置上設置為`primary`。 + +```json title="opencode.json" +{ + "command": { + "analyze": { + "subtask": true + } + } +} +``` + +這是一個**可選**配置選項。 + +--- + +### 模型 + +使用 `model` 配置覆蓋此命令的默認模型。 + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +這是一個**可選**配置選項。 + +--- + +## 內建 + +opencode包含`/init`、`/undo`、`/redo`、`/share`、`/help`等內置命令; [了解更多](/docs/tui#commands)。 + +:::note +自定義命令可以覆蓋內置命令。 +::: + +如果您定義同名的自定義命令,它將覆蓋內置命令。 diff --git a/packages/web/src/content/docs/zh-tw/config.mdx b/packages/web/src/content/docs/zh-tw/config.mdx new file mode 100644 index 000000000..a15d1c19c --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/config.mdx @@ -0,0 +1,685 @@ +--- +title: 配置 +description: 使用 OpenCode JSON 配置。 +--- + +您可以使用 JSON 配置文件配置 OpenCode。 + +--- + +## 格式 + +OpenCode 支持 **JSON** 和 **JSONC**(帶註釋的 JSON)格式。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-5", + "autoupdate": true, +} +``` + +--- + +## 地點 + +您可以將配置放置在幾個不同的位置,它們有一個 +不同的優先順序。 + +:::note +配置文件**合併在一起**,而不是替換。 +::: + +配置文件被合併在一起,而不是被替換。以下配置位置的設置被合併。僅當密鑰衝突時,後面的配置才會覆蓋前面的配置。保留所有配置中的非衝突設置。 + +例如,如果您的全局配置設置`theme: "opencode"`和`autoupdate: true`,並且您的項目配置設置`model: "anthropic/claude-sonnet-4-5"`,則最終配置將包括所有三個設置。 + +--- + +### 優先順序 + +配置源按以下順序加載(後面的源覆蓋前面的源): + +1. **遠程配置**(來自`.well-known/opencode`)-組織默認值 +2. **全局配置** (`~/.config/opencode/opencode.json`) - 用戶首選項 +3. **自定義配置** (`OPENCODE_CONFIG` env var) - 自定義覆蓋 +4. **項目配置**(項目中的`opencode.json`)- 項目特定的設置 +5. **`.opencode` 目錄** - 代理、命令、插件 +6. **內聯配置** (`OPENCODE_CONFIG_CONTENT` env var) - 運行時覆蓋 + +這意味著項目配置可以覆蓋全局默認值,全局配置可以覆蓋遠程組織默認值。 + +:::note +`.opencode` 和`~/.config/opencode` 目錄對子目錄使用**複數名稱**:`agents/`、`commands/`、`modes/`、`plugins/`、`skills/`、`tools/` 和`themes/`。為了向後兼容,還支持單數名稱(例如`agent/`)。 +::: + +--- + +### 偏僻的 + +組織可以通過 `.well-known/opencode` 端點提供默認配置。當您向支持它的提供商進行身份驗證時,會自動獲取該信息。 + +首先加載遠程配置,作為基礎層。所有其他配置源(全局、項目)都可以覆蓋這些默認值。 + +例如,如果您的組織提供默認禁用的 MCP 服務器: + +```json title="Remote config from .well-known/opencode" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": false + } + } +} +``` + +您可以在本地配置中啟用特定服務器: + +```json title="opencode.json" +{ + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +--- + +### 全球的 + +將全局 OpenCode 配置放在 `~/.config/opencode/opencode.json` 中。使用全局配置來實現用戶範圍的首選項,例如主題、提供程序或按鍵綁定。 + +全局配置覆蓋遠程組織默認值。 + +--- + +### 每個項目 + +在項目根目錄中添加`opencode.json`。項目配置在標準配置文件中具有最高優先級 - 它覆蓋全局配置和遠程配置。 + +:::tip +將項目特定配置放在項目的根目錄中。 +::: + +當 OpenCode 啟動時,它會在當前目錄中查找配置文件或遍歷到最近的 Git 目錄。 + +這也可以安全地簽入 Git 並使用與全局模式相同的模式。 + +--- + +### 自定義路徑 + +使用 `OPENCODE_CONFIG` 環境變量指定自定義配置文件路徑。 + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +自定義配置按優先順序在全局配置和項目配置之間加載。 + +--- + +### 自定義目錄 + +使用`OPENCODE_CONFIG_DIR`指定自定義配置目錄 +環境變量。將在該目錄中搜索代理、命令、 +模式和插件就像標準`.opencode`目錄一樣,並且應該 +遵循相同的結構。 + +```bash +export OPENCODE_CONFIG_DIR=/path/to/my/config-directory +opencode run "Hello world" +``` + +自定義目錄在全局配置和`.opencode`目錄之後加載,因此它**可以覆蓋**它們的設置。 + +--- + +## 模式 + +配置文件具有在 [**`opencode.ai/config.json`**](https://opencode.ai/config.json) 中定義的架構。 + +您的編輯器應該能夠根據架構進行驗證和自動完成。 + +--- + +### TUI + +您可以通過 `tui` 選項配置特定於 TUI 的設置。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + }, + "diff_style": "auto" + } +} +``` + +可用選項: + +- `scroll_acceleration.enabled` - 啟用 macOS 風格的滾動加速。 **優先於`scroll_speed`。 ** +- `scroll_speed` - 自定義滾動速度倍增(默認值:`3`,最小值:`1`)。如果`scroll_acceleration.enabled` 是`true`,則忽略。 +- `diff_style` - 控制差異渲染。 `"auto"` 適應終端寬度,`"stacked"` 始終顯示單列。 + +[在此處了解有關使用 TUI 的更多信息](/docs/tui)。 + +--- + +### 伺服器 + +您可以通過`server` 選項為`opencode serve` 和`opencode web` 命令配置服務器設置。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "mdnsDomain": "myproject.local", + "cors": ["http://localhost:5173"] + } +} +``` + +可用選項: + +- `port` - 監聽的端口。 +- `hostname` - 要監聽的主機名。當`mdns`啟用且未設置主機名時,默認為`0.0.0.0`。 +- `mdns` - 啟用 mDNS 服務發現。這允許網絡上的其他設備發現您的 OpenCode 服務器。 +- `mdnsDomain` - mDNS 服務的自定義域名。默認為`opencode.local`。對於在同一網絡上運行多個實例很有用。 +- `cors` - 從基於瀏覽器的客戶端使用 HTTP 服務器時允許 CORS 的其他來源。值必須是完整來源(方案+主機+可選端口),例如`https://app.example.com`。 + +[在此處了解有關服務器的更多信息](/docs/server)。 + +--- + +### 工具 + +您可以通過 `tools` 選項管理法學碩士可以使用的工具。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tools": { + "write": false, + "bash": false + } +} +``` + +[在此處了解有關工具的更多信息](/docs/tools)。 + +--- + +### 型號 + +您可以通過 `provider`、`model` 和 `small_model` 選項來配置要在 OpenCode 配置中使用的提供程序和模型。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-5", + "small_model": "anthropic/claude-haiku-4-5" +} +``` + +`small_model` 選項為標題生成等輕量級任務配置單獨的模型。默認情況下,如果您的提供商可以提供更便宜的模型,OpenCode 會嘗試使用更便宜的模型,否則它會回退到您的主模型。 + +提供者選項可以包括`timeout`和`setCacheKey`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "timeout": 600000, + "setCacheKey": true + } + } + } +} +``` + +- `timeout` - 請求超時以毫秒為單位(默認值:300000)。設置為 `false` 以禁用。 +- `setCacheKey` - 確保始終為指定的提供者設置緩存密鑰。 + +您還可以配置[本地模型](/docs/models#local)。 [了解更多](/docs/models)。 + +--- + +#### 特定於提供商的選項 + +某些提供程序支持除通用`timeout` 和`apiKey` 設置之外的其他配置選項。 + +##### 亞馬遜基岩 + +Amazon Bedrock 支持 AWS 特定配置: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } +} +``` + +- `region` - Bedrock 的 AWS 區域(默認為 `AWS_REGION` env var 或 `us-east-1`) +- `profile` - 來自 `~/.aws/credentials` 的 AWS 命名配置文件(默認為 `AWS_PROFILE` env var) +- `endpoint` - VPC 終端節點的自定義終端節點 URL。這是使用 AWS 特定術語的通用 `baseURL` 選項的別名。如果兩者都指定,`endpoint` 優先。 + +:::note +承載令牌(`AWS_BEARER_TOKEN_BEDROCK` 或`/connect`)優先於基於配置文件的身份驗證。詳情請參閱[認證優先級](/docs/providers#authentication-precedence)。 +::: + +[了解有關 Amazon Bedrock 配置的更多信息](/docs/providers#amazon-bedrock)。 + +--- + +### 主題 + +您可以通過 `theme` 選項在 OpenCode 配置中配置要使用的主題。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[在這裡了解更多](/docs/themes)。 + +--- + +### 代理商 + +您可以通過 `agent` 選項為特定任務配置專用代理。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-5", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +您還可以使用 `~/.config/opencode/agents/` 或 `.opencode/agents/` 中的 markdown 文件定義代理。 [在這裡了解更多](/docs/agents)。 + +--- + +### 默認代理 + +您可以使用 `default_agent` 選項設置默認代理。當沒有明確指定時,這將確定使用哪個代理。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan" +} +``` + +默認代理必須是主代理(而不是子代理)。這可以是內置代理,例如`"build"`或`"plan"`,或者您定義的[定制代理](/docs/agents)。如果指定的代理不存在或者是子代理,OpenCode 將回退到 `"build"` 並發出警告。 + +此設置適用於所有界面:TUI、CLI (`opencode run`)、桌面應用程序和 GitHub Action。 + +--- + +### 分享 + +您可以通過`share`選項配置[分享](/docs/share)功能。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +這需要: + +- `"manual"` - 允許通過命令手動共享(默認) +- `"auto"` - 自動分享新對話 +- `"disabled"` - 完全禁用共享 + +默認情況下,共享設置為手動模式,您需要使用 `/share` 命令顯式共享對話。 + +--- + +### 命令 + +您可以通過`command`選項為重複任務配置自定義命令。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-haiku-4-5", + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component", + }, + }, +} +``` + +您還可以使用 `~/.config/opencode/commands/` 或 `.opencode/commands/` 中的 Markdown 文件定義命令。 [在這裡了解更多](/docs/commands)。 + +--- + +### 按鍵綁定 + +您可以通過 `keybinds` 選項自定義您的按鍵綁定。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[在這裡了解更多](/docs/keybinds)。 + +--- + +### 自動更新 + +OpenCode 將在啟動時自動下載任何新的更新。您可以使用 `autoupdate` 選項禁用此功能。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +如果您不想更新但希望在新版本可用時收到通知,請將`autoupdate` 設置為`"notify"`。 +請注意,這僅在未使用 Homebrew 等包管理器安裝時才有效。 + +--- + +### 格式化程序 + +您可以通過`formatter`選項配置代碼格式化程序。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[在此處了解有關格式化程序的更多信息](/docs/formatters)。 + +--- + +### 權限 + +默認情況下,opencode **允許所有操作**,無需明確批准。您可以使用`permission` 選項更改此設置。 + +例如,要確保 `edit` 和 `bash` 工具需要用戶批准: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +[在此處了解有關權限的更多信息](/docs/permissions)。 + +--- + +### 壓實 + +您可以通過 `compaction` 選項控制上下文壓縮行為。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "auto": true, + "prune": true + } +} +``` + +- `auto` - 當上下文已滿時自動壓縮會話(默認值:`true`)。 +- `prune` - 刪除舊工具輸出以保存令牌(默認值:`true`)。 + +--- + +### 守望者 + +您可以通過`watcher`選項配置文件觀察器忽略模式。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "watcher": { + "ignore": ["node_modules/**", "dist/**", ".git/**"] + } +} +``` + +模式遵循 glob 語法。使用它可以從文件監視中排除嘈雜的目錄。 + +--- + +### MCP服務器 + +您可以通過 `mcp` 選項配置要使用的 MCP 服務器。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[在這裡了解更多](/docs/mcp-servers)。 + +--- + +### 插件 + +[插件](/docs/plugins) 使用自定義工具、掛鉤和集成擴展 OpenCode。 + +將插件文件放置在`.opencode/plugins/` 或`~/.config/opencode/plugins/` 中。您還可以通過 `plugin` 選項從 npm 加載插件。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] +} +``` + +[在這裡了解更多](/docs/plugins)。 + +--- + +### 指示 + +您可以通過 `instructions` 選項配置您正在使用的型號的說明。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +這需要指令文件的路徑和全局模式數組。 [了解更多 +關於規則在這裡](/docs/rules)。 + +--- + +### 殘疾服務提供者 + +您可以通過 `disabled_providers` 選項禁用自動加載的提供程序。當您想要阻止加載某些提供程序(即使其憑據可用)時,這非常有用。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +:::note +`disabled_providers` 優先於`enabled_providers`。 +::: + +`disabled_providers` 選項接受提供者 ID 數組。當提供者被禁用時: + +- 即使設置了環境變量也不會加載。 +- 即使通過 `/connect` 命令配置 API 密鑰,也不會加載它。 +- 提供商的型號不會出現在型號選擇列表中。 + +--- + +### 啟用的提供商 + +您可以通過 `enabled_providers` 選項指定提供商的允許列表。設置後,僅啟用指定的提供程序,所有其他提供程序將被忽略。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "enabled_providers": ["anthropic", "openai"] +} +``` + +當您想要限制 OpenCode 僅使用特定的提供程序而不是一一禁用它們時,這非常有用。 + +:::note +`disabled_providers` 優先於`enabled_providers`。 +::: + +如果某個提供程序同時出現在`enabled_providers` 和`disabled_providers` 中,則`disabled_providers` 優先考慮向後兼容性。 + +--- + +### 實驗性的 + +`experimental` 鍵包含正在積極開發的選項。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": {} +} +``` + +:::caution +實驗選項不穩定。它們可能會更改或被刪除,恕不另行通知。 +::: + +--- + +## 變量 + +您可以在配置文件中使用變量替換來引用環境變量和文件內容。 + +--- + +### 環境變量 + +使用`{env:VARIABLE_NAME}`替換環境變量: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +如果未設置環境變量,它將被替換為空字符串。 + +--- + +### 文件 + +使用 `{file:path/to/file}` 替換文件的內容: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +文件路徑可以是: + +- 相對於配置文件目錄 +- 或者以 `/` 或 `~` 開頭的絕對路徑 + +這些對於: + +- 將 API 密鑰等敏感數據保存在單獨的文件中。 +- 包含大型指令文件,而不會弄亂您的配置。 +- 跨多個配置文件共享通用配置片段。 diff --git a/packages/web/src/content/docs/zh-tw/custom-tools.mdx b/packages/web/src/content/docs/zh-tw/custom-tools.mdx new file mode 100644 index 000000000..4a5ea7648 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/custom-tools.mdx @@ -0,0 +1,170 @@ +--- +title: 定制工具 +description: 創建法學碩士可以在開放代碼中調用的工具。 +--- + +自定義工具是您創建的函數,LLM 可以在對話期間調用。它們與 opencode 的 [內置工具](/docs/tools) 一起工作,例如 `read`、`write` 和 `bash`。 + +--- + +## 創建工具 + +工具定義為 **TypeScript** 或 **JavaScript** 文件。但是,工具定義可以調用用 **任何語言** 編寫的腳本 - TypeScript 或 JavaScript 僅用於工具定義本身。 + +--- + +### 地點 + +它們可以定義為: + +- 通過將它們放在項目的 `.opencode/tools/` 目錄中來本地進行。 +- 或者在全局範圍內,將它們放置在 `~/.config/opencode/tools/` 中。 + +--- + +### 結構 + +創建工具的最簡單方法是使用 `tool()` 幫助程序,它提供類型安全和驗證。 + +```ts title=".opencode/tools/database.ts" {1} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Query the project database", + args: { + query: tool.schema.string().describe("SQL query to execute"), + }, + async execute(args) { + // Your database logic here + return `Executed query: ${args.query}` + }, +}) +``` + +**文件名**成為**工具名稱**。以上創建了一個 `database` 工具。 + +--- + +#### 每個文件多個工具 + +您還可以從單個文件導出多個工具。每個導出都會成為**一個單獨的工具**,名稱為**`_`**: + +```ts title=".opencode/tools/math.ts" +import { tool } from "@opencode-ai/plugin" + +export const add = tool({ + description: "Add two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a + args.b + }, +}) + +export const multiply = tool({ + description: "Multiply two numbers", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args) { + return args.a * args.b + }, +}) +``` + +這將創建兩個工具:`math_add` 和`math_multiply`。 + +--- + +### 論據 + +您可以使用`tool.schema`(即[佐德](https://zod.dev))來定義參數類型。 + +```ts "tool.schema" +args: { + query: tool.schema.string().describe("SQL query to execute") +} +``` + +您還可以直接導入[佐德](https://zod.dev)並返回一個普通對象: + +```ts {6} +import { z } from "zod" + +export default { + description: "Tool description", + args: { + param: z.string().describe("Parameter description"), + }, + async execute(args, context) { + // Tool implementation + return "result" + }, +} +``` + +--- + +### 情境 + +工具接收有關當前會話的上下文: + +```ts title=".opencode/tools/project.ts" {8} +import { tool } from "@opencode-ai/plugin" + +export default tool({ + description: "Get project information", + args: {}, + async execute(args, context) { + // Access context information + const { agent, sessionID, messageID, directory, worktree } = context + return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` + }, +}) +``` + +使用 `context.directory` 作為會話工作目錄。 +使用 `context.worktree` 作為 git 工作樹根。 + +--- + +## 示例 + +### 用Python編寫一個工具 + +您可以用任何您想要的語言編寫工具。下面是一個使用 Python 將兩個數字相加的示例。 + +首先,將該工具創建為 Python 腳本: + +```python title=".opencode/tools/add.py" +import sys + +a = int(sys.argv[1]) +b = int(sys.argv[2]) +print(a + b) +``` + +然後創建調用它的工具定義: + +```ts title=".opencode/tools/python-add.ts" {10} +import { tool } from "@opencode-ai/plugin" +import path from "path" + +export default tool({ + description: "Add two numbers using Python", + args: { + a: tool.schema.number().describe("First number"), + b: tool.schema.number().describe("Second number"), + }, + async execute(args, context) { + const script = path.join(context.worktree, ".opencode/tools/add.py") + const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text() + return result.trim() + }, +}) +``` + +這裡我們使用 [`Bun.$`](https://bun.com/docs/runtime/shell) 實用程序來運行 Python 腳本。 diff --git a/packages/web/src/content/docs/zh-tw/ecosystem.mdx b/packages/web/src/content/docs/zh-tw/ecosystem.mdx new file mode 100644 index 000000000..1761ad5f9 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/ecosystem.mdx @@ -0,0 +1,76 @@ +--- +title: 生態系統 +description: 使用 OpenCode 構建的項目和集成。 +--- + +基於 OpenCode 的社區項目集合。 + +:::note +想要將您的 OpenCode 相關項目添加到此列表中嗎?提交 PR。 +::: + +您還可以查看[很棒的開放代碼](https://github.com/awesome-opencode/awesome-opencode)和[開放代碼咖啡館](https://opencode.cafe),這是一個聚合生態系統和社區的社區。 + +--- + +## 插件 + +|名稱 |描述 | +| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [Opencode-Daytona](https://github.com/jamesmurdza/daytona/blob/main/guides/typescript/opencode/README.md) |使用 git 同步和實時預覽在隔離的 Daytona 沙箱中自動運行 OpenCode 會話 | +| [opencode-helicone-會話](https://github.com/H2Shami/opencode-helicone-session) |自動注入 Helicone 會話標頭以進行請求分組 | +| [打開代碼類型注入](https://github.com/nick-vi/opencode-type-inject) |使用查找工具將 TypeScript/Svelte 類型自動注入到文件讀取中 | +| [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) |使用您的 ChatGPT Plus/Pro 訂閱而不是 API 積分 | +| [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) |使用您現有的 Gemini 計劃而不是 API 計費 | +| [opencode-反重力-auth](https://github.com/NoeFabris/opencode-antigravity-auth) |使用 Antigravity 的免費模型代替 API 計費 | +| [opencode-devcontainers 開放代碼開發容器](https://github.com/athal7/opencode-devcontainers) |具有淺克隆和自動分配端口的多分支開發容器隔離 | +| [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Antigravity OAuth 插件,支持 Google 搜索和更強大的 API 處理 | +| [opencode-動態上下文修剪](https://github.com/Tarquinen/opencode-dynamic-context-pruning) |通過修剪過時的工具輸出來優化代幣使用 | +| [opencode-websearch-引用](https://github.com/ghoulr/opencode-websearch-cited.git) |為具有 Google 接地風格的受支持提供商添加本機網絡搜索支持 | +| [opencode-pty](https://github.com/shekohex/opencode-pty.git) |使 AI 代理能夠在 PTY 中運行後台進程,並向其發送交互式輸入。 | +| [opencode-shell-策略](https://github.com/JRedeker/opencode-shell-strategy) |非交互式 shell 命令說明 - 防止依賴 TTY 的操作掛起 +| [opencode-wakatime](https://github.com/angristan/opencode-wakatime) |使用 Wakatime 跟踪 OpenCode 使用情況 | +| [opencode-md-表格式化程序](https://github.com/franlol/opencode-md-table-formatter/tree/main) |清理法學碩士生成的降價表 | +| [開放代碼變形快速應用](https://github.com/JRedeker/opencode-morph-fast-apply) |使用 Morph Fast Apply API 和惰性編輯標記將代碼編輯速度提高 10 倍 | +| [哦我的開放代碼](https://github.com/code-yeongyu/oh-my-opencode) |後台代理、預構建的 LSP/AST/MCP 工具、精選代理、兼容 Claude 代碼 | +| [開放代碼通知器](https://github.com/panta82/opencode-notificator) | OpenCode 會話的桌面通知和聲音警報 | +| [開放代碼通知程序](https://github.com/mohak34/opencode-notifier) |針對權限、完成和錯誤事件的桌面通知和聲音警報 | +| [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) |基於 OpenCode 上下文的 AI 支持的自動 Zellij 會話命名 | +| [開放代碼熟練](https://github.com/zenobi-us/opencode-skillful) |允許 OpenCode 代理通過技能發現和注入按需延遲加載提示 | +| [開放代碼超級內存](https://github.com/supermemoryai/opencode-supermemory) |使用超級內存跨會話持久內存 | +| [@Plannotator/OpenCode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) |具有視覺註釋和私人/離線共享的交互式計劃審查| +| [@openspoon/子任務2](https://github.com/spoons-and-mirrors/subtask2) |將開放代碼/命令擴展為具有精細流程控制的強大編排系統 | +| [開放代碼調度程序](https://github.com/different-ai/opencode-scheduler) |使用帶有 cron 語法的 launchd (Mac) 或 systemd (Linux) 安排重複作業 | +| [微碼](https://github.com/vtemian/micode) |結構化頭腦風暴 → 計劃 → 實施具有會議連續性的工作流程 | +| [奧克托](https://github.com/vtemian/octto) |用於通過多問題形式進行 AI 頭腦風暴的交互式瀏覽器 UI +| [opencode-後台代理](https://github.com/kdcokenny/opencode-background-agents) |具有異步委託和上下文持久性的 Claude Code 風格後台代理 | +| [打開代碼通知](https://github.com/kdcokenny/opencode-notify) | OpenCode 的本機操作系統通知 – 了解任務何時完成 | +| [開放代碼工作區](https://github.com/kdcokenny/opencode-workspace) |捆綁的多代理編排工具 – 16 個組件,一次安裝 | +| [開放代碼工作樹](https://github.com/kdcokenny/opencode-worktree) | OpenCode 的零摩擦 git 工作樹 | + +--- + +## 專案 + +|名稱 |描述 | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | +| [木牧](https://github.com/remorses/kimaki) |用於控制 OpenCode 會話的 Discord 機器人,基於 SDK 構建 | +| [開放代碼.nvim](https://github.com/NickvanDyke/opencode.nvim) | Neovim 插件,用於編輯器感知提示,基於 API 構建 | +| [門戶網站](https://github.com/hosenur/portal) |通過 Tailscale/VPN 實現 OpenCode 的移動優先 Web UI | +| [打開代碼插件模板](https://github.com/zenobi-us/opencode-plugin-template/) |用於構建 OpenCode 插件的模板 | +| [開放代碼.nvim](https://github.com/sudo-tee/opencode.nvim) | Neovim opencode 前端 - 基於終端的 AI 編碼代理 | +| [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Vercel AI SDK 提供程序,用於通過 @opencode-ai/sdk 使用 OpenCode | +| [開放室](https://github.com/btriapitsyn/openchamber) | OpenCode 的 Web/桌面應用程序和 VS Code 擴展 | +| [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) |在 Obsidian 的 UI 中嵌入 OpenCode 的 Obsidian 插件 | +| [開放式工作](https://github.com/different-ai/openwork) | Claude Cowork 的開源替代方案,由 OpenCode 提供支持 | +| [奧克斯](https://github.com/kdcokenny/ocx) | OpenCode 擴展管理器具有可移植、隔離的配置文件。 | +| [代碼游牧者](https://github.com/NeuralNomadsAI/CodeNomad) | OpenCode 的桌面、Web、移動和遠程客戶端應用程序 | + +--- + +## 代理商 + +|名稱 |描述 | +| ----------------------------------------------------------------- | ------------------------------------------------------------ | +| [代理](https://github.com/Cluster444/agentic) |用於結構化開發的模塊化人工智能代理和命令 | +| [開放代碼代理](https://github.com/darrenhinde/opencode-agents) |用於增強工作流程的配置、提示、代理和插件 | diff --git a/packages/web/src/content/docs/zh-tw/enterprise.mdx b/packages/web/src/content/docs/zh-tw/enterprise.mdx new file mode 100644 index 000000000..2b6e85561 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/enterprise.mdx @@ -0,0 +1,170 @@ +--- +title: 企業 +description: 在您的組織中安全地使用 OpenCode。 +--- + +import config from "../../../../config.mjs" +export const email = `mailto:${config.email}` + +OpenCode Enterprise 適用於希望確保其代碼和數據永遠不會離開其基礎設施的組織。它可以通過使用與 SSO 和內部 AI 網關集成的集中式配置來實現此目的。 + +:::note +OpenCode 不存儲您的任何代碼或上下文數據。 +::: + +要開始使用 OpenCode Enterprise: + +1. 與您的團隊進行內部試驗。 +2. **聯繫我們**討論定價和實施選項。 + +--- + +## 審判 + +OpenCode 是開源的,不存儲您的任何代碼或上下文數據,因此您的開發人員只需 [開始吧](/docs/) 並進行試用。 + +--- + +### 數據處理 + +**OpenCode 不會存儲您的代碼或上下文數據。 ** 所有處理都在本地進行或通過直接 API 調用您的 AI 提供商。 + +這意味著只要您使用您信任的提供商或內部提供商 +AI網關,您可以安全使用OpenCode。 + +這裡唯一需要注意的是可選的 `/share` 功能。 + +--- + +#### 分享對話 + +如果用戶啟用 `/share` 功能,對話和與之關聯的數據將被發送到我們用於在 opencode.ai 上託管這些共享頁面的服務。 + +數據當前通過我們的 CDN 邊緣網絡提供服務,並緩存在用戶附近的邊緣。 + +我們建議您在試用時禁用此功能。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[了解更多關於分享的信息](/docs/share)。 + +--- + +### 代碼所有權 + +**您擁有 OpenCode 生成的所有代碼。 ** 沒有許可限製或所有權聲明。 + +--- + +## 定價 + +我們對 OpenCode Enterprise 使用單機模型。如果您有自己的 LLM 網關,我們不會對使用的令牌收取費用。有關定價和實施選項的更多詳細信息,請**聯繫我們**。 + +--- + +## 部署 + +完成試用並準備好使用 OpenCode 後,請訪問: +您的組織,您可以**聯繫我們**進行討論 +定價和實施選項。 + +--- + +### 中央配置 + +我們可以將 OpenCode 設置為為您的整個組織使用單一的中央配置。 + +這種集中式配置可以與您的 SSO 提供商集成,並確保所有用戶僅訪問您的內部 AI 網關。 + +--- + +### 單點登錄集成 + +通過中央配置,OpenCode 可以與您組織的 SSO 提供商集成以進行身份​​驗證。 + +這使得 OpenCode 能夠通過現有的身份管理系統獲取內部 AI 網關的憑據。 + +--- + +### 內部AI網關 + +通過中央配置,OpenCode 還可以配置為僅使用您的內部 AI 網關。 + +您還可以禁用所有其他 AI 提供商,確保所有請求都通過組織批准的基礎設施。 + +--- + +### 自託管 + +雖然我們建議禁用共享頁面以確保您的數據永遠不會離開 +您的組織,我們還可以幫助您在您的基礎設施上自行託管它們。 + +目前這已在我們的路線圖上。如果您有興趣,**讓我們知道**。 + +--- + +## 常問問題 + +

+什麼是 OpenCode Enterprise? + +OpenCode Enterprise 適用於希望確保其代碼和數據永遠不會離開其基礎設施的組織。它可以通過使用與 SSO 和內部 AI 網關集成的集中式配置來實現此目的。 + +
+ +
+如何開始使用 OpenCode Enterprise? + +只需與您的團隊進行內部試用即可。 OpenCode 默認情況下不存儲您的代碼或上下文數據,因此可以輕鬆上手。 + +然後**聯繫我們**討論定價和實施選項。 + +
+ +
+企業定價如何運作? + +我們提供按席位企業定價。如果您有自己的 LLM 網關,我們不會對使用的令牌收取費用。如需了解更多詳情,請**聯繫我們**,獲取根據您組織的需求定制的報價。 + +
+ +
+OpenCode Enterprise 保證我的數據安全嗎? + +是的。 OpenCode 不存儲您的代碼或上下文數據。所有處理都在本地進行或通過直接 API 調用您的 AI 提供商。通過中央配置和 SSO 集成,您的數據在組織的基礎架構中保持安全。 + +
+ +
+我們可以使用自己的私有 NPM 註冊表嗎? + +OpenCode 通過 Bun 的本機 `.npmrc` 文件支持來支持私有 npm 註冊表。如果您的組織使用私有註冊表,例如 JFrog Artifactory、Nexus 或類似的註冊表,請確保開發人員在運行 OpenCode 之前經過身份驗證。 + +要使用您的私有註冊表設置身份驗證: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +這將創建帶有身份驗證詳細信息的`~/.npmrc`。 OpenCode 會自動 +拿起這個。 + +:::caution +在運行 OpenCode 之前,您必須登錄私有註冊表。 +::: + +或者,您可以手動配置 `.npmrc` 文件: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +開發人員必須在運行 OpenCode 之前登錄私有註冊表,以確保可以從企業註冊表安裝軟件包。 + +
diff --git a/packages/web/src/content/docs/zh-tw/formatters.mdx b/packages/web/src/content/docs/zh-tw/formatters.mdx new file mode 100644 index 000000000..c41d82fdc --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/formatters.mdx @@ -0,0 +1,130 @@ +--- +title: 格式化程序 +description: OpenCode 使用特定於語言的格式化程序。 +--- + +使用特定於語言的格式化程序編寫或編輯文件後,OpenCode 會自動格式化文件。這可確保生成的代碼遵循項目的代碼風格。 + +--- + +## 內建 + +OpenCode 附帶了多個適用於流行語言和框架的內置格式化程序。下面是格式化程序、支持的文件擴展名以及所需的命令或配置選項的列表。 + +|格式化程序|擴展 |要求| +| -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +|政府| .go | `gofmt` 命令可用 | +|混合| .ex、.exs、.eex、.heex、.leex、.neex、.sface | `mix` 命令可用 | +|更漂亮 | .js、.jsx、.ts、.tsx、.html、.css、.md、.json、.yaml 和 [更多的](https://prettier.io/docs/en/index.html) | `package.json` | `prettier` 依賴關係 +|生物群系 | .js、.jsx、.ts、.tsx、.html、.css、.md、.json、.yaml 和 [更多的](https://biomejs.dev/) | `biome.json(c)` 配置文件 | +|之字形 | .zig、.zon | `zig` 命令可用 | +| clang 格式 | .c、.cpp、.h、.hpp、.ino 和 [更多的](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` 配置文件 | +|克特林特 | .kt、.kts | `ktlint` 命令可用 | +|領子 | .py, .pyi | `ruff` 命令可通過配置 | +|生鏽 | .rs | `rustfmt` 命令可用 | +|貨物運輸 | .rs | `cargo fmt` 命令可用 | +|紫外線| .py, .pyi | `uv` 命令可用 | +|魯博科普 | .rb、.rake、.gemspec、.ru | `rubocop` 命令可用 | +|標準rb | .rb、.rake、.gemspec、.ru | `standardrb` 命令可用 | +| html美化器 | .erb、.html.erb | `htmlbeautifier` 命令可用 | +|空氣| .R | `air` 命令可用 | +|飛鏢 | .dart | `dart` 命令可用 | +| ocaml 格式 | .ml、.mli | `ocamlformat` 可用命令和 `.ocamlformat` 配置文件 | +|地形 | .tf、.tfvars | `terraform` 命令可用 | +|微光| .gleam | `gleam` 命令可用 | +|尼克斯夫MTT | .nix | `nixfmt` 命令可用 | +| sfmt| .sh、.bash | `shfmt` 命令可用 | +|品脫 | .php | `composer.json` | `laravel/pint` 依賴關係 +| oxfmt(實驗)| .js、.jsx、.ts、.tsx | `package.json` 和[實驗環境變量標誌](/docs/cli/#experimental) | `oxfmt` 依賴關係 +|奧爾莫魯 | .hs | `ormolu` 命令可用 | + +因此,如果您的項目的`package.json`中有`prettier`,OpenCode將自動使用它。 + +--- + +## 它是如何運作的 + +當 OpenCode 寫入或編輯文件時,它: + +1. 根據所有啟用的格式化程序檢查文件擴展名。 +2. 對文件運行適當的格式化程序命令。 +3. 自動應用格式更改。 + +此過程在後台進行,確保無需任何手動步驟即可維護您的代碼樣式。 + +--- + +## 配置 + +您可以通過 OpenCode 配置中的 `formatter` 部分自定義格式化程序。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": {} +} +``` + +每個格式化程序配置支持以下內容: + +|物業 |類型 |描述 | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` |布爾 |將其設置為 `true` 以禁用格式化程序 | +| `command` |字符串[] |格式化運行的命令 | +| `environment` |對象|運行格式化程序時要設置的環境變量 | +| `extensions` |字符串[] |此格式化程序應處理的文件擴展名 | + +讓我們看一些例子。 + +--- + +### 禁用格式化程序 + +要全局禁用**所有**格式化程序,請將`formatter`設置為`false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": false +} +``` + +要禁用**特定**格式化程序,請將`disabled`設置為`true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### 自定義格式化程序 + +您可以覆蓋內置格式化程序或通過指定命令、環境變量和文件擴展名添加新格式化程序: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +命令中的 **`$FILE` 佔位符** 將替換為正在格式化的文件的路徑。 diff --git a/packages/web/src/content/docs/zh-tw/github.mdx b/packages/web/src/content/docs/zh-tw/github.mdx new file mode 100644 index 000000000..bb206cd9d --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/github.mdx @@ -0,0 +1,321 @@ +--- +title: GitHub +description: 在 GitHub 問題和拉取請求中使用 OpenCode。 +--- + +OpenCode 與您的 GitHub 工作流程集成。在評論中提及`/opencode` 或`/oc`,OpenCode 將在您的 GitHub Actions 運行器中執行任務。 + +--- + +## 特徵 + +- **分類問題**:要求 OpenCode 調查問題並向您解釋。 +- **修復和實施**:要求 OpenCode 修復問題或實施功能。它將在一個新分支中工作並提交包含所有更改的 PR。 +- **安全**:OpenCode 在 GitHub 的運行器中運行。 + +--- + +## 安裝 + +在 GitHub 存儲庫中的項目中運行以下命令: + +```bash +opencode github install +``` + +這將引導您完成安裝 GitHub 應用程序、創建工作流程和設置機密。 + +--- + +### 手動設置 + +或者您可以手動設置。 + +1. Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + + 前往[**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent)。確保它已安裝在目標存儲庫上。 + +2. **添加工作流程** + + 將以下工作流程文件添加到存儲庫中的 `.github/workflows/opencode.yml` 中。確保在`env`中設置適當的`model`和所需的API密鑰。 + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + + jobs: + opencode: + if: | + contains(github.event.comment.body, '/oc') || + contains(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 1 + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + # share: true + # github_token: xxxx + ``` + +3. Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + + 在您的組織或項目的**設置**中,展開左側的**秘密和變量**,然後選擇**操作**。並添加所需的 API 密鑰。 + +--- + +## 配置 + +- `model`:與 OpenCode 一起使用的模型。採用`provider/model` 格式。這是**必需的**。 +- `agent`: The agent to use.必須是一級代理。如果未找到,則從配置回退到 `default_agent` 或 `"build"`。 +- `share`:是否共享OpenCode會話。對於公共存儲庫,默認為 **true**。 +- `prompt`:可選的自定義提示以覆蓋默認行為。使用它來自定義 OpenCode 處理請求的方式。 +- `token`:可選的 GitHub 訪問令牌,用於執行創建評論、提交更改和打開拉取請求等操作。默認情況下,OpenCode 使用來自 OpenCode GitHub 應用程序的安裝訪問令牌,因此提交、評論和拉取請求顯示為來自應用程序。 + + 或者,您可以使用 GitHub Action 運行程序的[內置`GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token),而無需安裝 OpenCode GitHub 應用程序。只需確保在您的工作流程中授予所需的權限: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + +--- + +## 支持的活動 + +OpenCode 可以由以下 GitHub 事件觸發: + +|事件類型 |觸發者 |詳情 | +| ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `issue_comment` |對問題或 PR 發表評論 | Mention `/opencode` or `/oc` in your comment. OpenCode 讀取上下文並可以創建分支、打開 PR 或回复。 | +| `pull_request_review_comment` |對 PR 中的特定代碼行進行評論 |在檢查代碼時提及`/opencode` 或`/oc`。 OpenCode receives file path, line numbers, and diff context. | +| `issues` |問題已打開或已編輯 |創建或修改問題時自動觸發 OpenCode。需要 `prompt` 輸入。 | +| `pull_request` | PR 已開啟或已更新 | Automatically trigger OpenCode when PRs are opened, synchronized, or reopened.對於自動評論很有用。 | +| `schedule` |基於 Cron 的計劃 |按計劃運行 OpenCode。需要 `prompt` 輸入。輸出進入日誌和 PR(沒有可評論的問題)。 | +| `workflow_dispatch` |從 GitHub UI 手動觸發 |通過“操作”選項卡按需觸發 OpenCode。需要 `prompt` 輸入。輸出進入日誌和 PR。 | + +### 時間表示例 + +按計劃運行 OpenCode 以執行自動化任務: + +```yaml title=".github/workflows/opencode-scheduled.yml" +name: Scheduled OpenCode Task + +on: + schedule: + - cron: "0 9 * * 1" # Every Monday at 9am UTC + +jobs: + opencode: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Run OpenCode + uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review the codebase for any TODO comments and create a summary. + If you find issues worth addressing, open an issue to track them. +``` + +For scheduled events, the `prompt` input is **required** since there's no comment to extract instructions from.計劃工作流在沒有用戶上下文的情況下運行以進行權限檢查,因此如果您希望 OpenCode 創建分支或 PR,工作流必須授予 `contents: write` 和 `pull-requests: write`。 + +--- + +### 拉取請求示例 + +打開或更新 PR 時自動審核: + +```yaml title=".github/workflows/opencode-review.yml" +name: opencode-review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + review: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + pull-requests: read + issues: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: anomalyco/opencode/github@latest + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + model: anthropic/claude-sonnet-4-20250514 + use_github_token: true + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +對於 `pull_request` 事件,如果未提供 `prompt`,OpenCode 將默認審核拉取請求。 + +--- + +### 問題分類示例 + +自動分類新問題。此示例過濾超過 30 天的帳戶以減少垃圾郵件: + +```yaml title=".github/workflows/opencode-triage.yml" +name: Issue Triage + +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Check account age + id: check + uses: actions/github-script@v7 + with: + script: | + const user = await github.rest.users.getByUsername({ + username: context.payload.issue.user.login + }); + const created = new Date(user.data.created_at); + const days = (Date.now() - created) / (1000 * 60 * 60 * 24); + return days >= 30; + result-encoding: string + + - uses: actions/checkout@v6 + if: steps.check.outputs.result == 'true' + with: + persist-credentials: false + + - uses: anomalyco/opencode/github@latest + if: steps.check.outputs.result == 'true' + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + with: + model: anthropic/claude-sonnet-4-20250514 + prompt: | + Review this issue. If there's a clear fix or relevant docs: + - Provide documentation links + - Add error handling guidance for code examples + Otherwise, do not comment. +``` + +對於 `issues` 事件,`prompt` 輸入是**必需的**,因為沒有註釋可從中提取指令。 + +--- + +## 自定義提示 + +覆蓋默認提示,為您的工作流程自定義 OpenCode 的行為。 + +```yaml title=".github/workflows/opencode.yml" +- uses: anomalyco/opencode/github@latest + with: + model: anthropic/claude-sonnet-4-5 + prompt: | + Review this pull request: + - Check for code quality issues + - Look for potential bugs + - Suggest improvements +``` + +這對於執行與您的項目相關的特定審查標準、編碼標准或重點領域非常有用。 + +--- + +## 示例 + +以下是如何在 GitHub 中使用 OpenCode 的一些示例。 + +- **解釋一個問題** + + 在 GitHub 問題中添加此評論。 + + ``` + /opencode explain this issue + ``` + + OpenCode 將閱讀整個線程,包括所有評論,並回复並提供清晰的解釋。 + +- **解決問題** + + 在 GitHub 問題中,說: + + ``` + /opencode fix this + ``` + + OpenCode 將創建一個新分支,實施更改,並使用更改打開 PR。 + +- **審查 PR 並進行更改** + + 在 GitHub PR 上留下以下評論。 + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + +- **查看特定代碼行** + + 直接在 PR 的“文件”選項卡中的代碼行上留下評論。 OpenCode 自動檢測文件、行號和差異上下文以提供精確的響應。 + + ``` + [Comment on specific lines in Files tab] + /oc add error handling here + ``` + + Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. + - 正在審查的確切文件 + - 具體代碼行 + - 周圍的 diff 上下文 + - 行號信息 + + 這允許更有針對性的請求,而無需手動指定文件路徑或行號。 diff --git a/packages/web/src/content/docs/zh-tw/gitlab.mdx b/packages/web/src/content/docs/zh-tw/gitlab.mdx new file mode 100644 index 000000000..d24b5bff0 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/gitlab.mdx @@ -0,0 +1,195 @@ +--- +title: GitLab +description: 在 GitLab 問題和合併請求中使用 OpenCode。 +--- + +OpenCode 通過 GitLab CI/CD 管道或與 GitLab Duo 與您的 GitLab 工作流程集成。 + +在這兩種情況下,OpenCode 都將在您的 GitLab 運行器上運行。 + +--- + +## GitLab。 + +OpenCode 在常規 GitLab 管道中工作。您可以將其構建為管道作為 [CI組件](https://docs.gitlab.com/ee/ci/components/) + +在這裡,我們使用社區創建的 OpenCode CI/CD 組件 — [nagyv/gitlab-opencode](https://gitlab.com/nagyv/gitlab-opencode)。 + +--- + +### 特徵 + +- **每個作業使用自定義配置**:使用自定義配置目錄配置 OpenCode,例如 `./config/#custom-directory` 以啟用或禁用每個 OpenCode 調用的功能。 +- Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know. +- **靈活**:CI 組件支持多種輸入來自定義其行為 + +--- + +### 設定 + +1. 將 OpenCode 身份驗證 JSON 作為文件類型 CI 環境變量存儲在 **設置** > **CI/CD** > **變量** 下。確保將它們標記為“屏蔽和隱藏”。 +2. 將以下內容添加到您的 `.gitlab-ci.yml` 文件中。 + + ```yaml title=".gitlab-ci.yml" + include: + - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2 + inputs: + config_dir: ${CI_PROJECT_DIR}/opencode-config + auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON + command: optional-custom-command + message: "Your prompt here" + ``` + +有關此組件的更多輸入和用例[查看文檔](https://gitlab.com/explore/catalog/nagyv/gitlab-opencode)。 + +--- + +## 亞搏體育app二人組 + +OpenCode 與您的 GitLab 工作流程集成。 +在評論中提及`@opencode`,OpenCode 將在您的 GitLab CI 管道中執行任務。 + +--- + +### 特徵 + +- **分類問題**:要求 OpenCode 調查問題並向您解釋。 +- **修復和實施**:要求 OpenCode 修復問題或實施功能。 + 它將創建一個新分支並提出包含更改的合併請求。 +- **安全**:OpenCode 在您的 GitLab 運行器上運行。 + +--- + +### 設定 + +OpenCode 在您的 GitLab CI/CD 管道中運行,您需要進行以下設置: + +:::tip +查看[**GitLab 文檔**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) 以獲取最新說明。 +::: + +1. 配置您的 GitLab 環境 +2. 設置 CI/CD +3. 獲取 AI 模型提供商 API 密鑰 +4. 創建服務帳戶 +5. 配置 CI/CD 變量 +6. 創建一個流配置文件,這是一個示例: + +
+ + Flow configuration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating OpenCode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "OpenCode" + - echo "Testing glab" + - glab issue list + - echo "Running OpenCode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarize an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +詳細說明可以參考[GitLab CLI 代理文檔](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/)。 + +--- + +### 示例 + +以下是如何在 GitLab 中使用 OpenCode 的一些示例。 + +:::tip +您可以配置使用與 `@opencode` 不同的觸發短語。 +::: + +- **解釋一個問題** + + 在 GitLab 問題中添加此評論。 + + ``` + @opencode explain this issue + ``` + + OpenCode 將閱讀該問題並回复並提供清晰的解釋。 + +- **解決問題** + + 在 GitLab 問題中,說: + + ``` + @opencode fix this + ``` + + OpenCode 將創建一個新分支,實施更改,並打開包含更改的合併請求。 + +- **審查合併請求** + + 對 GitLab 合併請求留下以下評論。 + + ``` + @opencode review this merge request + ``` + + OpenCode 將審核合併請求並提供反饋。 diff --git a/packages/web/src/content/docs/zh-tw/ide.mdx b/packages/web/src/content/docs/zh-tw/ide.mdx new file mode 100644 index 000000000..2bcca6cf1 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/ide.mdx @@ -0,0 +1,48 @@ +--- +title: 集成開發環境 +description: VS Code、Cursor 和其他 IDE 的 OpenCode 擴展 +--- + +OpenCode 與 VS Code、Cursor 或任何支持終端的 IDE 集成。只需在終端中運行 `opencode` 即可開始。 + +--- + +## 用法 + +- **快速啟動**:使用 `Cmd+Esc` (Mac) 或 `Ctrl+Esc` (Windows/Linux) 在拆分終端視圖中打開 OpenCode,或者聚焦現有終端會話(如果已有終端會話正在運行)。 +- **新會話**:使用 `Cmd+Shift+Esc` (Mac) 或 `Ctrl+Shift+Esc` (Windows/Linux) 啟動新的 OpenCode 終端會話,即使該會話已打開。您還可以單擊 UI 中的 OpenCode 按鈕。 +- **上下文感知**:自動與 OpenCode 共享您當前的選擇或選項卡。 +- **文件引用快捷方式**:使用`Cmd+Option+K` (Mac) 或`Alt+Ctrl+K` (Linux/Windows) 插入文件引用。例如,`@File#L37-42`。 + +--- + +## 安裝 + +要在 VS Code 和 Cursor、Windsurf、VSCodium 等流行分支上安裝 OpenCode: + +1. 打開 VS 代碼 +2. 打開集成終端 +3. 運行 `opencode` - 擴展會自動安裝 + +另一方面,如果您想在從 TUI 運行 `/editor` 或 `/export` 時使用自己的 IDE,則需要設置 `export EDITOR="code --wait"`。 [了解更多](/docs/tui/#editor-setup)。 + +--- + +### 手動安裝 + +在擴展市場中搜索 **OpenCode**,然後單擊 **安裝**。 + +--- + +### 故障排除 + +如果擴展無法自動安裝: + +- 確保您在集成終端中運行`opencode`。 +- 確認您的 IDE 的 CLI 已安裝: + - 對於 VS 代碼:`code` 命令 + - 對於光標:`cursor` 命令 + - 對於風帆衝浪:`windsurf` 命令 + - 對於 VSCodium:`codium` 命令 + - 如果沒有,請運行 `Cmd+Shift+P` (Mac) 或 `Ctrl+Shift+P` (Windows/Linux) 並蒐索“Shell Command: Install 'code' command in PATH”(或適用於您的 IDE 的等效命令) +- 確保 VS Code 有權安裝擴展 diff --git a/packages/web/src/content/docs/zh-tw/index.mdx b/packages/web/src/content/docs/zh-tw/index.mdx new file mode 100644 index 000000000..3895addec --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/index.mdx @@ -0,0 +1,359 @@ +--- +title: 簡介 +description: 開始使用 OpenCode。 +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" +import config from "../../../../config.mjs" +export const console = config.console + +[**開放代碼**](/) 是一個開源人工智能編碼代理。它可用作基於終端的界面、桌面應用程序或 IDE 擴展。 + +![具有 opencode 主題的 OpenCode TUI](../../../assets/lander/screenshot.png) + +讓我們開始吧。 + +--- + +#### 先決條件 + +要在終端中使用 OpenCode,您需要: + +1. 現代終端模擬器,例如: + - [韋茲術語](https://wezterm.org),跨平台 + - [阿拉克里蒂](https://alacritty.org),跨平台 + - [幽靈般的](https://ghostty.org),Linux 和 macOS + - [貓咪](https://sw.kovidgoyal.net/kitty/),Linux 和 macOS + +2. 您想要使用的 LLM 提供商的 API 密鑰。 + +--- + +## 安裝 + +安裝 OpenCode 最簡單的方法是通過安裝腳本。 + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +您還可以使用以下命令安裝它: + +- **使用 Node.js** + + + + + ```bash + npm install -g opencode-ai + ``` + + + + + ```bash + bun install -g opencode-ai + ``` + + + + + ```bash + pnpm install -g opencode-ai + ``` + + + + + ```bash + yarn global add opencode-ai + ``` + + + + + +- **在 macOS 和 Linux 上使用 Homebrew** + + ```bash + brew install anomalyco/tap/opencode + ``` + + > 我們建議使用 OpenCode Tap 來獲取最新版本。官方 `brew install opencode` 公式由 Homebrew 團隊維護,更新頻率較低。 + +- **在 Arch Linux 上使用 Paru** + + ```bash + paru -S opencode-bin + ``` + +#### 視窗 + +:::tip[Recommended: Use WSL] +為了在 Windows 上獲得最佳體驗,我們建議使用[適用於 Linux 的 Windows 子系統 (WSL)](/docs/windows-wsl)。它提供了更好的性能並與 OpenCode 的功能完全兼容。 +::: + +- **使用巧克力** + + ```bash + choco install opencode + ``` + +- **使用勺子** + + ```bash + scoop install opencode + ``` + +- **使用 NPM** + + ```bash + npm install -g opencode-ai + ``` + +- **使用米塞** + + ```bash + mise use -g github:anomalyco/opencode + ``` + +- **使用 Docker** + + ```bash + docker run -it --rm ghcr.io/anomalyco/opencode + ``` + +目前正在支持使用 Bun 在 Windows 上安裝 OpenCode。 + +您還可以從[發布](https://github.com/anomalyco/opencode/releases) 獲取二進製文件。 + +--- + +## 配置 + +借助 OpenCode,您可以通過配置 API 密鑰來使用任何 LLM 提供商。 + +如果您不熟悉使用 LLM 提供商,我們建議使用[開放代碼禪](/docs/zen)。 +這是經過 OpenCode 測試和驗證的精選模型列表 +團隊。 + +1. 在 TUI 中運行 `/connect` 命令,選擇 opencode,然後前往 [opencode.ai/auth](https://opencode.ai/auth)。 + + ```txt + /connect + ``` + +2. 登錄,添加您的賬單詳細信息,然後復制您的 API 密鑰。 + +3. 粘貼您的 API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +或者,您可以選擇其他提供商之一。 [了解更多](/docs/providers#directory)。 + +--- + +## 初始化 + +現在您已經配置了提供程序,您可以導航到一個項目 +你想繼續工作。 + +```bash +cd /path/to/project +``` + +並運行 OpenCode。 + +```bash +opencode +``` + +接下來,通過運行以下命令來初始化項目的 OpenCode。 + +```bash frame="none" +/init +``` + +這將使 OpenCode 分析您的項目並在以下位置創建 `AGENTS.md` 文件 +項目根。 + +:::tip +您應該將項目的 `AGENTS.md` 文件提交到 Git。 +::: + +這有助於 OpenCode 理解項目結構和編碼模式 +用過的。 + +--- + +## 用法 + +您現在已準備好使用 OpenCode 來處理您的項目。請隨意詢問 +任何事物! + +如果您不熟悉使用 AI 編碼代理,以下是一些可能會有所幫助的示例 +幫助。 + +--- + +### 提出問題 + +您可以要求 OpenCode 向您解釋代碼庫。 + +:::tip +使用`@`鍵模糊搜索工程中的文件。 +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +如果您沒有處理代碼庫的一部分,這會很有幫助。 + +--- + +### 添加功能 + +您可以要求 OpenCode 向您的項目添加新功能。不過我們首先建議要求它制定一個計劃。 + +1. **制定計劃** + + OpenCode 有一個*計劃模式*,該模式禁用其進行更改和 + 相反,建議*如何*實現該功能。 + + 使用 **Tab** 鍵切換到它。您會在右下角看到一個指示符。 + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + 現在讓我們描述一下我們想要它做什麼。 + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + 您需要為 OpenCode 提供足夠的詳細信息以了解您想要的內容。它有幫助 + 就像與團隊中的初級開發人員交談一樣與它交談。 + + :::tip + 為 OpenCode 提供大量上下文和示例,以幫助其理解您的內容 + 想。 + ::: + +2. **迭代計劃** + + 一旦它為您提供了計劃,您就可以提供反饋或添加更多詳細信息。 + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::tip + 將圖像拖放到終端中以將其添加到提示中。 + ::: + + OpenCode 可以掃描您提供的任何圖像並將其添加到提示中。你可以 + 通過將圖像拖放到終端中來完成此操作。 + +3. **構建功能** + + 一旦您對計劃感到滿意,請切換回*構建模式* + 再次按 **Tab** 鍵。 + + ```bash frame="none" + + ``` + + 並要求它做出改變。 + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### 做出改變 + +對於更直接的更改,您可以要求 OpenCode 直接構建它 +無需先審查計劃。 + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +您需要確保提供大量詳細信息,以便 OpenCode 做出正確的決定 +變化。 + +--- + +### 撤消更改 + +假設您要求 OpenCode 進行一些更改。 + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +但你意識到這不是你想要的。您**可以撤消**更改 +使用 `/undo` 命令。 + +```bash frame="none" +/undo +``` + +OpenCode 現在將恢復您所做的更改並顯示您的原始消息 +再次。 + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +從這裡您可以調整提示並要求 OpenCode 重試。 + +:::tip +您可以多次運行 `/undo` 以撤消多項更改。 +::: + +或者您**可以使用 `/redo` 命令重做**更改。 + +```bash frame="none" +/redo +``` + +--- + +## 分享 + +您與 OpenCode 的對話可以[與您的 +團隊](/docs/分享)。 + +```bash frame="none" +/share +``` + +這將創建當前對話的鏈接並將其複製到剪貼板。 + +:::note +默認情況下不共享對話。 +::: + +這是帶有 OpenCode 的[示例對話](https://opencode.ai/s/4XP1fce5)。 + +--- + +## 定制 + +就是這樣!您現在已經是使用 OpenCode 的專家了。 + +要使其成為您自己的,我們建議 [選擇一個主題](/docs/themes)、[自定義按鍵綁定](/docs/keybinds)、[配置代碼格式化程序](/docs/formatters)、[創建自定義命令](/docs/commands) 或使用 [開放代碼配置](/docs/config)。 diff --git a/packages/web/src/content/docs/zh-tw/keybinds.mdx b/packages/web/src/content/docs/zh-tw/keybinds.mdx new file mode 100644 index 000000000..8979fcd32 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/keybinds.mdx @@ -0,0 +1,192 @@ +--- +title: 按鍵綁定 +description: 自定義您的按鍵綁定。 +--- + +OpenCode 有一個按鍵綁定列表,您可以通過 OpenCode 配置進行自定義。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_exit": "ctrl+c,ctrl+d,q", + "editor_open": "e", + "theme_list": "t", + "sidebar_toggle": "b", + "scrollbar_toggle": "none", + "username_toggle": "none", + "status_view": "s", + "tool_details": "none", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_timeline": "g", + "session_fork": "none", + "session_rename": "none", + "session_share": "none", + "session_unshare": "none", + "session_interrupt": "escape", + "session_compact": "c", + "session_child_cycle": "right", + "session_child_cycle_reverse": "left", + "session_parent": "up", + "messages_page_up": "pageup,ctrl+alt+b", + "messages_page_down": "pagedown,ctrl+alt+f", + "messages_line_up": "ctrl+alt+y", + "messages_line_down": "ctrl+alt+e", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g,home", + "messages_last": "ctrl+alt+g,end", + "messages_next": "none", + "messages_previous": "none", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "messages_last_user": "none", + "messages_toggle_conceal": "h", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "model_cycle_favorite": "none", + "model_cycle_favorite_reverse": "none", + "variant_cycle": "ctrl+t", + "command_list": "ctrl+p", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "return", + "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", + "input_move_left": "left,ctrl+b", + "input_move_right": "right,ctrl+f", + "input_move_up": "up", + "input_move_down": "down", + "input_select_left": "shift+left", + "input_select_right": "shift+right", + "input_select_up": "shift+up", + "input_select_down": "shift+down", + "input_line_home": "ctrl+a", + "input_line_end": "ctrl+e", + "input_select_line_home": "ctrl+shift+a", + "input_select_line_end": "ctrl+shift+e", + "input_visual_line_home": "alt+a", + "input_visual_line_end": "alt+e", + "input_select_visual_line_home": "alt+shift+a", + "input_select_visual_line_end": "alt+shift+e", + "input_buffer_home": "home", + "input_buffer_end": "end", + "input_select_buffer_home": "shift+home", + "input_select_buffer_end": "shift+end", + "input_delete_line": "ctrl+shift+d", + "input_delete_to_line_end": "ctrl+k", + "input_delete_to_line_start": "ctrl+u", + "input_backspace": "backspace,shift+backspace", + "input_delete": "ctrl+d,delete,shift+delete", + "input_undo": "ctrl+-,super+z", + "input_redo": "ctrl+.,super+shift+z", + "input_word_forward": "alt+f,alt+right,ctrl+right", + "input_word_backward": "alt+b,alt+left,ctrl+left", + "input_select_word_forward": "alt+shift+f,alt+shift+right", + "input_select_word_backward": "alt+shift+b,alt+shift+left", + "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", + "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", + "history_previous": "up", + "history_next": "down", + "terminal_suspend": "ctrl+z", + "terminal_title_toggle": "none", + "tips_toggle": "h", + "display_thinking": "none" + } +} +``` + +--- + +## 領袖鑰匙 + +OpenCode 對大多數按鍵綁定使用 `leader` 鍵。這可以避免終端中的衝突。 + +默認情況下,`ctrl+x` 是主鍵,大多數操作要求您先按主鍵,然後再按快捷鍵。例如,要開始新會話,請先按`ctrl+x`,然後按`n`。 + +您不需要為鍵綁定使用主鍵,但我們建議您這樣做。 + +--- + +## 禁用按鍵綁定 + +您可以通過將鍵添加到您的配置中並使用值“none”來禁用鍵綁定。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` + +--- + +## 桌面提示快捷方式 + +OpenCode 桌面應用程序提示輸入支持常見的 Readline/Emacs 風格的文本編輯快捷方式。這些是內置的,目前無法通過`opencode.json`進行配置。 + +|快捷方式 |行動| +| -------- | ---------------------------------------- | +| `ctrl+a` |移至當前行開頭 | +| `ctrl+e` |移至當前行尾 | +| `ctrl+b` |將光標向後移動一個字符 | +| `ctrl+f` |將光標向前移動一個字符 | +| `alt+b` |將光標向後移動一個字 | +| `alt+f` |將光標向前移動一個字 | +| `ctrl+d` |刪除光標下的字符| +| `ctrl+k` |殺到行尾 | +| `ctrl+u` |殺至行首 | +| `ctrl+w` |刪除前一個單詞 | +| `alt+d` |殺死下一個詞 | +| `ctrl+t` |轉置字符 | +| `ctrl+g` |取消彈出窗口/中止運行響應 | + +--- + +## Shift+Enter + +默認情況下,某些終端不發送帶有 Enter 的修飾鍵。您可能需要將終端配置為發送 `Shift+Enter` 作為轉義序列。 + +### Windows 終端 + +打開您的`settings.json`: + +``` +%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json +``` + +將其添加到根級 `actions` 數組: + +```json +"actions": [ + { + "command": { + "action": "sendInput", + "input": "\u001b[13;2u" + }, + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +將其添加到根級 `keybindings` 數組: + +```json +"keybindings": [ + { + "keys": "shift+enter", + "id": "User.sendInput.ShiftEnterCustom" + } +] +``` + +保存文件並重新啟動 Windows 終端或打開新選項卡。 diff --git a/packages/web/src/content/docs/zh-tw/lsp.mdx b/packages/web/src/content/docs/zh-tw/lsp.mdx new file mode 100644 index 000000000..feaff92a4 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/lsp.mdx @@ -0,0 +1,188 @@ +--- +title: LSP服務器 +description: OpenCode 與您的 LSP 服務器集成。 +--- + +OpenCode 與您的語言服務器協議 (LSP) 集成,以幫助 LLM 與您的代碼庫交互。它使用診斷向法學碩士提供反饋。 + +--- + +## 內建 + +OpenCode 附帶了多種適用於流行語言的內置 LSP 服務器: + +| LSP服務器|擴展 |要求| +| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------ | +|天文 | .astro | Astro 項目自動安裝 | +| bash | .sh、.bash、.zsh、.ksh |自動安裝 bash-語言-服務器 | +|叮叮 | .c、.cpp、.cc、.cxx、.c++、.h、.hpp、.hh、.hxx、.h++ |自動安裝 C/C++ 項目 | +|夏普| .cs | `.NET SDK` 已安裝 | +| Clojure-lsp | 語言.clj、.cljs、.cljc、.edn | `clojure-lsp` 命令可用 | +|飛鏢 | .dart | `dart` 命令可用 | +|給定 | .ts、.tsx、.js、.jsx、.mjs | `deno` 命令可用(自動檢測 deno.json/deno.jsonc)| +|長生不老藥-LS | .ex、.exs | `elixir` 命令可用 | +|埃斯林特 | .ts、.tsx、.js、.jsx、.mjs、.cjs、.mts、.cts、.vue | `eslint` 項目中的依賴項 | +|銳利 | .fs、.fsi、.fsx、.fsscript | `.NET SDK` 已安裝 | +|微光| .gleam | `gleam` 命令可用 | +|伙計們| .go | `go` 命令可用 | +| HLS | .hs、.lhs | `haskell-language-server-wrapper` 命令可用 | +| jdtls| .java | `Java SDK (version 21+)` 已安裝 | +| kotlin-ls | .kt、.kts | Kotlin 項目的自動安裝 | +| lua-ls | .lua |自動安裝 Lua 項目 | +|尼克斯 | .nix | `nixd` 命令可用 | +| ocaml-lsp | .ml、.mli | `ocamllsp` 命令可用 | +|奧克斯林特 | .ts、.tsx、.js、.jsx、.mjs、.cjs、.mts、.cts、.vue、.astro、.svelte | `oxlint` 項目中的依賴項 | +| php intelephense | php .php | PHP 項目的自動安裝 | +|棱鏡| .prisma | `prisma` 命令可用 | +|皮賴特| .py, .pyi | `pyright` 依賴項已安裝 | +| ruby-lsp(rubocop)| .rb、.rake、.gemspec、.ru | `ruby` 和 `gem` 命令可用 | +|生鏽| .rs | `rust-analyzer` 命令可用 | +|源套件-lsp | .swift、.objc、.objcpp | `swift` 已安裝(`xcode` 在 macOS 上)| +|苗條| .svelte | Svelte 項目的自動安裝 | +|地形 | .tf、.tfvars |從 GitHub 版本自動安裝 | +|微霧| .typ、.typc |從 GitHub 版本自動安裝 | +|打字稿 | .ts、.tsx、.js、.jsx、.mjs、.cjs、.mts、.cts | `typescript` 項目中的依賴項 | +|視圖 | .vue | Vue 項目自動安裝 | +| yaml-ls | .yaml、.yml |自動安裝 Red Hat yaml-language-server | +|中立 | .zig、.zon | `zig` 命令可用 | + +當檢測到上述文件擴展名之一併且滿足要求時,LSP 服務器將自動啟用。 + +:::note +您可以通過將`OPENCODE_DISABLE_LSP_DOWNLOAD` 環境變量設置為`true` 來禁用自動LSP 服務器下載。 +::: + +--- + +## 它是如何運作的 + +當 opencode 打開一個文件時,它: + +1. 根據所有啟用的 LSP 服務器檢查文件擴展名。 +2. 如果尚未運行,則啟動相應的 LSP 服務器。 + +--- + +## 配置 + +您可以通過 opencode 配置中的 `lsp` 部分自定義 LSP 服務器。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +每個LSP服務器支持以下功能: + +|物業 |類型 |描述 | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` |布爾 |將其設置為`true` 以禁用LSP 服務器| +| `command` |字符串[] |啟動LSP服務器的命令| +| `extensions` |字符串[] |此 LSP 服務器應處理的文件擴展名 | +| `env` |對象|啟動服務器時設置的環境變量| +| `initialization` |對象|發送到LSP服務器的初始化選項| + +讓我們看一些例子。 + +--- + +### 環境變量 + +啟動LSP服務器時使用`env`屬性設置環境變量: + +```json title="opencode.json" {5-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "rust": { + "env": { + "RUST_LOG": "debug" + } + } + } +} +``` + +--- + +### 初始化選項 + +使用`initialization` 屬性將初始化選項傳遞給LSP 服務器。這些是在 LSP `initialize` 請求期間發送的服務器特定設置: + +```json title="opencode.json" {5-9} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "initialization": { + "preferences": { + "importModuleSpecifierPreference": "relative" + } + } + } + } +} +``` + +:::note +初始化選項因 LSP 服務器而異。檢查 LSP 服務器的文檔以獲取可用選項。 +::: + +--- + +### 禁用LSP服務器 + +要全局禁用**所有** LSP 服務器,請將`lsp` 設置為`false`: + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": false +} +``` + +要禁用**特定** LSP 服務器,請將`disabled` 設置為`true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### 自定義 LSP 服務器 + +您可以通過指定命令和文件擴展名來添加自定義 LSP 服務器: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` + +--- + +## 附加信息 + +### PHP 英特爾芬斯 + +PHP Intelephense 通過許可證密鑰提供高級功能。您可以通過將(僅)密鑰放入位於以下位置的文本文件中來提供許可證密鑰: + +- 在 macOS/Linux 上:`$HOME/intelephense/licence.txt` +- 在 Windows 上:`%USERPROFILE%/intelephense/licence.txt` + +該文件應僅包含許可證密鑰,不包含其他內容。 diff --git a/packages/web/src/content/docs/zh-tw/mcp-servers.mdx b/packages/web/src/content/docs/zh-tw/mcp-servers.mdx new file mode 100644 index 000000000..ae1c5a1f1 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/mcp-servers.mdx @@ -0,0 +1,511 @@ +--- +title: MCP服務器 +description: 添加本地和遠程 MCP 工具。 +--- + +您可以使用“模型上下文協議”或 MCP 將外部工具添加到 OpenCode。 OpenCode 支持本地和遠程服務器。 + +添加後,MCP 工具將自動與內置工具一起供法學碩士使用。 + +--- + +#### 注意事項 + +當您使用 MCP 服務器時,它會添加到上下文中。如果您有很多工具,這會很快增加。因此,我們建議您謹慎選擇使用哪些 MCP 服務器。 + +:::tip +MCP 服務器會添加到您的上下文中,因此您需要小心啟用哪些服務器。 +::: + +某些 MCP 服務器(例如 GitHub MCP 服務器)往往會添加大量令牌,並且很容易超出上下文限制。 + +--- + +## 使能夠 + +您可以在`mcp` 下的[開放代碼配置](https://opencode.ai/docs/config/) 中定義MCP 服務器。為每個 MCP 添加唯一的名稱。當提示 LLM 時,您可以通過名稱引用該 MCP。 + +```jsonc title="opencode.jsonc" {6} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "name-of-mcp-server": { + // ... + "enabled": true, + }, + "name-of-other-mcp-server": { + // ... + }, + }, +} +``` + +您還可以通過將`enabled` 設置為`false` 來禁用服務器。如果您想暫時禁用服務器而不將其從配置中刪除,這非常有用。 + +--- + +### 覆蓋遠程默認值 + +組織可以通過其 `.well-known/opencode` 端點提供默認 MCP 服務器。這些服務器可能默認被禁用,允許用戶選擇他們需要的服務器。 + +要從組織的遠程配置啟用特定服務器,請使用 `enabled: true` 將其添加到本地配置: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "jira": { + "type": "remote", + "url": "https://jira.example.com/mcp", + "enabled": true + } + } +} +``` + +您的本地配置值會覆蓋遠程默認值。有關更多詳細信息,請參閱[配置優先級](/docs/config#precedence-order)。 + +--- + +## 當地的 + +使用`type` 將本地MCP 服務器添加到MCP 對像中的`"local"`。 + +```jsonc title="opencode.jsonc" {15} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + // Or ["bun", "x", "my-mcp-command"] + "command": ["npx", "-y", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value", + }, + }, + }, +} +``` + +該命令是本地 MCP 服務器的啟動方式。您還可以傳入環境變量列表。 + +例如,以下是添加測試 [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP 服務器的方法。 + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "mcp_everything": { + "type": "local", + "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], + }, + }, +} +``` + +要使用它,我可以將 `use the mcp_everything tool` 添加到我的提示中。 + +```txt "mcp_everything" +use the mcp_everything tool to add the number 3 and 4 +``` + +--- + +#### 選項 + +以下是配置本地 MCP 服務器的所有選項。 + +|選項|類型 |必填 |描述 | +| ------------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` |字符串|是 | MCP 服務器連接類型,必須是`"local"`。 | +| `command` |數組 |是 |運行 MCP 服務器的命令和參數。 | +| `environment` |對象| |運行服務器時設置的環境變量。 | +| `enabled` |布爾 | |在啟動時啟用或禁用 MCP 服務器。 | +| `timeout` |數量 | |從 MCP 服務器獲取工具的超時(以毫秒為單位)。默認為 5000(5 秒)。 | + +--- + +## 偏僻的 + +通過將`type` 設置為`"remote"` 添加遠程MCP 服務器。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +`url` 是遠程 MCP 服務器的 URL,使用 `headers` 選項您可以傳入標頭列表。 + +--- + +#### 選項 + +|選項|類型 |必填 |描述 | +| --------- | ------- | -------- | ----------------------------------------------------------------------------------- | +| `type` |字符串|是 | MCP 服務器連接類型,必須是`"remote"`。 | +| `url` |字符串|是 |遠程 MCP 服務器的 URL。 | +| `enabled` |布爾 | |在啟動時啟用或禁用 MCP 服務器。 | +| `headers` |對象| |隨請求一起發送的標頭。 | +| `oauth` |對象| | OAuth 身份驗證配置。請參閱下面的[開放認證](#oauth) 部分。 | +| `timeout` |數量 | |從 MCP 服務器獲取工具的超時(以毫秒為單位)。默認為 5000(5 秒)。 | + +--- + +## 開放認證 + +OpenCode 自動處理遠程 MCP 服務器的 OAuth 身份驗證。當服務器需要身份驗證時,OpenCode 將: + +1. 檢測 401 響應並啟動 OAuth 流程 +2. 如果服務器支持,請使用**動態客戶端註冊 (RFC 7591)** +3. 安全地存儲令牌以供將來的請求 + +--- + +### 自動的 + +對於大多數支持 OAuth 的 MCP 服務器,不需要特殊配置。只需配置遠程服務器: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp" + } + } +} +``` + +如果服務器需要身份驗證,OpenCode 將在您第一次嘗試使用它時提示您進行身份驗證。如果沒有,您可以使用 `opencode mcp auth `[手動觸發流量](#authenticating)。 + +--- + +### 預登記 + +如果您有來自 MCP 服務器提供商的客戶端憑據,則可以配置它們: + +```json title="opencode.json" {7-11} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-oauth-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:MY_MCP_CLIENT_ID}", + "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +--- + +### 正在驗證 + +您可以手動觸發身份驗證或管理憑據。 + +使用特定 MCP 服務器進行身份驗證: + +```bash +opencode mcp auth my-oauth-server +``` + +列出所有 MCP 服務器及其身份驗證狀態: + +```bash +opencode mcp list +``` + +刪除存儲的憑據: + +```bash +opencode mcp logout my-oauth-server +``` + +`mcp auth` 命令將打開您的瀏覽器進行授權。授權後,OpenCode 會將令牌安全地存儲在`~/.local/share/opencode/mcp-auth.json` 中。 + +--- + +#### 禁用 OAuth + +如果要禁用服務器的自動 OAuth(例如,對於使用 API 密鑰的服務器),請將 `oauth` 設置為 `false`: + +```json title="opencode.json" {7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-api-key-server": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": false, + "headers": { + "Authorization": "Bearer {env:MY_API_KEY}" + } + } + } +} +``` + +--- + +#### OAuth 選項 + +|選項|類型 |描述 | +| -------------- | --------------- | -------------------------------------------------------------------------------- | +| `oauth` |對象\|假 | OAuth 配置對象,或 `false` 以禁用 OAuth 自動檢測。 | +| `clientId` |字符串| OAuth 客戶端 ID。如果未提供,將嘗試動態客戶端註冊。 | +| `clientSecret` |字符串| OAuth 客戶端密鑰(如果授權服務器需要)。 | +| `scope` |字符串|授權期間請求的 OAuth 範圍。 | + +#### 偵錯 + +如果遠程 MCP 服務器無法進行身份驗證,您可以通過以下方式診斷問題: + +```bash +# View auth status for all OAuth-capable servers +opencode mcp auth list + +# Debug connection and OAuth flow for a specific server +opencode mcp debug my-oauth-server +``` + +`mcp debug` 命令顯示當前身份驗證狀態、測試 HTTP 連接並嘗試 OAuth 發現流程。 + +--- + +## 管理 + +您的 MCP 可作為 OpenCode 中的工具以及內置工具使用。因此,您可以像任何其他工具一樣通過 OpenCode 配置來管理它們。 + +--- + +### 全球的 + +這意味著您可以全局啟用或禁用它們。 + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp-foo": false + } +} +``` + +我們還可以使用 glob 模式來禁用所有匹配的 MCP。 + +```json title="opencode.json" {14} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp-foo": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-foo"] + }, + "my-mcp-bar": { + "type": "local", + "command": ["bun", "x", "my-mcp-command-bar"] + } + }, + "tools": { + "my-mcp*": false + } +} +``` + +這裡我們使用 glob 模式 `my-mcp*` 來禁用所有 MCP。 + +--- + +### 每個代理人 + +如果您有大量 MCP 服務器,您可能只想為每個代理啟用它們並全局禁用它們。為此: + +1. 全局禁用它作為工具。 +2. 在您的[代理配置](/docs/agents#tools) 中,啟用MCP 服務器作為工具。 + +```json title="opencode.json" {11, 14-18} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-mcp": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true + } + }, + "tools": { + "my-mcp*": false + }, + "agent": { + "my-agent": { + "tools": { + "my-mcp*": true + } + } + } +} +``` + +--- + +#### 全局模式 + +glob 模式使用簡單的正則表達式 globbing 模式: + +- `*` 匹配零個或多個任意字符(例如,`"my-mcp*"` 匹配 `my-mcp_search`、`my-mcp_list` 等) +- `?` 恰好匹配一個字符 +- 所有其他字符均按字面意思匹配 + +:::note +MCP 服務器工具以服務器名稱作為前綴進行註冊,因此要禁用服務器的所有工具,只需使用: + +``` +"mymcpservername_*": false +``` + +::: + +--- + +## 示例 + +以下是一些常見 MCP 服務器的示例。如果您想記錄其他服務器,您可以提交 PR。 + +--- + +### 哨兵 + +添加 [哨兵 MCP 服務器](https://mcp.sentry.dev) 以與您的 Sentry 項目和問題進行交互。 + +```json title="opencode.json" {4-8} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +添加配置後,使用Sentry進行身份驗證: + +```bash +opencode mcp auth sentry +``` + +這將打開一個瀏覽器窗口以完成 OAuth 流程並將 OpenCode 連接到您的 Sentry 帳戶。 + +通過身份驗證後,您可以在提示中使用 Sentry 工具來查詢問題、項目和錯誤數據。 + +```txt "use sentry" +Show me the latest unresolved issues in my project. use sentry +``` + +--- + +### 背景7 + +添加[Context7 MCP 服務器](https://github.com/upstash/context7) 以搜索文檔。 + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp" + } + } +} +``` + +如果您註冊了免費帳戶,則可以使用 API 密鑰並獲得更高的速率限制。 + +```json title="opencode.json" {7-9} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { + "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" + } + } + } +} +``` + +這裡我們假設您設置了 `CONTEXT7_API_KEY` 環境變量。 + +將 `use context7` 添加到提示中以使用 Context7 MCP 服務器。 + +```txt "use context7" +Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 +``` + +或者,您可以將類似的內容添加到您的[代理.md](/docs/rules/)。 + +```md title="AGENTS.md" +When you need to search docs, use `context7` tools. +``` + +--- + +### Vercel 的 Grep + +添加 [Vercel 的 Grep](https://grep.app) MCP 服務器以搜索 GitHub 上的代碼片段。 + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} +``` + +由於我們將 MCP 服務器命名為 `gh_grep`,因此您可以將 `use the gh_grep tool` 添加到提示中以使代理使用它。 + +```txt "use the gh_grep tool" +What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool +``` + +或者,您可以將類似的內容添加到您的[代理.md](/docs/rules/)。 + +```md title="AGENTS.md" +If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. +``` diff --git a/packages/web/src/content/docs/zh-tw/models.mdx b/packages/web/src/content/docs/zh-tw/models.mdx new file mode 100644 index 000000000..c49458642 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/models.mdx @@ -0,0 +1,223 @@ +--- +title: 型號 +description: 配置LLM提供者和模型。 +--- + +OpenCode 使用[人工智能軟件開發工具包](https://ai-sdk.dev/) 和[模型.dev](https://models.dev) 來支持**75+ LLM 提供商**,並且它支持運行本地模型。 + +--- + +## 供應商 + +默認情況下會預加載大多數流行的提供程序。如果您已通過 `/connect` 命令添加了提供程序的憑據,那麼它們將在您啟動 OpenCode 時可用。 + +了解有關[提供者](/docs/providers) 的更多信息。 + +--- + +## 選擇型號 + +配置完提供商後,您可以通過輸入以下內容來選擇您想要的型號: + +```bash frame="none" +/models +``` + +--- + +## 推薦型號 + +那裡有很多型號,每週都會有新型號問世。 + +:::tip +考慮使用我們推薦的模型之一。 +::: + +然而,既擅長生成代碼又擅長工具調用的只有少數。 + +以下是與 OpenCode 配合良好的幾個模型,排名不分先後。 (這不是詳盡的列表,也不一定是最新的): + +- GPT 5.2 +- GPT 5.1 法典 +- 近距離工作4.5 +- 克勞德十四行詩 4.5 +- 極小極大M2.1 +- 雙子座 3 專業版 + +--- + +## 設置默認值 + +要將其中之一設置為默認模型,您可以在您的 +打開代碼配置。 + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +這裡完整的 ID 是`provider_id/model_id`。例如,如果您使用 [開放代碼禪](/docs/zen),則您將使用 `opencode/gpt-5.1-codex` 來表示 GPT 5.1 Codex。 + +如果您配置了[定制提供商](/docs/providers#custom),則`provider_id` 是配置中`provider` 部分的密鑰,`model_id` 是`provider.models` 中的密鑰。 + +--- + +## 配置模型 + +您可以通過 config.json 全局配置模型的選項。 + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-5-20250929": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +在這裡,我們為兩個內置模型配置全局設置:`gpt-5`(通過 `openai` 提供程序訪問時)和 `claude-sonnet-4-20250514`(通過 `anthropic` 提供程序訪問時)。 +內置提供商和型號名稱可以在[模型.dev](https://models.dev) 上找到。 + +您還可以為您正在使用的任何代理配置這些選項。代理配置會覆蓋此處的所有全局選項。 [了解更多](/docs/agents/#additional)。 + +您還可以定義擴展內置變體的自定義變體。變體允許您為同一模型配置不同的設置,而無需創建重複的條目: + +```jsonc title="opencode.jsonc" {6-21} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "opencode": { + "models": { + "gpt-5": { + "variants": { + "high": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + "low": { + "reasoningEffort": "low", + "textVerbosity": "low", + "reasoningSummary": "auto", + }, + }, + }, + }, + }, + }, +} +``` + +--- + +## 變體 + +許多型號支持具有不同配置的多種變體。 OpenCode 附帶了流行提供商的內置默認變體。 + +### 內置變體 + +OpenCode 附帶了許多提供商的默認變體: + +**人擇**: + +- `high` - 高思維預算(默認) +- `max` - 最大思維預算 + +**開放人工智能**: + +因型號而異,但大致如下: + +- `none` - 沒有推理 +- `minimal` - 最少的推理工作 +- `low` - 推理工作量低 +- `medium` - 中等推理努力 +- `high` - 高推理能力 +- `xhigh` - 極高的推理能力 + +**Google**: + +- `low` - 降低工作量/代幣預算 +- `high` - 更高的努力/代幣預算 + +:::tip +該列表並不全面。許多其他提供商也有內置的默認值。 +::: + +### 定制變體 + +您可以覆蓋現有變體或添加您自己的變體: + +```jsonc title="opencode.jsonc" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "variants": { + "thinking": { + "reasoningEffort": "high", + "textVerbosity": "low", + }, + "fast": { + "disabled": true, + }, + }, + }, + }, + }, + }, +} +``` + +### 循環變體 + +使用鍵綁定 `variant_cycle` 在變體之間快速切換。 [了解更多](/docs/keybinds)。 + +--- + +## 加載模型 + +當 OpenCode 啟動時,它會按以下優先順序檢查模型: + +1. `--model` 或 `-m` 命令行標誌。格式與配置文件中的相同:`provider_id/model_id`。 + +2. OpenCode 配置中的模型列表。 + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + 這裡的格式是`provider/model`。 + +3. 最後使用的型號。 + +4. 第一個模型使用內部優先級。 diff --git a/packages/web/src/content/docs/zh-tw/modes.mdx b/packages/web/src/content/docs/zh-tw/modes.mdx new file mode 100644 index 000000000..cc8e5d6e3 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/modes.mdx @@ -0,0 +1,331 @@ +--- +title: 模式 +description: 不同的模式適用於不同的用例。 +--- + +:::caution +現在通過 opencode 配置中的 `agent` 選項配置模式。這 +`mode` 選項現已棄用。 [了解更多](/docs/agents)。 +::: + +opencode 中的模式允許您自定義不同用例的行為、工具和提示。 + +它具有兩種內置模式:**構建**和**計劃**。您可以定制 +這些或通過 opencode 配置配置您自己的。 + +您可以在會話期間在模式之間切換或在配置文件中配置它們。 + +--- + +## 內建 + +opencode 有兩種內置模式。 + +--- + +### 建造 + +構建是啟用所有工具的**默認**模式。這是開發工作的標準模式,您需要完全訪問文件操作和系統命令。 + +--- + +### 計劃 + +專為規劃和分析而設計的受限模式。在計劃模式下,默認情況下禁用以下工具: + +- `write` - 無法創建新文件 +- `edit` - 無法修改現有文件,位於 `.opencode/plans/*.md` 的用於詳細說明計劃本身的文件除外 +- `patch` - 無法應用補丁 +- `bash` - 無法執行 shell 命令 + +當您希望 AI 分析代碼、建議更改或創建計劃而不對代碼庫進行任何實際修改時,此模式非常有用。 + +--- + +## 交換 + +您可以在會話期間使用 _Tab_ 鍵在模式之間切換。或者您配置的 `switch_mode` 鍵綁定。 + +另請參閱:[格式化程序](/docs/formatters) 有關代碼格式配置的信息。 + +--- + +## 配置 + +您可以自定義內置模式或通過配置創建自己的模式。可以通過兩種方式配置模式: + +### JSON 配置 + +在 `opencode.json` 配置文件中配置模式: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### 降價配置 + +您還可以使用 Markdown 文件定義模式。將它們放入: + +- 全球:`~/.config/opencode/modes/` +- 項目:`.opencode/modes/` + +```markdown title="~/.config/opencode/modes/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +Markdown 文件名成為模式名稱(例如,`review.md` 創建`review` 模式)。 + +讓我們詳細看看這些配置選項。 + +--- + +### 模型 + +使用`model` 配置覆蓋此模式的默認模型。對於使用針對不同任務優化的不同模型很有用。例如,更快的規劃模型、更強大的實施模型。 + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### 溫度 + +使用 `temperature` 配置控制 AI 響應的隨機性和創造性。較低的值使響應更加集中和確定,而較高的值則增加創造力和可變性。 + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +溫度值的範圍通常為 0.0 到 1.0: + +- **0.0-0.2**:非常集中且確定的響應,非常適合代碼分析和規劃 +- **0.3-0.5**:具有一定創造力的平衡響應,適合一般開發任務 +- **0.6-1.0**:更有創意和多樣化的反應,有助於頭腦風暴和探索 + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +如果未指定溫度,opencode 將使用特定於模型的默認值(大多數模型通常為 0,Qwen 模型為 0.55)。 + +--- + +### 迅速的 + +使用 `prompt` 配置為此模式指定自定義系統提示文件。提示文件應包含特定於該模式用途的指令。 + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +該路徑是相對於配置文件所在位置的。所以這適用於 +全局 opencode 配置和項目特定配置。 + +--- + +### 工具 + +使用 `tools` 配置控制在此模式下可用的工具。您可以通過將特定工具設置為`true` 或`false` 來啟用或禁用特定工具。 + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +如果未指定任何工具,則默認啟用所有工具。 + +--- + +#### 可用工具 + +這裡是所有可以通過模式配置控制的工具。 + +|工具|描述 | +| ----------- | ----------------------- | +| `bash` |執行 shell 命令 | +| `edit` |修改現有文件 | +| `write` |創建新文件 | +| `read` |讀取文件內容 | +| `grep` |搜索文件內容 | +| `glob` |按模式查找文件 | +| `list` |列出目錄內容 | +| `patch` |對文件應用補丁 | +| `todowrite` |管理待辦事項列表 | +| `todoread` |閱讀待辦事項列表 | +| `webfetch` |獲取網頁內容 | + +--- + +## 自定義模式 + +您可以通過將自定義模式添加到配置來創建自己的自定義模式。以下是使用這兩種方法的示例: + +### 使用 JSON 配置 + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### 使用 Markdown 文件 + +在`.opencode/modes/`中為項目特定模式創建模式文件,在`~/.config/opencode/modes/`中為全局模式創建模式文件: + +```markdown title=".opencode/modes/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/modes/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### 使用案例 + +以下是不同模式的一些常見用例。 + +- **構建模式**:啟用所有工具的完整開發工作 +- **計劃模式**:分析和計劃,無需更改 +- **審閱模式**:使用只讀訪問權限和文檔工具進行代碼審閱 +- **調試模式**:專注於啟用 bash 和讀取工具的調查 +- **文檔模式**:使用文件操作但不使用系統命令的文檔編寫 + +您可能還會發現不同的模型適用於不同的用例。 diff --git a/packages/web/src/content/docs/zh-tw/network.mdx b/packages/web/src/content/docs/zh-tw/network.mdx new file mode 100644 index 000000000..0ff1cc3e2 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/network.mdx @@ -0,0 +1,57 @@ +--- +title: 網絡 +description: 配置代理和自定義證書。 +--- + +OpenCode 支持企業網絡環境的標準代理環境變量和自定義證書。 + +--- + +## 代理人 + +OpenCode 尊重標準代理環境變量。 + +```bash +# HTTPS proxy (recommended) +export HTTPS_PROXY=https://proxy.example.com:8080 + +# HTTP proxy (if HTTPS not available) +export HTTP_PROXY=http://proxy.example.com:8080 + +# Bypass proxy for local server (required) +export NO_PROXY=localhost,127.0.0.1 +``` + +:::caution +TUI 與本地 HTTP 服務器通信。您必須繞過此連接的代理以防止路由循環。 +::: + +您可以使用[CLI 標誌](/docs/cli#run)配置服務器的端口和主機名。 + +--- + +### 認證 + +如果您的代理需要基本身份驗證,請在 URL 中包含憑據。 + +```bash +export HTTPS_PROXY=http://username:password@proxy.example.com:8080 +``` + +:::caution +避免對密碼進行硬編碼。使用環境變量或安全憑證存儲。 +::: + +對於需要高級身份驗證(例如 NTLM 或 Kerberos)的代理,請考慮使用支持您的身份驗證方法的 LLM 網關。 + +--- + +## 定制證書 + +如果您的企業使用自定義 CA 進行 HTTPS 連接,請配置 OpenCode 以信任它們。 + +```bash +export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem +``` + +這適用於代理連接和直接 API 訪問。 diff --git a/packages/web/src/content/docs/zh-tw/permissions.mdx b/packages/web/src/content/docs/zh-tw/permissions.mdx new file mode 100644 index 000000000..4024b0863 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/permissions.mdx @@ -0,0 +1,237 @@ +--- +title: 權限 +description: 控制哪些操作需要批准才能運行。 +--- + +OpenCode 使用`permission` 配置來決定給定的操作是否應自動運行、提示您或被阻止。 + +從 `v1.1.1` 開始,舊版 `tools` 布爾配置已被棄用,並已合併到 `permission` 中。仍支持舊的 `tools` 配置以實現向後兼容性。 + +--- + +## 行動 + +每個權限規則解析為以下之一: + +- `"allow"` — 未經批准運行 +- `"ask"` — 提示批准 +- `"deny"` — 阻止該操作 + +--- + +## 配置 + +您可以全局設置權限(使用`*`),並覆蓋特定工具。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "*": "ask", + "bash": "allow", + "edit": "deny" + } +} +``` + +您還可以一次設置所有權限: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": "allow" +} +``` + +--- + +## 粒度規則(對象語法) + +對於大多數權限,您可以使用對像根據工具輸入應用不同的操作。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "npm *": "allow", + "rm *": "deny", + "grep *": "allow" + }, + "edit": { + "*": "deny", + "packages/web/src/content/docs/*.mdx": "allow" + } + } +} +``` + +規則通過模式匹配進行評估,**最後匹配的規則獲勝**。常見的模式是將包羅萬象的 `"*"` 規則放在前面,然後再放置更具體的規則。 + +### 通配符 + +權限模式使用簡單的通配符匹配: + +- `*` 匹配零個或多個任意字符 +- `?` 恰好匹配一個字符 +- 所有其他字符均按字面意思匹配 + +### 主目錄擴展 + +您可以在模式開頭使用 `~` 或 `$HOME` 來引用您的主目錄。這對於 [`external_directory`](#external-directories) 規則特別有用。 + +- `~/projects/*` -> `/Users/username/projects/*` +- `$HOME/projects/*` -> `/Users/username/projects/*` +- `~` -> `/Users/username` + +### 外部目錄 + +使用 `external_directory` 允許工具調用觸及啟動 OpenCode 的工作目錄之外的路徑。這適用於任何採用路徑作為輸入的工具(例如`read`、`edit`、`list`、`glob`、`grep` 和許多`bash` 命令)。 + +主擴展(如`~/...`)僅影響模式的編寫方式。它不會使外部路徑成為當前工作空間的一部分,因此仍必須通過 `external_directory` 允許工作目錄之外的路徑。 + +例如,這允許訪問 `~/projects/personal/` 下的所有內容: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + } + } +} +``` + +此處允許的任何目錄都會繼承與當前工作空間相同的默認值。自[`read` 默認為 `allow`](#defaults) 起,也允許讀取`external_directory` 下的條目,除非被覆蓋。當工具應限制在這些路徑中時添加顯式規則,例如在保留讀取的同時阻止編輯: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "external_directory": { + "~/projects/personal/**": "allow" + }, + "edit": { + "~/projects/personal/**": "deny" + } + } +} +``` + +將列表重點放在受信任的路徑上,並根據其他工具的需要分層額外的允許或拒絕規則(例如 `bash`)。 + +--- + +## 可用權限 + +OpenCode 權限由工具名稱和一些安全防護措施決定: + +- `read` — 讀取文件(與文件路徑匹配) +- `edit` — 所有文件修改(涵蓋`edit`、`write`、`patch`、`multiedit`) +- `glob` — 文件通配符(匹配通配符模式) +- `grep` — 內容搜索(匹配正則表達式模式) +- `list` — 列出目錄中的文件(與目錄路徑匹配) +- `bash` — 運行 shell 命令(匹配 `git status --porcelain` 等解析命令) +- `task` — 啟動子代理(與子代理類型匹配) +- `skill` — 加載技能(與技能名稱匹配) +- `lsp` — 運行 LSP 查詢(當前非粒度) +- `todoread`、`todowrite` — 讀取/更新待辦事項列表 +- `webfetch` — 獲取 URL(與 URL 匹配) +- `websearch`、`codesearch` — 網頁/代碼搜索(與查詢匹配) +- `external_directory` — 當工具觸及項目工作目錄之外的路徑時觸發 +- `doom_loop` — 當相同的工具調用使用相同的輸入重複 3 次時觸發 + +--- + +## 預設值 + +如果您不指定任何內容,OpenCode 將從許可的默認值開始: + +- 大多數權限默認為`"allow"`。 +- `doom_loop` 和`external_directory` 默認為`"ask"`。 +- `read` 是 `"allow"`,但 `.env` 文件默認被拒絕: + +```json title="opencode.json" +{ + "permission": { + "read": { + "*": "allow", + "*.env": "deny", + "*.env.*": "deny", + "*.env.example": "allow" + } + } +} +``` + +--- + +## “問”的作用是什麼 + +當 OpenCode 提示批准時,UI 會提供三種結果: + +- `once` — 僅批准此請求 +- `always` — 批准與建議模式匹配的未來請求(對於當前 OpenCode 會話的其餘部分) +- `reject` — 拒絕請求 + +`always` 將批准的模式集由該工具提供(例如,bash 批准通常將安全命令前綴(如 `git status*`)列入白名單)。 + +--- + +## 代理商 + +您可以覆蓋每個代理的權限。代理權限與全局​​配置合併,代理規則優先。 [了解更多](/docs/agents#permissions) 關於代理權限。 + +:::note +有關更詳細的模式匹配示例,請參閱上面的 [粒度規則(對象語法)](#granular-rules-object-syntax) 部分。 +::: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "deny", + "git push *": "deny", + "grep *": "allow" + } + }, + "agent": { + "build": { + "permission": { + "bash": { + "*": "ask", + "git *": "allow", + "git commit *": "ask", + "git push *": "deny", + "grep *": "allow" + } + } + } + } +} +``` + +您還可以在 Markdown 中配置代理權限: + +```markdown title="~/.config/opencode/agents/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +:::tip +對帶有參數的命令使用模式匹配。 `"grep *"` 允許`grep pattern file.txt`,而`"grep"` 單獨會阻止它。像 `git status` 這樣的命令適用於默認行為,但在傳遞參數時需要顯式許可(如 `"git status *"`)。 +::: diff --git a/packages/web/src/content/docs/zh-tw/plugins.mdx b/packages/web/src/content/docs/zh-tw/plugins.mdx new file mode 100644 index 000000000..edebcdcd7 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/plugins.mdx @@ -0,0 +1,385 @@ +--- +title: 插件 +description: 編寫您自己的插件來擴展 OpenCode。 +--- + +插件允許您通過掛鉤各種事件和自定義行為來擴展 OpenCode。您可以創建插件來添加新功能、與外部服務集成或修改 OpenCode 的默認行為。 + +例如,查看社區創建的[插件](/docs/ecosystem#plugins)。 + +--- + +## 使用插件 + +有兩種加載插件的方法。 + +--- + +### 從本地文件 + +將 JavaScript 或 TypeScript 文件放置在插件目錄中。 + +- `.opencode/plugins/` - 項目級插件 +- `~/.config/opencode/plugins/` - 全局插件 + +這些目錄中的文件會在啟動時自動加載。 + +--- + +### 來自 npm + +在配置文件中指定 npm 包。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] +} +``` + +支持常規和範圍 npm 包。 + +瀏覽[生態系統](/docs/ecosystem#plugins)中的可用插件。 + +--- + +### 插件是如何安裝的 + +**npm 插件** 在啟動時使用 Bun 自動安裝。包及其依賴項緩存在`~/.cache/opencode/node_modules/`中。 + +**本地插件**直接從插件目錄加載。要使用外部包,您必須在配置目錄中創建`package.json`(請參閱[依賴關係](#dependencies)),或將插件發佈到npm和[將其添加到您的配置中](/docs/config#plugins)。 + +--- + +### 加載順序 + +插件從所有源加載,所有掛鉤按順序運行。加載順序為: + +1. 全局配置 (`~/.config/opencode/opencode.json`) +2. 項目配置(`opencode.json`) +3. 全局插件目錄 (`~/.config/opencode/plugins/`) +4. 項目插件目錄(`.opencode/plugins/`) + +具有相同名稱和版本的重複 npm 包將被加載一次。但是,本地插件和名稱相似的 npm 插件都是分開加載的。 + +--- + +## 創建一個插件 + +插件是一個 **JavaScript/TypeScript 模塊**,它導出一個或多個插件 +功能。每個函數接收一個上下文對象並返回一個鉤子對象。 + +--- + +### 依賴關係 + +本地插件和自定義工具可以使用外部 npm 包。將 `package.json` 添加到您的配置目錄,其中包含您需要的依賴項。 + +```json title=".opencode/package.json" +{ + "dependencies": { + "shescape": "^2.1.0" + } +} +``` + +OpenCode 在啟動時運行 `bun install` 來安裝這些。然後您的插件和工具就可以導入它們。 + +```ts title=".opencode/plugins/my-plugin.ts" +import { escape } from "shescape" + +export const MyPlugin = async (ctx) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "bash") { + output.args.command = escape(output.args.command) + } + }, + } +} +``` + +--- + +### 基本結構 + +```js title=".opencode/plugins/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +插件函數接收: + +- `project`:當前項目信息。 +- `directory`:當前工作目錄。 +- `worktree`:git 工作樹路徑。 +- `client`:用於與 AI 交互的開放代碼 SDK 客戶端。 +- `$`:Bun的[外殼API](https://bun.com/docs/runtime/shell)用於執行命令。 + +--- + +### TypeScript 支持 + +對於 TypeScript 插件,您可以從插件包中導入類型: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +### 活動 + +插件可以訂閱事件,如下面的示例部分所示。以下是可用的不同事件的列表。 + +#### 命令事件 + +- `command.executed` + +#### 文件事件 + +- `file.edited` +- `file.watcher.updated` + +#### 安裝活動 + +- `installation.updated` + +#### LSP活動 + +- `lsp.client.diagnostics` +- `lsp.updated` + +#### 消息事件 + +- `message.part.removed` +- `message.part.updated` +- `message.removed` +- `message.updated` + +#### 權限事件 + +- `permission.asked` +- `permission.replied` + +#### 服務器事件 + +- `server.connected` + +#### 會議活動 + +- `session.created` +- `session.compacted` +- `session.deleted` +- `session.diff` +- `session.error` +- `session.idle` +- `session.status` +- `session.updated` + +#### 都都活動 + +- `todo.updated` + +#### 殼牌活動 + +- `shell.env` + +#### 工具事件 + +- `tool.execute.after` +- `tool.execute.before` + +#### 途易活動 + +- `tui.prompt.append` +- `tui.command.execute` +- `tui.toast.show` + +--- + +## 示例 + +以下是一些可用於擴展 opencode 的插件示例。 + +--- + +### 發送通知 + +當某些事件發生時發送通知: + +```js title=".opencode/plugins/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +我們使用 `osascript` 在 macOS 上運行 AppleScript。這裡我們用它來發送通知。 + +:::note +如果您使用 OpenCode 桌面應用程序,它可以在響應準備就緒或會話出錯時自動發送系統通知。 +::: + +--- + +### .env 保護 + +阻止 opencode 讀取 `.env` 文件: + +```javascript title=".opencode/plugins/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` + +--- + +### 注入環境變量 + +將環境變量注入所有 shell 執行(AI 工具和用戶終端): + +```javascript title=".opencode/plugins/inject-env.js" +export const InjectEnvPlugin = async () => { + return { + "shell.env": async (input, output) => { + output.env.MY_API_KEY = "secret" + output.env.PROJECT_ROOT = input.cwd + }, + } +} +``` + +--- + +### 定制工具 + +插件還可以向 opencode 添加自定義工具: + +```ts title=".opencode/plugins/custom-tools.ts" +import { type Plugin, tool } from "@opencode-ai/plugin" + +export const CustomToolsPlugin: Plugin = async (ctx) => { + return { + tool: { + mytool: tool({ + description: "This is a custom tool", + args: { + foo: tool.schema.string(), + }, + async execute(args, context) { + const { directory, worktree } = context + return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` + }, + }), + }, + } +} +``` + +`tool` 幫助器創建一個 opencode 可以調用的自定義工具。它採用 Zod 模式函數並返回一個工具定義: + +- `description`:該工具的作用 +- `args`:工具參數的 Zod 模式 +- `execute`:調用工具時運行的函數 + +您的自定義工具將可與內置工具一起用於開放代碼。 + +--- + +### 記錄 + +使用 `client.app.log()` 而不是 `console.log` 進行結構化日誌記錄: + +```ts title=".opencode/plugins/my-plugin.ts" +export const MyPlugin = async ({ client }) => { + await client.app.log({ + body: { + service: "my-plugin", + level: "info", + message: "Plugin initialized", + extra: { foo: "bar" }, + }, + }) +} +``` + +級別:`debug`、`info`、`warn`、`error`。詳情請參閱[SDK文檔](https://opencode.ai/docs/sdk)。 + +--- + +### 壓實鉤 + +自定義壓縮會話時包含的上下文: + +```ts title=".opencode/plugins/compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Inject additional context into the compaction prompt + output.context.push(` +## Custom Context + +Include any state that should persist across compaction: +- Current task status +- Important decisions made +- Files being actively worked on +`) + }, + } +} +``` + +`experimental.session.compacting` 鉤子在 LLM 生成延續摘要之前觸發。使用它來注入默認壓縮提示會錯過的特定於域的上下文。 + +您還可以通過設置`output.prompt`來完全替換壓縮提示: + +```ts title=".opencode/plugins/custom-compaction.ts" +import type { Plugin } from "@opencode-ai/plugin" + +export const CustomCompactionPlugin: Plugin = async (ctx) => { + return { + "experimental.session.compacting": async (input, output) => { + // Replace the entire compaction prompt + output.prompt = ` +You are generating a continuation prompt for a multi-agent swarm session. + +Summarize: +1. The current task and its status +2. Which files are being modified and by whom +3. Any blockers or dependencies between agents +4. The next steps to complete the work + +Format as a structured prompt that a new agent can use to resume work. +` + }, + } +} +``` + +當設置`output.prompt`時,它完全取代默認的壓縮提示。在這種情況下,`output.context` 數組將被忽略。 diff --git a/packages/web/src/content/docs/zh-tw/providers.mdx b/packages/web/src/content/docs/zh-tw/providers.mdx new file mode 100644 index 000000000..bba1341ca --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/providers.mdx @@ -0,0 +1,1889 @@ +--- +title: 供應商 +description: 使用 OpenCode 中的任何 LLM 提供商。 +--- + +import config from "../../../../config.mjs" +export const console = config.console + +OpenCode 使用[人工智能軟件開發工具包](https://ai-sdk.dev/) 和[模型.dev](https://models.dev) 來支持**75+ LLM 提供商**,並且它支持運行本地模型。 + +要添加提供商,您需要: + +1. 使用 `/connect` 命令添加提供程序的 API 密鑰。 +2. 在 OpenCode 配置中配置提供程序。 + +--- + +### 證書 + +當您使用 `/connect` 命令添加提供商的 API 密鑰時,它們會被存儲 +在`~/.local/share/opencode/auth.json`。 + +--- + +### 配置 + +您可以通過 OpenCode 中的 `provider` 部分自定義提供程序 +配置。 + +--- + +#### 基本網址 + +您可以通過設置 `baseURL` 選項來自定義任何提供程序的基本 URL。這在使用代理服務或自定義端點時非常有用。 + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## 開放代碼禪 + +OpenCode Zen 是 OpenCode 團隊提供的模型列表,這些模型已被 +經過測試和驗證,可以與 OpenCode 良好配合。 [了解更多](/docs/zen)。 + +:::tip +如果您是新手,我們建議您從 OpenCode Zen 開始。 +::: + +1. 在 TUI 中運行 `/connect` 命令,選擇 opencode,然後前往 [opencode.ai/auth](https://opencode.ai/auth)。 + + ```txt + /connect + ``` + +2. 登錄,添加您的賬單詳細信息,然後復制您的 API 密鑰。 + +3. 粘貼您的 API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 在 TUI 中運行 `/models` 以查看我們推薦的型號列表。 + + ```txt + /models + ``` + +它的工作方式與 OpenCode 中的任何其他提供程序一樣,並且完全可以選擇使用。 + +--- + +## 目錄 + +讓我們詳細了解一些提供商。如果您想將提供商添加到 +列表,請隨時打開 PR。 + +:::note +在這裡沒有看到提供商?提交 PR。 +::: + +--- + +### 302.艾伊 + +1. 前往[302.AI控制台](https://302.ai/),創建一個帳戶並生成一個 API 密鑰。 + +2. 運行`/connect`命令並蒐索**302.AI**。 + + ```txt + /connect + ``` + +3. 輸入您的 302.AI API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 執行`/models`命令選擇型號。 + + ```txt + /models + ``` + +--- + +### 亞馬遜基岩 + +要將 Amazon Bedrock 與 OpenCode 結合使用: + +1. 前往 Amazon Bedrock 控制台中的 **模型目錄** 並請求 + 訪問您想要的模型。 + + :::tip + 您需要能夠在 Amazon Bedrock 中訪問所需的模型。 + ::: + +2. **使用以下方法之一配置身份驗證**: + + #### 環境變量(快速啟動) + + 運行 opencode 時設置以下環境變量之一: + + ```bash + # Option 1: Using AWS access keys + AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode + + # Option 2: Using named AWS profile + AWS_PROFILE=my-profile opencode + + # Option 3: Using Bedrock bearer token + AWS_BEARER_TOKEN_BEDROCK=XXX opencode + ``` + + 或者將它們添加到您的 bash 配置文件中: + + ```bash title="~/.bash_profile" + export AWS_PROFILE=my-dev-profile + export AWS_REGION=us-east-1 + ``` + + #### 配置文件(推薦) + + 對於特定於項目或持久的配置,請使用 `opencode.json`: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "my-aws-profile" + } + } + } + } + ``` + + **可用選項:** + - `region` - AWS 區域(例如`us-east-1`、`eu-west-1`) + - `profile` - 來自 `~/.aws/credentials` 的 AWS 命名配置文件 + - `endpoint` - VPC 終端節點的自定義終端節點 URL(通用 `baseURL` 選項的別名) + + :::tip + 配置文件選項優先於環境變量。 + ::: + + #### 高級:VPC 端點 + + 如果您使用 Bedrock 的 VPC 終端節點: + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + "options": { + "region": "us-east-1", + "profile": "production", + "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com" + } + } + } + } + ``` + + :::note + `endpoint` 選項是通用 `baseURL` 選項的別名,使用 AWS 特定術語。如果同時指定`endpoint` 和`baseURL`,則`endpoint` 優先。 + ::: + + #### 認證方式 + - **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**:創建 IAM 用戶並在 AWS 控制台中生成訪問密鑰 + - **`AWS_PROFILE`**:使用`~/.aws/credentials` 中的命名配置文件。首先配置`aws configure --profile my-profile`或`aws sso login` + - **`AWS_BEARER_TOKEN_BEDROCK`**:從 Amazon Bedrock 控制台生成長期 API 密鑰 + - **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**:適用於 EKS IRSA(服務賬戶的 IAM 角色)或具有 OIDC 聯合的其他 Kubernetes 環境。使用服務帳戶註釋時,這些環境變量由 Kubernetes 自動注入。 + + #### 認證優先級 + + Amazon Bedrock 使用以下身份驗證優先級: + 1. **不記名令牌** - `AWS_BEARER_TOKEN_BEDROCK` 環境變量或來自 `/connect` 命令的令牌 + 2. **AWS 憑證鏈** - 配置文件、訪問密鑰、共享憑證、IAM 角色、Web 身份令牌 (EKS IRSA)、實例元數據 + + :::note + 設置不記名令牌(通過 `/connect` 或 `AWS_BEARER_TOKEN_BEDROCK`)時,它優先於所有 AWS 憑證方法(包括配置的配置文件)。 + ::: + +3. 運行`/models`命令選擇所需的型號。 + + ```txt + /models + ``` + +:::note +對於自定義推理配置文件,請在密鑰中使用模型和提供程序名稱,並將 `id` 屬性設置為 arn。這確保了正確的緩存: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "amazon-bedrock": { + // ... + "models": { + "anthropic-claude-sonnet-4.5": { + "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy" + } + } + } + } +} +``` + +::: + +--- + +### 人擇 + +1. 註冊後,運行 `/connect` 命令並選擇 Anthropic。 + + ```txt + /connect + ``` + +2. 在這裡您可以選擇 **Claude Pro/Max** 選項,它將打開您的瀏覽器 + 並要求您進行身份驗證。 + + ```txt + ┌ Select auth method + │ + │ Claude Pro/Max + │ Create an API Key + │ Manually enter API Key + └ + ``` + +3. 現在,當您使用 `/models` 命令時,所有 Anthropic 模型都應該可用。 + + ```txt + /models + ``` + +:::info +[人擇](https://anthropic.com) 不正式支持在 OpenCode 中使用您的 Claude Pro/Max 訂閱。 +::: + +##### 使用 API 密鑰 + +如果您沒有 Pro/Max 訂閱,您還可以選擇 **創建 API 密鑰**。它還會打開您的瀏覽器並要求您登錄 Anthropic 並為您提供一個可以粘貼到終端中的代碼。 + +或者,如果您已有 API 密鑰,則可以選擇 **手動輸入 API 密鑰** 並將其粘貼到您的終端中。 + +--- + +### Azure 開放人工智能 + +:::note +如果遇到“抱歉,但我無法協助該請求”錯誤,請嘗試將 Azure 資源中的內容篩選器從 **DefaultV2** 更改為 **Default**。 +::: + +1. 轉到 [Azure 門戶](https://portal.azure.com/) 並創建 **Azure OpenAI** 資源。你需要: + - **資源名稱**:這將成為您的 API 端點 (`https://RESOURCE_NAME.openai.azure.com/`) 的一部分 + - **API 密鑰**:來自您的資源的 `KEY 1` 或 `KEY 2` + +2. 轉到[Azure 人工智能鑄造廠](https://ai.azure.com/) 並部署模型。 + + :::note + 部署名稱必須與模型名稱匹配,opencode 才能正常工作。 + ::: + +3. 運行 `/connect` 命令並蒐索 **Azure**。 + + ```txt + /connect + ``` + +4. 輸入您的 API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. 將您的資源名稱設置為環境變量: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + 或者將其添加到您的 bash 配置文件中: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. 運行 `/models` 命令以選擇您部署的模型。 + + ```txt + /models + ``` + +--- + +### Azure 認知服務 + +1. 轉到 [Azure 門戶](https://portal.azure.com/) 並創建 **Azure OpenAI** 資源。你需要: + - **資源名稱**:這將成為您的 API 端點 (`https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/`) 的一部分 + - **API 密鑰**:來自您的資源的 `KEY 1` 或 `KEY 2` + +2. 轉到[Azure 人工智能鑄造廠](https://ai.azure.com/) 並部署模型。 + + :::note + 部署名稱必須與模型名稱匹配,opencode 才能正常工作。 + ::: + +3. 運行 `/connect` 命令並蒐索 **Azure 認知服務**。 + + ```txt + /connect + ``` + +4. 輸入您的 API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +5. 將您的資源名稱設置為環境變量: + + ```bash + AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode + ``` + + 或者將其添加到您的 bash 配置文件中: + + ```bash title="~/.bash_profile" + export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX + ``` + +6. 運行 `/models` 命令以選擇您部署的模型。 + + ```txt + /models + ``` + +--- + +### 巴吉度獵犬 + +1. 前往[巴吉度獵犬](https://app.baseten.co/),創建一個帳戶並生成一個 API 密鑰。 + +2. 運行`/connect`命令並蒐索**Baseten**。 + + ```txt + /connect + ``` + +3. 輸入您的 Baseten API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 執行`/models`命令選擇型號。 + + ```txt + /models + ``` + +--- + +### 大腦 + +1. 前往[大腦控制台](https://inference.cerebras.ai/),創建一個帳戶並生成一個 API 密鑰。 + +2. 運行 `/connect` 命令並蒐索 **Cerebras**。 + + ```txt + /connect + ``` + +3. 輸入您的 Cerebras API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇型號,如_Qwen 3 Coder 480B_。 + + ```txt + /models + ``` + +--- + +### Cloudflare AI 網關 + +Cloudflare AI Gateway 讓您可以通過統一端點訪問來自 OpenAI、Anthropic、Workers AI 等的模型。使用[統一計費](https://developers.cloudflare.com/ai-gateway/features/unified-billing/),您不需要為每個提供商提供單獨的 API 密鑰。 + +1. 前往[Cloudflare 儀表板](https://dash.cloudflare.com/),導航至 **AI** > **AI Gateway**,然後創建一個新網關。 + +2. 將您的帳戶 ID 和網關 ID 設置為環境變量。 + + ```bash title="~/.bash_profile" + export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id + export CLOUDFLARE_GATEWAY_ID=your-gateway-id + ``` + +3. 運行 `/connect` 命令並蒐索 **Cloudflare AI Gateway**。 + + ```txt + /connect + ``` + +4. 輸入您的 Cloudflare API 令牌。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + + 或者將其設置為環境變量。 + + ```bash title="~/.bash_profile" + export CLOUDFLARE_API_TOKEN=your-api-token + ``` + +5. 執行`/models`命令選擇型號。 + + ```txt + /models + ``` + + 您還可以通過 opencode 配置添加模型。 + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "cloudflare-ai-gateway": { + "models": { + "openai/gpt-4o": {}, + "anthropic/claude-sonnet-4": {} + } + } + } + } + ``` + +--- + +### 皮質 + +1. 前往[Cortecs 控制台](https://cortecs.ai/),創建一個帳戶並生成一個 API 密鑰。 + +2. 運行 `/connect` 命令並蒐索 **Cortecs**。 + + ```txt + /connect + ``` + +3. 輸入您的 Cortecs API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇一個模型,如_Kimi K2 Instruct_。 + + ```txt + /models + ``` + +--- + +### 深度搜索 + +1. 前往[DeepSeek 控制台](https://platform.deepseek.com/),創建一個帳戶,然後單擊“**創建新的 API 密鑰**”。 + +2. 運行`/connect`命令並蒐索**DeepSeek**。 + + ```txt + /connect + ``` + +3. 輸入您的 DeepSeek API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行 `/models` 命令以選擇 DeepSeek 模型,例如 _DeepSeek Reasoner_。 + + ```txt + /models + ``` + +--- + +### 深層基礎設施 + +1. 前往[深度基礎設施儀表板](https://deepinfra.com/dash),創建一個帳戶並生成一個 API 密鑰。 + +2. 運行 `/connect` 命令並蒐索 **Deep Infra**。 + + ```txt + /connect + ``` + +3. 輸入您的 Deep Infra API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 執行`/models`命令選擇型號。 + + ```txt + /models + ``` + +--- + +### 韌體 + +1. 前往[固件儀表板](https://app.firmware.ai/signup),創建一個帳戶並生成一個 API 密鑰。 + +2. 運行`/connect`命令並蒐索**固件**。 + + ```txt + /connect + ``` + +3. 輸入您的固件 API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 執行`/models`命令選擇型號。 + + ```txt + /models + ``` + +--- + +### 煙花人工智能 + +1. 前往[Fireworks AI 控制台](https://app.fireworks.ai/),創建一個帳戶,然後單擊“**創建 API 密鑰**”。 + +2. 運行 `/connect` 命令並蒐索 **Fireworks AI**。 + + ```txt + /connect + ``` + +3. 輸入您的 Fireworks AI API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇一個模型,如_Kimi K2 Instruct_。 + + ```txt + /models + ``` + +--- + +### 亞搏體育app二人組 + +GitLab Duo 通過 GitLab 的 Anthropic 代理提供具有本機工具調用功能的 AI 驅動的代理聊天。 + +1. 運行 `/connect` 命令並選擇 GitLab。 + + ```txt + /connect + ``` + +2. 選擇您的身份驗證方法: + + ```txt + ┌ Select auth method + │ + │ OAuth (Recommended) + │ Personal Access Token + └ + ``` + + #### 使用 OAuth(推薦) + + 選擇**OAuth**,您的瀏覽器將打開以進行授權。 + + #### 使用個人訪問令牌 + 1. 前往[GitLab 用戶設置 > 訪問令牌](https://gitlab.com/-/user_settings/personal_access_tokens) + 2. 單擊**添加新令牌** + 3. 名稱:`OpenCode`,範圍:`api` + 4. 複製令牌(以`glpat-`開頭) + 5. 在終端中輸入 + +3. 運行 `/models` 命令以查看可用模型。 + + ```txt + /models + ``` + + 提供三種基於 Claude 的模型: + - **duo-chat-haiku-4-5**(默認)- 快速任務的快速響應 + - **duo-chat-sonnet-4-5** - 大多數工作流程的平衡性能 + - **duo-chat-opus-4-5** - 最有能力進行複雜分析 + +:::note +如果您不想,也可以指定“GITLAB_TOKEN”環境變量 +將令牌存儲在 opencode auth 存儲中。 +::: + +##### 自託管 GitLab + +:::note[compliance 筆記] +OpenCode 使用小型模型來執行某些 AI 任務,例如生成會話標題。 +默認情況下,它配置為使用 gpt-5-nano,由 Zen 託管。鎖定 OpenCode +要僅使用您自己的 GitLab 託管實例,請將以下內容添加到您的 +`opencode.json` 文件。還建議禁用會話共享。 + +```json +{ + "$schema": "https://opencode.ai/config.json", + "small_model": "gitlab/duo-chat-haiku-4-5", + "share": "disabled" +} +``` + +::: + +對於自託管的 GitLab 實例: + +```bash +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_TOKEN=glpat-... +``` + +如果您的實例運行自定義 AI 網關: + +```bash +GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +``` + +或者添加到您的 bash 配置文件中: + +```bash title="~/.bash_profile" +export GITLAB_INSTANCE_URL=https://gitlab.company.com +export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com +export GITLAB_TOKEN=glpat-... +``` + +:::note +您的 GitLab 管理員必須啟用以下功能: + +1. [雙代理平台](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) 用於用戶、組或實例 +2. 功能標誌(通過 Rails 控制台): + - `agent_platform_claude_code` + - `third_party_agents_enabled` + ::: + +##### 適用於自託管實例的 OAuth + +為了使 Oauth 適用於您的自託管實例,您需要創建 +一個新的應用程序(設置→應用程序) +回調 URL `http://127.0.0.1:8080/callback` 和以下範圍: + +- api(代表您訪問API) +- read_user(讀取您的個人信息) +- read_repository(允許對存儲庫進行只讀訪問) + +然後將應用程序 ID 公開為環境變量: + +```bash +export GITLAB_OAUTH_CLIENT_ID=your_application_id_here +``` + +更多文檔請參見 [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth) 主頁。 + +##### 配置 + +通過`opencode.json`定制: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "gitlab": { + "options": { + "instanceUrl": "https://gitlab.com", + "featureFlags": { + "duo_agent_platform_agentic_chat": true, + "duo_agent_platform": true + } + } + } + } +} +``` + +##### GitLab API 工具(可選,但強烈推薦) + +要訪問 GitLab 工具(合併請求、問題、管道、CI/CD 等): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@gitlab/opencode-gitlab-plugin"] +} +``` + +該插件提供全面的 GitLab 存儲庫管理功能,包括 MR 審查、問題跟踪、管道監控等。 + +--- + +### GitHub 副駕駛 + +要將 GitHub Copilot 訂閱與 opencode 結合使用: + +:::note +某些型號可能需要 [Pro+ +訂閱](https://github.com/features/copilot/plans) 來使用。 + +某些模型需要在您的[GitHub Copilot 設置](https://docs.github.com/en/copilot/how-tos/use-ai-models/configure-access-to-ai-models#setup-for-individual-use) 中手動啟用。 +::: + +1. 運行 `/connect` 命令並蒐索 GitHub Copilot。 + + ```txt + /connect + ``` + +2. 導航至[github.com/login/device](https://github.com/login/device) 並輸入代碼。 + + ```txt + ┌ Login with GitHub Copilot + │ + │ https://github.com/login/device + │ + │ Enter code: 8F43-6FCF + │ + └ Waiting for authorization... + ``` + +3. 現在運行`/models`命令來選擇您想要的型號。 + + ```txt + /models + ``` + +--- + +### 谷歌頂點人工智能 + +要將 Google Vertex AI 與 OpenCode 結合使用: + +1. 前往 Google Cloud Console 中的 **Model Garden** 並檢查 + 您所在地區提供的型號。 + + :::note + 您需要有一個啟用了 Vertex AI API 的 Google Cloud 項目。 + ::: + +2. 設置所需的環境變量: + - `GOOGLE_CLOUD_PROJECT`:您的 Google Cloud 項目 ID + - `VERTEX_LOCATION`(可選):Vertex AI 的區域(默認為`global`) + - 身份驗證(選擇一項): + - `GOOGLE_APPLICATION_CREDENTIALS`: Path to your service account JSON key file + - Authenticate using gcloud CLI: `gcloud auth application-default login` + + 在運行 opencode 時設置它們。 + + ```bash + GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode + ``` + + 或者將它們添加到您的 bash 配置文件中。 + + ```bash title="~/.bash_profile" + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json + export GOOGLE_CLOUD_PROJECT=your-project-id + export VERTEX_LOCATION=global + ``` + +:::tip +`global` 區域無需額外成本即可提高可用性並減少錯誤。使用區域端點(例如`us-central1`)來滿足數據駐留要求。 [了解更多](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#regional_and_global_endpoints) +::: + +3. 運行`/models`命令選擇所需的型號。 + + ```txt + /models + ``` + +--- + +### 格羅克 + +1. 前往[格羅克控制台](https://console.groq.com/),單擊“**創建 API 密鑰**”,然後復制密鑰。 + +2. 運行`/connect`命令並蒐索Groq。 + + ```txt + /connect + ``` + +3. 輸入提供商的 API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇您想要的。 + + ```txt + /models + ``` + +--- + +### 抱臉 + +[Error 500 (Server Error)!!1500.That’s an error.There was an error. Please try again later.That’s all we know.](https://huggingface.co/docs/inference-providers) 提供對超過 17 個提供商支持的開放模型的訪問。 + +1. 前往[擁抱臉部設置](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) 創建一個具有調用推理提供程序權限的令牌。 + +2. 運行 `/connect` 命令並蒐索 **Hugging Face**。 + + ```txt + /connect + ``` + +3. 輸入您的擁抱臉標記。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行 `/models` 命令來選擇模型,如 _Kimi-K2-Instruct_ 或 _GLM-4.6_。 + + ```txt + /models + ``` + +--- + +### 螺旋錐 + +[螺旋錐](https://helicone.ai) 是一個 LLM 可觀察性平台,可為您的 AI 應用程序提供日誌記錄、監控和分析。 Helicone AI Gateway 根據模型自動將您的請求路由到適當的提供商。 + +1. 前往[螺旋錐](https://helicone.ai),創建一個帳戶,並從您的儀表板生成 API 密鑰。 + +2. 運行 `/connect` 命令並蒐索 **Helicone**。 + + ```txt + /connect + ``` + +3. 輸入您的 Helicone API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 執行`/models`命令選擇型號。 + + ```txt + /models + ``` + +有關更多提供程序和高級功能(例如緩存和速率限制),請查看[螺旋錐文檔](https://docs.helicone.ai)。 + +#### 可選配置 + +如果您發現 Helicone 的功能或模型未通過開放代碼自動配置,您始終可以自行配置。 + +這是[Helicone 的模型目錄](https://helicone.ai/models),您將需要它來獲取要添加的模型的 ID。 + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + }, + "models": { + "gpt-4o": { + // Model ID (from Helicone's model directory page) + "name": "GPT-4o", // Your own custom name for the model + }, + "claude-sonnet-4-20250514": { + "name": "Claude Sonnet 4", + }, + }, + }, + }, +} +``` + +#### 自定義標頭 + +Helicone 支持緩存、用戶跟踪和會話管理等功能的自定義標頭。使用 `options.headers` 將它們添加到您的提供程序配置中: + +```jsonc title="~/.config/opencode/opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "helicone": { + "npm": "@ai-sdk/openai-compatible", + "name": "Helicone", + "options": { + "baseURL": "https://ai-gateway.helicone.ai", + "headers": { + "Helicone-Cache-Enabled": "true", + "Helicone-User-Id": "opencode", + }, + }, + }, + }, +} +``` + +##### 會話跟踪 + +Helicone 的 [會議](https://docs.helicone.ai/features/sessions) 功能可讓您將相關的 LLM 請求分組在一起。使用 [opencode-helicone-會話](https://github.com/H2Shami/opencode-helicone-session) 插件自動將每個 OpenCode 對話記錄為 Helicone 中的會話。 + +```bash +npm install -g opencode-helicone-session +``` + +將其添加到您的配置中。 + +```json title="opencode.json" +{ + "plugin": ["opencode-helicone-session"] +} +``` + +該插件將 `Helicone-Session-Id` 和 `Helicone-Session-Name` 標頭注入您的請求中。在 Helicone 的會話頁面中,您將看到每個 OpenCode 對話都列為單獨的會話。 + +##### 常見 Helicone 接頭 + +|標題 |描述 | +| -------------------------- | ------------------------------------------------------------- | +| `Helicone-Cache-Enabled` |啟用響應緩存 (`true`/`false`) | +| `Helicone-User-Id` |按用戶跟踪指標 | +| `Helicone-Property-[Name]` |添加自定義屬性(例如`Helicone-Property-Environment`)| +| `Helicone-Prompt-Id` |將請求與提示版本相關聯 | + +有關所有可用標頭,請參閱[Helicone 頭目錄](https://docs.helicone.ai/helicone-headers/header-directory)。 + +--- + +### 調用.cpp + +您可以通過[駱駝.cpp 的](https://github.com/ggml-org/llama.cpp) llama-server實用程序配置opencode以使用本地模型 + +```json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llama-server (local)", + "options": { + "baseURL": "http://127.0.0.1:8080/v1" + }, + "models": { + "qwen3-coder:a3b": { + "name": "Qwen3-Coder: a3b-30b (local)", + "limit": { + "context": 128000, + "output": 65536 + } + } + } + } + } +} +``` + +在這個例子中: + +- `llama.cpp` 是自定義提供商 ID。這可以是您想要的任何字符串。 +- `npm` 指定用於此提供程序的包。這裡,`@ai-sdk/openai-compatible` 用於任何 OpenAI 兼容的 API。 +- `name` 是 UI 中提供程序的顯示名稱。 +- `options.baseURL` 是本地服務器的端點。 +- `models` 是模型 ID 與其配置的映射。型號名稱將顯示在型號選擇列表中。 + +--- + +### IO網絡 + +IO.NET 提供了 17 種針對各種用例進行優化的模型: + +1. 前往[IO.NET控制台](https://ai.io.net/),創建一個帳戶並生成一個 API 密鑰。 + +2. 運行`/connect`命令並蒐索**IO.NET**。 + + ```txt + /connect + ``` + +3. 輸入您的 IO.NET API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 執行`/models`命令選擇型號。 + + ```txt + /models + ``` + +--- + +### LM工作室 + +您可以通過 LM Studio 配置 opencode 以使用本地模型。 + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +在這個例子中: + +- `lmstudio` 是自定義提供商 ID。這可以是您想要的任何字符串。 +- `npm` 指定用於此提供程序的包。這裡,`@ai-sdk/openai-compatible` 用於任何 OpenAI 兼容的 API。 +- `name` 是 UI 中提供程序的顯示名稱。 +- `options.baseURL` 是本地服務器的端點。 +- `models` 是模型 ID 與其配置的映射。型號名稱將顯示在型號選擇列表中。 + +--- + +### 登月人工智能 + +要使用 Moonshot AI 中的 Kimi K2: + +1. 前往[Moonshot 人工智能控制台](https://platform.moonshot.ai/console),創建一個帳戶,然後單擊“**創建 API 密鑰**”。 + +2. 運行 `/connect` 命令並蒐索 **Moonshot AI**。 + + ```txt + /connect + ``` + +3. 輸入您的 Moonshot API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇_Kimi K2_。 + + ```txt + /models + ``` + +--- + +### 最小最大 + +1. 前往[MiniMax API 控制台](https://platform.minimax.io/login),創建一個帳戶並生成一個 API 密鑰。 + +2. 運行 `/connect` 命令並蒐索 **MiniMax**。 + + ```txt + /connect + ``` + +3. 輸入您的 MiniMax API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇型號,如_M2.1_。 + + ```txt + /models + ``` + +--- + +### Nebius 代幣工廠 + +1. 前往[Nebius 令牌工廠控制台](https://tokenfactory.nebius.com/),創建一個帳戶,然後單擊“**添加密鑰**”。 + +2. 運行`/connect`命令並蒐索**Nebius令牌工廠**。 + + ```txt + /connect + ``` + +3. 輸入您的 Nebius 令牌工廠 API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇一個模型,如_Kimi K2 Instruct_。 + + ```txt + /models + ``` + +--- + +### 成為 + +您可以通過 Ollama 配置 opencode 以使用本地模型。 + +:::tip +Ollama 可以自動為 OpenCode 配置自身。詳情請參閱[Ollama 集成文檔](https://docs.ollama.com/integrations/opencode)。 +::: + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +在這個例子中: + +- `ollama` 是自定義提供商 ID。這可以是您想要的任何字符串。 +- `npm` 指定用於此提供程序的包。這裡,`@ai-sdk/openai-compatible` 用於任何 OpenAI 兼容的 API。 +- `name` 是 UI 中提供程序的顯示名稱。 +- `options.baseURL` 是本地服務器的端點。 +- `models` 是模型 ID 與其配置的映射。型號名稱將顯示在型號選擇列表中。 + +:::tip +如果工具調用不起作用,請嘗試增加 Ollama 中的`num_ctx`。從 16k - 32k 左右開始。 +::: + +--- + +### 奧拉馬雲 + +要將 Ollama Cloud 與 OpenCode 結合使用: + +1. 前往[https://llama.com/](https://ollama.com/) 並登錄或創建帳戶。 + +2. 導航到 **設置** > **密鑰**,然後單擊 **添加 API 密鑰** 以生成新的 API 密鑰。 + +3. 複製 API 密鑰以在 OpenCode 中使用。 + +4. 運行 `/connect` 命令並蒐索 **Ollama Cloud**。 + + ```txt + /connect + ``` + +5. 輸入您的 Ollama Cloud API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +6. **重要**:在OpenCode中使用雲模型之前,必須將模型信息拉取到本地: + + ```bash + ollama pull gpt-oss:20b-cloud + ``` + +7. 運行 `/models` 命令以選擇您的 Ollama Cloud 型號。 + + ```txt + /models + ``` + +--- + +### 開放人工智能 + +我們建議註冊[ChatGPT Plus 或 Pro](https://chatgpt.com/pricing)。 + +1. 註冊後,運行 `/connect` 命令並選擇 OpenAI。 + + ```txt + /connect + ``` + +2. 在這裡您可以選擇 **ChatGPT Plus/Pro** 選項,它將打開您的瀏覽器 + 並要求您進行身份驗證。 + + ```txt + ┌ Select auth method + │ + │ ChatGPT Plus/Pro + │ Manually enter API Key + └ + ``` + +3. 現在,當您使用 `/models` 命令時,所有 OpenAI 模型都應該可用。 + + ```txt + /models + ``` + +##### 使用 API 密鑰 + +如果您已有 API 密鑰,可以選擇 **手動輸入 API 密鑰** 並將其粘貼到您的終端中。 + +--- + +### 開放代碼禪 + +OpenCode Zen 是 OpenCode 團隊提供的經過測試和驗證的模型列表。 [了解更多](/docs/zen)。 + +1. 登錄 **OpenCode Zen** 並單擊 **創建 API 密鑰**。 + +2. 運行 `/connect` 命令並蒐索 **OpenCode Zen**。 + + ```txt + /connect + ``` + +3. 輸入您的 OpenCode API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇型號,如_Qwen 3 Coder 480B_。 + + ```txt + /models + ``` + +--- + +### 開放路由器 + +1. 前往[OpenRouter儀表板](https://openrouter.ai/settings/keys),單擊“**創建 API 密鑰**”,然後復制密鑰。 + +2. 運行`/connect`命令並蒐索OpenRouter。 + + ```txt + /connect + ``` + +3. 輸入提供商的 API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. OpenRouter默認預加載了多種型號,運行`/models`命令選擇您想要的型號。 + + ```txt + /models + ``` + + 您還可以通過 opencode 配置添加其他模型。 + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. 您還可以通過 opencode 配置自定義它們。這是指定提供商的示例 + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### SAP人工智能核心 + +SAP AI Core 通過統一平台提供對 OpenAI、Anthropic、Google、Amazon、Meta、Mistral 和 AI21 的 40 多個模型的訪問。 + +1. 轉到[SAP BTP 駕駛艙](https://account.hana.ondemand.com/),導航到 SAP AI Core 服務實例,然後創建服務密鑰。 + + :::tip + 服務密鑰是一個包含`clientid`、`clientsecret`、`url` 和`serviceurls.AI_API_URL` 的JSON 對象。您可以在 BTP Cockpit 的 **服務** > **實例和訂閱** 下找到您的 AI Core 實例。 + ::: + +2. 運行 `/connect` 命令並蒐索 **SAP AI Core**。 + + ```txt + /connect + ``` + +3. 輸入您的服務密鑰 JSON。 + + ```txt + ┌ Service key + │ + │ + └ enter + ``` + + 或者設置`AICORE_SERVICE_KEY`環境變量: + + ```bash + AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode + ``` + + 或者將其添加到您的 bash 配置文件中: + + ```bash title="~/.bash_profile" + export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' + ``` + +4. (可選)設置部署 ID 和資源組: + + ```bash + AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode + ``` + + :::note + 這些設置是可選的,應根據您的 SAP AI Core 設置進行配置。 + ::: + +5. 運行 `/models` 命令從 40 多個可用型號中進行選擇。 + + ```txt + /models + ``` + +--- + +### OVHcloud AI 端點 + +1. 前往[OVH雲面板](https://ovh.com/manager)。導航到 `Public Cloud` 部分,`AI & Machine Learning` > `AI Endpoints`,然後在 `API Keys` 選項卡中單擊 **創建新的 API 密鑰**。 + +2. 運行 `/connect` 命令並蒐索 **OVHcloud AI Endpoints**。 + + ```txt + /connect + ``` + +3. 輸入您的 OVHcloud AI Endpoints API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇型號,如_gpt-oss-120b_。 + + ```txt + /models + ``` + +--- + +### 斯卡威 + +要將 [Scaleway 生成 API](https://www.scaleway.com/en/docs/generative-apis/) 與 Opencode 一起使用: + +1. 前往[Scaleway 控制台 IAM 設置](https://console.scaleway.com/iam/api-keys) 生成新的 API 密鑰。 + +2. 運行 `/connect` 命令並蒐索 **Scaleway**。 + + ```txt + /connect + ``` + +3. 輸入您的 Scaleway API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇模型,如_devstral-2-123b-instruct-2512_或_gpt-oss-120b_。 + + ```txt + /models + ``` + +--- + +### 一起人工智能 + +1. 前往[一起AI控制台](https://api.together.ai),創建一個帳戶,然後單擊“**添加密鑰**”。 + +2. 運行 `/connect` 命令並蒐索 **Together AI**。 + + ```txt + /connect + ``` + +3. 輸入您的 Together AI API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇一個模型,如_Kimi K2 Instruct_。 + + ```txt + /models + ``` + +--- + +### 威尼斯人工智能 + +1. 前往[威尼斯人工智能控制台](https://venice.ai),創建一個帳戶並生成一個 API 密鑰。 + +2. 運行`/connect`命令並蒐索**Venice AI**。 + + ```txt + /connect + ``` + +3. 輸入您的 Venice AI API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇型號,如_Llama 3.3 70B_。 + + ```txt + /models + ``` + +--- + +### Vercel人工智能網關 + +Vercel AI Gateway 可讓您通過統一端點訪問來自 OpenAI、Anthropic、Google、xAI 等的模型。型號按標價提供,不加價。 + +1. 前往[維塞爾儀表板](https://vercel.com/),導航至 **AI Gateway** 選項卡,然後單擊 **API 密鑰** 以創建新的 API 密鑰。 + +2. 運行 `/connect` 命令並蒐索 **Vercel AI Gateway**。 + + ```txt + /connect + ``` + +3. 輸入您的 Vercel AI Gateway API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 執行`/models`命令選擇型號。 + + ```txt + /models + ``` + +您還可以通過 opencode 配置自定義模型。以下是指定提供者路由順序的示例。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "vercel": { + "models": { + "anthropic/claude-sonnet-4": { + "options": { + "order": ["anthropic", "vertex"] + } + } + } + } + } +} +``` + +一些有用的路由選項: + +|選項 |描述 | +| ------------------- | ---------------------------------------------------- | +| `order` |提供者嘗試順序| +| `only` |限制特定提供商 | +| `zeroDataRetention` |僅使用零數據保留政策的提供商 | + +--- + +### 人工智慧 + +1. 前往[xAI控制台](https://console.x.ai/),創建一個帳戶並生成一個 API 密鑰。 + +2. 運行`/connect`命令並蒐索**xAI**。 + + ```txt + /connect + ``` + +3. 輸入您的 xAI API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇一個模型,如_Grok Beta_。 + + ```txt + /models + ``` + +--- + +### 扎艾 + +1. 前往[Z.AI API控制台](https://z.ai/manage-apikey/apikey-list),創建一個帳戶,然後單擊“**創建新的 API 密鑰**”。 + +2. 運行`/connect`命令並蒐索**Z.AI**。 + + ```txt + /connect + ``` + + 如果您訂閱了 **GLM 編碼計劃**,請選擇 **Z.AI 編碼計劃**。 + +3. 輸入您的 Z.AI API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 運行`/models`命令選擇_GLM-4.7_等模型。 + + ```txt + /models + ``` + +--- + +### 多路復用器 + +1. 前往[ZenMux 儀表板](https://zenmux.ai/settings/keys),單擊“**創建 API 密鑰**”,然後復制密鑰。 + +2. 運行`/connect`命令並蒐索ZenMux。 + + ```txt + /connect + ``` + +3. 輸入提供商的 API 密鑰。 + + ```txt + ┌ API key + │ + │ + └ enter + ``` + +4. 默認情況下預加載了許多 ZenMux 模型,運行 `/models` 命令選擇您想要的模型。 + + ```txt + /models + ``` + + 您還可以通過 opencode 配置添加其他模型。 + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "zenmux": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +--- + +## 定制提供商 + +要添加 `/connect` 命令中未列出的任何 **OpenAI 兼容** 提供程序: + +:::tip +您可以將任何與 OpenAI 兼容的提供程序與 opencode 結合使用。大多數現代人工智能提供商都提供與 OpenAI 兼容的 API。 +::: + +1. 運行 `/connect` 命令並向下滾動到 **其他**。 + + ```bash + $ /connect + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. 輸入提供商的唯一 ID。 + + ```bash + $ /connect + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note + 選擇一個容易記住的 ID,您將在配置文件中使用它。 + ::: + +3. 輸入提供商的 API 密鑰。 + + ```bash + $ /connect + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. 在項目目錄中創建或更新 `opencode.json` 文件: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + 以下是配置選項: + - **npm**:要使用的 AI SDK 包,`@ai-sdk/openai-compatible` 用於 OpenAI 兼容提供商 + - **名稱**:UI 中的顯示名稱。 + - **型號**:可用型號。 + - **options.baseURL**:API 端點 URL。 + - **options.apiKey**:如果不使用身份驗證,可以選擇設置 API 密鑰。 + - **options.headers**:可選擇設置自定義標頭。 + + 有關高級選項的更多信息,請參見下面的示例。 + +5. 運行 `/models` 命令,您的自定義提供程序和模型將出現在選擇列表中。 + +--- + +##### 例子 + +以下是設置`apiKey`、`headers` 和模型`limit` 選項的示例。 + +```json title="opencode.json" {9,11,17-20} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name", + "limit": { + "context": 200000, + "output": 65536 + } + } + } + } + } +} +``` + +配置詳情: + +- **apiKey**:使用`env`變量語法[了解更多](/docs/config#env-vars)設置。 +- ** headers **:隨每個請求發送的自定義標頭。 +- **limit.context**:模型接受的最大輸入標記。 +- **limit.output**:模型可以生成的最大令牌。 + +`limit` 字段允許 OpenCode 了解您還剩下多少上下文。標準提供商會自動從 models.dev 中提取這些內容。 + +--- + +## 故障排除 + +如果您在配置提供商時遇到問題,請檢查以下內容: + +1. **檢查身份驗證設置**:運行 `opencode auth list` 以查看憑據是否 + 提供商的配置已添加到您的配置中。 + + 這不適用於 Amazon Bedrock 等依賴環境變量進行身份驗證的提供商。 + +2. 對於自定義提供程序,請檢查 opencode 配置並: + - 確保 `/connect` 命令中使用的提供程序 ID 與 opencode 配置中的 ID 匹配。 + - 正確的 npm 包用於提供程序。例如,對 Cerebras 使用 `@ai-sdk/cerebras`。對於所有其他 OpenAI 兼容提供商,請使用 `@ai-sdk/openai-compatible`。 + - 檢查 `options.baseURL` 字段中使用了正確的 API 端點。 diff --git a/packages/web/src/content/docs/zh-tw/rules.mdx b/packages/web/src/content/docs/zh-tw/rules.mdx new file mode 100644 index 000000000..8dfa662fe --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/rules.mdx @@ -0,0 +1,180 @@ +--- +title: 規則 +description: 設置開放代碼的自定義指令。 +--- + +您可以通過創建 `AGENTS.md` 文件來提供 opencode 的自定義指令。這和Cursor的規則類似。它包含將包含在 LLM 上下文中的說明,以便為您的特定項目自定義其行為。 + +--- + +## 初始化 + +要創建新的`AGENTS.md`文件,您可以在opencode中運行`/init`命令。 + +:::tip +您應該將項目的 `AGENTS.md` 文件提交到 Git。 +::: + +這將掃描您的項目及其所有內容,以了解該項目的內容並生成一個 `AGENTS.md` 文件。這有助於 opencode 更好地導航項目。 + +如果您有現有的 `AGENTS.md` 文件,這將嘗試添加到其中。 + +--- + +## 例子 + +您也可以手動創建此文件。以下是您可以放入 `AGENTS.md` 文件中的一些內容的示例。 + +```markdown title="AGENTS.md" +# SST v3 Monorepo Project + +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` +``` + +我們在此處添加特定於項目的說明,這將在您的團隊中共享。 + +--- + +## 類型 + +opencode 還支持從多個位置讀取 `AGENTS.md` 文件。這有不同的目的。 + +### 專案 + +將 `AGENTS.md` 放置在項目根目錄中以獲取特定於項目的規則。這些僅適用於您在此目錄或其子目錄中工作時。 + +### 全球的 + +您還可以在 `~/.config/opencode/AGENTS.md` 文件中包含全局規則。這適用於所有開放代碼會話。 + +由於這未提交給 Git 或與您的團隊共享,因此我們建議使用它來指定 LLM 應遵循的任何個人規則。 + +### 克勞德代碼兼容性 + +對於從 Claude Code 遷移的用戶,OpenCode 支持 Claude Code 的文件約定作為後備: + +- **項目規則**:項目目錄中的`CLAUDE.md`(如果`AGENTS.md`不存在則使用) +- **全局規則**:`~/.claude/CLAUDE.md`(如果不存在`~/.config/opencode/AGENTS.md`則使用) +- **技能**:`~/.claude/skills/` — 詳情請參閱[代理技巧](/docs/skills/) + +要禁用 Claude Code 兼容性,請設置以下環境變量之一: + +```bash +export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills +``` + +--- + +## 優先級 + +當 opencode 啟動時,它會按以下順序查找規則文件: + +1. **本地文件**,從當前目錄向上遍歷(`AGENTS.md`,`CLAUDE.md`) +2. **全局文件** `~/.config/opencode/AGENTS.md` +3. **克勞德代碼文件**位於`~/.claude/CLAUDE.md`(除非禁用) + +第一個匹配的文件在每個類別中獲勝。例如,如果您同時擁有`AGENTS.md` 和`CLAUDE.md`,則僅使用`AGENTS.md`。同樣,`~/.config/opencode/AGENTS.md` 優先於`~/.claude/CLAUDE.md`。 + +--- + +## 定制說明 + +您可以在 `opencode.json` 或全局 `~/.config/opencode/opencode.json` 中指定自定義指令文件。這允許您和您的團隊重用現有規則,而不必將它們複製到 AGENTS.md。 + +例子: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +您還可以使用遠程 URL 從 Web 加載說明。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"] +} +``` + +遠程指令的獲取有 5 秒的超時時間。 + +所有說明文件均與您的`AGENTS.md` 文件合併。 + +--- + +## 引用外部文件 + +雖然 opencode 不會自動解析 `AGENTS.md` 中的文件引用,但您可以通過兩種方式實現類似的功能: + +### 使用 opencode.json + +推薦的方法是在`opencode.json`中使用`instructions`字段: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### AGENTS.md 中的手動說明 + +您可以通過在 `AGENTS.md` 中提供明確的指令來教 opencode 讀取外部文件。這是一個實際的例子: + +```markdown title="AGENTS.md" +# TypeScript Project Rules + +## External File Loading + +CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. + +Instructions: + +- Do NOT preemptively load all references - use lazy loading based on actual need +- When loaded, treat content as mandatory instructions that override defaults +- Follow references recursively when needed + +## Development Guidelines + +For TypeScript code style and best practices: @docs/typescript-guidelines.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For testing strategies and coverage requirements: @test/testing-guidelines.md + +## General Guidelines + +Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. +``` + +這種方法允許您: + +- 創建模塊化、可重用的規則文件 +- 通過符號鏈接或 git 子模塊在項目之間共享規則 +- 保持 AGENTS.md 簡潔,同時參考詳細指南 +- 確保 opencode 僅在特定任務需要時加載文件 + +:::tip +對於 monorepos 或具有共享標準的項目,使用 `opencode.json` 和 glob 模式(如 `packages/*/AGENTS.md`)比手動指令更易於維護。 +::: diff --git a/packages/web/src/content/docs/zh-tw/sdk.mdx b/packages/web/src/content/docs/zh-tw/sdk.mdx new file mode 100644 index 000000000..89be68cad --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/sdk.mdx @@ -0,0 +1,391 @@ +--- +title: 軟件開發工具包 +description: Opencode 服務器的類型安全 JS 客戶端。 +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +opencode JS/TS SDK 提供類型安全的客戶端用於與服務器交互。 +使用它以編程方式構建集成和控制開放代碼。 + +[了解更多](/docs/server) 關於服務器如何工作。例如,查看社區構建的[專案](/docs/ecosystem#projects)。 + +--- + +## 安裝 + +從 npm 安裝 SDK: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## 創建客戶端 + +創建 opencode 的實例: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const { client } = await createOpencode() +``` + +這會同時啟動服務器和客戶端 + +#### 選項 + +|選項 |類型 |描述 |默認 | +| ---------- | ------------- | ------------------------------ | ----------- | +| `hostname` | `string` |服務器主機名 | `127.0.0.1` | +| `port` | `number` |服務器端口 | `4096` | +| `signal` | `AbortSignal` |取消的中止信號 | `undefined` | +| `timeout` | `number` |服務器啟動超時(以毫秒為單位)| `5000` | +| `config` | `Config` |配置對象| `{}` | + +--- + +## 配置 + +您可以傳遞配置對象來自定義行為。該實例仍然會選擇您的`opencode.json`,但您可以覆蓋或添加內聯配置: + +```javascript +import { createOpencode } from "@opencode-ai/sdk" + +const opencode = await createOpencode({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${opencode.server.url}`) + +opencode.server.close() +``` + +## 僅限客戶 + +如果您已經有一個正在運行的 opencode 實例,您可以創建一個客戶端實例來連接到它: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", +}) +``` + +#### 選項 + +|選項 |類型 |描述 |默認| +| --------------- | ---------- | -------------------------------- | ----------------------- | +| `baseUrl` | `string` |服務器的 URL | `http://localhost:4096` | +| `fetch` | `function` |自定義獲取實現 | `globalThis.fetch` | +| `parseAs` | `string` |響應解析方法 | `auto` | +| `responseStyle` | `string` |返回樣式:`data` 或 `fields` | `fields` | +| `throwOnError` | `boolean` |拋出錯誤而不是返回 | `false` | + +--- + +## 類型 + +SDK 包含所有 API 類型的 TypeScript 定義。直接導入它們: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +所有類型均根據服務器的 OpenAPI 規範生成,並可在 types 文件中找到。 + +--- + +## 錯誤 + +SDK 可能會拋出錯誤,您可以捕獲並處理這些錯誤: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## 蜜蜂 + +SDK 通過類型安全的客戶端公開所有服務器 API。 + +--- + +### 全球的 + +|方法|描述 |回應 | +| ----------------- | ------------------------------- | ------------------------------------ | +| `global.health()` |檢查服務器健康狀況和版本 | `{ healthy: true, version: string }` | + +--- + +#### 示例 + +```javascript +const health = await client.global.health() +console.log(health.data.version) +``` + +--- + +### 應用程式 + +|方法|描述 |回應 | +| -------------- | ------------------------- | ------------------------------------------- | +| `app.log()` |寫入日誌條目 | `boolean` | +| `app.agents()` |列出所有可用的代理 | 代理[] | + +--- + +#### 示例 + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### 專案 + +|方法|描述 |回應 | +| ------------------- | ------------------- | --------------------------------------------- | +| `project.list()` |列出所有項目 | 項目[] | +| `project.current()` |獲取當前項目 | 項目 | + +--- + +#### 示例 + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### 小路 + +|方法|描述 |回應 | +| ------------ | ---------------- | ---------------------------------------- | +| `path.get()` |獲取當前路徑 | 路徑 | + +--- + +#### 示例 + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### 配置 + +|方法|描述 |回應 | +| -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` |獲取配置信息 | 配置 | +| `config.providers()` |列出提供商和默認模型 | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +#### 示例 + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### 會議 + +|方法|描述 |筆記| +| ---------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `session.list()` |列出會話 |返回 Session[] | +| `session.get({ path })` |獲取會話 |返回 Session | +| `session.children({ path })` |列出子會話 |返回 Session[] | +| `session.create({ body })` |創建會話 |返回 Session | +| `session.delete({ path })` |刪除會話 |返回 `boolean` | +| `session.update({ path, body })` |更新會話屬性 |返回 Session | +| `session.init({ path, body })` |分析應用程序並創建`AGENTS.md` |返回 `boolean` | +| `session.abort({ path })` |中止正在運行的會話 |返回 `boolean` | +| `session.share({ path })` |分享會 |返回 Session | +| `session.unshare({ path })` |取消共享會話 |返回 Session | +| `session.summarize({ path, body })` |會議總結 |返回 `boolean` | +| `session.messages({ path })` |列出會話中的消息 |返回 `{ info: `消息`, parts: `Part[]`}[]` | +| `session.message({ path })` |獲取消息詳情 |返回 `{ info: `消息`, parts: `Part[]`}` | +| `session.prompt({ path, body })` |發送提示信息 | `body.noReply: true` 返回 UserMessage(僅上下文)。默認返回帶有 AI 響應的 AssistantMessage | +| `session.command({ path, body })` |向會話發送命令 |返回 `{ info: `AssistantMessage`, parts: `Part[]`}` | +| `session.shell({ path, body })` |運行 shell 命令 |返回 AssistantMessage | +| `session.revert({ path, body })` |回复消息 |返回 Session | +| `session.unrevert({ path })` |恢復已恢復的消息 |返回 Session | +| `postSessionByIdPermissionsByPermissionId({ path, body })` |回復權限請求 |返回 `boolean` | + +--- + +#### 示例 + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) + +// Inject context without triggering AI response (useful for plugins) +await client.session.prompt({ + path: { id: session.id }, + body: { + noReply: true, + parts: [{ type: "text", text: "You are a helpful assistant." }], + }, +}) +``` + +--- + +### 文件 + +|方法|描述 |回應 | +| ------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `find.text({ query })` |搜索文件中的文本 |具有 `path`、`lines`、`line_number`、`absolute_offset`、`submatches` | 的匹配對像數組 | +| `find.files({ query })` |按名稱查找文件和目錄 | `string[]`(路徑)| +| `find.symbols({ query })` |查找工作區符號 | 符號[] | +| `file.read({ query })` |讀取文件 | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` |獲取跟踪文件的狀態 | 文件[] | + +`find.files` 支持一些可選的查詢字段: + +- `type`:`"file"`或`"directory"` +- `directory`:覆蓋搜索的項目根目錄 +- `limit`:最大結果 (1–200) + +--- + +#### 示例 + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts", type: "file" }, +}) + +const directories = await client.find.files({ + query: { query: "packages", type: "directory", limit: 20 }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +|方法|描述 |回應 | +| ------------------------------ | ------------------------- | --------- | +| `tui.appendPrompt({ body })` |將文本附加到提示 | `boolean` | +| `tui.openHelp()` |打開幫助對話框 | `boolean` | +| `tui.openSessions()` |打開會話選擇器 | `boolean` | +| `tui.openThemes()` |打開主題選擇器 | `boolean` | +| `tui.openModels()` |打開模型選擇器 | `boolean` | +| `tui.submitPrompt()` |提交當前提示| `boolean` | +| `tui.clearPrompt()` |清除提示| `boolean` | +| `tui.executeCommand({ body })` |執行命令| `boolean` | +| `tui.showToast({ body })` |顯示 toast 通知 | `boolean` | + +--- + +#### 示例 + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### 授權 + +|方法|描述 |回應 | +| ------------------- | ------------------------------ | --------- | +| `auth.set({ ... })` |設置身份驗證憑據 | `boolean` | + +--- + +#### 示例 + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### 活動 + +|方法|描述 |回應 | +| ------------------- | ------------------------- | ------------------------- | +| `event.subscribe()` |服務器發送的事件流 |服務器發送的事件流 | + +--- + +#### 示例 + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/zh-tw/server.mdx b/packages/web/src/content/docs/zh-tw/server.mdx new file mode 100644 index 000000000..161f234cd --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/server.mdx @@ -0,0 +1,287 @@ +--- +title: 伺服器 +description: 通過 HTTP 與 opencode 服務器交互。 +--- + +import config from "../../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +`opencode serve` 命令運行一個無頭 HTTP 服務器,該服務器公開開放代碼客戶端可以使用的 OpenAPI 端點。 + +--- + +### 用法 + +```bash +opencode serve [--port ] [--hostname ] [--cors ] +``` + +#### 選項 + +|旗幟|描述 |默認 | +| --------------- | ----------------------------------- | ---------------- | +| `--port` |監聽端口 | `4096` | +| `--hostname` |監聽的主機名 | `127.0.0.1` | +| `--mdns` |啟用 mDNS 發現 | `false` | +| `--mdns-domain` | mDNS 服務的自定義域名 | `opencode.local` | +| `--cors` |允許的其他瀏覽器來源 | `[]` | + +`--cors` 可以多次傳遞: + +```bash +opencode serve --cors http://localhost:5173 --cors https://app.example.com +``` + +--- + +### 驗證 + +設置`OPENCODE_SERVER_PASSWORD`以使用HTTP基本身份驗證保護服務器。用戶名默認為`opencode`,或設置`OPENCODE_SERVER_USERNAME`來覆蓋它。這適用於`opencode serve` 和`opencode web`。 + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve +``` + +--- + +### 它是如何運作的 + +當您運行 `opencode` 時,它會啟動 TUI 和服務器。 TUI 是哪裡 +與服務器對話的客戶端。服務器公開 OpenAPI 3.1 規範 +端點。該端點還用於生成[軟件開發工具包](/docs/sdk)。 + +:::tip +使用 opencode 服務器以編程方式與 opencode 進行交互。 +::: + +此架構讓 opencode 支持多個客戶端,並允許您以編程方式與 opencode 進行交互。 + +您可以運行 `opencode serve` 來啟動獨立服務器。如果您有 +opencode TUI 運行,`opencode serve` 將啟動一個新服務器。 + +--- + +#### 連接到現有服務器 + +當您啟動 TUI 時,它會隨機分配端口和主機名。您可以改為傳入`--hostname` 和`--port` [旗幟](/docs/cli)。然後使用它連接到其服務器。 + +[`/tui`](#tui) 端點可用於通過服務器驅動 TUI。例如,您可以預填充或運行提示。此設置由 OpenCode [集成開發環境](/docs/ide) 插件使用。 + +--- + +## 規格 + +服務器發布了 OpenAPI 3.1 規範,可以在以下位置查看: + +``` +http://:/doc +``` + +例如,`http://localhost:4096/doc`。使用規範生成客戶端或檢查請求和響應類型。或者在 Swagger 瀏覽器中查看它。 + +--- + +## 蜜蜂 + +opencode 服務器公開以下 API。 + +--- + +### 全球的 + +|方法|路徑|描述 |回應 | +| ------ | ---------------- | ------------------------------ | ------------------------------------ | +| `GET` | `/global/health` |獲取服務器運行狀況和版本 | `{ healthy: true, version: string }` | +| `GET` | `/global/event` |獲取全局事件(SSE 流)|事件流 | + +--- + +### 專案 + +|方法|路徑|描述 |回應 | +| ------ | ------------------ | ----------------------- | --------------------------------------------- | +| `GET` | `/project` |列出所有項目 | 項目[] | +| `GET` | `/project/current` |獲取當前項目 | 項目 | + +--- + +### 路徑和VCS + +|方法|路徑|描述 |回應 | +| ------ | ------- | ------------------------------------ | ------------------------------------------- | +| `GET` | `/path` |獲取當前路徑| 路徑 | +| `GET` | `/vcs` |獲取當前項目的 VCS 信息 | VcsInfo | + +--- + +### 實例 + +|方法|路徑|描述 |回應 | +| ------ | ------------------- | ---------------------------- | --------- | +| `POST` | `/instance/dispose` |處置當前實例 | `boolean` | + +--- + +### 配置 + +|方法|路徑|描述 |回應 | +| ------- | ------------------- | --------------------------------- | ---------------------------------------------------------------------------------------- | +| `GET` | `/config` |獲取配置信息 | 配置 | +| `PATCH` | `/config` |更新配置| 配置 | +| `GET` | `/config/providers` |列出提供商和默認模型 | `{ providers: `提供商[]`, default: { [key: string]: string } }` | + +--- + +### 提供者 + +|方法|路徑|描述 |回應 | +| ------ | -------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------- | +| `GET` | `/provider` |列出所有提供商 | `{ all: `提供商[]`, default: {...}, connected: string[] }` | +| `GET` | `/provider/auth` |獲取提供商身份驗證方法 | `{ [providerID: string]: `ProviderAuthMethod[]` }` | +| `POST` | `/provider/{id}/oauth/authorize` |使用 OAuth 授權提供商 | ProviderAuthAuthorization | +| `POST` | `/provider/{id}/oauth/callback` |處理提供商的 OAuth 回調 | `boolean` | + +--- + +### 會議 + +|方法|路徑|描述 |筆記| +| -------- | ---------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------- | +| `GET` | `/session` |列出所有會話 |返回 Session[] | +| `POST` | `/session` |創建新會話 |正文:`{ parentID?, title? }`,返回 Session | +| `GET` | `/session/status` |獲取所有會話的會話狀態 |返回 `{ [sessionID: string]: `SessionStatus` }` | +| `GET` | `/session/:id` |獲取會話詳細信息 |返回 Session | +| `DELETE` | `/session/:id` |刪除會話及其所有數據 |返回 `boolean` | +| `PATCH` | `/session/:id` |更新會話屬性 |正文:`{ title? }`,返回 Session | +| `GET` | `/session/:id/children` |獲取會話的子會話 |返回 Session[] | +| `GET` | `/session/:id/todo` |獲取會話的待辦事項列表 |返回 Todo[] | +| `POST` | `/session/:id/init` |分析應用程序並創建`AGENTS.md` |主體:`{ messageID, providerID, modelID }`,返回`boolean` | +| `POST` | `/session/:id/fork` |在消息中分叉現有會話 |正文:`{ messageID? }`,返回 Session | +| `POST` | `/session/:id/abort` |中止正在運行的會話 |返回 `boolean` | +| `POST` | `/session/:id/share` |分享會議 |返回 Session | +| `DELETE` | `/session/:id/share` |取消共享會話 |返回 Session | +| `GET` | `/session/:id/diff` |獲取本次會話的差異 |查詢:`messageID?`,返回 FileDiff[] | +| `POST` | `/session/:id/summarize` |會議總結 |主體:`{ providerID, modelID }`,返回`boolean` | +| `POST` | `/session/:id/revert` |回复消息 |主體:`{ messageID, partID? }`,返回`boolean` | +| `POST` | `/session/:id/unrevert` |恢復所有已恢復的消息 |返回 `boolean` | +| `POST` | `/session/:id/permissions/:permissionID` |回復權限請求 |主體:`{ response, remember? }`,返回`boolean` | + +--- + +### 留言 + +|方法|路徑|描述 |筆記| +| ------ | --------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session/:id/message` |列出會話中的消息 |查詢:`limit?`,返回`{ info: `消息`, parts: `Part[]`}[]` | +| `POST` | `/session/:id/message` |發送消息並等待回复 |主體:`{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`,返回`{ info: `消息`, parts: `部分[]`}` | +| `GET` | `/session/:id/message/:messageID` |獲取消息詳情 |返回`{ info: `消息`, parts: `部分[]`}` | +| `POST` | `/session/:id/prompt_async` |異步發送消息(無需等待)| body:與`/session/:id/message`相同,返回`204 No Content` | +| `POST` | `/session/:id/command` |執行斜杠命令|主體:`{ messageID?, agent?, model?, command, arguments }`,返回`{ info: `消息`, parts: `部分[]`}` | +| `POST` | `/session/:id/shell` |運行 shell 命令 |主體:`{ agent, model?, command }`,返回`{ info: `消息`, parts: `部分[]`}` | + +--- + +### 命令 + +|方法|路徑|描述 |回應 | +| ------ | ---------- | ----------------- | --------------------------------------------- | +| `GET` | `/command` |列出所有命令 | 命令[] | + +--- + +### 文件 + +|方法|路徑|描述 |回應 | +| ------ | ------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` |搜索文件中的文本 |具有 `path`、`lines`、`line_number`、`absolute_offset`、`submatches` | 的匹配對像數組 | +| `GET` | `/find/file?query=` |按名稱查找文件和目錄 | `string[]`(路徑)| +| `GET` | `/find/symbol?query=` |查找工作區符號 | 符號[] | +| `GET` | `/file?path=` |列出文件和目錄 | FileNode[] | +| `GET` | `/file/content?path=

` |讀取文件 | FileContent | +| `GET` | `/file/status` |獲取跟踪文件的狀態 | 文件[] | + +#### `/find/file`查詢參數 + +- `query`(必需)- 搜索字符串(模糊匹配) +- `type`(可選)- 將結果限制為`"file"` 或`"directory"` +- `directory` (可選) — 覆蓋搜索的項目根目錄 +- `limit`(可選)— 最大結果 (1–200) +- `dirs`(可選)- 舊標誌(`"false"` 僅返回文件) + +--- + +### 工具(實驗) + +|方法|路徑|描述 |回應 | +| ------ | ------------------------------------------- | ---------------------------------------- | -------------------------------------------- | +| `GET` | `/experimental/tool/ids` |列出所有工具 ID | ToolID | +| `GET` | `/experimental/tool?provider=

&model=` |列出具有模型 JSON 架構的工具 | 工具列表 | + +--- + +### LSP、格式化程序和 MCP + +|方法|路徑|描述 |回應 | +| ------ | ------------ | -------------------------- | -------------------------------------------------------- | +| `GET` | `/lsp` |獲取LSP服務器狀態| LSPStatus[] | +| `GET` | `/formatter` |獲取格式化程序狀態 | FormatterStatus[] | +| `GET` | `/mcp` |獲取 MCP 服務器狀態 | `{ [name: string]: `MCPStatus` }` | +| `POST` | `/mcp` |動態添加MCP服務器| body: `{ name, config }`, 返回 MCP 狀態對象 | + +--- + +### 代理商 + +|方法|路徑|描述 |回應 | +| ------ | -------- | ------------------------- | ------------------------------------------- | +| `GET` | `/agent` |列出所有可用的代理 | 代理[] | + +--- + +### 記錄 + +|方法|路徑|描述 |回應 | +| ------ | ------ | ------------------------------------------------------------ | --------- | +| `POST` | `/log` |寫入日誌條目。正文:`{ service, level, message, extra? }` | `boolean` | + +--- + +### TUI + +|方法|路徑|描述 |回應 | +| ------ | ----------------------- | ------------------------------------------- | ---------------------- | +| `POST` | `/tui/append-prompt` |將文本附加到提示 | `boolean` | +| `POST` | `/tui/open-help` |打開幫助對話框 | `boolean` | +| `POST` | `/tui/open-sessions` |打開會話選擇器 | `boolean` | +| `POST` | `/tui/open-themes` |打開主題選擇器 | `boolean` | +| `POST` | `/tui/open-models` |打開模型選擇器 | `boolean` | +| `POST` | `/tui/submit-prompt` |提交當前提示| `boolean` | +| `POST` | `/tui/clear-prompt` |清除提示| `boolean` | +| `POST` | `/tui/execute-command` |執行命令(`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` |顯示祝酒 (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` |等待下一個控制請求 |控制請求對象| +| `POST` | `/tui/control/response` |響應控制請求 (`{ body }`) | `boolean` | + +--- + +### 授權 + +|方法|路徑|描述 |回應 | +| ------ | ----------- | --------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` |設置身份驗證憑據。正文必須與提供者架構匹配 | `boolean` | + +--- + +### 活動 + +|方法|路徑|描述 |回應 | +| ------ | -------- | ----------------------------------------------------------------------------- | ------------------------- | +| `GET` | `/event` |服務器發送的事件流。第一個活動是`server.connected`,然後是巴士活動 |服務器發送的事件流 | + +--- + +### 文件 + +|方法|路徑|描述 |回應 | +| ------ | ------ | ------------------------- | --------------------------- | +| `GET` | `/doc` | OpenAPI 3.1 規範 |具有 OpenAPI 規範的 HTML 頁面 | diff --git a/packages/web/src/content/docs/zh-tw/share.mdx b/packages/web/src/content/docs/zh-tw/share.mdx new file mode 100644 index 000000000..901b2bcf7 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/share.mdx @@ -0,0 +1,128 @@ +--- +title: 分享 +description: 分享您的 OpenCode 對話。 +--- + +OpenCode 的共享功能允許您創建 OpenCode 對話的公共鏈接,以便您可以與團隊成員協作或從其他人那裡獲得幫助。 + +:::note +任何知道鏈接的人都可以公開訪問共享對話。 +::: + +--- + +## 它是如何運作的 + +當您共享對話時,OpenCode: + +1. 為您的會話創建唯一的公共 URL +2. 將您的對話歷史記錄同步到我們的服務器 +3. 通過可共享鏈接進行對話 — `opncd.ai/s/` + +--- + +## 分享 + +OpenCode 支持三種控制對話共享方式的共享模式: + +--- + +### 手動(默認) + +OpenCode默認使用手動共享模式。會話不會自動共享,但您可以使用 `/share` 命令手動共享它們: + +``` +/share +``` + +這將生成一個唯一的 URL,並將其複製到您的剪貼板。 + +要在 [配置文件](/docs/config) 中顯式設置手動模式: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "manual" +} +``` + +--- + +### 自動分享 + +您可以通過將[配置文件](/docs/config)中的`share`選項設置為`"auto"`來為所有新對話啟用自動共享: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "auto" +} +``` + +啟用自動共享後,每個新對話都會自動共享並生成鏈接。 + +--- + +### 殘疾人 + +您可以通過將[配置文件](/docs/config)中的`share`選項設置為`"disabled"`來完全禁用共享: + +```json title="opencode.json" +{ + "$schema": "https://opncd.ai/config.json", + "share": "disabled" +} +``` + +要在整個團隊中針對給定項目強制執行此操作,請將其添加到項目中的 `opencode.json` 並簽入 Git。 + +--- + +## 取消共享 + +要停止共享對話並將其從公共訪問中刪除: + +``` +/unshare +``` + +這將刪除共享鏈接並刪除與對話相關的數據。 + +--- + +## 隱私 + +分享對話時需要記住一些事項。 + +--- + +### 數據保留 + +共享對話仍然可以訪問,直到您明確取消共享。這 +包括: + +- 完整的對話歷史記錄 +- 所有消息和回复 +- 會話元數據 + +--- + +### 建議 + +- 僅共享不包含敏感信息的對話。 +- 分享之前查看對話內容。 +- 協作完成後取消共享對話。 +- 避免與專有代碼或機密數據共享對話。 +- 對於敏感項目,完全禁用共享。 + +--- + +## 對於企業 + +對於企業部署,共享功能可以是: + +- **出於安全合規性完全禁用** +- **僅限**僅通過 SSO 進行身份驗證的用戶 +- **在您自己的基礎設施上自行託管** + +[了解更多](/docs/enterprise) 關於在您的組織中使用開放代碼。 diff --git a/packages/web/src/content/docs/zh-tw/skills.mdx b/packages/web/src/content/docs/zh-tw/skills.mdx new file mode 100644 index 000000000..c88e75a55 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/skills.mdx @@ -0,0 +1,222 @@ +--- +title: 《代理技巧》 +description: “通過 SKILL.md 定義定義可重用行為” +--- + +代理技能讓 OpenCode 從您的存儲庫或主目錄中發現可重用的指令。 +技能通過本機 `skill` 工具按需加載 - 代理可以查看可用技能並可以在需要時加載完整內容。 + +--- + +## 放置文件 + +每個技能名稱創建一個文件夾,並在其中放入`SKILL.md`。 +OpenCode 搜索這些位置: + +- 項目配置:`.opencode/skills//SKILL.md` +- 全局配置:`~/.config/opencode/skills//SKILL.md` +- 克勞德項目兼容:`.claude/skills//SKILL.md` +- 全球克勞德兼容:`~/.claude/skills//SKILL.md` +- 項目代理兼容:`.agents/skills//SKILL.md` +- 全球代理兼容:`~/.agents/skills//SKILL.md` + +--- + +## 了解發現 + +對於項目本地路徑,OpenCode 將從當前工作目錄開始,直到到達 git 工作樹。 +它加載 `.opencode/` 中任何匹配的 `skills/*/SKILL.md` 以及一路上任何匹配的 `.claude/skills/*/SKILL.md` 或 `.agents/skills/*/SKILL.md`。 + +全局定義也從`~/.config/opencode/skills/*/SKILL.md`、`~/.claude/skills/*/SKILL.md` 和`~/.agents/skills/*/SKILL.md` 加載。 + +--- + +## 寫前言 + +每個`SKILL.md` 必須以 YAML frontmatter 開頭。 +僅識別這些字段: + +- `name`(必填) +- `description`(必填) +- `license`(可選) +- `compatibility`(可選) +- `metadata`(可選,字符串到字符串映射) + +未知的 frontmatter 字段將被忽略。 + +--- + +## 驗證姓名 + +`name` 必須: + +- 長度為 1–64 個字符 +- 為小寫字母數字並帶有單個連字符分隔符 +- 不以 `-` 開頭或結尾 +- 不包含連續`--` +- 匹配包含`SKILL.md`的目錄名 + +等效的正則表達式: + +```text +^[a-z0-9]+(-[a-z0-9]+)*$ +``` + +--- + +## 遵循長度規則 + +`description` 必須是 1-1024 個字符。 +保持足夠具體,以便代理能夠正確選擇。 + +--- + +## 使用一個例子 + +像這樣創建`.opencode/skills/git-release/SKILL.md`: + +```markdown +--- +name: git-release +description: Create consistent releases and changelogs +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do + +- Draft release notes from merged PRs +- Propose a version bump +- Provide a copy-pasteable `gh release create` command + +## When to use me + +Use this when you are preparing a tagged release. +Ask clarifying questions if the target versioning scheme is unclear. +``` + +--- + +## 識別工具說明 + +OpenCode 在`skill` 工具描述中列出了可用的技能。 +每個條目都包含技能名稱和描述: + +```xml + + + git-release + Create consistent releases and changelogs + + +``` + +代理通過調用工具來加載技能: + +``` +skill({ name: "git-release" }) +``` + +--- + +## 配置權限 + +使用 `opencode.json` 中基於模式的權限控制客服人員可以訪問哪些技能: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +|許可|行為 | +| ---------- | ----------------------------------------- | +| `allow` |技能立即加載 | +| `deny` |技能對特工隱藏,訪問被拒絕 | +| `ask` |加載前提示用戶批准 | + +模式支持通配符:`internal-*` 匹配`internal-docs`、`internal-tools` 等。 + +--- + +## 覆蓋每個代理 + +為特定代理授予與全局默認權限不同的權限。 + +**對於自定義代理**(在代理前言中): + +```yaml +--- +permission: + skill: + "documents-*": "allow" +--- +``` + +**對於內置代理**(在 `opencode.json` 中): + +```json +{ + "agent": { + "plan": { + "permission": { + "skill": { + "internal-*": "allow" + } + } + } + } +} +``` + +--- + +## 禁用技能工具 + +完全禁用不應該使用技能的特工: + +**對於定制代理**: + +```yaml +--- +tools: + skill: false +--- +``` + +**對於內置代理**: + +```json +{ + "agent": { + "plan": { + "tools": { + "skill": false + } + } + } +} +``` + +禁用時,`` 部分將被完全省略。 + +--- + +## 解決加載問題 + +如果某項技能沒有顯示: + +1. 驗證 `SKILL.md` 是否全部大寫拼寫 +2. 檢查 frontmatter 是否包含 `name` 和 `description` +3. 確保技能名稱在所有位置都是唯一的 +4. 檢查權限 - `deny` 的技能對代理隱藏 diff --git a/packages/web/src/content/docs/zh-tw/themes.mdx b/packages/web/src/content/docs/zh-tw/themes.mdx new file mode 100644 index 000000000..c3b2462c9 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/themes.mdx @@ -0,0 +1,369 @@ +--- +title: 主題 +description: 選擇內置主題或定義您自己的主題。 +--- + +使用 OpenCode,您可以從多個內置主題之一中進行選擇,使用適合您的終端主題的主題,或者定義您自己的自定義主題。 + +默認情況下,OpenCode 使用我們自己的 `opencode` 主題。 + +--- + +## 終端要求 + +為了使主題能夠正確顯示完整的調色板,您的終端必須支持**真彩色**(24 位顏色)。大多數現代終端默認支持此功能,但您可能需要啟用它: + +- **檢查支持**:運行`echo $COLORTERM` - 它應該輸出`truecolor`或`24bit` +- **啟用真彩色**:在 shell 配置文件中設置環境變量 `COLORTERM=truecolor` +- **終端兼容性**:確保您的終端模擬器支持 24 位顏色(大多數現代終端,​​如 iTerm2、Alacritty、Kitty、Windows 終端和最新版本的 GNOME 終端都支持) + +如果沒有真彩色支持,主題的顏色精度可能會降低或回落到最接近的 256 色近似值。 + +--- + +## 內置主題 + +OpenCode 附帶了幾個內置主題。 + +|名稱 |描述 | +| ---------------------- | ---------------------------------------------------------------------------- | +| `system` |適應您終端的背景顏色 | +| `tokyonight` |基於[東京之夜](https://github.com/folke/tokyonight.nvim)主題 | +| `everforest` |基於[永福森林](https://github.com/sainnhe/everforest)主題 | +| `ayu` |基於[香魚](https://github.com/ayu-theme)深色主題 | +| `catppuccin` |基於[卡普布辛](https://github.com/catppuccin)主題 | +| `catppuccin-macchiato` |基於[卡普布辛](https://github.com/catppuccin)主題 | +| `gruvbox` |基於[礦箱](https://github.com/morhetz/gruvbox)主題 | +| `kanagawa` |基於[神奈川](https://github.com/rebelot/kanagawa.nvim)主題 | +| `nord` |基於[諾德](https://github.com/nordtheme/nord)主題 | +| `matrix` |黑客風格黑底綠主題| +| `one-dark` |基於[原子一號](https://github.com/Th3Whit3Wolf/one-nvim) 深色主題 | + +此外,我們還在不斷添加新主題。 + +--- + +## 系統主題 + +`system` 主題旨在自動適應您終端的配色方案。與使用固定顏色的傳統主題不同,_system_ 主題: + +- **生成灰度**:根據終端的背景顏色創建自定義灰度,確保最佳對比度。 +- **使用 ANSI 顏色**:利用標準 ANSI 顏色 (0-15) 進行語法突出顯示和 UI 元素,尊重終端的調色板。 +- **保留終端默認設置**:使用 `none` 作為文本和背景顏色,以保持終端的本機外觀。 + +系統主題適合以下用戶: + +- 希望 OpenCode 與其終端的外觀相匹配 +- 使用自定義終端配色方案 +- 希望所有終端應用程序具有一致的外觀 + +--- + +## 使用主題 + +您可以通過使用 `/theme` 命令調出主題選擇來選擇主題。或者您可以在[配置](/docs/config) 中指定它。 + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## 自定義主題 + +OpenCode 支持靈活的基於 JSON 的主題系統,允許用戶輕鬆創建和自定義主題。 + +--- + +### 等級制度 + +主題按以下順序從多個目錄加載,其中後面的目錄覆蓋前面的目錄: + +1. **內置主題** - 這些主題嵌入在二進製文件中 +2. **用戶配置目錄** - 在`~/.config/opencode/themes/*.json` 或`$XDG_CONFIG_HOME/opencode/themes/*.json` 中定義 +3. **項目根目錄** - 定義在`/.opencode/themes/*.json` +4. **當前工作目錄** - 在`./.opencode/themes/*.json`中定義 + +如果多個目錄包含同名主題,則將使用優先級較高的目錄中的主題。 + +--- + +### 創建主題 + +要創建自定義主題,請在主題目錄之一中創建一個 JSON 文件。 + +對於用戶範圍的主題: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +以及針對特定項目的主題。 + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON格式 + +主題使用靈活的 JSON 格式,支持: + +- **十六進制顏色**:`"#ffffff"` +- **ANSI 顏色**:`3` (0-255) +- **顏色參考**:`"primary"` 或自定義定義 +- **深色/淺色版本**:`{"dark": "#000", "light": "#fff"}` +- **無顏色**:`"none"` - 使用終端的默認顏色或透明 + +--- + +### 顏色定義 + +`defs` 部分是可選的,它允許您定義可在主題中引用的可重用顏色。 + +--- + +### 終端默認值 + +特殊值`"none"`可用於任何顏色以繼承終端的默認顏色。這對於創建與終端配色方案無縫融合的主題特別有用: + +- `"text": "none"` - 使用終端的默認前景色 +- `"background": "none"` - 使用終端的默認背景顏色 + +--- + +### 例子 + +以下是自定義主題的示例: + +```json title="my-theme.json" +{ + "$schema": "https://opencode.ai/theme.json", + "defs": { + "nord0": "#2E3440", + "nord1": "#3B4252", + "nord2": "#434C5E", + "nord3": "#4C566A", + "nord4": "#D8DEE9", + "nord5": "#E5E9F0", + "nord6": "#ECEFF4", + "nord7": "#8FBCBB", + "nord8": "#88C0D0", + "nord9": "#81A1C1", + "nord10": "#5E81AC", + "nord11": "#BF616A", + "nord12": "#D08770", + "nord13": "#EBCB8B", + "nord14": "#A3BE8C", + "nord15": "#B48EAD" + }, + "theme": { + "primary": { + "dark": "nord8", + "light": "nord10" + }, + "secondary": { + "dark": "nord9", + "light": "nord9" + }, + "accent": { + "dark": "nord7", + "light": "nord7" + }, + "error": { + "dark": "nord11", + "light": "nord11" + }, + "warning": { + "dark": "nord12", + "light": "nord12" + }, + "success": { + "dark": "nord14", + "light": "nord14" + }, + "info": { + "dark": "nord8", + "light": "nord10" + }, + "text": { + "dark": "nord4", + "light": "nord0" + }, + "textMuted": { + "dark": "nord3", + "light": "nord1" + }, + "background": { + "dark": "nord0", + "light": "nord6" + }, + "backgroundPanel": { + "dark": "nord1", + "light": "nord5" + }, + "backgroundElement": { + "dark": "nord1", + "light": "nord4" + }, + "border": { + "dark": "nord2", + "light": "nord3" + }, + "borderActive": { + "dark": "nord3", + "light": "nord2" + }, + "borderSubtle": { + "dark": "nord2", + "light": "nord3" + }, + "diffAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffContext": { + "dark": "nord3", + "light": "nord3" + }, + "diffHunkHeader": { + "dark": "nord3", + "light": "nord3" + }, + "diffHighlightAdded": { + "dark": "nord14", + "light": "nord14" + }, + "diffHighlightRemoved": { + "dark": "nord11", + "light": "nord11" + }, + "diffAddedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffContextBg": { + "dark": "nord1", + "light": "nord5" + }, + "diffLineNumber": { + "dark": "nord2", + "light": "nord4" + }, + "diffAddedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "diffRemovedLineNumberBg": { + "dark": "#3B4252", + "light": "#E5E9F0" + }, + "markdownText": { + "dark": "nord4", + "light": "nord0" + }, + "markdownHeading": { + "dark": "nord8", + "light": "nord10" + }, + "markdownLink": { + "dark": "nord9", + "light": "nord9" + }, + "markdownLinkText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCode": { + "dark": "nord14", + "light": "nord14" + }, + "markdownBlockQuote": { + "dark": "nord3", + "light": "nord3" + }, + "markdownEmph": { + "dark": "nord12", + "light": "nord12" + }, + "markdownStrong": { + "dark": "nord13", + "light": "nord13" + }, + "markdownHorizontalRule": { + "dark": "nord3", + "light": "nord3" + }, + "markdownListItem": { + "dark": "nord8", + "light": "nord10" + }, + "markdownListEnumeration": { + "dark": "nord7", + "light": "nord7" + }, + "markdownImage": { + "dark": "nord9", + "light": "nord9" + }, + "markdownImageText": { + "dark": "nord7", + "light": "nord7" + }, + "markdownCodeBlock": { + "dark": "nord4", + "light": "nord0" + }, + "syntaxComment": { + "dark": "nord3", + "light": "nord3" + }, + "syntaxKeyword": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxFunction": { + "dark": "nord8", + "light": "nord8" + }, + "syntaxVariable": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxString": { + "dark": "nord14", + "light": "nord14" + }, + "syntaxNumber": { + "dark": "nord15", + "light": "nord15" + }, + "syntaxType": { + "dark": "nord7", + "light": "nord7" + }, + "syntaxOperator": { + "dark": "nord9", + "light": "nord9" + }, + "syntaxPunctuation": { + "dark": "nord4", + "light": "nord0" + } + } +} +``` diff --git a/packages/web/src/content/docs/zh-tw/tools.mdx b/packages/web/src/content/docs/zh-tw/tools.mdx new file mode 100644 index 000000000..ac4296f43 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/tools.mdx @@ -0,0 +1,379 @@ +--- +title: 工具 +description: 管理法學碩士可以使用的工具。 +--- + +工具允許 LLM 在您的代碼庫中執行操作。 OpenCode 附帶了一組內置工具,但您可以使用[定制工具](/docs/custom-tools) 或[MCP服務器](/docs/mcp-servers) 對其進行擴展。 + +默認情況下,所有工具都是**啟用**並且不需要運行權限。您可以通過[權限](/docs/permissions)控制工具行為。 + +--- + +## 配置 + +使用 `permission` 字段控制工具行為。您可以允許、拒絕或要求批准每個工具。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "deny", + "bash": "ask", + "webfetch": "allow" + } +} +``` + +您還可以使用通配符同時控制多個工具。例如,要求 MCP 服務器批准所有工具: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "mymcp_*": "ask" + } +} +``` + +[了解更多](/docs/permissions) 關於配置權限。 + +--- + +## 內建 + +以下是 OpenCode 中可用的所有內置工具。 + +--- + +### bash + +在項目環境中執行 shell 命令。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "allow" + } +} +``` + +該工具允許法學碩士運行 `npm install`、`git status` 等終端命令或任何其他 shell 命令。 + +--- + +### edit + +使用精確的字符串替換修改現有文件。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +該工具通過替換精確的文本匹配來對文件執行精確編輯。這是法學碩士修改代碼的主要方式。 + +--- + +### write + +創建新文件或覆蓋現有文件。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +使用它允許法學碩士創建新文件。如果現有文件已經存在,它將覆蓋它們。 + +:::note +`write`工具由`edit`權限控制,該權限涵蓋所有文件修改(`edit`、`write`、`patch`、`multiedit`)。 +::: + +--- + +### read + +從代碼庫中讀取文件內容。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "read": "allow" + } +} +``` + +該工具讀取文件並返回其內容。它支持讀取大文件的特定行範圍。 + +--- + +### grep + +使用正則表達式搜索文件內容。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "grep": "allow" + } +} +``` + +在您的代碼庫中快速進行內容搜索。支持完整的正則表達式語法和文件模式過濾。 + +--- + +### glob + +通過模式匹配查找文件。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "glob": "allow" + } +} +``` + +使用`**/*.js` 或`src/**/*.ts` 等全局模式搜索文件。返回按修改時間排序的匹配文件路徑。 + +--- + +### list + +列出給定路徑中的文件和目錄。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "list": "allow" + } +} +``` + +該工具列出目錄內容。它接受全局模式來過濾結果。 + +--- + +### lsp(實驗性) + +與您配置的 LSP 服務器交互,以獲得代碼智能功能,例如定義、引用、懸停信息和調用層次結構。 + +:::note +該工具僅在`OPENCODE_EXPERIMENTAL_LSP_TOOL=true`(或`OPENCODE_EXPERIMENTAL=true`)時可用。 +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "lsp": "allow" + } +} +``` + +支持的操作包括`goToDefinition`、`findReferences`、`hover`、`documentSymbol`、`workspaceSymbol`、`goToImplementation`、`prepareCallHierarchy`、`incomingCalls` 和`outgoingCalls`。 + +要配置哪些 LSP 服務器可用於您的項目,請參閱[LSP服務器](/docs/lsp)。 + +--- + +### patch + +對文件應用補丁。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "allow" + } +} +``` + +該工具將補丁文件應用到您的代碼庫。對於應用來自各種來源的差異和補丁很有用。 + +:::note +`patch`工具由`edit`權限控制,該權限涵蓋所有文件修改(`edit`、`write`、`patch`、`multiedit`)。 +::: + +--- + +### skill + +加載[技能](/docs/skills)(`SKILL.md` 文件)並在對話中返回其內容。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "skill": "allow" + } +} +``` + +--- + +### todowrite + +在編碼會話期間管理待辦事項列表。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todowrite": "allow" + } +} +``` + +創建和更新任務列表以跟踪複雜操作期間的進度。法學碩士使用它來組織多步驟任務。 + +:::note +默認情況下,子代理禁用此工具,但您可以手動啟用它。 [了解更多](/docs/agents/#permissions) +::: + +--- + +### todoread + +閱讀現有的待辦事項列表。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "todoread": "allow" + } +} +``` + +讀取當前待辦事項列表狀態。法學碩士用來跟踪哪些任務待處理或已完成。 + +:::note +默認情況下,子代理禁用此工具,但您可以手動啟用它。 [了解更多](/docs/agents/#permissions) +::: + +--- + +### webfetch + +獲取網頁內容。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "webfetch": "allow" + } +} +``` + +允許法學碩士獲取和閱讀網頁。對於查找文檔或研究在線資源很有用。 + +--- + +### websearch + +在網絡上搜索信息。 + +:::note +僅當使用 OpenCode 提供程序或 `OPENCODE_ENABLE_EXA` 環境變量設置為任何真值(例如 `true` 或 `1`)時,此工具才可用。 + +要在啟動 OpenCode 時啟用: + +```bash +OPENCODE_ENABLE_EXA=1 opencode +``` + +::: + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "websearch": "allow" + } +} +``` + +使用 Exa AI 執行網絡搜索以在線查找相關信息。對於研究主題、查找時事或收集超出訓練數據截止範圍的信息很有用。 + +不需要 API 密鑰 - 該工具無需身份驗證即可直接連接到 Exa AI 的託管 MCP 服務。 + +:::tip +當您需要查找信息(發現)時,請使用 `websearch`;當您需要從特定 URL 檢索內容(檢索)時,請使用 `webfetch`。 +::: + +--- + +### question + +在執行過程中詢問用戶問題。 + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "question": "allow" + } +} +``` + +該工具允許法學碩士在任務期間詢問用戶問題。它適用於: + +- 收集用戶偏好或要求 +- 澄清不明確的指令 +- 就實施選擇做出決策 +- 提供選擇方向 + +每個問題都包含標題、問題文本和選項列表。用戶可以從提供的選項中進行選擇或輸入自定義答案。當存在多個問題時,用戶可以在提交所有答案之前在這些問題之間導航。 + +--- + +## 定制工具 + +自定義工具可讓您定義法學碩士可以調用的自己的函數。這些是在您的配置文件中定義的並且可以執行任意代碼。 + +[了解更多](/docs/custom-tools) 關於創建自定義工具。 + +--- + +## MCP服務器 + +MCP(模型上下文協議)服務器允許您集成外部工具和服務。這包括數據庫訪問、API 集成和第三方服務。 + +[了解更多](/docs/mcp-servers) 關於配置 MCP 服務器。 + +--- + +## 內部結構 + +在內部,`grep`、`glob` 和`list` 等工具在底層使用[ripgrep](https://github.com/BurntSushi/ripgrep)。默認情況下,ripgrep 遵循 `.gitignore` 模式,這意味著 `.gitignore` 中列出的文件和目錄將從搜索和列表中排除。 + +--- + +### 忽略模式 + +要包含通常會被忽略的文件,請在項目根目錄中創建一個 `.ignore` 文件。該文件可以明確允許某些路徑。 + +```text title=".ignore" +!node_modules/ +!dist/ +!build/ +``` + +例如,此 `.ignore` 文件允許 ripgrep 在 `node_modules/`、`dist/` 和 `build/` 目錄中搜索,即使它們列在 `.gitignore` 中。 diff --git a/packages/web/src/content/docs/zh-tw/troubleshooting.mdx b/packages/web/src/content/docs/zh-tw/troubleshooting.mdx new file mode 100644 index 000000000..db1319d4d --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/troubleshooting.mdx @@ -0,0 +1,300 @@ +--- +title: 故障排除 +description: 常見問題以及如何解決它們。 +--- + +要調試 OpenCode 問題,請首先檢查其存儲在磁盤上的日誌和本地數據。 + +--- + +## 紀錄 + +日誌文件寫入: + +- **macOS/Linux**:`~/.local/share/opencode/log/` +- **Windows**:按`WIN+R`並粘貼`%USERPROFILE%\.local\share\opencode\log` + +日誌文件以時間戳命名(例如`2025-01-09T123456.log`),並保留最近的 10 個日誌文件。 + +您可以使用 `--log-level` 命令行選項設置日誌級別以獲取更詳細的調試信息。例如,`opencode --log-level DEBUG`。 + +--- + +## 貯存 + +opencode 將會話數據和其他應用程序數據存儲在磁盤上: + +- **macOS/Linux**:`~/.local/share/opencode/` +- **Windows**:按`WIN+R`並粘貼`%USERPROFILE%\.local\share\opencode` + +該目錄包含: + +- `auth.json` - 身份驗證數據,例如 API 密鑰、OAuth 令牌 +- `log/` - 應用程序日誌 +- `project/` - 項目特定數據,例如會話和消息數據 + - 如果項目位於 Git 存儲庫中,則它存儲在 `.//storage/` 中 + - 如果不是 Git 存儲庫,則存儲在 `./global/storage/` 中 + +--- + +## 桌面應用程序 + +OpenCode Desktop 在後台運行本地 OpenCode 服務器(`opencode-cli` sidecar)。大多數問題是由行為不當的插件、損壞的緩存或錯誤的服務器設置引起的。 + +### 快速檢查 + +- 完全退出並重新啟動應用程序。 +- 如果應用程序顯示錯誤屏幕,請單擊“**重新啟動**”並複制錯誤詳細信息。 +- 僅限 macOS:`OpenCode` 菜單 -> **重新加載 Webview**(如果 UI 為空白/凍結,則有幫助)。 + +--- + +### 禁用插件 + +如果桌面應用程序在啟動時崩潰、掛起或行為異常,請首先禁用插件。 + +#### 檢查全局配置 + +打開全局配置文件並查找 `plugin` 密鑰。 + +- **macOS/Linux**:`~/.config/opencode/opencode.jsonc`(或`~/.config/opencode/opencode.json`) +- **macOS/Linux**(較舊的安裝):`~/.local/share/opencode/opencode.jsonc` +- **Windows**:按`WIN+R`並粘貼`%USERPROFILE%\.config\opencode\opencode.jsonc` + +如果您配置了插件,請通過刪除密鑰或將其設置為空數組來暫時禁用它們: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [], +} +``` + +#### 檢查插件目錄 + +OpenCode 還可以從磁盤加載本地插件。暫時將它們移開(或重命名文件夾)並重新啟動桌面應用程序: + +- **全局插件** + - **macOS/Linux**:`~/.config/opencode/plugins/` + - **Windows**:按`WIN+R`並粘貼`%USERPROFILE%\.config\opencode\plugins` +- **項目插件**(僅當您使用每個項目配置時) + - `/.opencode/plugins/` + +如果應用程序再次開始工作,請一次重新啟用一個插件,以找出導致問題的插件。 + +--- + +### 清除緩存 + +如果禁用插件沒有幫助(或者插件安裝被卡住),請清除緩存,以便 OpenCode 可以重建它。 + +1. 完全退出 OpenCode Desktop。 +2. 刪除緩存目錄: + +- **macOS**:Finder -> `Cmd+Shift+G` -> 粘貼`~/.cache/opencode` +- **Linux**:刪除`~/.cache/opencode`(或運行`rm -rf ~/.cache/opencode`) +- **Windows**:按`WIN+R`並粘貼`%USERPROFILE%\.cache\opencode` + +3. 重新啟動 OpenCode 桌面。 + +--- + +### 修復服務器連接問題 + +OpenCode Desktop 可以啟動自己的本地服務器(默認)或連接到您配置的服務器 URL。 + +如果您看到 **“連接失敗”** 對話框(或者應用程序永遠無法通過啟動屏幕),請檢查自定義服務器 URL。 + +#### 清除桌面默認服務器 URL + +在主屏幕中,單擊服務器名稱(帶有狀態點)以打開服務器選取器。在“**默認服務器**”部分中,單擊“**清除**”。 + +#### 從您的配置中刪除`server.port` / `server.hostname` + +如果您的 `opencode.json(c)` 包含 `server` 部分,請將其暫時刪除並重新啟動桌面應用程序。 + +#### 檢查環境變量 + +如果您在環境中設置了 `OPENCODE_PORT`,桌面應用程序將嘗試將該端口用於本地服務器。 + +- 取消設置`OPENCODE_PORT`(或選擇一個空閒端口)並重新啟動。 + +--- + +### Linux:Wayland / X11 問題 + +在 Linux 上,某些 Wayland 設置可能會導致空白窗口或合成器錯誤。 + +- 如果您在 Wayland 上且應用程序空白/崩潰,請嘗試使用 `OC_ALLOW_WAYLAND=1` 啟動。 +- 如果這讓事情變得更糟,請將其刪除並嘗試在 X11 會話下啟動。 + +--- + +### Windows:WebView2 運行時 + +在 Windows 上,OpenCode Desktop 需要 Microsoft Edge **WebView2 運行時**。如果應用程序打開為空白窗口或無法啟動,請安裝/更新 WebView2,然後重試。 + +--- + +### Windows:一般性能問題 + +如果您在 Windows 上遇到性能緩慢、文件訪問問題或終端問題,請嘗試使用[WSL(適用於 Linux 的 Windows 子系統)](/docs/windows-wsl)。 WSL 提供了一個可以與 OpenCode 功能更加無縫協作的 Linux 環境。 + +--- + +### 通知不顯示 + +OpenCode Desktop 僅在以下情況下顯示系統通知: + +- 在您的操作系統設置中啟用 OpenCode 通知,並且 +- 應用程序窗口未聚焦。 + +--- + +### 重置桌面應用程序存儲(最後的手段) + +如果應用程序無法啟動並且您無法從 UI 內部清除設置,請重置桌面應用程序的保存狀態。 + +1. 退出 OpenCode Desktop。 +2. 查找並刪除這些文件(它們位於 OpenCode Desktop 應用程序數據目錄中): + +- `opencode.settings.dat`(桌面默認服務器 URL) +- `opencode.global.dat` 和 `opencode.workspace.*.dat`(UI 狀態,如最近的服務器/項目) + +快速找到目錄: + +- **macOS**:Finder -> `Cmd+Shift+G` -> `~/Library/Application Support`(然後搜索上面的文件名) +- **Linux**:在 `~/.local/share` 下搜索上述文件名 +- **Windows**:按`WIN+R` -> `%APPDATA%`(然後搜索上面的文件名) + +--- + +## 尋求幫助 + +如果您遇到 OpenCode 問題: + +1. **在 GitHub 上報告問題** + + 報告錯誤或請求功能的最佳方式是通過我們的 GitHub 存儲庫: + + [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) + + 在創建新問題之前,請搜索現有問題以查看您的問題是否已被報告。 + +2. **加入我們的不和諧** + + 如需實時幫助和社區討論,請加入我們的 Discord 服務器: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## 常見問題 + +以下是一些常見問題以及解決方法。 + +--- + +### OpenCode 無法啟動 + +1. 檢查日誌中是否有錯誤消息 +2. 嘗試使用 `--print-logs` 運行以查看終端中的輸出 +3. 確保您擁有最新版本`opencode upgrade` + +--- + +### 身份驗證問題 + +1. 嘗試使用 TUI 中的 `/connect` 命令重新進行身份驗證 +2. 檢查您的 API 密鑰是否有效 +3. 確保您的網絡允許連接到提供商的 API + +--- + +### 型號不可用 + +1. 檢查您是否已通過提供商的身份驗證 +2. 驗證配置中的型號名稱是否正確 +3. 某些型號可能需要特定的訪問權限或訂閱 + +如果您遇到`ProviderModelNotFoundError`,您很可能是錯誤的 +在某處引用模型。 +模型應該像這樣引用:`/` + +示例: + +- `openai/gpt-4.1` +- `openrouter/google/gemini-2.5-flash` +- `opencode/kimi-k2` + +要了解您可以訪問哪些模型,請運行`opencode models` + +--- + +### 提供者初始化錯誤 + +如果遇到 ProviderInitError,您的配置可能無效或損壞。 + +要解決這個問題: + +1. 首先,按照 [供應商指南](/docs/providers) 驗證您的提供商是否已正確設置 +2. 如果問題仍然存在,請嘗試清除存儲的配置: + + ```bash + rm -rf ~/.local/share/opencode + ``` + + 在 Windows 上,按 `WIN+R` 並刪除:`%USERPROFILE%\.local\share\opencode` + +3. 使用 TUI 中的 `/connect` 命令向您的提供商重新進行身份驗證。 + +--- + +### AI_APICallError 和提供程序包問題 + +如果您遇到 API 調用錯誤,這可能是由於過時的提供程序包造成的。 opencode 根據需要動態安裝提供程序包(OpenAI、Anthropic、Google 等)並將其緩存在本地。 + +要解決提供程序包問題: + +1. 清除提供程序包緩存: + + ```bash + rm -rf ~/.cache/opencode + ``` + + 在 Windows 上,按 `WIN+R` 並刪除:`%USERPROFILE%\.cache\opencode` + +2. 重新啟動 opencode 以重新安裝最新的提供程序包 + +這將強制 opencode 下載最新版本的提供程序包,這通常可以解決模型參數和 API 更改的兼容性問題。 + +--- + +### 複製/粘貼在 Linux 上不起作用 + +Linux 用戶需要安裝以下剪貼板實用程序之一才能使用複制/粘貼功能: + +**對於 X11 系統:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**對於 Wayland 系統:** + +```bash +apt install -y wl-clipboard +``` + +**對於無頭環境:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode 將檢測您是否使用 Wayland 並更喜歡 `wl-clipboard`,否則它將嘗試按 `xclip` 和 `xsel` 的順序查找剪貼板工具。 diff --git a/packages/web/src/content/docs/zh-tw/tui.mdx b/packages/web/src/content/docs/zh-tw/tui.mdx new file mode 100644 index 000000000..9f22506ff --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/tui.mdx @@ -0,0 +1,390 @@ +--- +title: 途易 +description: 使用 OpenCode 終端用戶界面。 +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +OpenCode 提供了一個交互式終端界面或 TUI,供您與法學碩士一起處理項目。 + +運行 OpenCode 會啟動當前目錄的 TUI。 + +```bash +opencode +``` + +或者您可以為特定的工作目錄啟動它。 + +```bash +opencode /path/to/project +``` + +進入 TUI 後,您可以通過消息進行提示。 + +```text +Give me a quick summary of the codebase. +``` + +--- + +## 文件參考 + +您可以使用 `@` 在消息中引用文件。這會在當前工作目錄中進行模糊文件搜索。 + +:::tip +您還可以使用 `@` 來引用消息中的文件。 +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +文件的內容會自動添加到對話中。 + +--- + +## bash 命令 + +以 `!` 開始一條消息以運行 shell 命令。 + +```bash frame="none" +!ls -la +``` + +命令的輸出將作為工具結果添加到對話中。 + +--- + +## 命令 + +使用 OpenCode TUI 時,您可以鍵入 `/` 後跟命令名稱來快速執行操作。例如: + +```bash frame="none" +/help +``` + +Most commands also have keybind using `ctrl+x` as the leader key, where `ctrl+x` is the default leader key. [了解更多](/docs/keybinds)。 + +以下是所有可用的斜杠命令: + +--- + +### connect + +將提供程序添加到 OpenCode。允許您從可用的提供商中進行選擇並添加其 API 密鑰。 + +```bash frame="none" +/connect +``` + +--- + +### compact + +壓縮當前會話。 _別名_:`/summarize` + +```bash frame="none" +/compact +``` + +**按鍵綁定:** `ctrl+x c` + +--- + +### details + +切換工具執行詳細信息。 + +```bash frame="none" +/details +``` + +**按鍵綁定:** `ctrl+x d` + +--- + +### editor + +打開外部編輯器來撰寫消息。使用 `EDITOR` 環境變量中設置的編輯器。 [了解更多](#editor-setup)。 + +```bash frame="none" +/editor +``` + +**按鍵綁定:** `ctrl+x e` + +--- + +### exit + +退出 OpenCode。 _別名_:`/quit`、`/q` + +```bash frame="none" +/exit +``` + +**按鍵綁定:** `ctrl+x q` + +--- + +### export + +將當前對話導出到 Markdown 並在默認編輯器中打開。使用 `EDITOR` 環境變量中設置的編輯器。 [了解更多](#editor-setup)。 + +```bash frame="none" +/export +``` + +**按鍵綁定:** `ctrl+x x` + +--- + +### help + +顯示幫助對話框。 + +```bash frame="none" +/help +``` + +**按鍵綁定:** `ctrl+x h` + +--- + +### init + +創建或更新`AGENTS.md` 文件。 [了解更多](/docs/rules)。 + +```bash frame="none" +/init +``` + +**按鍵綁定:** `ctrl+x i` + +--- + +### models + +列出可用型號。 + +```bash frame="none" +/models +``` + +**按鍵綁定:** `ctrl+x m` + +--- + +### new + +開始新的會話。 _別名_:`/clear` + +```bash frame="none" +/new +``` + +**按鍵綁定:** `ctrl+x n` + +--- + +### redo + +重做之前撤消的消息。僅在使用`/undo`後可用。 + +:::tip +任何文件更改也將被恢復。 +::: + +在內部,這使用 Git 來管理文件更改。所以你的項目**需要 +是一個 Git 存儲庫**。 + +```bash frame="none" +/redo +``` + +**按鍵綁定:** `ctrl+x r` + +--- + +### sessions + +列出會話並在會話之間切換。 _別名_:`/resume`、`/continue` + +```bash frame="none" +/sessions +``` + +**按鍵綁定:** `ctrl+x l` + +--- + +### share + +共享當前會話。 [了解更多](/docs/share)。 + +```bash frame="none" +/share +``` + +**按鍵綁定:** `ctrl+x s` + +--- + +### themes + +列出可用的主題。 + +```bash frame="none" +/theme +``` + +**按鍵綁定:** `ctrl+x t` + +--- + +### thinking + +切換對話中思維/推理塊的可見性。啟用後,您可以看到支持擴展思維的模型的推理過程。 + +:::note +該命令僅控制是否**顯示** - 它不啟用或禁用模型的推理功能。要切換實際推理功能,請使用 `ctrl+t` 循環切換模型變體。 +::: + +```bash frame="none" +/thinking +``` + +--- + +### undo + +撤消對話中的最後一條消息。刪除最近的用戶消息、所有後續響應以及任何文件更改。 + +:::tip +所做的任何文件更改也將被恢復。 +::: + +在內部,這使用 Git 來管理文件更改。所以你的項目**需要 +是一個 Git 存儲庫**。 + +```bash frame="none" +/undo +``` + +**按鍵綁定:** `ctrl+x u` + +--- + +### unshare + +取消共享當前會話。 [了解更多](/docs/share#un-sharing)。 + +```bash frame="none" +/unshare +``` + +--- + +## 編輯器設置 + +`/editor` 和`/export` 命令都使用`EDITOR` 環境變量中指定的編輯器。 + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + export EDITOR="code --wait" + ``` + + To make it permanent, add this to your shell profile; + `~/.bashrc`, `~/.zshrc`, etc. + + + + + ```bash + set EDITOR=notepad + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + set EDITOR=code --wait + ``` + + To make it permanent, use **System Properties** > **Environment + Variables**. + + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc. + # include --wait + $env:EDITOR = "code --wait" + ``` + + To make it permanent, add this to your PowerShell profile. + + + + +流行的編輯器選項包括: + +- `code` - Visual Studio 代碼 +- `cursor` - 光標 +- `windsurf` - 風帆衝浪 +- `nvim` - Neo 的編輯 +- `vim` - 我來編輯了 +- `nano` - 納米編輯器 +- `notepad` - Windows 記事本 +- `subl` - Sublime Text + +:::note +某些編輯器(例如 VS Code)需要以 `--wait` 標誌啟動。 +::: + +某些編輯器需要命令行參數才能在阻止模式下運行。 `--wait` 標誌使編輯器進程阻塞直到關閉。 + +--- + +## 配置 + +您可以通過 OpenCode 配置文件自定義 TUI 行為。 + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "tui": { + "scroll_speed": 3, + "scroll_acceleration": { + "enabled": true + } + } +} +``` + +### 選項 + +- `scroll_acceleration` - 啟用 macOS 風格的滾動加速,實現平滑、自然的滾動。啟用後,滾動速度會隨著快速滾動手勢而增加,並在較慢的移動時保持精確。 **此設置優先於`scroll_speed`,並在啟用時覆蓋它。 ** +- `scroll_speed` - 控制使用滾動命令時 TUI 滾動的速度(最小值:`1`)。默認為`3`。 **注意:如果`scroll_acceleration.enabled` 設置為`true`,則忽略此設置。 ** + +--- + +## 定制化 + +您可以使用命令選項板(`ctrl+x h` 或`/help`)自定義 TUI 視圖的各個方面。這些設置在重新啟動後仍然存在。 + +--- + +#### 用戶名顯示 + +切換您的用戶名是否出現在聊天消息中。通過以下方式訪問: + +- 命令面板:搜索“用戶名”或“隱藏用戶名” +- 該設置會自動保留並在 TUI 會話中被記住 diff --git a/packages/web/src/content/docs/zh-tw/web.mdx b/packages/web/src/content/docs/zh-tw/web.mdx new file mode 100644 index 000000000..c43b017a0 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/web.mdx @@ -0,0 +1,142 @@ +--- +title: 網絡 +description: 在瀏覽器中使用 OpenCode。 +--- + +OpenCode 可以在瀏覽器中作為 Web 應用程序運行,無需終端即可提供同樣強大的 AI 編碼體驗。 + +![OpenCode Web - 新會話](../../../assets/web/web-homepage-new-session.png) + +## 入門 + +通過運行以下命令啟動 Web 界面: + +```bash +opencode web +``` + +這將在 `127.0.0.1` 上啟動一個具有隨機可用端口的本地服務器,並自動在默認瀏覽器中打開 OpenCode。 + +:::caution +如果未設置`OPENCODE_SERVER_PASSWORD`,服務器將不安全。這對於本地使用來說很好,但應該針對網絡訪問進行設置。 +::: + +:::tip[Windows 用戶] +為了獲得最佳體驗,請從 [世界SL](/docs/windows-wsl) 而不是 PowerShell 運行 `opencode web`。這確保了正確的文件系統訪問和終端集成。 +::: + +--- + +## 配置 + +您可以使用命令行標誌或在 [配置文件](/docs/config) 中配置 Web 服務器。 + +### 港口 + +默認情況下,OpenCode 選擇一個可用端口。您可以指定一個端口: + +```bash +opencode web --port 4096 +``` + +### 主機名 + +默認情況下,服務器綁定到`127.0.0.1`(僅限本地主機)。要使 OpenCode 在您的網絡上可訪問: + +```bash +opencode web --hostname 0.0.0.0 +``` + +當使用`0.0.0.0`時,OpenCode將顯示本地地址和網絡地址: + +``` + Local access: http://localhost:4096 + Network access: http://192.168.1.100:4096 +``` + +### mDNS 發現 + +啟用 mDNS 以使您的服務器在本地網絡上可發現: + +```bash +opencode web --mdns +``` + +這會自動將主機名設置為 `0.0.0.0` 並將服務器通告為 `opencode.local`。 + +您可以自定義 mDNS 域名以在同一網絡上運行多個實例: + +```bash +opencode web --mdns --mdns-domain myproject.local +``` + +### CORS + +允許 CORS 的其他域(對於自定義前端有用): + +```bash +opencode web --cors https://example.com +``` + +### 驗證 + +要保護訪問,請使用 `OPENCODE_SERVER_PASSWORD` 環境變量設置密碼: + +```bash +OPENCODE_SERVER_PASSWORD=secret opencode web +``` + +用戶名默認為`opencode`,但可以使用`OPENCODE_SERVER_USERNAME` 進行更改。 + +--- + +## 使用網絡界面 + +啟動後,Web 界面將提供對 OpenCode 會話的訪問。 + +### 會議 + +從主頁查看和管理您的會話。您可以查看活動會話並開始新會話。 + +![OpenCode Web - 活動會話](../../../assets/web/web-homepage-active-session.png) + +### 服務器狀態 + +單擊“查看服務器”可查看連接的服務器及其狀態。 + +![OpenCode Web - 查看服務器](../../../assets/web/web-homepage-see-servers.png) + +--- + +## 連接終端 + +您可以將終端 TUI 連接到正在運行的 Web 服務器: + +```bash +# Start the web server +opencode web --port 4096 + +# In another terminal, attach the TUI +opencode attach http://localhost:4096 +``` + +這允許您同時使用 Web 界面和終端,共享相同的會話和狀態。 + +--- + +## 配置文件 + +您還可以在 `opencode.json` 配置文件中配置服務器設置: + +```json +{ + "server": { + "port": 4096, + "hostname": "0.0.0.0", + "mdns": true, + "cors": ["https://example.com"] + } +} +``` + +命令行標誌優先於配置文件設置。 diff --git a/packages/web/src/content/docs/zh-tw/windows-wsl.mdx b/packages/web/src/content/docs/zh-tw/windows-wsl.mdx new file mode 100644 index 000000000..efcc8c6f6 --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/windows-wsl.mdx @@ -0,0 +1,113 @@ +--- +title: Windows (WSL) +description: 在 Windows 透過 WSL 使用 OpenCode。 +--- + +import { Steps } from "@astrojs/starlight/components" + +雖然 OpenCode 可以直接在 Windows 上執行,但為了獲得最佳體驗,我們建議使用 [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install)。WSL 提供了可與 OpenCode 功能順暢配合的 Linux 環境。 + +:::tip[為什麼要用 WSL?] +WSL 提供更好的檔案系統效能、完整的終端支援,以及與 OpenCode 依賴之開發工具的相容性。 +::: + +--- + +## 設定 + + + +1. **安裝 WSL** + + 如果你尚未安裝,請依照 Microsoft 官方指南[安裝 WSL](https://learn.microsoft.com/en-us/windows/wsl/install)。 + +2. **在 WSL 中安裝 OpenCode** + + 完成 WSL 設定後,打開 WSL 終端機,並使用其中一種[安裝方式](/docs/)安裝 OpenCode。 + + ```bash + curl -fsSL https://opencode.ai/install | bash + ``` + +3. **從 WSL 使用 OpenCode** + + 移動到你的專案目錄(可透過 `/mnt/c/`、`/mnt/d/` 等路徑存取 Windows 檔案),然後執行 OpenCode。 + + ```bash + cd /mnt/c/Users/YourName/project + opencode + ``` + + + +--- + +## 桌面應用程式 + WSL 伺服器 + +如果你偏好使用 OpenCode 桌面應用程式,但希望在 WSL 內執行伺服器: + +1. **在 WSL 中啟動伺服器**,並使用 `--hostname 0.0.0.0` 允許外部連線: + + ```bash + opencode serve --hostname 0.0.0.0 --port 4096 + ``` + +2. **將桌面應用程式連線到** `http://localhost:4096` + +:::note +若你的環境中 `localhost` 無法使用,請改用 WSL 的 IP 位址連線(在 WSL 執行:`hostname -I`),並使用 `http://:4096`。 +::: + +:::caution +使用 `--hostname 0.0.0.0` 時,請設定 `OPENCODE_SERVER_PASSWORD` 來保護伺服器。 + +```bash +OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 +``` + +::: + +--- + +## Web 用戶端 + WSL + +在 Windows 上取得最佳 Web 體驗: + +1. **請在 WSL 終端機執行 `opencode web`**,而不是在 PowerShell 執行: + + ```bash + opencode web --hostname 0.0.0.0 + ``` + +2. **在 Windows 瀏覽器中開啟** `http://localhost:`(OpenCode 會輸出該 URL) + +從 WSL 執行 `opencode web` 可確保正確的檔案系統存取與終端整合,同時仍可由 Windows 瀏覽器使用。 + +--- + +## 存取 Windows 檔案 + +WSL 可透過 `/mnt/` 目錄存取你所有的 Windows 檔案: + +- `C:` drive → `/mnt/c/` +- `D:` drive → `/mnt/d/` +- 其他磁碟機也相同 + +範例: + +```bash +cd /mnt/c/Users/YourName/Documents/project +opencode +``` + +:::tip +為了更流暢的使用體驗,建議將你的儲存庫 clone 或複製到 WSL 檔案系統(例如 `~/code/`)中,再從那裡執行 OpenCode。 +::: + +--- + +## 提示 + +- 即使專案存放在 Windows 磁碟機上,也建議在 WSL 中執行 OpenCode,檔案存取會更順暢 +- 可將 OpenCode 與 VS Code 的 [WSL 擴充套件](https://code.visualstudio.com/docs/remote/wsl)搭配使用,建立整合式開發流程 +- OpenCode 的設定與工作階段會儲存在 WSL 環境中的 `~/.local/share/opencode/` diff --git a/packages/web/src/content/docs/zh-tw/zen.mdx b/packages/web/src/content/docs/zh-tw/zen.mdx new file mode 100644 index 000000000..94042f79d --- /dev/null +++ b/packages/web/src/content/docs/zh-tw/zen.mdx @@ -0,0 +1,254 @@ +--- +title: 禪 +description: OpenCode 提供的精選模型列表。 +--- + +import config from "../../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +OpenCode Zen 是 OpenCode 團隊提供的經過測試和驗證的模型列表。 + +:::note +OpenCode Zen 目前處於測試階段。 +::: + +Zen 的工作方式與 OpenCode 中的任何其他提供程序一樣。您登錄 OpenCode Zen 並獲取 +您的 API 密鑰。它是**完全可選的**,您不需要使用它即可使用 +開放代碼。 + +--- + +## 背景 + +市面上有很多型號,但其中只有少數幾個 +這些模型可以很好地用作編碼代理。此外,大多數提供商都 +配置非常不同;所以你會得到截然不同的性能和質量。 + +:::tip +我們測試了一組精選的與 OpenCode 配合良好的模型和提供程序。 +::: + +因此,如果您通過 OpenRouter 之類的東西使用模型,那麼您永遠無法 +確定您是否獲得了您想要的模型的最佳版本。 + +為了解決這個問題,我們做了幾件事: + +1. 我們測試了一組選定的模型,並與他們的團隊討論瞭如何 + 最好運行它們。 +2. 然後我們與一些提供商合作以確保這些服務得到服務 + 正確。 +3. 最後,我們對模型/提供商的組合進行了基準測試並提出了 + 並附上一份我們覺得不錯的推薦清單。 + +OpenCode Zen 是一個 AI 網關,可讓您訪問這些模型。 + +--- + +## 它是如何運作的 + +OpenCode Zen 的工作方式與 OpenCode 中的任何其他提供程序一樣。 + +1. 您登錄 **OpenCode Zen**,添加您的帳單 + 詳細信息,然後復制您的 API 密鑰。 +2. 您在 TUI 中運行 `/connect` 命令,選擇 OpenCode Zen,然後粘貼您的 API 密鑰。 +3. 在 TUI 中運行 `/models` 以查看我們推薦的型號列表。 + +您需要按請求付費,並且可以將積分添加到您的帳戶中。 + +--- + +## 端點 + +您還可以通過以下 API 端點訪問我們的模型。 + +|型號|型號 ID |端點 |人工智能SDK包| +| ------------------ | ------------------ | -------------------------------------------------- | --------------------------- | +| GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.2 法典 | gpt-5.2-codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 法典 | gpt-5.1-codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 法典最大 | gpt-5.1-codex-max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5.1 迷你版 | gpt-5.1-codex-mini | gpt-5.1-codex-mini | gpt-5.1-codex-mini `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 法典 | gpt-5-法典 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | +| GPT 5 納米 | GPT-5-納米| @@c0@@ | @@c1@ | +|克勞德十四行詩 4.5 |克勞德十四行詩-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|克勞德十四行詩 4 |克勞德十四行詩-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|克勞德俳句 4.5 |克勞德俳句-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|克勞德俳句 3.5 | claude-3-5-俳句 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|近距離工作4.6 |近距離工作4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|近距離工作4.5 |近距離工作4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|近距離工作4.1 |近距離工作4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +|雙子座 3 Pro |雙 3 為 | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | +|雙子座3閃光|雙子座 3 閃光 | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | +|迷你最大M2.1 |極小極大-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| MiniMax M2.1 免費 | minimax-m2.1-免費 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | +| GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.7 免費 | glm-4.7-免費 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +|作為K2.5| as-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2.5 免費 | kimi-k2.5-免費 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Kimi K2 思考 | kimi-k2-思考 | kimi-k2-thinking | kimi-k2-thinking `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +|作為K2 | as-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +| Qwen3 編碼器 480B | qwen3-編碼器 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | +|大泡菜|大泡菜| `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | + +OpenCode 配置中的 [型號編號](/docs/config/#models) +使用格式`opencode/`。例如,對於 GPT 5.2 Codex,您將 +在您的配置中使用`opencode/gpt-5.2-codex`。 + +--- + +### 型號 + +您可以從以下位置獲取可用模型及其元數據的完整列表: + +``` +https://opencode.ai/zen/v1/models +``` + +--- + +## 定價 + +我們支持即用即付模式。以下是**每 100 萬代幣的價格**。 + +|型號|輸入 |輸出|緩存讀取 |緩存寫入| +| --------------------------------- | ------ | ------ | ----------- | ------------ | +|大泡菜|免費|免費|免費| - | +| MiniMax M2.1 免費 |免費|免費|免費| - | +|迷你最大M2.1 | 0.30 美元 | 1.20 美元 | 0.10 美元 | - | +| GLM 4.7 免費 |免費|免費|免費| - | +| GLM 4.7 | 0.60 美元 | 2.20 美元 | 0.10 美元 | - | +| GLM 4.6 | 0.60 美元 | 2.20 美元 | 0.10 美元 | - | +| Kimi K2.5 免費 |免費|免費|免費| - | +|作為K2.5| 0.60 美元 | $3.00 | 0.08 美元 | - | +| Kimi K2 思考 | 0.40 美元 | 2.50 美元 | - | - | +|作為K2 | 0.40 美元 | 2.50 美元 | - | - | +| Qwen3 編碼器 480B | 0.45 美元 | 1.50 美元 | - | - | +|克勞德十四行詩 4.5(≤ 200K 代幣)| $3.00 | 15.00 美元 | 0.30 美元 | 3.75 美元 | +| Claude Sonnet 4.5(> 200K 代幣)| 6.00 美元 | 22.50 美元 | 0.60 美元 | 7.50 美元 | +|克勞德十四行詩 4(≤ 200K 代幣)| $3.00 | 15.00 美元 | 0.30 美元 | 3.75 美元 | +|克勞德十四行詩 4(> 200K 代幣)| 6.00 美元 | 22.50 美元 | 0.60 美元 | 7.50 美元 | +|克勞德俳句 4.5 | 1.00 美元 | 5.00 美元 | 0.10 美元 | 1.25 美元 | +|克勞德俳句 3.5 | 0.80 美元 | 4.00 美元 | 0.08 美元 | 1.00 美元 | +| Claude Opus 4.6(≤ 200K 代幣)| 5.00 美元 | 25.00 美元 | 0.50 美元 | 6.25 美元 | +| Claude Opus 4.6(> 200K 代幣)| 10.00 美元 | 37.50 美元 | 1.00 美元 | 12.50 美元 | +|近距離工作4.5 | 5.00 美元 | 25.00 美元 | 0.50 美元 | 6.25 美元 | +|近距離工作4.1 | 15.00 美元 | 75.00 美元 | 1.50 美元 | 18.75 美元 | +| Gemini 3 Pro(≤ 200K 代幣)| 2.00 美元 | 12.00 美元 | 0.20 美元 | - | +| Gemini 3 Pro(> 200K 代幣)| 4.00 美元 | 18.00 美元 | 0.40 美元 | - | +|雙子座3閃光| 0.50 美元 | $3.00 | 0.05 美元 | - | +| GPT 5.2 | 1.75 美元 | 14.00 美元 | 0.175 美元 | - | +| GPT 5.2 法典 | 1.75 美元 | 14.00 美元 | 0.175 美元 | - | +| GPT 5.1 | 1.07 美元 | 8.50 美元 | 0.107 美元 | - | +| GPT 5.1 法典 | 1.07 美元 | 8.50 美元 | 0.107 美元 | - | +| GPT 5.1 法典最大 | 1.25 美元 | 10.00 美元 | 0.125 美元 | - | +| GPT 5.1 迷你版 | 0.25 美元 | 2.00 美元 | 0.025 美元 | - | +| GPT 5 | 1.07 美元 | 8.50 美元 | 0.107 美元 | - | +| GPT 5 法典 | 1.07 美元 | 8.50 美元 | 0.107 美元 | - | +| GPT 5 納米 |免費|免費|免費| - | + +您可能會在使用歷史記錄中註意到_Claude Haiku 3.5_。這是一個[低成本模式](/docs/config/#models),用於生成會話標題。 + +:::note +信用卡費用按成本轉嫁(4.4% + 每筆交易 0.30 美元);除此之外我們不收取任何費用。 +::: + +免費模型: + +- GLM 4.7 免費版在 OpenCode 上限時提供。團隊正在利用這段時間收集反饋並改進模型。 +- Kimi K2.5 Free 在 OpenCode 上限時提供。團隊正在利用這段時間收集反饋並改進模型。 +- MiniMax M2.1 免費版在 OpenCode 上限時提供。團隊正在利用這段時間收集反饋並改進模型。 +- Big Pickle 是一個秘密模型,在 OpenCode 上限時免費。團隊正在利用這段時間收集反饋並改進模型。 + +如果您有任何疑問,請聯繫我們。 + +--- + +### 自動重新加載 + +如果您的餘額低於 5 美元,Zen 將自動充值 20 美元。 + +您可以更改自動充值金額。您還可以完全禁用自動重新加載。 + +--- + +### 每月限額 + +您還可以為整個工作區和每個工作區設置每月使用限制 +你的團隊的成員。 + +例如,假設您將每月使用限額設置為 20 美元,Zen 將不會使用 +一個月超過20美元。但如果你啟用了自動重新加載,Zen 可能會結束 +如果您的餘額低於 5 美元,則向您收取超過 20 美元的費用。 + +--- + +## 隱私 + +我們所有的模型都在美國託管。我們的提供商遵循零保留政策,不會將您的數據用於模型訓練,但以下情況除外: + +- Big Pickle:在免費期間,收集的數據可用於改進模型。 +- GLM 4.7 免費:在免費期間,收集的數據可用於改進模型。 +- Kimi K2.5 免費:在免費期間,收集的數據可用於改進模型。 +- MiniMax M2.1 免費:在免費期間,收集的數據可用於改進模型。 +- OpenAI API:根據[OpenAI 的數據政策](https://platform.openai.com/docs/guides/your-data),請求將保留 30 天。 +- Anthropic API:根據[Anthropic 的數據政策](https://docs.anthropic.com/en/docs/claude-code/data-usage),請求將保留 30 天。 + +--- + +## 對於團隊 + +Zen 對團隊也很有效。您可以邀請隊友、分配角色、策劃 +您的團隊使用的模型等等。 + +:::note +作為測試版的一部分,工作空間目前對團隊免費。 +::: + +作為測試版的一部分,管理工作空間目前對團隊免費。我們將會 +很快就會分享更多有關定價的細節。 + +--- + +### 角色 + +您可以邀請團隊成員到您的工作區並分配角色: + +- **管理員**:管理模型、成員、API 密鑰和計費 +- **成員**:僅管理自己的 API 密鑰 + +管理員還可以為每個成員設置每月支出限額,以控製成本。 + +--- + +### 模型訪問 + +管理員可以啟用或禁用工作區的特定模型。對禁用模型發出的請求將返回錯誤。 + +這對於您想要禁用以下模型的情況很有用: +收集數據。 + +--- + +### 帶上你自己的鑰匙 + +您可以使用自己的 OpenAI 或 Anthropic API 密鑰,同時仍然訪問 Zen 中的其他模型。 + +當您使用自己的密鑰時,令牌將由提供商直接計費,而不是由 Zen。 + +例如,您的組織可能已經擁有 OpenAI 或 Anthropic 的密鑰 +你想使用它而不是 Zen 提供的。 + +--- + +## 目標 + +我們創建 OpenCode Zen 的目的是: + +1. **對標**編碼代理的最佳模型/提供商。 +2. 可以使用**最高質量**選項,而不是降低性能或轉向更便宜的提供商。 +3. 通過按成本價銷售來傳遞任何**價格下跌**;所以唯一的加價就是支付我們的加工費。 +4. 通過允許您將其與任何其他編碼代理一起使用,**無鎖定**。並且始終允許您將任何其他提供程序與 OpenCode 一起使用。 diff --git a/packages/web/src/content/i18n/ar.json b/packages/web/src/content/i18n/ar.json new file mode 100644 index 000000000..9f9845e3f --- /dev/null +++ b/packages/web/src/content/i18n/ar.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "وكيل برمجة بالذكاء الاصطناعي مصمم للطرفية", + "app.header.home": "الرئيسية", + "app.header.docs": "التوثيق", + "app.footer.issueLink": "وجدت خطأ؟ افتح بلاغا", + "app.footer.discordLink": "انضم إلى مجتمع Discord الخاص بنا", + "app.lander.hero.title": "وكيل البرمجة بالذكاء الاصطناعي المصمم للطرفية.", + "app.lander.cta.getStarted": "ابدأ الآن", + "app.lander.features.native_tui.title": "TUI أصلي", + "app.lander.features.native_tui.description": "واجهة طرفية أصلية، سريعة الاستجابة، وقابلة للتخصيص.", + "app.lander.features.lsp_enabled.title": "يدعم LSP", + "app.lander.features.lsp_enabled.description": "يحمّل تلقائيا خوادم LSP المناسبة لـ LLM.", + "app.lander.features.multi_session.title": "جلسات متعددة", + "app.lander.features.multi_session.description": "شغّل عدة وكلاء بالتوازي على نفس المشروع.", + "app.lander.features.shareable_links.title": "روابط قابلة للمشاركة", + "app.lander.features.shareable_links.description": "شارك رابطا لأي جلسة للرجوع إليها أو لتصحيح الأخطاء.", + "app.lander.features.github_copilot.description": "سجّل الدخول عبر GitHub لاستخدام حساب Copilot الخاص بك.", + "app.lander.features.chatgpt_plus_pro.description": "سجّل الدخول عبر OpenAI لاستخدام حساب ChatGPT Plus أو Pro.", + "app.lander.features.use_any_model.title": "استخدم أي نموذج", + "app.lander.features.use_any_model.prefix": "يدعم أكثر من 75 مزودا لـ LLM عبر", + "app.lander.features.use_any_model.suffix": "بما في ذلك النماذج المحلية.", + "app.lander.images.tui.caption": "opencode TUI مع سمة tokyonight", + "app.lander.images.tui.alt": "opencode TUI مع سمة tokyonight", + "app.lander.images.vscode.caption": "opencode في VS Code", + "app.lander.images.vscode.alt": "opencode في VS Code", + "app.lander.images.github.caption": "opencode في GitHub", + "app.lander.images.github.alt": "opencode في GitHub", + "share.meta_description": "opencode - وكيل البرمجة بالذكاء الاصطناعي المصمم للطرفية.", + "share.not_found": "غير موجود", + "share.link_to_message": "رابط إلى هذه الرسالة", + "share.copied": "تم النسخ!", + "share.copy": "نسخ", + "share.show_more": "عرض المزيد", + "share.show_less": "عرض أقل", + "share.show_results": "عرض النتائج", + "share.hide_results": "إخفاء النتائج", + "share.show_details": "عرض التفاصيل", + "share.hide_details": "إخفاء التفاصيل", + "share.show_preview": "عرض المعاينة", + "share.hide_preview": "إخفاء المعاينة", + "share.show_contents": "عرض المحتويات", + "share.hide_contents": "إخفاء المحتويات", + "share.show_output": "عرض المخرجات", + "share.hide_output": "إخفاء المخرجات", + "share.error": "خطأ", + "share.waiting_for_messages": "بانتظار الرسائل...", + "share.status_connected_waiting": "متصل، بانتظار الرسائل...", + "share.status_connecting": "جارٍ الاتصال...", + "share.status_disconnected": "غير متصل", + "share.status_reconnecting": "جارٍ إعادة الاتصال...", + "share.status_error": "خطأ", + "share.status_unknown": "غير معروف", + "share.error_id_not_found": "لم يتم العثور على id", + "share.error_api_url_not_found": "لم يتم العثور على API URL", + "share.error_connection_failed": "فشل الاتصال", + "share.opencode_version": "إصدار opencode", + "share.opencode_name": "opencode", + "share.models": "النماذج", + "share.cost": "التكلفة", + "share.input_tokens": "رموز الإدخال", + "share.output_tokens": "رموز الإخراج", + "share.reasoning_tokens": "رموز الاستدلال", + "share.scroll_to_bottom": "التمرير إلى الأسفل", + "share.attachment": "مرفق", + "share.thinking": "تفكير", + "share.thinking_pending": "جارٍ التفكير...", + "share.creating_plan": "جارٍ إنشاء الخطة", + "share.completing_plan": "جارٍ إكمال الخطة", + "share.updating_plan": "جارٍ تحديث الخطة", + "share.match_one": "مطابقة", + "share.match_other": "مطابقات", + "share.result_one": "نتيجة", + "share.result_other": "نتائج", + "share.debug_key": "المفتاح" +} diff --git a/packages/web/src/content/i18n/bs.json b/packages/web/src/content/i18n/bs.json new file mode 100644 index 000000000..bac324367 --- /dev/null +++ b/packages/web/src/content/i18n/bs.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "Agent za AI kodiranje napravljen za terminal", + "app.header.home": "Dom", + "app.header.docs": "Docs", + "app.footer.issueLink": "Pronašli ste grešku? Otvorite issue", + "app.footer.discordLink": "Pridružite se našoj Discord zajednici", + "app.lander.hero.title": "Agent za AI kodiranje napravljen za terminal.", + "app.lander.cta.getStarted": "Započnite", + "app.lander.features.native_tui.title": "Native TUI", + "app.lander.features.native_tui.description": "Prilagodljivo, izvorno, tematsko korisničko sučelje terminala.", + "app.lander.features.lsp_enabled.title": "LSP omogućen", + "app.lander.features.lsp_enabled.description": "Automatski učitava ispravne LSP-ove za LLM.", + "app.lander.features.multi_session.title": "Više sesija", + "app.lander.features.multi_session.description": "Pokrenite više agenata paralelno na istom projektu.", + "app.lander.features.shareable_links.title": "Linkovi za dijeljenje", + "app.lander.features.shareable_links.description": "Podijelite vezu do bilo koje sesije za referencu ili za otklanjanje grešaka.", + "app.lander.features.github_copilot.description": "Prijavite se na GitHub da koristite svoj Copilot nalog.", + "app.lander.features.chatgpt_plus_pro.description": "Prijavite se na OpenAI da biste koristili svoj ChatGPT Plus ili Pro nalog.", + "app.lander.features.use_any_model.title": "Koristite bilo koji model", + "app.lander.features.use_any_model.prefix": "Podržava 75+ LLM provajdera", + "app.lander.features.use_any_model.suffix": "uključujući lokalne modele.", + "app.lander.images.tui.caption": "opencode TUI u tokyonight temi", + "app.lander.images.tui.alt": "opencode TUI u tokyonight temi", + "app.lander.images.vscode.caption": "opencode u VS kodu", + "app.lander.images.vscode.alt": "opencode u VS kodu", + "app.lander.images.github.caption": "opencode u GitHubu", + "app.lander.images.github.alt": "opencode u GitHubu", + "share.meta_description": "opencode - AI agent za kodiranje napravljen za terminal.", + "share.not_found": "Nije pronađeno", + "share.link_to_message": "Link do ove poruke", + "share.copied": "Kopirano!", + "share.copy": "Kopiraj", + "share.show_more": "Pokaži više", + "share.show_less": "Prikaži manje", + "share.show_results": "Prikaži rezultate", + "share.hide_results": "Sakrij rezultate", + "share.show_details": "Prikaži detalje", + "share.hide_details": "Sakrij detalje", + "share.show_preview": "Prikaži pregled", + "share.hide_preview": "Sakrij pregled", + "share.show_contents": "Prikaži sadržaj", + "share.hide_contents": "Sakrij sadržaj", + "share.show_output": "Prikaži izlaz", + "share.hide_output": "Sakrij izlaz", + "share.error": "Greška", + "share.waiting_for_messages": "Čekaju se poruke...", + "share.status_connected_waiting": "Povezano, čekam poruke...", + "share.status_connecting": "Povezivanje...", + "share.status_disconnected": "Isključeno", + "share.status_reconnecting": "Ponovno povezivanje...", + "share.status_error": "Greška", + "share.status_unknown": "Nepoznato", + "share.error_id_not_found": "id nije pronađen", + "share.error_api_url_not_found": "API URL nije pronađen", + "share.error_connection_failed": "Povezivanje nije uspjelo", + "share.opencode_version": "opencode verzija", + "share.opencode_name": "opencode", + "share.models": "Model", + "share.cost": "Troškovi", + "share.input_tokens": "Input Tokens", + "share.output_tokens": "Izlazni tokeni", + "share.reasoning_tokens": "Reasoning Tokens", + "share.scroll_to_bottom": "Skrolujte do dna", + "share.attachment": "Prilog", + "share.thinking": "Reflections", + "share.thinking_pending": "mislim...", + "share.creating_plan": "Kreiranje plana", + "share.completing_plan": "Završavanje plana", + "share.updating_plan": "Ažuriranje plana", + "share.match_one": "match", + "share.match_other": "utakmice", + "share.result_one": "rezultat", + "share.result_other": "rezultat", + "share.debug_key": "Ključ" +} diff --git a/packages/web/src/content/i18n/da.json b/packages/web/src/content/i18n/da.json new file mode 100644 index 000000000..bffc34ab6 --- /dev/null +++ b/packages/web/src/content/i18n/da.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "AI-kodningsagent bygget til terminalen", + "app.header.home": "Hjem", + "app.header.docs": "Dokumenter", + "app.footer.issueLink": "Har du fundet en fejl? Opret en issue", + "app.footer.discordLink": "Bliv en del af vores Discord-fællesskab", + "app.lander.hero.title": "AI-kodningsagenten bygget til terminalen.", + "app.lander.cta.getStarted": "Kom i gang", + "app.lander.features.native_tui.title": "Native TUI", + "app.lander.features.native_tui.description": "En responsiv, indbygget, temavenlig terminal-brugergrænseflade.", + "app.lander.features.lsp_enabled.title": "LSP aktiveret", + "app.lander.features.lsp_enabled.description": "Indlæser automatisk de rigtige LSPs for LLM.", + "app.lander.features.multi_session.title": "Multi-session", + "app.lander.features.multi_session.description": "Start flere agenter parallelt på det samme projekt.", + "app.lander.features.shareable_links.title": "Delbare links", + "app.lander.features.shareable_links.description": "Del et link til enhver session til reference eller til fejlretning.", + "app.lander.features.github_copilot.description": "Log ind med GitHub for at bruge din Copilot konto.", + "app.lander.features.chatgpt_plus_pro.description": "Log ind med OpenAI for at bruge din ChatGPT Plus eller Pro-konto.", + "app.lander.features.use_any_model.title": "Brug enhver model", + "app.lander.features.use_any_model.prefix": "Understøtter 75+ LLM udbydere igennem", + "app.lander.features.use_any_model.suffix": "herunder lokale modeller.", + "app.lander.images.tui.caption": "opencode TUI med tokyonight-temaet", + "app.lander.images.tui.alt": "opencode TUI med tokyonight-temaet", + "app.lander.images.vscode.caption": "opencode og VS Code", + "app.lander.images.vscode.alt": "opencode og VS Code", + "app.lander.images.github.caption": "opencode og GitHub", + "app.lander.images.github.alt": "opencode og GitHub", + "share.meta_description": "opencode - AI-kodningsagenten bygget til terminalen.", + "share.not_found": "Ikke fundet", + "share.link_to_message": "Link til denne besked", + "share.copied": "Kopieret!", + "share.copy": "Kopi", + "share.show_more": "Vis mere", + "share.show_less": "Vis mindre", + "share.show_results": "Vis resultater", + "share.hide_results": "Skjul resultater", + "share.show_details": "Vis detaljer", + "share.hide_details": "Skjul detaljer", + "share.show_preview": "Vis forhåndsvisning", + "share.hide_preview": "Skjul forhåndsvisning", + "share.show_contents": "Vis indhold", + "share.hide_contents": "Skjul indhold", + "share.show_output": "Vis output", + "share.hide_output": "Skjul output", + "share.error": "Fejl", + "share.waiting_for_messages": "Venter på beskeder...", + "share.status_connected_waiting": "Forbundet, venter på beskeder...", + "share.status_connecting": "Opretter forbindelse...", + "share.status_disconnected": "Afbrudt", + "share.status_reconnecting": "Genopretter forbindelse...", + "share.status_error": "Fejl", + "share.status_unknown": "Ukendt", + "share.error_id_not_found": "id ikke fundet", + "share.error_api_url_not_found": "API URL ikke fundet", + "share.error_connection_failed": "Forbindelsen mislykkedes", + "share.opencode_version": "opencode version", + "share.opencode_name": "opencode", + "share.models": "Modeller", + "share.cost": "Koste", + "share.input_tokens": "Indtast tokens", + "share.output_tokens": "Output tokens", + "share.reasoning_tokens": "Ræsonneringstegn", + "share.scroll_to_bottom": "Rul til bunden", + "share.attachment": "Vedhæftet fil", + "share.thinking": "Tænker", + "share.thinking_pending": "Tænker...", + "share.creating_plan": "Oprettelse af plan", + "share.completing_plan": "Færdiggør plan", + "share.updating_plan": "Opdatering af plan", + "share.match_one": "kamp", + "share.match_other": "kampe", + "share.result_one": "resultat", + "share.result_other": "resultater", + "share.debug_key": "Nøgle" +} diff --git a/packages/web/src/content/i18n/de.json b/packages/web/src/content/i18n/de.json new file mode 100644 index 000000000..0ec852b2c --- /dev/null +++ b/packages/web/src/content/i18n/de.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "AI Codierungsagent, der für das Terminal erstellt wurde", + "app.header.home": "Heim", + "app.header.docs": "Dokumente", + "app.footer.issueLink": "Einen Fehler gefunden? Eröffne ein Issue", + "app.footer.discordLink": "Tritt unserer Discord-Community bei", + "app.lander.hero.title": "Der für das Terminal erstellte Codierungsagent AI.", + "app.lander.cta.getStarted": "Legen Sie los", + "app.lander.features.native_tui.title": "Native TUI", + "app.lander.features.native_tui.description": "Ein reaktionsfähiges, natives, thematisch anpassbares Terminal UI.", + "app.lander.features.lsp_enabled.title": "LSP aktiviert", + "app.lander.features.lsp_enabled.description": "Lädt automatisch den richtigen LSPs für LLM.", + "app.lander.features.multi_session.title": "Mehrfachsitzung", + "app.lander.features.multi_session.description": "Starten Sie mehrere Agenten parallel für dasselbe Projekt.", + "app.lander.features.shareable_links.title": "Gemeinsam nutzbare Links", + "app.lander.features.shareable_links.description": "Teilen Sie einen Link zu beliebigen Sitzungen als Referenz oder zum Debuggen.", + "app.lander.features.github_copilot.description": "Melden Sie sich bei GitHub an, um Ihr Copilot-Konto zu verwenden.", + "app.lander.features.chatgpt_plus_pro.description": "Melden Sie sich mit OpenAI an, um Ihr ChatGPT Plus- oder Pro-Konto zu verwenden.", + "app.lander.features.use_any_model.title": "Verwenden Sie ein beliebiges Modell", + "app.lander.features.use_any_model.prefix": "Unterstützt 75+ LLM Anbieter durch", + "app.lander.features.use_any_model.suffix": "einschließlich lokaler Modelle.", + "app.lander.images.tui.caption": "Opencode TUI mit dem Tokyonight-Thema", + "app.lander.images.tui.alt": "Opencode TUI mit dem Tokyonight-Thema", + "app.lander.images.vscode.caption": "Opencode im VS-Code", + "app.lander.images.vscode.alt": "Opencode im VS-Code", + "app.lander.images.github.caption": "Opencode in GitHub", + "app.lander.images.github.alt": "Opencode in GitHub", + "share.meta_description": "opencode – Der für das Terminal erstellte AI-Codierungsagent.", + "share.not_found": "Nicht gefunden", + "share.link_to_message": "Link zu dieser Nachricht", + "share.copied": "Kopiert!", + "share.copy": "Kopie", + "share.show_more": "Mehr anzeigen", + "share.show_less": "Weniger anzeigen", + "share.show_results": "Ergebnisse anzeigen", + "share.hide_results": "Ergebnisse ausblenden", + "share.show_details": "Details anzeigen", + "share.hide_details": "Details ausblenden", + "share.show_preview": "Vorschau anzeigen", + "share.hide_preview": "Vorschau ausblenden", + "share.show_contents": "Inhalte anzeigen", + "share.hide_contents": "Inhalte ausblenden", + "share.show_output": "Ausgabe anzeigen", + "share.hide_output": "Ausgabe ausblenden", + "share.error": "Fehler", + "share.waiting_for_messages": "Warten auf Nachrichten...", + "share.status_connected_waiting": "Verbunden, warte auf Nachrichten...", + "share.status_connecting": "Verbinden...", + "share.status_disconnected": "Getrennt", + "share.status_reconnecting": "Verbindung wird wieder hergestellt...", + "share.status_error": "Fehler", + "share.status_unknown": "Unbekannt", + "share.error_id_not_found": "ID nicht gefunden", + "share.error_api_url_not_found": "API URL nicht gefunden", + "share.error_connection_failed": "Verbindung fehlgeschlagen", + "share.opencode_version": "Opencode-Version", + "share.opencode_name": "Opencode", + "share.models": "Modelle", + "share.cost": "Kosten", + "share.input_tokens": "Eingabetoken", + "share.output_tokens": "Ausgabetoken", + "share.reasoning_tokens": "Argumentationsmarken", + "share.scroll_to_bottom": "Scrollen Sie nach unten", + "share.attachment": "Anhang", + "share.thinking": "Denken", + "share.thinking_pending": "Denken...", + "share.creating_plan": "Plan erstellen", + "share.completing_plan": "Abschlussplan", + "share.updating_plan": "Aktualisierungsplan", + "share.match_one": "übereinstimmend", + "share.match_other": "Streichhölzer", + "share.result_one": "Ergebnis", + "share.result_other": "Ergebnisse", + "share.debug_key": "Schlüssel" +} diff --git a/packages/web/src/content/i18n/en.json b/packages/web/src/content/i18n/en.json new file mode 100644 index 000000000..fedb70a6c --- /dev/null +++ b/packages/web/src/content/i18n/en.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "AI coding agent built for the terminal", + "app.header.home": "Home", + "app.header.docs": "Docs", + "app.footer.issueLink": "Found a bug? Open an issue", + "app.footer.discordLink": "Join our Discord community", + "app.lander.hero.title": "The AI coding agent built for the terminal.", + "app.lander.cta.getStarted": "Get Started", + "app.lander.features.native_tui.title": "Native TUI", + "app.lander.features.native_tui.description": "A responsive, native, themeable terminal UI.", + "app.lander.features.lsp_enabled.title": "LSP enabled", + "app.lander.features.lsp_enabled.description": "Automatically loads the right LSPs for the LLM.", + "app.lander.features.multi_session.title": "Multi-session", + "app.lander.features.multi_session.description": "Start multiple agents in parallel on the same project.", + "app.lander.features.shareable_links.title": "Shareable links", + "app.lander.features.shareable_links.description": "Share a link to any sessions for reference or to debug.", + "app.lander.features.github_copilot.description": "Log in with GitHub to use your Copilot account.", + "app.lander.features.chatgpt_plus_pro.description": "Log in with OpenAI to use your ChatGPT Plus or Pro account.", + "app.lander.features.use_any_model.title": "Use any model", + "app.lander.features.use_any_model.prefix": "Supports 75+ LLM providers through", + "app.lander.features.use_any_model.suffix": "including local models.", + "app.lander.images.tui.caption": "opencode TUI with the tokyonight theme", + "app.lander.images.tui.alt": "opencode TUI with the tokyonight theme", + "app.lander.images.vscode.caption": "opencode in VS Code", + "app.lander.images.vscode.alt": "opencode in VS Code", + "app.lander.images.github.caption": "opencode in GitHub", + "app.lander.images.github.alt": "opencode in GitHub", + "share.meta_description": "opencode - The AI coding agent built for the terminal.", + "share.not_found": "Not found", + "share.link_to_message": "Link to this message", + "share.copied": "Copied!", + "share.copy": "Copy", + "share.show_more": "Show more", + "share.show_less": "Show less", + "share.show_results": "Show results", + "share.hide_results": "Hide results", + "share.show_details": "Show details", + "share.hide_details": "Hide details", + "share.show_preview": "Show preview", + "share.hide_preview": "Hide preview", + "share.show_contents": "Show contents", + "share.hide_contents": "Hide contents", + "share.show_output": "Show output", + "share.hide_output": "Hide output", + "share.error": "Error", + "share.waiting_for_messages": "Waiting for messages...", + "share.status_connected_waiting": "Connected, waiting for messages...", + "share.status_connecting": "Connecting...", + "share.status_disconnected": "Disconnected", + "share.status_reconnecting": "Reconnecting...", + "share.status_error": "Error", + "share.status_unknown": "Unknown", + "share.error_id_not_found": "id not found", + "share.error_api_url_not_found": "API URL not found", + "share.error_connection_failed": "Connection failed", + "share.opencode_version": "opencode version", + "share.opencode_name": "opencode", + "share.models": "Models", + "share.cost": "Cost", + "share.input_tokens": "Input Tokens", + "share.output_tokens": "Output Tokens", + "share.reasoning_tokens": "Reasoning Tokens", + "share.scroll_to_bottom": "Scroll to bottom", + "share.attachment": "Attachment", + "share.thinking": "Thinking", + "share.thinking_pending": "Thinking...", + "share.creating_plan": "Creating plan", + "share.completing_plan": "Completing plan", + "share.updating_plan": "Updating plan", + "share.match_one": "match", + "share.match_other": "matches", + "share.result_one": "result", + "share.result_other": "results", + "share.debug_key": "Key" +} diff --git a/packages/web/src/content/i18n/es.json b/packages/web/src/content/i18n/es.json new file mode 100644 index 000000000..c845cff95 --- /dev/null +++ b/packages/web/src/content/i18n/es.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "Agente de codificación de IA creado para la terminal", + "app.header.home": "Hogar", + "app.header.docs": "Documentos", + "app.footer.issueLink": "¿Encontraste un error? Abre una incidencia", + "app.footer.discordLink": "Únete a nuestra comunidad de Discord", + "app.lander.hero.title": "El agente de codificación de IA creado para la terminal.", + "app.lander.cta.getStarted": "Empezar", + "app.lander.features.native_tui.title": "Nativo TUI", + "app.lander.features.native_tui.description": "Una interfaz de usuario de terminal responsiva, nativa y temática.", + "app.lander.features.lsp_enabled.title": "LSP habilitado", + "app.lander.features.lsp_enabled.description": "Carga automáticamente los LSP correctos para LLM.", + "app.lander.features.multi_session.title": "Multisesión", + "app.lander.features.multi_session.description": "Inicie varios agentes en paralelo en el mismo proyecto.", + "app.lander.features.shareable_links.title": "Enlaces para compartir", + "app.lander.features.shareable_links.description": "Comparta un enlace a cualquier sesión como referencia o para depurar.", + "app.lander.features.github_copilot.description": "Inicie sesión con GitHub para usar su cuenta Copilot.", + "app.lander.features.chatgpt_plus_pro.description": "Inicie sesión con OpenAI para usar su cuenta ChatGPT Plus o Pro.", + "app.lander.features.use_any_model.title": "Usa cualquier modelo", + "app.lander.features.use_any_model.prefix": "Admite más de 75 proveedores LLM a través de", + "app.lander.features.use_any_model.suffix": "incluyendo modelos locales.", + "app.lander.images.tui.caption": "opencode TUI con el tema tokyonight", + "app.lander.images.tui.alt": "opencode TUI con el tema tokyonight", + "app.lander.images.vscode.caption": "opencode en VS Code", + "app.lander.images.vscode.alt": "opencode en VS Code", + "app.lander.images.github.caption": "opencode en GitHub", + "app.lander.images.github.alt": "opencode en GitHub", + "share.meta_description": "opencode: el agente de codificación de IA creado para el terminal.", + "share.not_found": "Extraviado", + "share.link_to_message": "Enlace a este mensaje", + "share.copied": "¡Copiado!", + "share.copy": "Copiar", + "share.show_more": "Mostrar más", + "share.show_less": "Mostrar menos", + "share.show_results": "Mostrar resultados", + "share.hide_results": "Ocultar resultados", + "share.show_details": "Mostrar detalles", + "share.hide_details": "Ocultar detalles", + "share.show_preview": "Mostrar vista previa", + "share.hide_preview": "Ocultar vista previa", + "share.show_contents": "Mostrar contenidos", + "share.hide_contents": "Ocultar contenidos", + "share.show_output": "Mostrar salida", + "share.hide_output": "Ocultar salida", + "share.error": "Error", + "share.waiting_for_messages": "Esperando mensajes...", + "share.status_connected_waiting": "Conectado, esperando mensajes...", + "share.status_connecting": "Conectando...", + "share.status_disconnected": "Desconectado", + "share.status_reconnecting": "Reconectando...", + "share.status_error": "Error", + "share.status_unknown": "Desconocido", + "share.error_id_not_found": "no encontrado", + "share.error_api_url_not_found": "API URL no encontrada", + "share.error_connection_failed": "La conexión falló", + "share.opencode_version": "Versión opencode", + "share.opencode_name": "opencode", + "share.models": "Modelos", + "share.cost": "Costo", + "share.input_tokens": "Fichas de entrada", + "share.output_tokens": "Fichas de salida", + "share.reasoning_tokens": "Fichas de razonamiento", + "share.scroll_to_bottom": "Desplazarse hacia abajo", + "share.attachment": "Adjunto", + "share.thinking": "Pensamiento", + "share.thinking_pending": "Pensamiento...", + "share.creating_plan": "Creando plan", + "share.completing_plan": "Completando el plan", + "share.updating_plan": "Plan de actualización", + "share.match_one": "fósforo", + "share.match_other": "partidos", + "share.result_one": "resultado", + "share.result_other": "resultados", + "share.debug_key": "Llave" +} diff --git a/packages/web/src/content/i18n/fr.json b/packages/web/src/content/i18n/fr.json new file mode 100644 index 000000000..607998c2d --- /dev/null +++ b/packages/web/src/content/i18n/fr.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "Agent de codage IA conçu pour le terminal", + "app.header.home": "Accueil", + "app.header.docs": "Docs", + "app.footer.issueLink": "Vous avez trouvé un bug ? Ouvrez une issue", + "app.footer.discordLink": "Rejoignez notre communauté Discord", + "app.lander.hero.title": "L'agent de codage IA conçu pour le terminal.", + "app.lander.cta.getStarted": "Commencer", + "app.lander.features.native_tui.title": "Natif TUI", + "app.lander.features.native_tui.description": "Une interface utilisateur de terminal réactive, native et thématique.", + "app.lander.features.lsp_enabled.title": "LSP activé", + "app.lander.features.lsp_enabled.description": "Charge automatiquement les bons LSP pour le LLM.", + "app.lander.features.multi_session.title": "Multi-session", + "app.lander.features.multi_session.description": "Démarrez plusieurs agents en parallèle sur le même projet.", + "app.lander.features.shareable_links.title": "Liens partageables", + "app.lander.features.shareable_links.description": "Partagez un lien vers n’importe quelle session pour référence ou pour déboguer.", + "app.lander.features.github_copilot.description": "Connectez-vous avec GitHub pour utiliser votre compte Copilot.", + "app.lander.features.chatgpt_plus_pro.description": "Connectez-vous avec OpenAI pour utiliser votre compte ChatGPT Plus ou Pro.", + "app.lander.features.use_any_model.title": "Utilisez n'importe quel modèle", + "app.lander.features.use_any_model.prefix": "Prend en charge plus de 75 fournisseurs LLM via", + "app.lander.features.use_any_model.suffix": "y compris des modèles locaux.", + "app.lander.images.tui.caption": "opencode TUI avec le thème tokyonight", + "app.lander.images.tui.alt": "opencode TUI avec le thème tokyonight", + "app.lander.images.vscode.caption": "OpenCode dans VS Code", + "app.lander.images.vscode.alt": "OpenCode dans VS Code", + "app.lander.images.github.caption": "OpenCode dans GitHub", + "app.lander.images.github.alt": "OpenCode dans GitHub", + "share.meta_description": "opencode - L'agent de codage AI conçu pour le terminal.", + "share.not_found": "Pas trouvé", + "share.link_to_message": "Lien vers ce message", + "share.copied": "Copié!", + "share.copy": "Copie", + "share.show_more": "Afficher plus", + "share.show_less": "Afficher moins", + "share.show_results": "Afficher les résultats", + "share.hide_results": "Masquer les résultats", + "share.show_details": "Afficher les détails", + "share.hide_details": "Masquer les détails", + "share.show_preview": "Afficher l'aperçu", + "share.hide_preview": "Masquer l'aperçu", + "share.show_contents": "Afficher le contenu", + "share.hide_contents": "Masquer le contenu", + "share.show_output": "Afficher la sortie", + "share.hide_output": "Masquer la sortie", + "share.error": "Erreur", + "share.waiting_for_messages": "En attente de messages...", + "share.status_connected_waiting": "Connecté, en attente de messages...", + "share.status_connecting": "Connexion...", + "share.status_disconnected": "Déconnecté", + "share.status_reconnecting": "Reconnexion...", + "share.status_error": "Erreur", + "share.status_unknown": "Inconnu", + "share.error_id_not_found": "id introuvable", + "share.error_api_url_not_found": "API URL introuvable", + "share.error_connection_failed": "La connexion a échoué", + "share.opencode_version": "version d'opencode", + "share.opencode_name": "opencode", + "share.models": "Modèles", + "share.cost": "Coût", + "share.input_tokens": "Jetons d'entrée", + "share.output_tokens": "Jetons de sortie", + "share.reasoning_tokens": "Jetons de raisonnement", + "share.scroll_to_bottom": "Faire défiler vers le bas", + "share.attachment": "Pièce jointe", + "share.thinking": "Pensée", + "share.thinking_pending": "Pensée...", + "share.creating_plan": "Créer un plan", + "share.completing_plan": "Terminer le plan", + "share.updating_plan": "Plan de mise à jour", + "share.match_one": "correspondre", + "share.match_other": "matchs", + "share.result_one": "résultat", + "share.result_other": "résultats", + "share.debug_key": "Clé" +} diff --git a/packages/web/src/content/i18n/it.json b/packages/web/src/content/i18n/it.json new file mode 100644 index 000000000..20594dd6a --- /dev/null +++ b/packages/web/src/content/i18n/it.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "Agente AI di coding creato per il terminale", + "app.header.home": "Home", + "app.header.docs": "Documentazione", + "app.footer.issueLink": "Hai trovato un bug? Apri una issue", + "app.footer.discordLink": "Unisciti alla nostra community Discord", + "app.lander.hero.title": "L'agente AI di coding creato per il terminale.", + "app.lander.cta.getStarted": "Inizia", + "app.lander.features.native_tui.title": "TUI nativa", + "app.lander.features.native_tui.description": "Un'interfaccia terminale reattiva, nativa e personalizzabile.", + "app.lander.features.lsp_enabled.title": "LSP abilitato", + "app.lander.features.lsp_enabled.description": "Carica automaticamente gli LSP corretti per l'LLM.", + "app.lander.features.multi_session.title": "Multi-sessione", + "app.lander.features.multi_session.description": "Avvia più agenti in parallelo sullo stesso progetto.", + "app.lander.features.shareable_links.title": "Link condivisibili", + "app.lander.features.shareable_links.description": "Condividi un link a qualsiasi sessione per riferimento o debug.", + "app.lander.features.github_copilot.description": "Accedi con GitHub per usare il tuo account Copilot.", + "app.lander.features.chatgpt_plus_pro.description": "Accedi con OpenAI per usare il tuo account ChatGPT Plus o Pro.", + "app.lander.features.use_any_model.title": "Usa qualsiasi modello", + "app.lander.features.use_any_model.prefix": "Supporta oltre 75 provider LLM tramite", + "app.lander.features.use_any_model.suffix": "inclusi i modelli locali.", + "app.lander.images.tui.caption": "TUI di opencode con il tema tokyonight", + "app.lander.images.tui.alt": "TUI di opencode con il tema tokyonight", + "app.lander.images.vscode.caption": "opencode in VS Code", + "app.lander.images.vscode.alt": "opencode in VS Code", + "app.lander.images.github.caption": "opencode in GitHub", + "app.lander.images.github.alt": "opencode in GitHub", + "share.meta_description": "opencode - L'agente AI di coding creato per il terminale.", + "share.not_found": "Non trovato", + "share.link_to_message": "Link a questo messaggio", + "share.copied": "Copiato!", + "share.copy": "Copia", + "share.show_more": "Mostra altro", + "share.show_less": "Mostra meno", + "share.show_results": "Mostra risultati", + "share.hide_results": "Nascondi risultati", + "share.show_details": "Mostra dettagli", + "share.hide_details": "Nascondi dettagli", + "share.show_preview": "Mostra anteprima", + "share.hide_preview": "Nascondi anteprima", + "share.show_contents": "Mostra contenuto", + "share.hide_contents": "Nascondi contenuto", + "share.show_output": "Mostra output", + "share.hide_output": "Nascondi output", + "share.error": "Errore", + "share.waiting_for_messages": "In attesa di messaggi...", + "share.status_connected_waiting": "Connesso, in attesa di messaggi...", + "share.status_connecting": "Connessione in corso...", + "share.status_disconnected": "Disconnesso", + "share.status_reconnecting": "Riconnessione in corso...", + "share.status_error": "Errore", + "share.status_unknown": "Sconosciuto", + "share.error_id_not_found": "id non trovato", + "share.error_api_url_not_found": "URL API non trovato", + "share.error_connection_failed": "Connessione non riuscita", + "share.opencode_version": "opencode version", + "share.opencode_name": "opencode", + "share.models": "Modelli", + "share.cost": "Costo", + "share.input_tokens": "Token di input", + "share.output_tokens": "Token di output", + "share.reasoning_tokens": "Token di ragionamento", + "share.scroll_to_bottom": "Scorri in basso", + "share.attachment": "Allegato", + "share.thinking": "Elaborazione", + "share.thinking_pending": "Elaborazione...", + "share.creating_plan": "Creazione piano", + "share.completing_plan": "Completamento piano", + "share.updating_plan": "Aggiornamento piano", + "share.match_one": "corrispondenza", + "share.match_other": "corrispondenze", + "share.result_one": "risultato", + "share.result_other": "risultati", + "share.debug_key": "Chiave" +} diff --git a/packages/web/src/content/i18n/ja.json b/packages/web/src/content/i18n/ja.json new file mode 100644 index 000000000..f9139f61e --- /dev/null +++ b/packages/web/src/content/i18n/ja.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "端末向けに構築されたAIコーディングエージェント", + "app.header.home": "家", + "app.header.docs": "ドキュメント", + "app.footer.issueLink": "バグを見つけましたか?Issueを作成", + "app.footer.discordLink": "Discordコミュニティに参加", + "app.lander.hero.title": "端末用に構築された AI コーディング エージェント。", + "app.lander.cta.getStarted": "始めましょう", + "app.lander.features.native_tui.title": "ネイティブ TUI", + "app.lander.features.native_tui.description": "レスポンシブでネイティブなテーマ対応のターミナル UI。", + "app.lander.features.lsp_enabled.title": "LSP が有効になっている", + "app.lander.features.lsp_enabled.description": "LLM に適切な LSP を自動的にロードします。", + "app.lander.features.multi_session.title": "マルチセッション", + "app.lander.features.multi_session.description": "同じプロジェクトで複数のエージェントを並行して起動します。", + "app.lander.features.shareable_links.title": "共有可能なリンク", + "app.lander.features.shareable_links.description": "参照またはデバッグのために、セッションへのリンクを共有します。", + "app.lander.features.github_copilot.description": "Copilot アカウントを使用するには、GitHub にログインします。", + "app.lander.features.chatgpt_plus_pro.description": "ChatGPT Plus または Pro アカウントを使用するには、OpenAI にログインします。", + "app.lander.features.use_any_model.title": "どのモデルでも使用可能", + "app.lander.features.use_any_model.prefix": "75 以上の LLM プロバイダーをサポート", + "app.lander.features.use_any_model.suffix": "地元モデルも含めて。", + "app.lander.images.tui.caption": "tokyonight をテーマにした opencode TUI", + "app.lander.images.tui.alt": "tokyonight をテーマにした opencode TUI", + "app.lander.images.vscode.caption": "VS Code のオープンコード", + "app.lander.images.vscode.alt": "VS Code のオープンコード", + "app.lander.images.github.caption": "GitHub のオープンコード", + "app.lander.images.github.alt": "GitHub のオープンコード", + "share.meta_description": "opencode - ターミナル用に構築された AI コーディング エージェント。", + "share.not_found": "見つかりません", + "share.link_to_message": "このメッセージへのリンク", + "share.copied": "コピーしました!", + "share.copy": "コピー", + "share.show_more": "もっと見る", + "share.show_less": "表示を少なくする", + "share.show_results": "結果を表示", + "share.hide_results": "結果を非表示にする", + "share.show_details": "詳細を表示", + "share.hide_details": "詳細を隠す", + "share.show_preview": "プレビューを表示", + "share.hide_preview": "プレビューを非表示にする", + "share.show_contents": "番組内容", + "share.hide_contents": "内容を隠す", + "share.show_output": "出力を表示", + "share.hide_output": "出力を非表示にする", + "share.error": "エラー", + "share.waiting_for_messages": "メッセージを待っています...", + "share.status_connected_waiting": "接続中、メッセージを待っています...", + "share.status_connecting": "接続中...", + "share.status_disconnected": "切断されました", + "share.status_reconnecting": "再接続中...", + "share.status_error": "エラー", + "share.status_unknown": "未知", + "share.error_id_not_found": "IDが見つかりません", + "share.error_api_url_not_found": "API URLが見つかりません", + "share.error_connection_failed": "接続に失敗しました", + "share.opencode_version": "オープンコードのバージョン", + "share.opencode_name": "オープンコード", + "share.models": "モデル", + "share.cost": "料金", + "share.input_tokens": "入力トークン", + "share.output_tokens": "出力トークン", + "share.reasoning_tokens": "推論トークン", + "share.scroll_to_bottom": "一番下までスクロール", + "share.attachment": "アタッチメント", + "share.thinking": "考え", + "share.thinking_pending": "考え...", + "share.creating_plan": "計画の作成", + "share.completing_plan": "計画を完了する", + "share.updating_plan": "計画の更新", + "share.match_one": "マッチ", + "share.match_other": "マッチ", + "share.result_one": "結果", + "share.result_other": "結果", + "share.debug_key": "鍵" +} diff --git a/packages/web/src/content/i18n/ko.json b/packages/web/src/content/i18n/ko.json new file mode 100644 index 000000000..5752dd215 --- /dev/null +++ b/packages/web/src/content/i18n/ko.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "맨끝을 위해 건축되는 AI 기호화 대리인", + "app.header.home": "홈 > 제품", + "app.header.docs": "사이트맵", + "app.footer.issueLink": "버그를 찾으셨나요? 이슈를 열어 주세요", + "app.footer.discordLink": "Discord 커뮤니티에 참여하세요", + "app.lander.hero.title": "터미널에 내장 된 AI 코딩 에이전트.", + "app.lander.cta.getStarted": "시작하기", + "app.lander.features.native_tui.title": "기본 TUI", + "app.lander.features.native_tui.description": "반응형, 네이티브, 테마형 터미널 UI.", + "app.lander.features.lsp_enabled.title": "LSP 활성화", + "app.lander.features.lsp_enabled.description": "자동적으로 LLM에 적합한 LSP를로드합니다.", + "app.lander.features.multi_session.title": "관련 기사", + "app.lander.features.multi_session.description": "동일한 프로젝트에 평행한 다수 대리인을 시작하십시오.", + "app.lander.features.shareable_links.title": "관련 링크", + "app.lander.features.shareable_links.description": "참고 또는 디버그에 대한 모든 세션에 대한 링크를 공유합니다.", + "app.lander.features.github_copilot.description": "GitHub에서 Copilot 계정을 사용하세요.", + "app.lander.features.chatgpt_plus_pro.description": "ChatGPT Plus 또는 Pro 계정을 사용하여 OpenAI로 로그인하십시오.", + "app.lander.features.use_any_model.title": "모든 모델 사용", + "app.lander.features.use_any_model.prefix": "75 + LLM 제공업체 지원", + "app.lander.features.use_any_model.suffix": "로컬 모델 포함.", + "app.lander.images.tui.caption": "오픈 코드 TUI 와 tokyonight 테마", + "app.lander.images.tui.alt": "오픈 코드 TUI 와 tokyonight 테마", + "app.lander.images.vscode.caption": "VS 코드에서 opencode", + "app.lander.images.vscode.alt": "VS 코드에서 opencode", + "app.lander.images.github.caption": "GitHub의 opencode", + "app.lander.images.github.alt": "GitHub의 opencode", + "share.meta_description": "opencode - 터미널에 내장 된 AI 코딩 에이전트.", + "share.not_found": "찾을 수 없음", + "share.link_to_message": "이 메시지에 링크", + "share.copied": "뚱 베어", + "share.copy": "관련 기사", + "share.show_more": "더 보기", + "share.show_less": "더보기", + "share.show_results": "결과 표시", + "share.hide_results": "결과 숨기기", + "share.show_details": "공지사항", + "share.hide_details": "자주 묻는 질문", + "share.show_preview": "쇼 미리보기", + "share.hide_preview": "Hide 미리보기", + "share.show_contents": "공지사항", + "share.hide_contents": "자주 묻는 질문", + "share.show_output": "출력 표시", + "share.hide_output": "출력을 숨기기", + "share.error": "오류 수정", + "share.waiting_for_messages": "메시지 대기 ...", + "share.status_connected_waiting": "연결, 메시지 대기 ...", + "share.status_connecting": "연결 ...", + "share.status_disconnected": "연결하기", + "share.status_reconnecting": "연결 ...", + "share.status_error": "오류 수정", + "share.status_unknown": "이름 *", + "share.error_id_not_found": "찾을 수 없음", + "share.error_api_url_not_found": "API URL을 찾을 수 없습니다", + "share.error_connection_failed": "연결 실패", + "share.opencode_version": "opencode 버전", + "share.opencode_name": "비밀번호", + "share.models": "모델 번호:", + "share.cost": "제품정보", + "share.input_tokens": "입력 토큰", + "share.output_tokens": "산출 토큰", + "share.reasoning_tokens": "수익 토큰", + "share.scroll_to_bottom": "맨 위로", + "share.attachment": "관련 기사", + "share.thinking": "관련 기사", + "share.thinking_pending": "사고 ...", + "share.creating_plan": "계획 만들기", + "share.completing_plan": "완료 계획", + "share.updating_plan": "숙박 플랜", + "share.match_one": "이름 *", + "share.match_other": "이름 *", + "share.result_one": "이름 *", + "share.result_other": "이름 *", + "share.debug_key": "이름 *" +} diff --git a/packages/web/src/content/i18n/nb.json b/packages/web/src/content/i18n/nb.json new file mode 100644 index 000000000..ceb6762ac --- /dev/null +++ b/packages/web/src/content/i18n/nb.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "AI kodeagent bygget for terminalen", + "app.header.home": "Hjem", + "app.header.docs": "Dokumenter", + "app.footer.issueLink": "Fant du en feil? Åpne en issue", + "app.footer.discordLink": "Bli med i Discord-fellesskapet vårt", + "app.lander.hero.title": "Kodeagenten AI bygget for terminalen.", + "app.lander.cta.getStarted": "Kom i gang", + "app.lander.features.native_tui.title": "Innebygd TUI", + "app.lander.features.native_tui.description": "En responsiv, innfødt, temabasert terminal UI.", + "app.lander.features.lsp_enabled.title": "LSP aktivert", + "app.lander.features.lsp_enabled.description": "Laster automatisk de riktige LSP-ene for LLM.", + "app.lander.features.multi_session.title": "Multi-sesjon", + "app.lander.features.multi_session.description": "Start flere agenter parallelt på samme prosjekt.", + "app.lander.features.shareable_links.title": "Delbare lenker", + "app.lander.features.shareable_links.description": "Del en kobling til alle økter for referanse eller for å feilsøke.", + "app.lander.features.github_copilot.description": "Logg på med GitHub for å bruke Copilot-kontoen din.", + "app.lander.features.chatgpt_plus_pro.description": "Logg på med OpenAI for å bruke ChatGPT Plus- eller Pro-kontoen din.", + "app.lander.features.use_any_model.title": "Bruk hvilken som helst modell", + "app.lander.features.use_any_model.prefix": "Støtter 75+ LLM-leverandører gjennom", + "app.lander.features.use_any_model.suffix": "inkludert lokale modeller.", + "app.lander.images.tui.caption": "opencode TUI med tokyonight-temaet", + "app.lander.images.tui.alt": "opencode TUI med tokyonight-temaet", + "app.lander.images.vscode.caption": "OpenCode i VS Code", + "app.lander.images.vscode.alt": "OpenCode i VS Code", + "app.lander.images.github.caption": "opencode i GitHub", + "app.lander.images.github.alt": "opencode i GitHub", + "share.meta_description": "opencode - AI-kodeagenten bygget for terminalen.", + "share.not_found": "Ikke funnet", + "share.link_to_message": "Link til denne meldingen", + "share.copied": "Kopiert!", + "share.copy": "Kopiere", + "share.show_more": "Vis mer", + "share.show_less": "Vis mindre", + "share.show_results": "Vis resultater", + "share.hide_results": "Skjul resultater", + "share.show_details": "Vis detaljer", + "share.hide_details": "Skjul detaljer", + "share.show_preview": "Vis forhåndsvisning", + "share.hide_preview": "Skjul forhåndsvisning", + "share.show_contents": "Vis innhold", + "share.hide_contents": "Skjul innholdet", + "share.show_output": "Vis utdata", + "share.hide_output": "Skjul utdata", + "share.error": "Feil", + "share.waiting_for_messages": "Venter på meldinger...", + "share.status_connected_waiting": "Tilkoblet, venter på meldinger...", + "share.status_connecting": "Kobler til...", + "share.status_disconnected": "Koblet fra", + "share.status_reconnecting": "Kobler til på nytt...", + "share.status_error": "Feil", + "share.status_unknown": "Ukjent", + "share.error_id_not_found": "id ikke funnet", + "share.error_api_url_not_found": "API URL ikke funnet", + "share.error_connection_failed": "Tilkobling mislyktes", + "share.opencode_version": "opencode versjon", + "share.opencode_name": "OpenCode", + "share.models": "Modeller", + "share.cost": "Koste", + "share.input_tokens": "Skriv inn tokens", + "share.output_tokens": "Output tokens", + "share.reasoning_tokens": "Resonneringstegn", + "share.scroll_to_bottom": "Rull til bunnen", + "share.attachment": "Vedlegg", + "share.thinking": "Tenker", + "share.thinking_pending": "Tenker...", + "share.creating_plan": "Lage plan", + "share.completing_plan": "Fullfører plan", + "share.updating_plan": "Oppdaterer plan", + "share.match_one": "kamp", + "share.match_other": "kamper", + "share.result_one": "resultat", + "share.result_other": "resultater", + "share.debug_key": "Nøkkel" +} diff --git a/packages/web/src/content/i18n/pl.json b/packages/web/src/content/i18n/pl.json new file mode 100644 index 000000000..fac5a1d7d --- /dev/null +++ b/packages/web/src/content/i18n/pl.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "Agent kodujący AI zbudowany dla terminala", + "app.header.home": "Strona główna", + "app.header.docs": "Dokumentacja", + "app.footer.issueLink": "Znalazles blad? Otworz issue", + "app.footer.discordLink": "Dolacz do naszej spolecznosci Discord", + "app.lander.hero.title": "Agent kodujący AI zbudowany dla terminala.", + "app.lander.cta.getStarted": "Rozpocznij", + "app.lander.features.native_tui.title": "Natywny TUI", + "app.lander.features.native_tui.description": "Responsywny, natywny, tematyczny interfejs terminala.", + "app.lander.features.lsp_enabled.title": "Włączone LSP", + "app.lander.features.lsp_enabled.description": "Automatycznie ładuje odpowiednie LSP dla LLM.", + "app.lander.features.multi_session.title": "Wiele sesji", + "app.lander.features.multi_session.description": "Uruchom wielu agentów równolegle w tym samym projekcie.", + "app.lander.features.shareable_links.title": "Udostępniane linki", + "app.lander.features.shareable_links.description": "Udostępnij link do dowolnych sesji w celach informacyjnych lub do debugowania.", + "app.lander.features.github_copilot.description": "Zaloguj się w GitHub, aby korzystać ze swojego konta Copilot.", + "app.lander.features.chatgpt_plus_pro.description": "Zaloguj się za pomocą OpenAI, aby korzystać ze swojego konta ChatGPT Plus lub Pro.", + "app.lander.features.use_any_model.title": "Użyj dowolnego modelu", + "app.lander.features.use_any_model.prefix": "Obsługuje ponad 75 dostawców LLM", + "app.lander.features.use_any_model.suffix": "w tym modele lokalne.", + "app.lander.images.tui.caption": "OpenCode TUI z motywem tokyonight", + "app.lander.images.tui.alt": "OpenCode TUI z motywem tokyonight", + "app.lander.images.vscode.caption": "OpenCode w VS Code", + "app.lander.images.vscode.alt": "OpenCode w VS Code", + "app.lander.images.github.caption": "OpenCode w GitHub", + "app.lander.images.github.alt": "OpenCode w GitHub", + "share.meta_description": "opencode — agent kodujący AI zbudowany dla terminala.", + "share.not_found": "Nie znaleziono", + "share.link_to_message": "Link do tej wiadomości", + "share.copied": "Skopiowano!", + "share.copy": "Kopiuj", + "share.show_more": "Pokaż więcej", + "share.show_less": "Pokaż mniej", + "share.show_results": "Pokaż wyniki", + "share.hide_results": "Ukryj wyniki", + "share.show_details": "Pokaż szczegóły", + "share.hide_details": "Ukryj szczegóły", + "share.show_preview": "Pokaż podgląd", + "share.hide_preview": "Ukryj podgląd", + "share.show_contents": "Pokaż zawartość", + "share.hide_contents": "Ukryj zawartość", + "share.show_output": "Pokaż dane wyjściowe", + "share.hide_output": "Ukryj dane wyjściowe", + "share.error": "Błąd", + "share.waiting_for_messages": "Czekam na wiadomości...", + "share.status_connected_waiting": "Połączono, czekam na wiadomości...", + "share.status_connecting": "Łączenie...", + "share.status_disconnected": "Rozłączono", + "share.status_reconnecting": "Ponowne łączenie...", + "share.status_error": "Błąd", + "share.status_unknown": "Nieznany", + "share.error_id_not_found": "nie znaleziono identyfikatora", + "share.error_api_url_not_found": "Nie znaleziono adresu URL interfejsu API", + "share.error_connection_failed": "Połączenie nie powiodło się", + "share.opencode_version": "wersja opencode", + "share.opencode_name": "opencode", + "share.models": "Modele", + "share.cost": "Koszt", + "share.input_tokens": "Tokeny wejściowe", + "share.output_tokens": "Tokeny wyjściowe", + "share.reasoning_tokens": "Tokeny rozumowania", + "share.scroll_to_bottom": "Przewiń w dół", + "share.attachment": "Załącznik", + "share.thinking": "Myślenie", + "share.thinking_pending": "Myślenie...", + "share.creating_plan": "Tworzenie planu", + "share.completing_plan": "Uzupełnianie planu", + "share.updating_plan": "Aktualizacja planu", + "share.match_one": "dopasowanie", + "share.match_other": "dopasowania", + "share.result_one": "wynik", + "share.result_other": "wyniki", + "share.debug_key": "Klawisz" +} diff --git a/packages/web/src/content/i18n/pt-BR.json b/packages/web/src/content/i18n/pt-BR.json new file mode 100644 index 000000000..1bebfcf7f --- /dev/null +++ b/packages/web/src/content/i18n/pt-BR.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "Agente de codificação AI construído para o terminal", + "app.header.home": "Início", + "app.header.docs": "Documentos", + "app.footer.issueLink": "Encontrou um bug? Abra uma issue", + "app.footer.discordLink": "Participe da nossa comunidade no Discord", + "app.lander.hero.title": "O agente de codificação AI construído para o terminal.", + "app.lander.cta.getStarted": "Começar", + "app.lander.features.native_tui.title": "TUI nativo", + "app.lander.features.native_tui.description": "Uma interface de terminal nativa, responsiva e com tema personalizável.", + "app.lander.features.lsp_enabled.title": "LSP habilitado", + "app.lander.features.lsp_enabled.description": "Carrega automaticamente os LSPs corretos para o LLM.", + "app.lander.features.multi_session.title": "Multi-sessão", + "app.lander.features.multi_session.description": "Inicie vários agentes em paralelo no mesmo projeto.", + "app.lander.features.shareable_links.title": "Links compartilháveis", + "app.lander.features.shareable_links.description": "Compartilhe um link para qualquer sessão para referência ou para depuração.", + "app.lander.features.github_copilot.description": "Faça login com o GitHub para usar sua conta do Copilot.", + "app.lander.features.chatgpt_plus_pro.description": "Faça login com a OpenAI para usar sua conta do ChatGPT Plus ou Pro.", + "app.lander.features.use_any_model.title": "Use qualquer modelo", + "app.lander.features.use_any_model.prefix": "Suporta mais de 75 provedores de LLM através de", + "app.lander.features.use_any_model.suffix": "incluindo modelos locais.", + "app.lander.images.tui.caption": "opencode TUI com o tema tokyonight", + "app.lander.images.tui.alt": "opencode TUI com o tema tokyonight", + "app.lander.images.vscode.caption": "opencode no VS Code", + "app.lander.images.vscode.alt": "opencode no VS Code", + "app.lander.images.github.caption": "opencode no GitHub", + "app.lander.images.github.alt": "opencode no GitHub", + "share.meta_description": "opencode - O agente de codificação AI construído para o terminal.", + "share.not_found": "Não encontrado", + "share.link_to_message": "Link para esta mensagem", + "share.copied": "Copiado!", + "share.copy": "Copiar", + "share.show_more": "Mostrar mais", + "share.show_less": "Mostrar menos", + "share.show_results": "Mostrar resultados", + "share.hide_results": "Ocultar resultados", + "share.show_details": "Mostrar detalhes", + "share.hide_details": "Ocultar detalhes", + "share.show_preview": "Mostrar pré-visualização", + "share.hide_preview": "Ocultar pré-visualização", + "share.show_contents": "Mostrar conteúdos", + "share.hide_contents": "Ocultar conteúdos", + "share.show_output": "Mostrar saída", + "share.hide_output": "Ocultar saída", + "share.error": "Erro", + "share.waiting_for_messages": "Aguardando mensagens...", + "share.status_connected_waiting": "Conectado, aguardando mensagens...", + "share.status_connecting": "Conectando...", + "share.status_disconnected": "Desconectado", + "share.status_reconnecting": "Reconectando...", + "share.status_error": "Erro", + "share.status_unknown": "Desconhecido", + "share.error_id_not_found": "id não encontrado", + "share.error_api_url_not_found": "URL da API não encontrada", + "share.error_connection_failed": "Falha na conexão", + "share.opencode_version": "versão do opencode", + "share.opencode_name": "opencode", + "share.models": "Modelos", + "share.cost": "Custo", + "share.input_tokens": "Tokens de Entrada", + "share.output_tokens": "Tokens de Saída", + "share.reasoning_tokens": "Tokens de Raciocínio", + "share.scroll_to_bottom": "Rolar para baixo", + "share.attachment": "Anexo", + "share.thinking": "Pensando", + "share.thinking_pending": "Pensando...", + "share.creating_plan": "Criando plano", + "share.completing_plan": "Concluindo plano", + "share.updating_plan": "Atualizando plano", + "share.match_one": "correspondência", + "share.match_other": "correspondências", + "share.result_one": "resultado", + "share.result_other": "resultados", + "share.debug_key": "Chave" +} diff --git a/packages/web/src/content/i18n/ru.json b/packages/web/src/content/i18n/ru.json new file mode 100644 index 000000000..92991fe9b --- /dev/null +++ b/packages/web/src/content/i18n/ru.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "AI-агент для программирования, созданный для терминала", + "app.header.home": "Главная", + "app.header.docs": "Документация", + "app.footer.issueLink": "Нашли ошибку? Откройте issue", + "app.footer.discordLink": "Присоединяйтесь к нашему сообществу в Discord", + "app.lander.hero.title": "AI-агент для программирования, созданный для терминала.", + "app.lander.cta.getStarted": "Начать", + "app.lander.features.native_tui.title": "Нативный TUI", + "app.lander.features.native_tui.description": "Отзывчивый нативный интерфейс терминала с поддержкой тем.", + "app.lander.features.lsp_enabled.title": "Поддержка LSP", + "app.lander.features.lsp_enabled.description": "Автоматически загружает подходящие LSP для LLM.", + "app.lander.features.multi_session.title": "Несколько сессий", + "app.lander.features.multi_session.description": "Запускайте несколько агентов параллельно в одном проекте.", + "app.lander.features.shareable_links.title": "Ссылки для общего доступа", + "app.lander.features.shareable_links.description": "Поделитесь ссылкой на любую сессию для справки или отладки.", + "app.lander.features.github_copilot.description": "Войдите через GitHub, чтобы использовать аккаунт Copilot.", + "app.lander.features.chatgpt_plus_pro.description": "Войдите через OpenAI, чтобы использовать аккаунт ChatGPT Plus или Pro.", + "app.lander.features.use_any_model.title": "Используйте любую модель", + "app.lander.features.use_any_model.prefix": "Поддерживает 75+ провайдеров LLM через", + "app.lander.features.use_any_model.suffix": "включая локальные модели.", + "app.lander.images.tui.caption": "opencode TUI с темой tokyonight", + "app.lander.images.tui.alt": "opencode TUI с темой tokyonight", + "app.lander.images.vscode.caption": "opencode в VS Code", + "app.lander.images.vscode.alt": "opencode в VS Code", + "app.lander.images.github.caption": "opencode в GitHub", + "app.lander.images.github.alt": "opencode в GitHub", + "share.meta_description": "opencode - AI-агент для программирования, созданный для терминала.", + "share.not_found": "Не найдено", + "share.link_to_message": "Ссылка на это сообщение", + "share.copied": "Скопировано!", + "share.copy": "Копировать", + "share.show_more": "Показать больше", + "share.show_less": "Показать меньше", + "share.show_results": "Показать результаты", + "share.hide_results": "Скрыть результаты", + "share.show_details": "Показать детали", + "share.hide_details": "Скрыть детали", + "share.show_preview": "Показать предпросмотр", + "share.hide_preview": "Скрыть предпросмотр", + "share.show_contents": "Показать содержимое", + "share.hide_contents": "Скрыть содержимое", + "share.show_output": "Показать вывод", + "share.hide_output": "Скрыть вывод", + "share.error": "Ошибка", + "share.waiting_for_messages": "Ожидание сообщений...", + "share.status_connected_waiting": "Подключено, ожидание сообщений...", + "share.status_connecting": "Подключение...", + "share.status_disconnected": "Отключено", + "share.status_reconnecting": "Повторное подключение...", + "share.status_error": "Ошибка", + "share.status_unknown": "Неизвестно", + "share.error_id_not_found": "id не найден", + "share.error_api_url_not_found": "API URL не найден", + "share.error_connection_failed": "Не удалось подключиться", + "share.opencode_version": "версия opencode", + "share.opencode_name": "opencode", + "share.models": "Модели", + "share.cost": "Стоимость", + "share.input_tokens": "Входные токены", + "share.output_tokens": "Выходные токены", + "share.reasoning_tokens": "Токены рассуждений", + "share.scroll_to_bottom": "Прокрутить вниз", + "share.attachment": "Вложение", + "share.thinking": "Размышление", + "share.thinking_pending": "Размышление...", + "share.creating_plan": "Создание плана", + "share.completing_plan": "Завершение плана", + "share.updating_plan": "Обновление плана", + "share.match_one": "совпадение", + "share.match_other": "совпадений", + "share.result_one": "результат", + "share.result_other": "результатов", + "share.debug_key": "Ключ" +} diff --git a/packages/web/src/content/i18n/th.json b/packages/web/src/content/i18n/th.json new file mode 100644 index 000000000..25efd36eb --- /dev/null +++ b/packages/web/src/content/i18n/th.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "เอเจนต์เขียนโค้ด AI ที่สร้างมาเพื่อเทอร์มินัล", + "app.header.home": "หน้าหลัก", + "app.header.docs": "เอกสาร", + "app.footer.issueLink": "พบข้อผิดพลาดหรือไม่? เปิด issue", + "app.footer.discordLink": "เข้าร่วมชุมชน Discord ของเรา", + "app.lander.hero.title": "เอเจนต์เขียนโค้ด AI ที่สร้างมาเพื่อเทอร์มินัล", + "app.lander.cta.getStarted": "เริ่มต้นใช้งาน", + "app.lander.features.native_tui.title": "TUI แบบเนทีฟ", + "app.lander.features.native_tui.description": "อินเทอร์เฟซเทอร์มินัลแบบเนทีฟที่ตอบสนองไวและปรับธีมได้", + "app.lander.features.lsp_enabled.title": "รองรับ LSP", + "app.lander.features.lsp_enabled.description": "โหลด LSP ที่เหมาะสมสำหรับ LLM โดยอัตโนมัติ", + "app.lander.features.multi_session.title": "หลายเซสชัน", + "app.lander.features.multi_session.description": "เริ่มเอเจนต์หลายตัวพร้อมกันบนโปรเจ็กต์เดียวกัน", + "app.lander.features.shareable_links.title": "ลิงก์ที่แชร์ได้", + "app.lander.features.shareable_links.description": "แชร์ลิงก์ไปยังเซสชันใดก็ได้เพื่ออ้างอิงหรือดีบัก", + "app.lander.features.github_copilot.description": "เข้าสู่ระบบด้วย GitHub เพื่อใช้บัญชี Copilot ของคุณ", + "app.lander.features.chatgpt_plus_pro.description": "เข้าสู่ระบบด้วย OpenAI เพื่อใช้บัญชี ChatGPT Plus หรือ Pro ของคุณ", + "app.lander.features.use_any_model.title": "ใช้ได้ทุกโมเดล", + "app.lander.features.use_any_model.prefix": "รองรับผู้ให้บริการ LLM มากกว่า 75 รายผ่าน", + "app.lander.features.use_any_model.suffix": "รวมถึงโมเดลภายในเครื่อง", + "app.lander.images.tui.caption": "opencode TUI พร้อมธีม tokyonight", + "app.lander.images.tui.alt": "opencode TUI พร้อมธีม tokyonight", + "app.lander.images.vscode.caption": "opencode ใน VS Code", + "app.lander.images.vscode.alt": "opencode ใน VS Code", + "app.lander.images.github.caption": "opencode ใน GitHub", + "app.lander.images.github.alt": "opencode ใน GitHub", + "share.meta_description": "opencode - เอเจนต์เขียนโค้ด AI ที่สร้างมาเพื่อเทอร์มินัล", + "share.not_found": "ไม่พบ", + "share.link_to_message": "ลิงก์ไปยังข้อความนี้", + "share.copied": "คัดลอกแล้ว!", + "share.copy": "คัดลอก", + "share.show_more": "แสดงเพิ่มเติม", + "share.show_less": "แสดงน้อยลง", + "share.show_results": "แสดงผลลัพธ์", + "share.hide_results": "ซ่อนผลลัพธ์", + "share.show_details": "แสดงรายละเอียด", + "share.hide_details": "ซ่อนรายละเอียด", + "share.show_preview": "แสดงตัวอย่าง", + "share.hide_preview": "ซ่อนตัวอย่าง", + "share.show_contents": "แสดงเนื้อหา", + "share.hide_contents": "ซ่อนเนื้อหา", + "share.show_output": "แสดงเอาต์พุต", + "share.hide_output": "ซ่อนเอาต์พุต", + "share.error": "ข้อผิดพลาด", + "share.waiting_for_messages": "กำลังรอข้อความ...", + "share.status_connected_waiting": "เชื่อมต่อแล้ว กำลังรอข้อความ...", + "share.status_connecting": "กำลังเชื่อมต่อ...", + "share.status_disconnected": "ตัดการเชื่อมต่อแล้ว", + "share.status_reconnecting": "กำลังเชื่อมต่อใหม่...", + "share.status_error": "ข้อผิดพลาด", + "share.status_unknown": "ไม่ทราบสถานะ", + "share.error_id_not_found": "ไม่พบ id", + "share.error_api_url_not_found": "ไม่พบ API URL", + "share.error_connection_failed": "การเชื่อมต่อล้มเหลว", + "share.opencode_version": "เวอร์ชัน opencode", + "share.opencode_name": "opencode", + "share.models": "โมเดล", + "share.cost": "ค่าใช้จ่าย", + "share.input_tokens": "โทเค็นอินพุต", + "share.output_tokens": "โทเค็นเอาต์พุต", + "share.reasoning_tokens": "โทเค็นการให้เหตุผล", + "share.scroll_to_bottom": "เลื่อนไปด้านล่าง", + "share.attachment": "ไฟล์แนบ", + "share.thinking": "กำลังคิด", + "share.thinking_pending": "กำลังคิด...", + "share.creating_plan": "กำลังสร้างแผน", + "share.completing_plan": "กำลังทำแผนให้เสร็จ", + "share.updating_plan": "กำลังอัปเดตแผน", + "share.match_one": "รายการที่ตรงกัน", + "share.match_other": "รายการที่ตรงกัน", + "share.result_one": "ผลลัพธ์", + "share.result_other": "ผลลัพธ์", + "share.debug_key": "คีย์" +} diff --git a/packages/web/src/content/i18n/tr.json b/packages/web/src/content/i18n/tr.json new file mode 100644 index 000000000..1309ffb10 --- /dev/null +++ b/packages/web/src/content/i18n/tr.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "Terminal için oluşturulan AI taşıma aracı", + "app.header.home": "ev", + "app.header.docs": "Dokumanlar", + "app.footer.issueLink": "Bir hata buldunuz mu? Issue acin", + "app.footer.discordLink": "Discord toplulugumuza katilin", + "app.lander.hero.title": "Terminal için oluşturulmuş AI taşıma aracı.", + "app.lander.cta.getStarted": "Başlayın", + "app.lander.features.native_tui.title": "Yerli TUI", + "app.lander.features.native_tui.description": "Duyarlı, yerel, temaya uygun bir terminal kullanıcı arayüzü.", + "app.lander.features.lsp_enabled.title": "LSP etkin", + "app.lander.features.lsp_enabled.description": "LLM için doğru LSP'leri otomatik olarak yükler.", + "app.lander.features.multi_session.title": "Çoklu giriş", + "app.lander.features.multi_session.description": "Aynı projeyi anında fazla aracı paralel olarak başlatın.", + "app.lander.features.shareable_links.title": "Paylaşılabilir ayrılabilir", + "app.lander.features.shareable_links.description": "Referans veya hata ayıklama amacıyla herhangi bir bilgisayarın bağlantısını değiştirir.", + "app.lander.features.github_copilot.description": "Copilot hesabını kullanmak için GitHub dosya kaydını açın.", + "app.lander.features.chatgpt_plus_pro.description": "ChatGPT Plus veya Pro hesabınızı kullanmak için OpenAI dosya kaydını açın.", + "app.lander.features.use_any_model.title": "Herhangi bir modeli kullanın", + "app.lander.features.use_any_model.prefix": "75'ten fazla LLM sağlayıcıyı sağlama", + "app.lander.features.use_any_model.suffix": "Yerel modeller dahil.", + "app.lander.images.tui.caption": "tokyonnight temasıyla açık kod TUI", + "app.lander.images.tui.alt": "tokyonnight temasıyla açık kod TUI", + "app.lander.images.vscode.caption": "VS Kodunda açık kod", + "app.lander.images.vscode.alt": "VS Kodunda açık kod", + "app.lander.images.github.caption": "GitHub'da açık kod", + "app.lander.images.github.alt": "GitHub'da açık kod", + "share.meta_description": "opencode - Terminal için oluşturulmuş AI oluşturma aracı.", + "share.not_found": "Bulunamadı", + "share.link_to_message": "Bu mesaja dönüştürücü", + "share.copied": "Kopyalandı!", + "share.copy": "Kopyala", + "share.show_more": "Daha fazlasını göster", + "share.show_less": "Daha az göster", + "share.show_results": "Sonuçları göster", + "share.hide_results": "Sonuçları gizle", + "share.show_details": "Ayrıntıları göster", + "share.hide_details": "Ayrıntıları gizle", + "share.show_preview": "Ölememeyi göster", + "share.hide_preview": "Ölemeyi gizle", + "share.show_contents": "İçeriği göster", + "share.hide_contents": "İçeriği gizle", + "share.show_output": "Çıktıyı göster", + "share.hide_output": "Çıktıyı gizle", + "share.error": "hata", + "share.waiting_for_messages": "Mesajları bekliyorum...", + "share.status_connected_waiting": "Bağlandım, mesajlarını bekliyorum...", + "share.status_connecting": "Bağlanıyor...", + "share.status_disconnected": "Bağlantı kesildi", + "share.status_reconnecting": "Yeniden bağlanıyor...", + "share.status_error": "hata", + "share.status_unknown": "Bilinmiyor", + "share.error_id_not_found": "kimliği bulunamadı", + "share.error_api_url_not_found": "API URL başarısız", + "share.error_connection_failed": "Bağlantı başarısız oldu", + "share.opencode_version": "açık kod sürümü", + "share.opencode_name": "açık kod", + "share.models": "Modelci", + "share.cost": "Maliyet", + "share.input_tokens": "Giriş Jetonları", + "share.output_tokens": "Çıkış Tokenları", + "share.reasoning_tokens": "Muhakeme Belirteçleri", + "share.scroll_to_bottom": "Aşağıya doğru kaydır", + "share.attachment": "ek", + "share.thinking": "Düşünme", + "share.thinking_pending": "Düşünüyorum...", + "share.creating_plan": "Plan oluşturuluyor", + "share.completing_plan": "Plan tamamlanıyor", + "share.updating_plan": "Plan güncelleniyor", + "share.match_one": "kibrit", + "share.match_other": "maçlar", + "share.result_one": "sonuç", + "share.result_other": "sonuçlar", + "share.debug_key": "Anahtar" +} diff --git a/packages/web/src/content/i18n/zh-CN.json b/packages/web/src/content/i18n/zh-CN.json new file mode 100644 index 000000000..503339f50 --- /dev/null +++ b/packages/web/src/content/i18n/zh-CN.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "为表达式构建的AI编码代理", + "app.header.home": "家", + "app.header.docs": "檔案", + "app.footer.issueLink": "发现了问题?提交 issue", + "app.footer.discordLink": "加入我们的 Discord 社区", + "app.lander.hero.title": "为表达式构建的AI编码代理。", + "app.lander.cta.getStarted": "開始使用", + "app.lander.features.native_tui.title": "本机TUI", + "app.lander.features.native_tui.description": "响应式、实时性、可主题化的终端UI。", + "app.lander.features.lsp_enabled.title": "LSP 已启用", + "app.lander.features.lsp_enabled.description": "自动为 LLM 加载正确的 LSP。", + "app.lander.features.multi_session.title": "多會話", + "app.lander.features.multi_session.description": "在同一專案上並行啟動多個代理。", + "app.lander.features.shareable_links.title": "可分享的連結", + "app.lander.features.shareable_links.description": "共享任何會話的連結以供參考或除錯。", + "app.lander.features.github_copilot.description": "使用 GitHub 登入以使用您的 Copilot 帐户。", + "app.lander.features.chatgpt_plus_pro.description": "使用 OpenAI 登入以使用您的 ChatGPT Plus 或 Pro 帐户。", + "app.lander.features.use_any_model.title": "使用任何型號", + "app.lander.features.use_any_model.prefix": "透过以下方式支持 75+ LLM 创业", + "app.lander.features.use_any_model.suffix": "包括本地模型。", + "app.lander.images.tui.caption": "opencode TUI 以东京之夜为主题", + "app.lander.images.tui.alt": "opencode TUI 以东京之夜为主题", + "app.lander.images.vscode.caption": "opencode 在 VS Code 中", + "app.lander.images.vscode.alt": "opencode 在 VS Code 中", + "app.lander.images.github.caption": "opencode 在 GitHub 中", + "app.lander.images.github.alt": "opencode 在 GitHub 中", + "share.meta_description": "opencode - 为终端构建的AI编码代理。", + "share.not_found": "未找到", + "share.link_to_message": "連結到此訊息", + "share.copied": "複製了!", + "share.copy": "複製", + "share.show_more": "顯示更多", + "share.show_less": "顯示較少", + "share.show_results": "顯示結果", + "share.hide_results": "隱藏結果", + "share.show_details": "顯示詳情", + "share.hide_details": "隱藏詳細資訊", + "share.show_preview": "顯示預覽", + "share.hide_preview": "隱藏預覽", + "share.show_contents": "顯示內容", + "share.hide_contents": "隱藏內容", + "share.show_output": "顯示輸出", + "share.hide_output": "隱藏輸出", + "share.error": "錯誤", + "share.waiting_for_messages": "等待訊息...", + "share.status_connected_waiting": "已連線,等待訊息...", + "share.status_connecting": "正在連線...", + "share.status_disconnected": "已斷開連線", + "share.status_reconnecting": "正在重新連線...", + "share.status_error": "錯誤", + "share.status_unknown": "未知", + "share.error_id_not_found": "未找到 ID", + "share.error_api_url_not_found": "API URL 未找到", + "share.error_connection_failed": "連線失敗", + "share.opencode_version": "opencode 版本", + "share.opencode_name": "开放代码", + "share.models": "型號", + "share.cost": "成本", + "share.input_tokens": "輸入令牌", + "share.output_tokens": "輸出代幣", + "share.reasoning_tokens": "推理代幣", + "share.scroll_to_bottom": "滾動到底部", + "share.attachment": "依戀", + "share.thinking": "思維", + "share.thinking_pending": "思維...", + "share.creating_plan": "制定計劃", + "share.completing_plan": "完成計劃", + "share.updating_plan": "更新計劃", + "share.match_one": "匹配", + "share.match_other": "比賽", + "share.result_one": "結果", + "share.result_other": "結果", + "share.debug_key": "鑰匙" +} diff --git a/packages/web/src/content/i18n/zh-TW.json b/packages/web/src/content/i18n/zh-TW.json new file mode 100644 index 000000000..6d5f9f9e7 --- /dev/null +++ b/packages/web/src/content/i18n/zh-TW.json @@ -0,0 +1,75 @@ +{ + "app.head.titleSuffix": "為終端打造的AI編碼代理", + "app.header.home": "首頁", + "app.header.docs": "文件", + "app.footer.issueLink": "發現問題?提交 issue", + "app.footer.discordLink": "加入我們的 Discord 社群", + "app.lander.hero.title": "為終端打造的AI編碼代理。", + "app.lander.cta.getStarted": "開始使用", + "app.lander.features.native_tui.title": "本機 TUI", + "app.lander.features.native_tui.description": "響應式、原生、可主題化的終端 UI。", + "app.lander.features.lsp_enabled.title": "LSP 已啟用", + "app.lander.features.lsp_enabled.description": "自動為 LLM 載入正確的 LSP。", + "app.lander.features.multi_session.title": "多會話", + "app.lander.features.multi_session.description": "在同一專案上並行啟動多個代理。", + "app.lander.features.shareable_links.title": "可分享的連結", + "app.lander.features.shareable_links.description": "共享任何會話的連結以供參考或除錯。", + "app.lander.features.github_copilot.description": "使用 GitHub 登入以使用您的 Copilot 帳戶。", + "app.lander.features.chatgpt_plus_pro.description": "使用 OpenAI 登入以使用您的 ChatGPT Plus 或 Pro 帳戶。", + "app.lander.features.use_any_model.title": "使用任何模型", + "app.lander.features.use_any_model.prefix": "透過以下方式支援 75+ LLM 提供商", + "app.lander.features.use_any_model.suffix": "包括本地模型。", + "app.lander.images.tui.caption": "opencode TUI 以東京之夜為主題", + "app.lander.images.tui.alt": "opencode TUI 以東京之夜為主題", + "app.lander.images.vscode.caption": "opencode 在 VS Code 中", + "app.lander.images.vscode.alt": "opencode 在 VS Code 中", + "app.lander.images.github.caption": "opencode 在 GitHub 中", + "app.lander.images.github.alt": "opencode 在 GitHub 中", + "share.meta_description": "opencode - 為終端構建的AI編碼代理。", + "share.not_found": "未找到", + "share.link_to_message": "連結到此訊息", + "share.copied": "複製了!", + "share.copy": "複製", + "share.show_more": "顯示更多", + "share.show_less": "顯示較少", + "share.show_results": "顯示結果", + "share.hide_results": "隱藏結果", + "share.show_details": "顯示詳情", + "share.hide_details": "隱藏詳細資訊", + "share.show_preview": "顯示預覽", + "share.hide_preview": "隱藏預覽", + "share.show_contents": "顯示內容", + "share.hide_contents": "隱藏內容", + "share.show_output": "顯示輸出", + "share.hide_output": "隱藏輸出", + "share.error": "錯誤", + "share.waiting_for_messages": "等待訊息...", + "share.status_connected_waiting": "已連線,等待訊息...", + "share.status_connecting": "正在連線...", + "share.status_disconnected": "已斷開連線", + "share.status_reconnecting": "正在重新連線...", + "share.status_error": "錯誤", + "share.status_unknown": "未知", + "share.error_id_not_found": "未找到 ID", + "share.error_api_url_not_found": "API URL 未找到", + "share.error_connection_failed": "連線失敗", + "share.opencode_version": "opencode 版本", + "share.opencode_name": "opencode", + "share.models": "模型", + "share.cost": "成本", + "share.input_tokens": "輸入 Token", + "share.output_tokens": "輸出 Token", + "share.reasoning_tokens": "推理 Token", + "share.scroll_to_bottom": "滾動到底部", + "share.attachment": "附件", + "share.thinking": "思考中", + "share.thinking_pending": "思考中...", + "share.creating_plan": "建立計畫", + "share.completing_plan": "完成計畫", + "share.updating_plan": "更新計畫", + "share.match_one": "符合項目", + "share.match_other": "符合項目", + "share.result_one": "結果", + "share.result_other": "結果", + "share.debug_key": "金鑰" +} -- cgit v1.2.3