opencode-apex 0.2.3 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -0
- package/README.md +1 -1
- package/advisor.ts +25 -3
- package/core/advisor-session.ts +42 -0
- package/core/config.ts +4 -2
- package/core/process-context.ts +664 -0
- package/core/server-endpoint.ts +74 -10
- package/docs/ADVISOR.md +55 -3
- package/docs/EVENTS.md +3 -1
- package/events.ts +10 -1
- package/index.ts +1 -1
- package/opencode-apex.jsonc +8 -2
- package/package.json +2 -2
- package/skills/apex-callbacks/SKILL.md +7 -5
- package/skills/apex-callbacks/references/examples.md +2 -2
- package/skills/apex-callbacks/references/reachability.md +32 -4
package/core/server-endpoint.ts
CHANGED
|
@@ -11,13 +11,17 @@
|
|
|
11
11
|
* cuando su pid es este proceso
|
|
12
12
|
* 3. los argumentos `--hostname`/`--port` de `opencode serve`
|
|
13
13
|
*
|
|
14
|
+
* La URL pública (emisores de otras máquinas) sale de: `apex_set_callback_url` (runtime) >
|
|
15
|
+
* `events.server.publicUrl` (config) > el acceso remoto del propio servicio
|
|
16
|
+
* (`opencode service set remote true`, un túnel OpenTunnel que OpenCode mantiene).
|
|
17
|
+
*
|
|
14
18
|
* La auth es HTTP Basic `opencode:<password>`. El password NUNCA se devuelve: solo
|
|
15
19
|
* dónde leerlo, para que no acabe en la conversación (ni en el proveedor del modelo).
|
|
16
20
|
*/
|
|
17
21
|
|
|
18
22
|
import { readdirSync, readFileSync } from "node:fs"
|
|
19
23
|
import { homedir } from "node:os"
|
|
20
|
-
import { join } from "node:path"
|
|
24
|
+
import { basename, join } from "node:path"
|
|
21
25
|
|
|
22
26
|
export const SERVER_USERNAME = "opencode"
|
|
23
27
|
|
|
@@ -35,22 +39,64 @@ export interface ServerEndpoint {
|
|
|
35
39
|
/** URL base del servidor, alcanzable desde esta máquina (null = desconocida). */
|
|
36
40
|
readonly baseUrl: string | null
|
|
37
41
|
readonly source: "config" | "service" | "argv" | null
|
|
38
|
-
/** URL para procesos FUERA de esta máquina (túnel / proxy inverso), si se
|
|
42
|
+
/** URL para procesos FUERA de esta máquina (túnel / proxy inverso), si se conoce. */
|
|
39
43
|
readonly publicUrl: string | null
|
|
44
|
+
/** De dónde salió publicUrl: runtime | config | service-remote (acceso remoto de OpenCode). */
|
|
45
|
+
readonly publicUrlSource: "runtime" | "config" | "service-remote" | null
|
|
40
46
|
/** Directorio del proyecto al que deben ir las llamadas RPC (`location[directory]`). */
|
|
41
47
|
readonly directory: string
|
|
42
48
|
readonly auth: { readonly scheme: "basic"; readonly username: string; readonly password: PasswordSource | null }
|
|
43
49
|
/** URLs completas de los métodos RPC de apex para este directorio. */
|
|
44
|
-
readonly rpc:
|
|
50
|
+
readonly rpc: RpcUrls
|
|
51
|
+
/** Las mismas URLs sobre publicUrl, para emisores de otras máquinas (null sin publicUrl). */
|
|
52
|
+
readonly publicRpc: RpcUrls | null
|
|
45
53
|
readonly hint?: string
|
|
46
54
|
}
|
|
47
55
|
|
|
56
|
+
type RpcUrls = Readonly<Record<"ingest" | "toolsRun" | "status" | "ping", string>>
|
|
57
|
+
|
|
48
58
|
/** `<state>/opencode` — respeta XDG_STATE_HOME igual que OpenCode. */
|
|
49
59
|
export function stateDirectory(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
|
|
50
60
|
const base = env.XDG_STATE_HOME && env.XDG_STATE_HOME.length > 0 ? env.XDG_STATE_HOME : join(home, ".local", "state")
|
|
51
61
|
return join(base, "opencode")
|
|
52
62
|
}
|
|
53
63
|
|
|
64
|
+
/** Config de OpenCode — `OPENCODE_CONFIG_DIR`, si no `<XDG_CONFIG_HOME>/opencode`, como el CLI. */
|
|
65
|
+
export function configDirectory(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
|
|
66
|
+
if (env.OPENCODE_CONFIG_DIR && env.OPENCODE_CONFIG_DIR.length > 0) return env.OPENCODE_CONFIG_DIR
|
|
67
|
+
const base = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.length > 0 ? env.XDG_CONFIG_HOME : join(home, ".config")
|
|
68
|
+
return join(base, "opencode")
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Identidades de OpenTunnel — `<XDG_DATA_HOME>/opentunnel`, como su SDK. */
|
|
72
|
+
export function tunnelDirectory(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
|
|
73
|
+
return join(env.XDG_DATA_HOME ?? join(home, ".local", "share"), "opentunnel")
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* URL del acceso remoto del servicio (`opencode service set remote true`), o null.
|
|
78
|
+
*
|
|
79
|
+
* El servicio sirve su ruta secreta (`remote.route` de su config, que se llama igual que su
|
|
80
|
+
* registro) en el túnel OpenTunnel del perfil `default`: `https://<route>.<hostname>`. Es lo
|
|
81
|
+
* mismo que calcula OpenCode (`RemoteTunnel.hostname`). Dice que está configurado, no que
|
|
82
|
+
* el túnel esté conectado en este momento.
|
|
83
|
+
*/
|
|
84
|
+
export function findServiceRemoteUrl(serviceFile: string, configDir: string, tunnelDir: string): string | null {
|
|
85
|
+
try {
|
|
86
|
+
const config = JSON.parse(readFileSync(join(configDir, basename(serviceFile)), "utf8")) as {
|
|
87
|
+
remote?: { route?: unknown }
|
|
88
|
+
}
|
|
89
|
+
const route = config.remote?.route
|
|
90
|
+
if (typeof route !== "string" || !/^[a-z0-9-]+$/.test(route)) return null
|
|
91
|
+
// Sin tunnel.json el certificado aún no está listo: no hay URL que dar.
|
|
92
|
+
const tunnel = JSON.parse(readFileSync(join(tunnelDir, "default", "tunnel.json"), "utf8")) as { hostname?: unknown }
|
|
93
|
+
if (typeof tunnel.hostname !== "string" || tunnel.hostname.length === 0) return null
|
|
94
|
+
return `https://${route}.${tunnel.hostname}`
|
|
95
|
+
} catch {
|
|
96
|
+
return null
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
54
100
|
/** Host/puerto de `opencode serve` según su argv; null si no es un serve con puerto explícito. */
|
|
55
101
|
export function parseServeArgv(argv: readonly string[]): { host: string; port: number } | null {
|
|
56
102
|
if (!argv.includes("serve")) return null
|
|
@@ -99,13 +145,26 @@ export function rpcUrl(base: string, method: string, directory: string): string
|
|
|
99
145
|
return `${base.replace(/\/+$/, "")}/api/rpc/apex/${method}?location%5Bdirectory%5D=${encodeURIComponent(directory)}`
|
|
100
146
|
}
|
|
101
147
|
|
|
148
|
+
function rpcUrls(base: string, directory: string): RpcUrls {
|
|
149
|
+
return {
|
|
150
|
+
ingest: rpcUrl(base, "events.ingest", directory),
|
|
151
|
+
toolsRun: rpcUrl(base, "tools.run", directory),
|
|
152
|
+
status: rpcUrl(base, "status", directory),
|
|
153
|
+
ping: rpcUrl(base, "ping", directory),
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
102
157
|
export function resolveServerEndpoint(input: {
|
|
103
158
|
readonly directory: string
|
|
104
159
|
readonly configUrl?: string
|
|
105
160
|
readonly publicUrl?: string | null
|
|
161
|
+
/** Quién fijó `publicUrl` (por defecto config). */
|
|
162
|
+
readonly publicUrlFrom?: "runtime" | "config"
|
|
106
163
|
readonly argv?: readonly string[]
|
|
107
164
|
readonly pid?: number
|
|
108
165
|
readonly stateDir?: string
|
|
166
|
+
readonly configDir?: string
|
|
167
|
+
readonly tunnelDir?: string
|
|
109
168
|
}): ServerEndpoint {
|
|
110
169
|
const argv = input.argv ?? process.argv
|
|
111
170
|
const pid = input.pid ?? process.pid
|
|
@@ -141,19 +200,24 @@ export function resolveServerEndpoint(input: {
|
|
|
141
200
|
: null
|
|
142
201
|
|
|
143
202
|
const base = baseUrl ?? "<server-url>"
|
|
144
|
-
const
|
|
203
|
+
const declared = input.publicUrl && input.publicUrl.trim().length > 0 ? input.publicUrl.trim() : null
|
|
204
|
+
// Solo el proceso del servicio sirve el acceso remoto; un `opencode serve` suelto no.
|
|
205
|
+
const remote =
|
|
206
|
+
declared === null && service
|
|
207
|
+
? findServiceRemoteUrl(service.file, input.configDir ?? configDirectory(), input.tunnelDir ?? tunnelDirectory())
|
|
208
|
+
: null
|
|
209
|
+
const publicUrl = declared ?? remote
|
|
210
|
+
const publicUrlSource: ServerEndpoint["publicUrlSource"] =
|
|
211
|
+
declared !== null ? (input.publicUrlFrom ?? "config") : remote !== null ? "service-remote" : null
|
|
145
212
|
return {
|
|
146
213
|
baseUrl,
|
|
147
214
|
source,
|
|
148
215
|
publicUrl,
|
|
216
|
+
publicUrlSource,
|
|
149
217
|
directory: input.directory,
|
|
150
218
|
auth: { scheme: "basic", username: SERVER_USERNAME, password },
|
|
151
|
-
rpc:
|
|
152
|
-
|
|
153
|
-
toolsRun: rpcUrl(base, "tools.run", input.directory),
|
|
154
|
-
status: rpcUrl(base, "status", input.directory),
|
|
155
|
-
ping: rpcUrl(base, "ping", input.directory),
|
|
156
|
-
},
|
|
219
|
+
rpc: rpcUrls(base, input.directory),
|
|
220
|
+
publicRpc: publicUrl ? rpcUrls(publicUrl, input.directory) : null,
|
|
157
221
|
...(baseUrl
|
|
158
222
|
? {}
|
|
159
223
|
: { hint: "Server URL unknown: set events.server.url in the apex config (e.g. http://127.0.0.1:4096)" }),
|
package/docs/ADVISOR.md
CHANGED
|
@@ -101,6 +101,7 @@ The advisor module is **on by default** (`modules.advisor`). Set `"advisor": fal
|
|
|
101
101
|
"timeoutMs": 10000, // wait this long for an answer, then leave the permission as it was
|
|
102
102
|
"actions": [], // tool names to judge; empty = all
|
|
103
103
|
"location": "", // advisor session directory; empty = <tmp>/opencode-apex-advisor
|
|
104
|
+
"processContext": true, // describe the processes a kill/pkill/killall would hit (Linux)
|
|
104
105
|
"system": "…", // optional: replaces the advisor's system prompt
|
|
105
106
|
"promptTemplate": "…", // optional: the request text sent to the advisor
|
|
106
107
|
"promptTemplateFile": "…" // optional: same, from a file (wins over promptTemplate)
|
|
@@ -109,10 +110,60 @@ The advisor module is **on by default** (`modules.advisor`). Set `"advisor": fal
|
|
|
109
110
|
|
|
110
111
|
- **Template placeholders:** `{{requestID}}`, `{{action}}`, `{{resources}}`, `{{sessionID}}`,
|
|
111
112
|
`{{agent}}`, `{{enforcement}}` (a sentence that tells the advisor whether its decision is
|
|
112
|
-
applied)
|
|
113
|
+
applied), `{{processes}}` (see [below](#killing-processes-whose-process-is-it)) and
|
|
114
|
+
`{{metadata.<path>}}`.
|
|
113
115
|
- **`promptTemplateFile`** must be a relative path, inside the project or your home
|
|
114
116
|
directory. If the file does not exist, it is created with the default template.
|
|
115
117
|
|
|
118
|
+
## Killing processes: whose process is it?
|
|
119
|
+
|
|
120
|
+
A permission for `kill 705875` tells the advisor nothing about process 705875. It could
|
|
121
|
+
be the dev server the agent started a minute ago, or your browser. An advisor told to
|
|
122
|
+
deny "killing processes that are not ours" can only guess, and a careful one denies. (Measured
|
|
123
|
+
before 0.2.4: every plain `kill <PID>` was denied, while `pkill -f "n8n start"` — where
|
|
124
|
+
the name is visible — was allowed.)
|
|
125
|
+
|
|
126
|
+
With `processContext: true` (the default), apex reads `/proc` before asking. For every
|
|
127
|
+
`kill`, `pkill`, `killall` and `kill $(pgrep …)` in a `shell` permission it adds a block like
|
|
128
|
+
this to the request:
|
|
129
|
+
|
|
130
|
+
```
|
|
131
|
+
Procesos afectados (leído de /proc por apex, no lo afirma el agente):
|
|
132
|
+
- PID 751365 · antonio · lanzado por un agente de ESTA conversación (o uno de sus subagentes)
|
|
133
|
+
sleep 60
|
|
134
|
+
- PID 2914 · antonio · del usuario, no lanzado por opencode
|
|
135
|
+
/usr/bin/kwin_wayland_wrapper --xwayland
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
For each process it reports:
|
|
139
|
+
|
|
140
|
+
| Field | How apex knows |
|
|
141
|
+
| --- | --- |
|
|
142
|
+
| owner | `Uid` in `/proc/<pid>/status` |
|
|
143
|
+
| command | `/proc/<pid>/cmdline` |
|
|
144
|
+
| who launched it | OpenCode's `shell` tool exports `OPENCODE_SESSION_ID` to every command it runs. apex reads it from `/proc/<pid>/environ` (or from a parent's, for processes started with `nohup`/`setsid`) and checks whether that session belongs to the same session tree as the one asking |
|
|
145
|
+
| critical | the OpenCode server itself, any of its parents (the terminal holding it) or PID 1 |
|
|
146
|
+
|
|
147
|
+
The labels are: **this conversation** (launched by the asking session, its root or any
|
|
148
|
+
subagent of that tree), **another OpenCode conversation**, **the user's** (same user, not
|
|
149
|
+
launched by OpenCode), **another user's** (root or a different account) and **unknown**
|
|
150
|
+
(environment not readable). `kill -1`, `kill 0` and process groups get an explicit
|
|
151
|
+
warning; a `pkill` pattern that matches nothing says so.
|
|
152
|
+
|
|
153
|
+
apex only **describes**; the advisor still decides. Give it a rule that uses the block,
|
|
154
|
+
for example: *"Allow killing processes launched by this conversation. Deny killing
|
|
155
|
+
processes marked CRÍTICO, other users' processes and `kill -1`. For the user's own
|
|
156
|
+
processes, allow only if the command is clearly what the agent is working on."*
|
|
157
|
+
|
|
158
|
+
Notes:
|
|
159
|
+
|
|
160
|
+
- The block is part of the cache key, so an answer for `kill 1234` is not reused once
|
|
161
|
+
PID 1234 belongs to a different process.
|
|
162
|
+
- Your own `promptTemplate` does not need `{{processes}}`: if it is missing, the block is
|
|
163
|
+
appended at the end.
|
|
164
|
+
- Linux only. On other systems, or if `/proc` cannot be read, nothing is added and the
|
|
165
|
+
request is the same as before.
|
|
166
|
+
|
|
116
167
|
## Keeping the project's AGENTS.md away from the advisor
|
|
117
168
|
|
|
118
169
|
OpenCode V2 has no per-agent instructions. Every session gets the instruction files found
|
|
@@ -138,8 +189,9 @@ in the session's `metadata.apexAdvisorLocation`.
|
|
|
138
189
|
the link in `metadata.apexAdvisorFor`.
|
|
139
190
|
- **Each uncached decision costs one model round trip.** With `evaluate: "all"`, every tool
|
|
140
191
|
call waits for it.
|
|
141
|
-
- **The cache key is only `(action, resources)
|
|
142
|
-
for any other agent asking the same thing within
|
|
192
|
+
- **The cache key is only `(action, resources)`**, plus the process block for kills. An
|
|
193
|
+
answer given for one agent is reused for any other agent asking the same thing within
|
|
194
|
+
10 minutes.
|
|
143
195
|
- **A missing answer never blocks you:** after `timeoutMs` the normal prompt appears.
|
|
144
196
|
|
|
145
197
|
## Working with the guard
|
package/docs/EVENTS.md
CHANGED
|
@@ -189,7 +189,9 @@ outside process reaches THIS server:
|
|
|
189
189
|
| `baseUrl` · `source` | Base URL and where it came from, in this order: `config` (`events.server.url`) > `service` (the background service record `<state>/opencode/service*.json` whose `pid` is this process; `<state>` is `$XDG_STATE_HOME` or `~/.local/state`) > `argv` (the `--hostname`/`--port` of `opencode serve`). `null` if none applies. |
|
|
190
190
|
| `rpc.ingest` · `rpc.toolsRun` · `rpc.status` · `rpc.ping` | Full URLs of the methods, already carrying this project's `location[directory]`. |
|
|
191
191
|
| `auth` | `{scheme:"basic", username:"opencode", password}`. `password` says **where** the password is, never the password itself: `{kind:"file", file, field:"password", shell}` for the background service (the record is a `0600` file), `{kind:"env", env:"OPENCODE_SERVER_PASSWORD", shell}` for `opencode serve`, or `null` if unknown. `shell` is a command that prints it. |
|
|
192
|
-
| `publicUrl` | URL for senders on **other machines** (a tunnel or reverse proxy in front of the server). Runtime value (tool `apex_set_callback_url`) > `events.server.publicUrl
|
|
192
|
+
| `publicUrl` | URL for senders on **other machines** (a tunnel or reverse proxy in front of the server). Runtime value (tool `apex_set_callback_url`) > `events.server.publicUrl` > OpenCode's remote access (`opencode service set remote true`), which is found automatically. |
|
|
193
|
+
| `publicUrlSource` | `runtime`, `config`, `service-remote` or `null` |
|
|
194
|
+
| `publicRpc` | The `rpc.*` URLs built on `publicUrl` (the `rpc.*` URLs always use `baseUrl`); `null` without `publicUrl` |
|
|
193
195
|
| `examples` | Ready-to-run `curl` commands for `ingest` and `toolsRun` (they read the password at run time). Tool only; `server.info` omits them. |
|
|
194
196
|
| `hint` | Present when `baseUrl` is unknown: set `events.server.url`. |
|
|
195
197
|
|
package/events.ts
CHANGED
|
@@ -463,6 +463,13 @@ function registerCallbackEndpointTool(
|
|
|
463
463
|
baseUrl: { type: ["string", "null"], description: "Server base URL, as reachable from this machine" },
|
|
464
464
|
source: { type: ["string", "null"], description: "Where baseUrl came from: config | service | argv" },
|
|
465
465
|
publicUrl: { type: ["string", "null"], description: "URL for senders on other machines (tunnel/proxy)" },
|
|
466
|
+
publicUrlSource: {
|
|
467
|
+
type: ["string", "null"],
|
|
468
|
+
description:
|
|
469
|
+
"runtime (apex_set_callback_url) | config | service-remote (OpenCode remote access: " +
|
|
470
|
+
"`opencode service set remote true`)",
|
|
471
|
+
},
|
|
472
|
+
publicRpc: { type: ["object", "null"], description: "The rpc URLs over publicUrl, for remote senders" },
|
|
466
473
|
directory: { type: "string", description: "Value of location[directory] for every call" },
|
|
467
474
|
auth: { type: "object", description: "Basic opencode:<password>; password says where it is, password.shell prints it" },
|
|
468
475
|
rpc: { type: "object", description: "Full URLs: ingest, toolsRun, status, ping" },
|
|
@@ -510,7 +517,8 @@ function registerSetCallbackUrlTool(
|
|
|
510
517
|
description:
|
|
511
518
|
"Sets (or clears) the public URL through which programs on OTHER machines reach this OpenCode " +
|
|
512
519
|
"server, e.g. a tunnel (cloudflared/ngrok) pointing at its base URL. It is persisted and shown by " +
|
|
513
|
-
"apex_callback_endpoint. Pass null to clear it. Precedence: runtime > config
|
|
520
|
+
"apex_callback_endpoint. Pass null to clear it. Precedence: runtime > config > OpenCode remote " +
|
|
521
|
+
"access (found on its own; usually there is no need to set it).",
|
|
514
522
|
input: {
|
|
515
523
|
type: "object",
|
|
516
524
|
properties: {
|
|
@@ -865,6 +873,7 @@ export function register(
|
|
|
865
873
|
directory: ctx.location.directory,
|
|
866
874
|
configUrl: eventsConfig.server.url,
|
|
867
875
|
publicUrl: state.runtimePublicUrl ?? eventsConfig.server.publicUrl ?? null,
|
|
876
|
+
publicUrlFrom: state.runtimePublicUrl ? "runtime" : "config",
|
|
868
877
|
})
|
|
869
878
|
yield* registerCallbackEndpointTool(ctx, endpoint)
|
|
870
879
|
yield* registerSetCallbackUrlTool(ctx, state, endpoint)
|
package/index.ts
CHANGED
|
@@ -26,7 +26,7 @@ import { registerSkills } from "./core/skills.js"
|
|
|
26
26
|
import { compatibilityWarnings } from "./core/compat.js"
|
|
27
27
|
|
|
28
28
|
// Plugin version
|
|
29
|
-
const VERSION = "0.2.
|
|
29
|
+
const VERSION = "0.2.5"
|
|
30
30
|
|
|
31
31
|
interface ModuleConfigs {
|
|
32
32
|
redact: RedactConfig & { enabled: boolean }
|
package/opencode-apex.jsonc
CHANGED
|
@@ -257,9 +257,14 @@
|
|
|
257
257
|
// injected. (The global AGENTS.md in ~/.config/opencode always applies.)
|
|
258
258
|
// actions: filter by tool name (empty = all)
|
|
259
259
|
// system: system prompt of the advisor agent (optional)
|
|
260
|
+
// processContext: before judging kill / pkill / killall, read /proc and tell the
|
|
261
|
+
// advisor whose process each target is: owner, command, whether an agent
|
|
262
|
+
// of THIS conversation launched it, and whether it is critical (OpenCode
|
|
263
|
+
// itself). Linux only. (default true)
|
|
260
264
|
// promptTemplate: template of each request ({{requestID}}, {{action}}, {{resources}},
|
|
261
|
-
// {{sessionID}}, {{agent}}, {{enforcement}}, {{metadata.<field>}}).
|
|
262
|
-
//
|
|
265
|
+
// {{sessionID}}, {{agent}}, {{enforcement}}, {{processes}}, {{metadata.<field>}}).
|
|
266
|
+
// A template without {{processes}} gets the block appended at the end.
|
|
267
|
+
// A single-line JSON string: write line breaks as \n.
|
|
263
268
|
// --------------------------------------------------------------------------
|
|
264
269
|
"advisor": {
|
|
265
270
|
"model": "opencode/big-pickle",
|
|
@@ -268,6 +273,7 @@
|
|
|
268
273
|
"timeoutMs": 10000,
|
|
269
274
|
"location": "",
|
|
270
275
|
"actions": [],
|
|
276
|
+
"processContext": true,
|
|
271
277
|
"promptTemplate": "Request {{requestID}}\nTool: {{action}}\nResources: {{resources}}\nSession: {{sessionID}} ({{agent}})\n{{enforcement}}\nDecide with apex_advisor_decide."
|
|
272
278
|
}
|
|
273
279
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-apex",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.5",
|
|
4
4
|
"description": "Modular plugin for OpenCode V2 (>= 2.1): secret redaction, RPC callbacks/webhooks/watchers that wake agents, tools.run, AI permission advisor, guard meta-permissions, external browser over CDP",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Antonio Orizondo Leyva",
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
"bun-types": "^1.1.0"
|
|
60
60
|
},
|
|
61
61
|
"scripts": {
|
|
62
|
-
"test": "bun test/events.test.ts && bun test/guard.test.ts",
|
|
62
|
+
"test": "bun test/events.test.ts && bun test/guard.test.ts && bun test/process-context.test.ts",
|
|
63
63
|
"typecheck": "tsc --noEmit -p .",
|
|
64
64
|
"check:install": "node scripts/check-install.mjs",
|
|
65
65
|
"prepublishOnly": "npm test && npm run typecheck && npm run check:install"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: apex-callbacks
|
|
3
|
-
description: Wake an agent up from outside the conversation with opencode-apex (OpenCode V2). Use it to build a relay that turns incoming events into agent tasks — messages (WhatsApp, Telegram, Slack, Matrix, Beeper…), emails, webhooks (GitHub, Stripe, n8n…), queues, any API — or a watcher that checks something on a schedule ("every 5 minutes, is X up?"), or a notification when a job finishes. Covers the server endpoint, subscriptions, writing and running relays in any language and OS, calling OpenCode tools and MCP servers from relay code (tools.run), and receiving Internet webhooks on a machine behind NAT (tunnels
|
|
3
|
+
description: Wake an agent up from outside the conversation with opencode-apex (OpenCode V2). Use it to build a relay that turns incoming events into agent tasks — messages (WhatsApp, Telegram, Slack, Matrix, Beeper…), emails, webhooks (GitHub, Stripe, n8n…), queues, any API — or a watcher that checks something on a schedule ("every 5 minutes, is X up?"), or a notification when a job finishes. Covers the server endpoint, subscriptions, writing and running relays in any language and OS, calling OpenCode tools and MCP servers from relay code (tools.run), and receiving Internet webhooks on a machine behind NAT (OpenTunnel or other tunnels, OpenCode remote access, reverse connections, store-and-forward).
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Waking agents from outside: relays, watchers and webhooks
|
|
@@ -38,7 +38,8 @@ Call **`apex_callback_endpoint`**. It returns:
|
|
|
38
38
|
| `rpc.ingest` / `rpc.toolsRun` | Full URLs of the methods, already carrying this project's `location[directory]` |
|
|
39
39
|
| `auth.username` | always `opencode` (HTTP Basic) |
|
|
40
40
|
| `auth.password` | **Where** the password is: `{kind:"file", file, field}` (the service's `0600` record) or `{kind:"env", env}` |
|
|
41
|
-
| `publicUrl` | URL for senders on **other** machines (
|
|
41
|
+
| `publicUrl` / `publicUrlSource` | URL for senders on **other** machines, if known. `service-remote` = OpenCode's own remote access (`opencode service set remote true`), found automatically; `runtime` / `config` = set by hand |
|
|
42
|
+
| `publicRpc` | The `rpc.*` URLs over `publicUrl`, for those remote senders |
|
|
42
43
|
| `examples` | `curl` commands ready to copy |
|
|
43
44
|
|
|
44
45
|
- **Never write the password** into code, unit files, crontab or the conversation. Programs read it when they need it, from `auth.password.file` or from the variable in `auth.password.env`. Read it again on every call: the port and the password change when OpenCode restarts.
|
|
@@ -100,10 +101,11 @@ Patterns, the source catalog (WebSocket, SSE, IMAP, polling, queues…), state a
|
|
|
100
101
|
- A relay that **connects out** to the source can run on a laptop behind NAT next to OpenCode. Examples: WebSocket, SSE, long-poll, IMAP IDLE, polling an API, consuming a queue. This is the default: prefer it whenever the service offers it.
|
|
101
102
|
- A **webhook** means the service connects **in**. A relay on `127.0.0.1` or a home PC behind NAT **cannot be reached from the Internet** unless you add one of these:
|
|
102
103
|
1. the service's outbound mode (Slack Socket Mode, Discord Gateway, Telegram `getUpdates`, Gmail via Pub/Sub pull);
|
|
103
|
-
2. a tunnel (Cloudflare Tunnel, Tailscale Funnel
|
|
104
|
+
2. a tunnel: **OpenTunnel** first (`opentunnel route add <relay port>`, from the makers of OpenCode, no account), then Cloudflare Tunnel, Tailscale Funnel or ngrok;
|
|
104
105
|
3. a reverse SSH connection to a VPS;
|
|
105
106
|
4. a small public receiver that stores events while the local relay pulls them (store-and-forward, which survives the PC being off).
|
|
106
|
-
- OpenCode listens on loopback. Run the relay **on the same machine** and expose **the relay**, with its own token, never the OpenCode server
|
|
107
|
+
- OpenCode listens on loopback. Run the relay **on the same machine** and expose **the relay**, with its own token, never the OpenCode server: the URL and password of the server give full control of OpenCode. Third-party webhooks (GitHub, Stripe…) always go to a relay.
|
|
108
|
+
- If a sender **you control** on another machine (n8n on a VPS, your phone) must call OpenCode itself, the user turns on OpenCode's remote access: `opencode service set remote true`. `apex_callback_endpoint` then reports it on its own (`publicUrlSource: "service-remote"`) and the sender uses `publicRpc.*`. Any other tunnel to the server: announce it with `apex_set_callback_url({url})`, clear it with `{url: null}`.
|
|
107
109
|
|
|
108
110
|
Options, commands and security for inbound traffic: **`references/reachability.md`**.
|
|
109
111
|
|
|
@@ -173,6 +175,6 @@ All of them: `POST <baseUrl>/api/rpc/apex/<method>?location[directory]=<project>
|
|
|
173
175
|
| File | When |
|
|
174
176
|
| --- | --- |
|
|
175
177
|
| `references/relays.md` | Designing any relay: the loop, source catalog, event shape, cursor and dedupe, outbox, several projects, `tools.run` in code |
|
|
176
|
-
| `references/reachability.md` | Webhooks or senders on other machines: outbound modes, Cloudflare/Tailscale/ngrok tunnels, reverse SSH, store-and-forward, signature checks |
|
|
178
|
+
| `references/reachability.md` | Webhooks or senders on other machines: outbound modes, OpenTunnel and OpenCode remote access, Cloudflare/Tailscale/ngrok tunnels, reverse SSH, store-and-forward, signature checks |
|
|
177
179
|
| `references/run-anywhere.md` | Keeping a relay or watcher alive on Linux, macOS, Windows, Docker, pm2, and removing it |
|
|
178
180
|
| `references/examples.md` | Copyable code: sh watcher, Python SSE relay, Node webhook relay, PowerShell ingest, n8n recipe, `tools.run` calls |
|
|
@@ -229,7 +229,7 @@ createServer(async (req, res) => {
|
|
|
229
229
|
```
|
|
230
230
|
|
|
231
231
|
- Generate the token with `openssl rand -hex 24`, or `[guid]::NewGuid()` twice on Windows.
|
|
232
|
-
- The sender calls `https://<tunnel>/<type>?token=<RELAY_TOKEN>`.
|
|
232
|
+
- Publish the port with `opentunnel route add 8787` (or another tunnel, `reachability.md`). The sender calls `https://<tunnel>/<type>?token=<RELAY_TOKEN>`.
|
|
233
233
|
- GitHub payloads are large. Before shipping, trim `payload.body` to the fields the agent needs.
|
|
234
234
|
|
|
235
235
|
## 4. Ingest from PowerShell (Windows PowerShell 5.1 and PowerShell 7)
|
|
@@ -258,4 +258,4 @@ Use a *Webhook* node, then an *HTTP Request* node: `POST <rpc.ingest>` with Basi
|
|
|
258
258
|
{"input":{"source":"github","type":"{{$json.headers['x-github-event']}}","eventID":"github:{{$json.headers['x-github-delivery']}}","payload":{{JSON.stringify($json.body)}}}}
|
|
259
259
|
```
|
|
260
260
|
|
|
261
|
-
If n8n runs on another machine, it cannot reach OpenCode's loopback. Either
|
|
261
|
+
If n8n runs on another machine, it cannot reach OpenCode's loopback. Either turn on OpenCode's remote access and use `publicRpc.ingest` from `apex_callback_endpoint` (`reachability.md`, last section), or let n8n store events while a local relay pulls them (`reachability.md`, option D).
|
|
@@ -13,7 +13,7 @@ Facts to start from:
|
|
|
13
13
|
| Stream or poll API (WebSocket, SSE, long-poll, IMAP, queue) | next to OpenCode | yes | default; nothing to expose |
|
|
14
14
|
| Internet webhook | next to OpenCode, behind NAT | **no** | A, B, C or D below |
|
|
15
15
|
| Service on the same LAN (n8n at home, a NAS) | next to OpenCode | yes, if routable | bind the relay to the LAN address, with a token and a firewall rule |
|
|
16
|
-
| Anything | on another machine (a VPS) | only if it can reach OpenCode | prefer D: the VPS stores events and the local relay pulls them. Otherwise
|
|
16
|
+
| Anything | on another machine (a VPS) | only if it can reach OpenCode | prefer D: the VPS stores events and the local relay pulls them. Otherwise OpenCode's remote access (see the end of this file) |
|
|
17
17
|
| Anything | OpenCode itself runs on a server with a public address | yes | the relay is local to it; expose the relay only |
|
|
18
18
|
|
|
19
19
|
## A. The provider's outbound mode (best: nothing exposed)
|
|
@@ -35,6 +35,23 @@ Look for it before reaching for a tunnel:
|
|
|
35
35
|
|
|
36
36
|
The tunnel client connects **out** to the provider. The provider gives you a public HTTPS URL that forwards to a local port. Point it at **the relay's port**, never at the OpenCode server.
|
|
37
37
|
|
|
38
|
+
**OpenTunnel (first choice)**: by Anomaly, the makers of OpenCode. No account. TLS ends on your machine, so the relay server cannot read the traffic. Prebuilt for Linux and macOS.
|
|
39
|
+
- Install: `curl -fsSL https://opentunnel.xyz/install | sh`, `brew install anomalyco/tap/opentunnel`, or `npm install -g opentunnel`.
|
|
40
|
+
- Publish the relay:
|
|
41
|
+
```sh
|
|
42
|
+
opentunnel route add 8787 # prints https://<random route>.<id>.opentunnel.xyz
|
|
43
|
+
opentunnel route add 8787 --name hooks # readable name instead: https://hooks.<id>.opentunnel.xyz
|
|
44
|
+
opentunnel status # routes, connection, log
|
|
45
|
+
opentunnel route remove <name> # unpublish
|
|
46
|
+
```
|
|
47
|
+
- The first run creates the device's tunnel and its certificate, which takes about a minute. After that, a background service (`opentunnel-default.service` with systemd, launchd on macOS) keeps the route connected, starts at login and reconnects by itself. The URL stays the same while the tunnel exists. `opentunnel delete --yes` drops it for good.
|
|
48
|
+
- It is the same tunnel that OpenCode's remote access uses. Each one claims its own route, so they live side by side. Never route the OpenCode server's port yourself: use remote access for that (end of this file).
|
|
49
|
+
- What the relay can trust:
|
|
50
|
+
- Every request arrives from `127.0.0.1` with the visitor's own `Host` header, so the relay **cannot** tell a tunneled request from a local one. Never skip the token or signature check because a request "looks local".
|
|
51
|
+
- A random route is hard to guess, but it is not authentication: anyone who has the URL reaches the relay.
|
|
52
|
+
- To get the visitor's IP, add `--proxy-protocol v2`, and only for a listener that expects that header.
|
|
53
|
+
- Limits: free hosted service without an uptime guarantee, about 30 new tunnels per hour per IP. You can self-host the server (`OPENTUNNEL_API=<your server>`).
|
|
54
|
+
|
|
38
55
|
**Cloudflare Tunnel (`cloudflared`)**
|
|
39
56
|
- **Quick tunnel**, no account, for tests: `cloudflared tunnel --url http://127.0.0.1:8787` prints a random `https://….trycloudflare.com`. The URL changes on every run and has no uptime guarantee.
|
|
40
57
|
- **Named tunnel**, stable. It needs a Cloudflare account and a domain on Cloudflare:
|
|
@@ -84,9 +101,20 @@ local relay ──▶ events.ingest
|
|
|
84
101
|
|
|
85
102
|
## Calling OpenCode from another machine (only if you must)
|
|
86
103
|
|
|
87
|
-
Prefer running the relay next to OpenCode.
|
|
88
|
-
|
|
89
|
-
|
|
104
|
+
Prefer running the relay next to OpenCode. Only a sender **you control** may call OpenCode itself, for example n8n on your VPS or a script on your phone. Never give the server URL and password to a third party: together they give full control of OpenCode (sessions, shell, files). Third-party webhooks go to a relay (section B).
|
|
105
|
+
|
|
106
|
+
**OpenCode's remote access (preferred).** The background service publishes itself through OpenTunnel:
|
|
107
|
+
1. The user runs `opencode service set remote true` or `opencode pair --remote`. It is a change to their machine, so ask first. It works only when OpenCode runs as the background service (`opencode service`), not with `opencode serve` in a terminal.
|
|
108
|
+
2. Call `apex_callback_endpoint`. It finds the URL on its own: `publicUrlSource: "service-remote"`, `publicUrl: https://<secret route>.<id>.opentunnel.xyz`, and the sender uses `publicRpc.*`. Auth is the same Basic `opencode:<password>`: without it the server answers 401.
|
|
109
|
+
3. The sender stores the password as its own secret, for example an n8n credential. It is the password from `auth.password` on this machine. It changes if the service password is reset.
|
|
110
|
+
4. Remote access tells you it is configured, not that it is connected right now. Check with `curl -u … <publicRpc.status>` and expect HTTP 200.
|
|
111
|
+
5. To turn it off: `opencode service set remote false`.
|
|
112
|
+
|
|
113
|
+
The tunnel lives in the OpenCode service, not in apex. It keeps working while apex is unloaded after 60 minutes idle, and the first RPC loads apex again.
|
|
114
|
+
|
|
115
|
+
**Any other tunnel or reverse proxy to the server** (Cloudflare, Tailscale, your own nginx):
|
|
116
|
+
1. Use TLS, and restrict access at the edge if you can (IP allowlist, Access policy).
|
|
117
|
+
2. Announce the URL with `apex_set_callback_url({url})`. `apex_callback_endpoint` then reports it as `publicUrl`, and it wins over remote access.
|
|
90
118
|
3. Clear it with `apex_set_callback_url({url: null})` when done.
|
|
91
119
|
|
|
92
120
|
## Securing an inbound relay
|