@eduardo191labs/opencode-free-pi 0.2.7 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +151 -157
  2. package/dist/ads/context.d.ts +18 -0
  3. package/dist/ads/context.js +125 -0
  4. package/dist/ads/impression.d.ts +7 -0
  5. package/dist/ads/impression.js +85 -0
  6. package/dist/ads/resolve.d.ts +11 -0
  7. package/dist/ads/resolve.js +35 -0
  8. package/dist/ads/turns.d.ts +6 -0
  9. package/dist/ads/turns.js +14 -0
  10. package/dist/api/quota.d.ts +8 -0
  11. package/dist/api/quota.js +90 -0
  12. package/dist/api/session.d.ts +9 -0
  13. package/dist/api/session.js +69 -0
  14. package/dist/auth/authorize.d.ts +14 -0
  15. package/dist/auth/authorize.js +60 -0
  16. package/dist/auth/connect.d.ts +7 -0
  17. package/dist/auth/connect.js +117 -0
  18. package/dist/auth/credential.d.ts +5 -0
  19. package/dist/auth/credential.js +34 -0
  20. package/dist/auth/credentials.d.ts +7 -0
  21. package/dist/auth/credentials.js +56 -0
  22. package/dist/auth/jwt.d.ts +7 -0
  23. package/dist/auth/jwt.js +60 -0
  24. package/dist/auth/token.d.ts +14 -0
  25. package/dist/auth/token.js +28 -0
  26. package/dist/catalog/catalog.d.ts +6 -0
  27. package/dist/catalog/catalog.js +80 -0
  28. package/dist/catalog/models.d.ts +15 -0
  29. package/dist/catalog/models.js +206 -0
  30. package/dist/catalog/registry.d.ts +9 -0
  31. package/dist/catalog/registry.js +96 -0
  32. package/dist/catalog/v2.d.ts +18 -0
  33. package/dist/catalog/v2.js +93 -0
  34. package/dist/constants.d.ts +46 -0
  35. package/dist/constants.js +46 -0
  36. package/dist/deps.d.ts +11 -0
  37. package/dist/deps.js +2 -0
  38. package/dist/errors/handle.d.ts +5 -0
  39. package/dist/errors/handle.js +64 -0
  40. package/dist/errors/invalid.d.ts +3 -0
  41. package/dist/errors/invalid.js +8 -0
  42. package/dist/errors/limit.d.ts +10 -0
  43. package/dist/errors/limit.js +110 -0
  44. package/dist/errors/messages.d.ts +6 -0
  45. package/dist/errors/messages.js +119 -0
  46. package/dist/errors/parse.d.ts +4 -0
  47. package/dist/errors/parse.js +153 -0
  48. package/dist/index.d.ts +9 -9
  49. package/dist/index.js +7 -3376
  50. package/dist/integration/setup.d.ts +4 -0
  51. package/dist/integration/setup.js +49 -0
  52. package/dist/logging.d.ts +9 -0
  53. package/dist/logging.js +62 -0
  54. package/dist/plugin.d.ts +4 -0
  55. package/dist/plugin.js +109 -0
  56. package/dist/session/events.d.ts +4 -0
  57. package/dist/session/events.js +96 -0
  58. package/dist/session/hooks.d.ts +8 -0
  59. package/dist/session/hooks.js +114 -0
  60. package/dist/session/track.d.ts +21 -0
  61. package/dist/session/track.js +107 -0
  62. package/dist/session/usage.d.ts +5 -0
  63. package/dist/session/usage.js +32 -0
  64. package/dist/state.d.ts +43 -0
  65. package/dist/state.js +26 -0
  66. package/dist/types.d.ts +272 -0
  67. package/dist/types.js +2 -0
  68. package/dist/utils/async.d.ts +8 -0
  69. package/dist/utils/async.js +29 -0
  70. package/dist/utils/browser.d.ts +3 -0
  71. package/dist/utils/browser.js +55 -0
  72. package/dist/utils/cache.d.ts +7 -0
  73. package/dist/utils/cache.js +45 -0
  74. package/dist/utils/device.d.ts +6 -0
  75. package/dist/utils/device.js +29 -0
  76. package/dist/utils/http.d.ts +4 -0
  77. package/dist/utils/http.js +42 -0
  78. package/dist/utils/json.d.ts +2 -0
  79. package/dist/utils/json.js +9 -0
  80. package/dist/utils/numbers.d.ts +6 -0
  81. package/dist/utils/numbers.js +49 -0
  82. package/dist/utils/text.d.ts +2 -0
  83. package/dist/utils/text.js +6 -0
  84. package/dist/utils/urls.d.ts +6 -0
  85. package/dist/utils/urls.js +41 -0
  86. package/install.ps1 +82 -46
  87. package/install.sh +98 -40
  88. package/package.json +5 -4
  89. package/scripts/postinstall.mjs +68 -34
  90. package/src/ads/context.ts +156 -0
  91. package/src/ads/impression.ts +111 -0
  92. package/src/ads/resolve.ts +62 -0
  93. package/src/ads/turns.ts +24 -0
  94. package/src/api/quota.ts +110 -0
  95. package/src/api/session.ts +76 -0
  96. package/src/auth/authorize.ts +104 -0
  97. package/src/auth/connect.ts +144 -0
  98. package/src/auth/credential.ts +39 -0
  99. package/src/auth/credentials.ts +60 -0
  100. package/src/auth/jwt.ts +75 -0
  101. package/src/auth/token.ts +52 -0
  102. package/src/catalog/catalog.ts +94 -0
  103. package/src/catalog/models.ts +291 -0
  104. package/src/catalog/registry.ts +122 -0
  105. package/src/catalog/v2.ts +124 -0
  106. package/src/constants.ts +61 -0
  107. package/src/deps.ts +13 -0
  108. package/src/errors/handle.ts +79 -0
  109. package/src/errors/invalid.ts +15 -0
  110. package/src/errors/limit.ts +114 -0
  111. package/src/errors/messages.ts +151 -0
  112. package/src/errors/parse.ts +156 -0
  113. package/src/index.ts +23 -4042
  114. package/src/integration/setup.ts +59 -0
  115. package/src/logging.ts +70 -0
  116. package/src/plugin.ts +143 -0
  117. package/src/session/events.ts +117 -0
  118. package/src/session/hooks.ts +192 -0
  119. package/src/session/track.ts +124 -0
  120. package/src/session/usage.ts +46 -0
  121. package/src/state.ts +82 -0
  122. package/src/types.ts +259 -0
  123. package/src/utils/async.ts +35 -0
  124. package/src/utils/browser.ts +61 -0
  125. package/src/utils/cache.ts +49 -0
  126. package/src/utils/device.ts +25 -0
  127. package/src/utils/http.ts +56 -0
  128. package/src/utils/json.ts +9 -0
  129. package/src/utils/numbers.ts +52 -0
  130. package/src/utils/text.ts +7 -0
  131. package/src/utils/urls.ts +47 -0
@@ -0,0 +1,41 @@
1
+ /** URL resolution and validation. */
2
+ import { DEFAULT_BASE_URL, DEFAULT_MODELS_REGISTRY_URL, } from "../constants.js";
3
+ export function resolveBaseUrl() {
4
+ const configured = process.env.FREEPI_BASE_URL?.trim();
5
+ return (configured || DEFAULT_BASE_URL).replace(/\/+$/, "");
6
+ }
7
+ export function completionsBaseUrl() {
8
+ const base = resolveBaseUrl();
9
+ return base.endsWith("/v1") ? base : `${base}/v1`;
10
+ }
11
+ export function modelsRegistryUrl() {
12
+ const configured = process.env.FREEPI_MODELS_URL?.trim() ||
13
+ process.env.OPENCODE_MODELS_URL?.trim();
14
+ return (configured || DEFAULT_MODELS_REGISTRY_URL).replace(/\/+$/, "");
15
+ }
16
+ export function normalizeIssuer(value) {
17
+ if (typeof value !== "string")
18
+ return undefined;
19
+ try {
20
+ const parsed = new URL(value);
21
+ return parsed.protocol === "https:" || parsed.protocol === "http:"
22
+ ? parsed.origin
23
+ : undefined;
24
+ }
25
+ catch {
26
+ return undefined;
27
+ }
28
+ }
29
+ export function safeUrl(value) {
30
+ if (typeof value !== "string")
31
+ return undefined;
32
+ try {
33
+ const parsed = new URL(value.trim());
34
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:")
35
+ return undefined;
36
+ return parsed.toString();
37
+ }
38
+ catch {
39
+ return undefined;
40
+ }
41
+ }
package/install.ps1 CHANGED
@@ -1,8 +1,7 @@
1
1
  $ErrorActionPreference = "Stop"
2
+ $Package = "@eduardo191labs/opencode-free-pi"
2
3
  $PluginName = "opencode-free-pi"
3
4
  $Uninstall = ($args -contains "-Uninstall") -or ($args -contains "--uninstall")
4
- $Repo = if ($env:FREEPI_OPENCODE_REPO) { $env:FREEPI_OPENCODE_REPO } else { "eduardo191-star/opencode-free-pi" }
5
- $Ref = if ($env:FREEPI_OPENCODE_REF) { $env:FREEPI_OPENCODE_REF } else { "main" }
6
5
 
7
6
  function Get-ConfigDir {
8
7
  if ($env:OPENCODE_CONFIG_DIR) { return $env:OPENCODE_CONFIG_DIR }
@@ -14,61 +13,98 @@ function Write-Step([string]$Message) {
14
13
  Write-Host $Message
15
14
  }
16
15
 
17
- if ($Uninstall) {
18
- $pluginDir = Join-Path (Get-ConfigDir) "plugins"
19
- Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $pluginDir "$PluginName.ts")
20
- Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $pluginDir "$PluginName.js")
21
- Write-Step "Removed $PluginName from $pluginDir"
22
- Write-Step "Restart OpenCode to finish."
23
- return
16
+ function Get-ConfigFile([string]$Dir) {
17
+ foreach ($name in @("opencode.json", "opencode.jsonc", "opencode.json5")) {
18
+ $candidate = Join-Path $Dir $name
19
+ if (Test-Path -LiteralPath $candidate) { return $candidate }
20
+ }
21
+ return (Join-Path $Dir "opencode.json")
24
22
  }
25
23
 
26
- [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
24
+ function Update-Config([string]$Dir, [bool]$Remove) {
25
+ New-Item -ItemType Directory -Force -Path $Dir | Out-Null
26
+ $file = Get-ConfigFile $Dir
27
+ $config = $null
28
+ if (Test-Path -LiteralPath $file) {
29
+ try {
30
+ $config = Get-Content -LiteralPath $file -Raw | ConvertFrom-Json
31
+ } catch {
32
+ Write-Step "free-pi: no se pudo editar $file automáticamente."
33
+ Write-Step "free-pi: edita `"plugins`" y quita o añade `"$Package`"."
34
+ return
35
+ }
36
+ }
37
+ if ($null -eq $config) {
38
+ $config = [pscustomobject]@{ '$schema' = "https://opencode.ai/config.json" }
39
+ }
27
40
 
28
- $configDir = Get-ConfigDir
29
- $pluginDir = Join-Path $configDir "plugins"
30
- $target = Join-Path $pluginDir "$PluginName.ts"
31
- $rawBase = if ($env:FREEPI_OPENCODE_RAW_BASE) { $env:FREEPI_OPENCODE_RAW_BASE } else { "https://raw.githubusercontent.com/$Repo/$Ref" }
32
- $temp = Join-Path ([System.IO.Path]::GetTempPath()) ("$PluginName-" + [guid]::NewGuid().ToString("N") + ".js")
41
+ $plugins = @()
42
+ if ($null -ne $config.plugins) { $plugins = @($config.plugins) }
33
43
 
34
- try {
35
- $localBuild = $null
36
- if ($PSScriptRoot) {
37
- $candidate = Join-Path $PSScriptRoot "dist\index.js"
38
- if (Test-Path -LiteralPath $candidate) { $localBuild = $candidate }
44
+ if ($Remove) {
45
+ $plugins = @($plugins | Where-Object {
46
+ if ($_ -is [string]) { return -not ($_ -eq $Package -or $_.StartsWith("$Package@")) }
47
+ return ($null -eq $_ -or $_.package -ne $Package)
48
+ })
49
+ } else {
50
+ $present = $plugins | Where-Object {
51
+ if ($_ -is [string]) { return ($_ -eq $Package -or $_.StartsWith("$Package@")) }
52
+ return ($null -ne $_ -and $_.package -eq $Package)
53
+ }
54
+ if (-not $present) { $plugins += $Package }
39
55
  }
40
56
 
41
- if ($localBuild) {
42
- Copy-Item -LiteralPath $localBuild -Destination $temp -Force
43
- Write-Step "Using local build: $localBuild"
57
+ if ($null -eq $config.PSObject.Properties["plugins"]) {
58
+ $config | Add-Member -NotePropertyName "plugins" -NotePropertyValue $plugins -Force
44
59
  } else {
45
- $url = "$rawBase/dist/index.js"
46
- Write-Step "Downloading $url"
47
- Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $temp
60
+ $config.plugins = $plugins
48
61
  }
49
62
 
50
- if (-not (Test-Path -LiteralPath $temp) -or (Get-Item -LiteralPath $temp).Length -eq 0) {
51
- throw "downloaded plugin is empty"
52
- }
53
- if (-not (Select-String -LiteralPath $temp -Pattern "FreePiPlugin" -Quiet)) {
54
- throw "downloaded file does not look like the free-pi plugin"
63
+ $config | ConvertTo-Json -Depth 100 | Set-Content -LiteralPath $file -Encoding UTF8
64
+ if ($Remove) {
65
+ Write-Step "free-pi: eliminado de $file."
66
+ } else {
67
+ Write-Step "free-pi: registrado en $file."
55
68
  }
69
+ }
56
70
 
57
- New-Item -ItemType Directory -Force -Path $pluginDir | Out-Null
58
- if (Test-Path -LiteralPath $target) {
59
- Copy-Item -LiteralPath $target -Destination "$target.bak" -Force
60
- }
61
- Copy-Item -LiteralPath $temp -Destination $target -Force
71
+ $configDir = Get-ConfigDir
72
+
73
+ if ($Uninstall) {
74
+ Update-Config $configDir $true
75
+ $pluginDir = Join-Path $configDir "plugins"
76
+ Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $pluginDir "$PluginName.ts")
62
77
  Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $pluginDir "$PluginName.js")
78
+ & npm uninstall -g $Package 2>$null | Out-Null
79
+ Write-Step "Removed $Package."
80
+ Write-Step "Restart OpenCode to finish."
81
+ return
82
+ }
63
83
 
64
- Write-Step "Installed $PluginName at $target"
65
- Write-Step ""
66
- Write-Step "Next steps:"
67
- Write-Step " 1. Run: opencode auth login -p free-pi"
68
- Write-Step " 2. Restart OpenCode."
69
- Write-Step ""
70
- $credentials = if ($env:FREEPI_CREDENTIALS_PATH) { $env:FREEPI_CREDENTIALS_PATH } else { "%USERPROFILE%\.free-pi\agent\credentials.json" }
71
- Write-Step "Credentials: $credentials"
72
- } finally {
73
- Remove-Item -Force -ErrorAction SilentlyContinue $temp
84
+ if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
85
+ throw "Node.js 20+ is required"
74
86
  }
87
+ if (-not (Get-Command npm -ErrorAction SilentlyContinue)) {
88
+ throw "npm is required"
89
+ }
90
+
91
+ Write-Step "Installing $Package..."
92
+ & npm install -g "$Package@latest"
93
+ if ($LASTEXITCODE -ne 0) { throw "npm install failed" }
94
+
95
+ if (Get-Command opencode -ErrorAction SilentlyContinue) {
96
+ & opencode plugin add "$Package@latest" 2>$null | Out-Null
97
+ if ($LASTEXITCODE -ne 0) {
98
+ & opencode plugin --global "$Package@latest" 2>$null | Out-Null
99
+ }
100
+ }
101
+
102
+ Update-Config $configDir $false
103
+
104
+ Write-Step ""
105
+ Write-Step "Next steps:"
106
+ Write-Step " 1. Run: opencode auth login free-pi"
107
+ Write-Step " 2. Restart OpenCode (or run /reload)."
108
+ Write-Step ""
109
+ $credentials = if ($env:FREEPI_CREDENTIALS_PATH) { $env:FREEPI_CREDENTIALS_PATH } else { "%USERPROFILE%\.free-pi\agent\credentials.json" }
110
+ Write-Step "Credentials: $credentials"
package/install.sh CHANGED
@@ -1,9 +1,7 @@
1
1
  #!/usr/bin/env bash
2
2
  set -euo pipefail
3
3
 
4
- REPO="${FREEPI_OPENCODE_REPO:-eduardo191-star/opencode-free-pi}"
5
- REF="${FREEPI_OPENCODE_REF:-main}"
6
- RAW_BASE="${FREEPI_OPENCODE_RAW_BASE:-https://raw.githubusercontent.com/${REPO}/${REF}}"
4
+ PACKAGE="@eduardo191labs/opencode-free-pi"
7
5
  PLUGIN_NAME="opencode-free-pi"
8
6
 
9
7
  say() {
@@ -15,11 +13,91 @@ fail() {
15
13
  exit 1
16
14
  }
17
15
 
16
+ config_dir="${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}"
17
+
18
+ ensure_config() {
19
+ mkdir -p "$config_dir"
20
+ node - "$config_dir" "$PACKAGE" <<'NODE'
21
+ const { existsSync } = require("node:fs");
22
+ const { readFileSync, writeFileSync } = require("node:fs");
23
+ const { join } = require("node:path");
24
+
25
+ const dir = process.argv[2];
26
+ const pkg = process.argv[3];
27
+ const names = ["opencode.json", "opencode.jsonc", "opencode.json5"];
28
+ let file;
29
+ for (const name of names) {
30
+ const candidate = join(dir, name);
31
+ if (!existsSync(candidate)) continue;
32
+ file = candidate;
33
+ break;
34
+ }
35
+ if (!file) file = join(dir, "opencode.json");
36
+
37
+ let config = { $schema: "https://opencode.ai/config.json" };
38
+ if (existsSync(file)) {
39
+ try {
40
+ config = JSON.parse(readFileSync(file, "utf8"));
41
+ } catch {
42
+ console.log(`free-pi: no se pudo editar ${file} automáticamente.`);
43
+ console.log(`free-pi: añade "${pkg}" a "plugins".`);
44
+ process.exit(0);
45
+ }
46
+ }
47
+
48
+ const plugins = Array.isArray(config.plugins) ? config.plugins : [];
49
+ const present = plugins.some((entry) => {
50
+ if (typeof entry === "string") return entry === pkg || entry.startsWith(`${pkg}@`);
51
+ return entry && entry.package === pkg;
52
+ });
53
+ if (!present) {
54
+ plugins.push(pkg);
55
+ config.plugins = plugins;
56
+ writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
57
+ console.log(`free-pi: registrado en ${file}.`);
58
+ } else {
59
+ console.log(`free-pi: ya estaba registrado en ${file}.`);
60
+ }
61
+ NODE
62
+ }
63
+
64
+ remove_config() {
65
+ node - "$config_dir" "$PACKAGE" <<'NODE'
66
+ const { existsSync } = require("node:fs");
67
+ const { readFileSync, writeFileSync } = require("node:fs");
68
+ const { join } = require("node:path");
69
+
70
+ const dir = process.argv[2];
71
+ const pkg = process.argv[3];
72
+ for (const name of ["opencode.json", "opencode.jsonc", "opencode.json5"]) {
73
+ const file = join(dir, name);
74
+ if (!existsSync(file)) continue;
75
+ try {
76
+ const config = JSON.parse(readFileSync(file, "utf8"));
77
+ if (!Array.isArray(config.plugins)) continue;
78
+ const next = config.plugins.filter((entry) => {
79
+ if (typeof entry === "string") {
80
+ return !(entry === pkg || entry.startsWith(`${pkg}@`));
81
+ }
82
+ return !entry || entry.package !== pkg;
83
+ });
84
+ if (next.length === config.plugins.length) continue;
85
+ config.plugins = next;
86
+ writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
87
+ console.log(`free-pi: eliminado de ${file}.`);
88
+ } catch {
89
+ console.log(`free-pi: edita ${file} y quita "${pkg}" de "plugins".`);
90
+ }
91
+ break;
92
+ }
93
+ NODE
94
+ }
95
+
18
96
  uninstall() {
19
- local config_dir="${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}"
20
- local plugin_dir="${config_dir}/plugins"
21
- rm -f "${plugin_dir}/${PLUGIN_NAME}.ts" "${plugin_dir}/${PLUGIN_NAME}.js"
22
- say "Removed ${PLUGIN_NAME} from ${plugin_dir}"
97
+ remove_config
98
+ rm -f "$config_dir/plugins/${PLUGIN_NAME}.ts" "$config_dir/plugins/${PLUGIN_NAME}.js"
99
+ npm uninstall -g "$PACKAGE" >/dev/null 2>&1 || true
100
+ say "Removed ${PACKAGE}."
23
101
  say "Restart OpenCode to finish."
24
102
  }
25
103
 
@@ -28,45 +106,25 @@ if [ "${1:-}" = "--uninstall" ]; then
28
106
  exit 0
29
107
  fi
30
108
 
31
- command -v curl >/dev/null 2>&1 || fail "curl is required"
32
- [ -n "${HOME:-}" ] || fail "HOME is not set"
33
-
34
- config_dir="${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}"
35
- plugin_dir="${config_dir}/plugins"
36
- target="${plugin_dir}/${PLUGIN_NAME}.ts"
37
- tmp="$(mktemp "${TMPDIR:-/tmp}/${PLUGIN_NAME}.XXXXXX")"
38
- cleanup() {
39
- rm -f "$tmp"
40
- }
41
- trap cleanup EXIT
109
+ command -v node >/dev/null 2>&1 || fail "Node.js 20+ is required"
110
+ command -v npm >/dev/null 2>&1 || fail "npm is required"
42
111
 
43
- script_dir=""
44
- if [ -n "${BASH_SOURCE[0]:-}" ] && [ -f "${BASH_SOURCE[0]}" ]; then
45
- script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
46
- fi
112
+ say "Installing ${PACKAGE}..."
113
+ npm install -g "${PACKAGE}@latest"
47
114
 
48
- if [ -n "$script_dir" ] && [ -f "${script_dir}/dist/index.js" ]; then
49
- cp "${script_dir}/dist/index.js" "$tmp"
50
- say "Using local build: ${script_dir}/dist/index.js"
51
- else
52
- say "Downloading ${RAW_BASE}/dist/index.js"
53
- curl -fsSL --retry 3 --retry-delay 1 "${RAW_BASE}/dist/index.js" -o "$tmp"
115
+ if command -v opencode >/dev/null 2>&1; then
116
+ if opencode plugin add "${PACKAGE}@latest" >/dev/null 2>&1; then
117
+ say "Registered with opencode plugin add."
118
+ elif opencode plugin --global "${PACKAGE}@latest" >/dev/null 2>&1; then
119
+ say "Registered with opencode plugin --global."
120
+ fi
54
121
  fi
55
122
 
56
- [ -s "$tmp" ] || fail "downloaded plugin is empty"
57
- grep -q "FreePiPlugin" "$tmp" || fail "downloaded file does not look like the free-pi plugin"
58
-
59
- mkdir -p "$plugin_dir"
60
- if [ -f "$target" ]; then
61
- cp "$target" "${target}.bak"
62
- fi
63
- mv "$tmp" "$target"
64
- rm -f "${plugin_dir}/${PLUGIN_NAME}.js"
123
+ ensure_config
65
124
 
66
- say "Installed ${PLUGIN_NAME} at ${target}"
67
125
  say ""
68
126
  say "Next steps:"
69
- say " 1. Run: opencode auth login -p free-pi"
70
- say " 2. Restart OpenCode."
127
+ say " 1. Run: opencode auth login free-pi"
128
+ say " 2. Restart OpenCode (or run /reload)."
71
129
  say ""
72
130
  say "Credentials: ${FREEPI_CREDENTIALS_PATH:-~/.free-pi/agent/credentials.json}"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.2.7",
3
+ "version": "0.3.1",
4
4
  "description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,7 +24,7 @@
24
24
  "scripts": {
25
25
  "build": "tsc -p tsconfig.json",
26
26
  "typecheck": "tsc -p tsconfig.json --noEmit",
27
- "test": "npm run build && node test/smoke.mjs",
27
+ "test": "npm run build && node test/smoke.mjs && node test/registry.mjs",
28
28
  "prepublishOnly": "npm run build",
29
29
  "postinstall": "node scripts/postinstall.mjs"
30
30
  },
@@ -47,7 +47,7 @@
47
47
  },
48
48
  "homepage": "https://github.com/eduardo191-star/opencode-free-pi#readme",
49
49
  "engines": {
50
- "node": ">=18"
50
+ "node": ">=20"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/node": "^24.0.0",
@@ -57,6 +57,7 @@
57
57
  "access": "public"
58
58
  },
59
59
  "dependencies": {
60
- "@opencode-ai/plugin": "^1.19.0"
60
+ "@opencode/plugin": "^2.3.2",
61
+ "@opencode/schema": "^2.3.2"
61
62
  }
62
63
  }
@@ -1,32 +1,26 @@
1
- import { copyFile, mkdir, readFile, rm } from "node:fs/promises";
1
+ /**
2
+ * Registers the published package in the global OpenCode configuration.
3
+ *
4
+ * OpenCode V2 loads plugins from the `plugins` list in `opencode.json(c)`.
5
+ * Copying the built file into a plugins directory does not work for this
6
+ * package because it imports `@opencode/plugin` at runtime, so the package has
7
+ * to stay resolvable from node_modules.
8
+ */
9
+
10
+ import { readFile, rm, writeFile } from "node:fs/promises";
2
11
  import { existsSync } from "node:fs";
3
12
  import { homedir } from "node:os";
4
- import { dirname, join, resolve } from "node:path";
5
- import { fileURLToPath } from "node:url";
13
+ import { join } from "node:path";
6
14
 
7
- const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
8
- const source = join(packageRoot, "dist", "index.js");
15
+ const PACKAGE_NAME = "@eduardo191labs/opencode-free-pi";
9
16
  const isGlobal = process.env.npm_config_global === "true";
10
-
11
- if (!isGlobal && process.env.FREEPI_CONFIGURE !== "1") {
12
- console.log(
13
- "free-pi: instalación local; usa `npm i -g` o FREEPI_CONFIGURE=1 para registrar el plugin.",
14
- );
15
- process.exit(0);
16
- }
17
-
18
- if (!existsSync(source)) {
19
- console.error(`free-pi: no se encontró ${source}`);
20
- process.exit(1);
21
- }
17
+ const shouldConfigure = isGlobal || process.env.FREEPI_CONFIGURE === "1";
22
18
 
23
19
  const configDir =
24
20
  process.env.OPENCODE_CONFIG_DIR ||
25
21
  (process.env.XDG_CONFIG_HOME
26
22
  ? join(process.env.XDG_CONFIG_HOME, "opencode")
27
23
  : join(homedir(), ".config", "opencode"));
28
- const pluginDir = join(configDir, "plugins");
29
- const target = join(pluginDir, "opencode-free-pi.ts");
30
24
 
31
25
  function display(file) {
32
26
  const home = homedir();
@@ -34,31 +28,71 @@ function display(file) {
34
28
  return file.replace(home, "~");
35
29
  }
36
30
 
37
- const configNames = ["opencode.json", "opencode.jsonc", "opencode.json5"];
38
- let configured = false;
39
- for (const name of configNames) {
31
+ async function removeLegacyCopy() {
32
+ const legacy = join(configDir, "plugins", "opencode-free-pi.ts");
33
+ if (!existsSync(legacy)) return;
34
+ try {
35
+ const text = await readFile(legacy, "utf8");
36
+ if (text.includes("free-pi")) await rm(legacy, { force: true });
37
+ } catch {}
38
+ }
39
+
40
+ if (!shouldConfigure) {
41
+ console.log(
42
+ `free-pi: instalación local. Añade "${PACKAGE_NAME}" a "plugins" en tu opencode.json.`,
43
+ );
44
+ process.exit(0);
45
+ }
46
+
47
+ await removeLegacyCopy();
48
+
49
+ const candidates = ["opencode.json", "opencode.jsonc", "opencode.json5"];
50
+ let configFile;
51
+ let config;
52
+
53
+ for (const name of candidates) {
40
54
  const file = join(configDir, name);
41
55
  if (!existsSync(file)) continue;
56
+ configFile = file;
42
57
  try {
43
- const text = await readFile(file, "utf8");
44
- configured = /@eduardo191labs\/opencode-free-pi/.test(text);
45
- } catch {}
46
- if (configured) break;
58
+ config = JSON.parse(await readFile(file, "utf8"));
59
+ } catch {
60
+ // Comments or JSON5 cannot be rewritten safely; report the manual step.
61
+ config = undefined;
62
+ }
63
+ break;
47
64
  }
48
65
 
49
- if (configured) {
50
- await rm(target, { force: true });
66
+ if (configFile && !config) {
51
67
  console.log(
52
- "free-pi: el paquete ya está configurado en OpenCode; se omitió el plugin local.",
68
+ `free-pi: no se pudo editar ${display(configFile)} automáticamente.`,
53
69
  );
54
- console.log("free-pi: reinicia OpenCode y ejecuta `opencode plugin list`.");
70
+ console.log(`free-pi: añade "${PACKAGE_NAME}" a "plugins".`);
55
71
  process.exit(0);
56
72
  }
57
73
 
58
- await mkdir(pluginDir, { recursive: true });
59
- await copyFile(source, target);
74
+ if (!config) {
75
+ configFile = join(configDir, "opencode.json");
76
+ config = { $schema: "https://opencode.ai/config.json" };
77
+ }
78
+
79
+ const plugins = Array.isArray(config.plugins) ? config.plugins : [];
80
+ const configured = plugins.some((entry) => {
81
+ if (typeof entry === "string") {
82
+ return entry === PACKAGE_NAME || entry.startsWith(`${PACKAGE_NAME}@`);
83
+ }
84
+ return entry?.package === PACKAGE_NAME;
85
+ });
86
+
87
+ if (!configured) {
88
+ plugins.push(PACKAGE_NAME);
89
+ config.plugins = plugins;
90
+ await writeFile(configFile, `${JSON.stringify(config, null, 2)}\n`);
91
+ console.log(`free-pi: registrado en ${display(configFile)}.`);
92
+ } else {
93
+ console.log(`free-pi: ya estaba registrado en ${display(configFile)}.`);
94
+ }
60
95
 
61
- console.log(`free-pi: plugin instalado en ${display(target)}`);
62
96
  console.log(
63
- "free-pi: reinicia OpenCode y ejecuta `opencode auth login -p free-pi`.",
97
+ "free-pi: ejecuta `opencode auth login -p free-pi` y luego /reload.",
64
98
  );