opencode-apex 0.6.0 → 0.8.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.
- package/CHANGELOG.md +107 -0
- package/README.md +5 -1
- package/advisor.ts +77 -10
- package/browser.ts +26 -0
- package/core/advisor-session.ts +164 -3
- package/core/config.ts +46 -1
- package/core/cred-channel.ts +300 -0
- package/core/cred.ts +145 -24
- package/core/kdbx.ts +374 -0
- package/core/server-endpoint.ts +16 -0
- package/core/tools-run.ts +22 -7
- package/cred.ts +865 -131
- package/daemon/main.ts +89 -7
- package/daemon/mcp.ts +261 -0
- package/daemon/shared.ts +9 -0
- package/docs/ADVISOR.md +17 -1
- package/docs/CONFIG.md +3 -1
- package/docs/CRED.md +129 -44
- package/docs/ENDPOINTS.md +11 -3
- package/docs/EVENTS.md +42 -0
- package/endpoints.ts +106 -2
- package/index.ts +14 -3
- package/opencode-apex.jsonc +3 -1
- package/package.json +10 -6
- package/skills/apex-callbacks/SKILL.md +7 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,113 @@ All notable changes to `opencode-apex`. Format based on
|
|
|
5
5
|
|
|
6
6
|
## [Unreleased]
|
|
7
7
|
|
|
8
|
+
## [0.8.1] — 2026-12-04
|
|
9
|
+
|
|
10
|
+
### Fixed (Cred)
|
|
11
|
+
|
|
12
|
+
- **`/cred help` (and every `/cred` reply) showed nothing.** A `synthetic` only appears when a
|
|
13
|
+
turn takes it from the inbox, and with `resume: false` that waited for the next prompt;
|
|
14
|
+
even then the app shows a synthetic by its one-line `description` only. Replies now use
|
|
15
|
+
`delivery: "queue"` with `resume: true`, so the session runs a turn that puts them on
|
|
16
|
+
screen right away: in a claude-* session acpbridge answers it itself, free and verbatim
|
|
17
|
+
(the text starts with its `<!-- acp-notice -->` marker); any other model is asked, in an
|
|
18
|
+
HTML comment, to repeat the block as is. The `context` hook keeps the reply only in that
|
|
19
|
+
turn's request; later requests, compactions and `generate` drop both the reply and the
|
|
20
|
+
text-only answer that echoed it.
|
|
21
|
+
|
|
22
|
+
### Added (Advisor)
|
|
23
|
+
|
|
24
|
+
- **`advisor.markRead`** (default `true`): when the advisor answers with
|
|
25
|
+
`apex_advisor_decide` and its turn ends, its session is marked read and archived again
|
|
26
|
+
(`session.prompt` unarchives it), so it no longer shows as unread in the app. A turn that
|
|
27
|
+
ends without a decision stays unread. The plugin API exposes neither `session.view` nor
|
|
28
|
+
`archived`, so apex calls its own server (`POST /api/session/:id/view`,
|
|
29
|
+
`PATCH /api/session/:id`) with the service password, read in-process and never exposed.
|
|
30
|
+
|
|
31
|
+
## [0.8.0] — 2026-12-04
|
|
32
|
+
|
|
33
|
+
### Added (Automations bridge)
|
|
34
|
+
|
|
35
|
+
- **`apex.event`: anything `events.ingest` accepts can trigger an OpenCode automation.**
|
|
36
|
+
Verified end to end against OpenCode 2.4.4 (shell and code actions, source filter, server
|
|
37
|
+
and daemon restarts). OpenCode's automations (≥ 2.4.1) run on timers or on MCP events, but have no webhook or HTTP
|
|
38
|
+
trigger. The apex daemon now serves an MCP server with the Events extension (SEP-3415,
|
|
39
|
+
protocol `2026-07-28`) on 127.0.0.1, and the plugin registers it as `apex` through
|
|
40
|
+
`ctx.mcp.transform`. Each accepted ingest (verified `apex_webhook`, relays, scripts) is
|
|
41
|
+
forwarded to it, so `{ type: "event", server: "apex", event: "apex.event", args: { source?,
|
|
42
|
+
type? } }` fires the automation with `{ id, source, type?, payload, receivedAt }`.
|
|
43
|
+
- Per-project URL (`/mcp/<directory>`): an automation only sees its own project's events.
|
|
44
|
+
- Replay after a disconnect from an in-memory buffer (500 events), with `truncated` when
|
|
45
|
+
events are missing (another daemon run, buffer overflow).
|
|
46
|
+
- Port and token stay the same across daemon restarts (`mcp.json`, 0600), so the MCP entry
|
|
47
|
+
stays valid; if the port is taken, the plugin re-registers it on its next ping.
|
|
48
|
+
- The daemon no longer exits idle while event streams are open or a plugin pinged it in
|
|
49
|
+
the last 10 minutes (the plugin pings every minute), so automations can always be created.
|
|
50
|
+
- New switch `modules.automations` (default on with `events` and `endpoints`). A server
|
|
51
|
+
named `apex` in your own MCP config takes precedence.
|
|
52
|
+
- Built on `createMcpHandler` from `@modelcontextprotocol/server` 2.4.0 (new dependency);
|
|
53
|
+
`events/list` and `events/stream` are implemented in `daemon/mcp.ts`.
|
|
54
|
+
- Docs: `docs/EVENTS.md` explains when to use automations (schedules, checks) and when apex
|
|
55
|
+
(anything that comes from outside); the `apex-callbacks` skill recommends automations over
|
|
56
|
+
writing a watcher when OpenCode has them.
|
|
57
|
+
- Version 0.8.0 in `package.json` and `index.ts`: a running 0.7.0 daemon (without the MCP
|
|
58
|
+
server) is replaced when the plugin loads.
|
|
59
|
+
|
|
60
|
+
### Added (Cred)
|
|
61
|
+
|
|
62
|
+
- **`/cred help`** (also `-h`, `--help`, `ayuda`, or `/cred` with no arguments): the full user
|
|
63
|
+
manual — saving, listing, removing, KDBX, `/cred learn`, how the agent uses `apex_cred`, tips.
|
|
64
|
+
An unknown subcommand prints the error followed by the manual.
|
|
65
|
+
|
|
66
|
+
### Fixed (Cred)
|
|
67
|
+
|
|
68
|
+
- **`/cred` replies were reaching the model.** They are `synthetic` messages, which the model
|
|
69
|
+
does see (an old comment claimed otherwise). Every reply now carries `metadata.apexUiOnly`
|
|
70
|
+
and the module drops those messages in the `context`, `compaction` and `generate` hooks, so
|
|
71
|
+
the manual, listings and notices show in the session without spending context or leaking into
|
|
72
|
+
a compaction summary. Verified live: the drop is logged on every model call, and a model asked
|
|
73
|
+
about the manual's first line reported not seeing it.
|
|
74
|
+
- **`/cred` replies used `delivery: "queue"`,** which delivered each one as a separate input
|
|
75
|
+
once the turn ended — a pointless model call, or never delivered when the turn failed. They
|
|
76
|
+
now use `steer` with `resume: false`: they wait in the inbox and ride on the next real call.
|
|
77
|
+
|
|
78
|
+
### Changed (Advisor)
|
|
79
|
+
|
|
80
|
+
- **The advisor session is named after the session it advises.** It was always titled
|
|
81
|
+
`apex advisor`, so with several active trees you could not tell which advisor decided for
|
|
82
|
+
which conversation. The title is now `apex advisor → <target title> [<target short id>]`
|
|
83
|
+
(or `apex advisor → sesión <id>` when the target has no title). The short id is stable
|
|
84
|
+
across renames and disambiguates equal titles; every permission evaluation refreshes it —
|
|
85
|
+
even when the verdict comes from the 10-minute decision cache, so a rename is picked up on
|
|
86
|
+
the next prompt without a model round trip (`syncAdvisorTitleForRoot`, called before the
|
|
87
|
+
cache fast-path in `advisor.ts`). New exports in `core/advisor-session.ts`:
|
|
88
|
+
`advisorTitleFor()` (pure), `ensureAdvisorTitle()` (best-effort, idempotent) and
|
|
89
|
+
`syncAdvisorTitleForRoot()`. The in-process advisor state cell moved to key `v2` to hold the
|
|
90
|
+
last-applied title per advisor session.
|
|
91
|
+
|
|
92
|
+
## [0.7.0] — 2026-12-02
|
|
93
|
+
|
|
94
|
+
### Added
|
|
95
|
+
|
|
96
|
+
- **Cred KDBX backing store.** `cred.kdbx` enables a `.kdbx` (KeePassXC/KeePass) file as the credential source of truth: loaded at startup, watched for external changes, and written on `/cred set`/`rm`. All protected values feed the redaction engine via cred patterns. Implemented with `kdbxweb` + `hash-wasm` (Argon2, pure WASM).
|
|
97
|
+
- **Extended `/cred` command.** `get`, richer `set` (URI parsing like `ssh://user:pass@host:22`, `--username/--password/--url/--kind/--secret.*`), and `kdbx status|reload|save`.
|
|
98
|
+
- **`apex_cred` agent tool + temporary channel tools.** Agent can list/get public metadata and `open` a handle without seeing secrets; apex spawns `apex_cred_use_<handle>` for safe actions (SSH exec, HTTP request with injected auth). Channel outputs are defensively redacted.
|
|
99
|
+
- **Cred redaction variants.** Added base64url variant; KDBX protected/custom fields included.
|
|
100
|
+
|
|
101
|
+
### Fixed
|
|
102
|
+
|
|
103
|
+
- **`apex_cred` channels could send the secret to any host.** `request` accepted an arbitrary `url` and `exec` an arbitrary `host`, so an agent could point a channel at its own server and receive the `Authorization` header or the password. The destination now always comes from the credential: HTTP only reaches the stored URL's own origin (other origins are refused before anything is sent, redirects are not followed, the auth header cannot be overridden), and SSH takes host, port and user from the credential. Channel code moved to `core/cred-channel.ts`.
|
|
104
|
+
- **Temporary `apex_cred_use_<handle>` tools never appeared.** They were only added when the tool transform first ran; opening or closing a channel now calls `ctx.tool.reload()`. `apex_cred action=use` is the same call without the dedicated tool.
|
|
105
|
+
- **SSH channel no longer needs `sshpass`.** The password is handed over through `SSH_ASKPASS` (`SSH_ASKPASS_REQUIRE=force`), still never in argv. A malformed `ssh://` URL returns an error instead of throwing.
|
|
106
|
+
- **KDBX entries sharing a title (or with no title) were left unredacted.** The second entry overwrote the first in the index; each now gets a unique name (`name#2`, `entry-<uuid>`).
|
|
107
|
+
- **KDBX watcher went blind after the first atomic save.** It watched the file's inode; it now watches the directory. A failed reload keeps the last good index.
|
|
108
|
+
- **KDBX file was created `0644`**; now `0600`. `/cred set` reports when the entry could not be saved to the file instead of claiming success.
|
|
109
|
+
- Channel output is scrubbed of every stored secret and of derived strings (the Basic base64); public metadata no longer includes the URL query.
|
|
110
|
+
|
|
111
|
+
### Changed
|
|
112
|
+
|
|
113
|
+
- **`@opencode/plugin` / `@opencode/plugin-browser` bumped to `^2.4.3`** (a fresh npm install already resolved inside that range). Code adapted to the 2.4 plugin API: the tool execute `Context` now requires `tool.call`, which `tools.run` implements by delegating to another registered tool under the same `events.tools` allow/deny; `browser.target` declares the `output` schema it always returned; `index.ts` `VERSION` was stuck at 0.5.0 and now matches the package.
|
|
114
|
+
|
|
8
115
|
## [0.6.0] — 2026-11-30
|
|
9
116
|
|
|
10
117
|
### Added (Advisor)
|
package/README.md
CHANGED
|
@@ -317,7 +317,11 @@ npm run typecheck # tsc --noEmit
|
|
|
317
317
|
npm run check:install # installs the package like OpenCode does; fails on duplicate `effect`
|
|
318
318
|
```
|
|
319
319
|
|
|
320
|
-
|
|
320
|
+
**Releasing.** Bump the version in `package.json` and `index.ts`, move the CHANGELOG entry to
|
|
321
|
+
`## [X.Y.Z]`, tag `vX.Y.Z` and publish a GitHub Release for that tag. The `Publish` workflow
|
|
322
|
+
(`.github/workflows/publish.yml`) then publishes to npm with provenance (Trusted Publishing).
|
|
323
|
+
Don't run `npm publish` by hand. Before it uploads, `npm publish` runs the tests, the
|
|
324
|
+
typecheck and the install check (`prepublishOnly`).
|
|
321
325
|
|
|
322
326
|
**Dependency rule.** OpenCode (≥ 2.1) serves `effect` and `@opencode/plugin` to plugins from
|
|
323
327
|
its own copy, so apex never pins `effect`: it is only an optional peer. The other `@opencode/*`
|
package/advisor.ts
CHANGED
|
@@ -16,11 +16,11 @@
|
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
import { createHash } from "node:crypto"
|
|
19
|
-
import { Effect } from "effect"
|
|
19
|
+
import { Effect, Stream } from "effect"
|
|
20
20
|
import type { Scope } from "effect"
|
|
21
21
|
import type { Plugin } from "@opencode/plugin/effect"
|
|
22
22
|
import { homedir } from "node:os"
|
|
23
|
-
import { ADVISOR_AGENT_ID, ensureAdvisorAgent } from "./core/advisor-agent.js"
|
|
23
|
+
import { ADVISOR_AGENT_ID, ADVISOR_TOOL_NAME, ensureAdvisorAgent } from "./core/advisor-agent.js"
|
|
24
24
|
import { readOrCreateTemplate } from "./core/templates.js"
|
|
25
25
|
import { registerAdvisorTool } from "./core/advisor-tool.js"
|
|
26
26
|
import {
|
|
@@ -28,9 +28,15 @@ import {
|
|
|
28
28
|
buildProcessContext,
|
|
29
29
|
DEFAULT_ADVISOR_REQUEST_TEMPLATE,
|
|
30
30
|
isAdvisorSession,
|
|
31
|
+
markAdvisorSessionRead,
|
|
32
|
+
noteAdvisorAnswered,
|
|
31
33
|
requestAdvisorDecision,
|
|
32
34
|
resolveRootSessionID,
|
|
35
|
+
syncAdvisorTitleForRoot,
|
|
36
|
+
takeAdvisorAnswered,
|
|
37
|
+
type ServerCall,
|
|
33
38
|
} from "./core/advisor-session.js"
|
|
39
|
+
import { readServerPassword, resolveServerEndpoint } from "./core/server-endpoint.js"
|
|
34
40
|
import { redactHandler } from "./redact.js"
|
|
35
41
|
|
|
36
42
|
// ---------------------------------------------------------------------------
|
|
@@ -83,6 +89,13 @@ export interface AdvisorConfig {
|
|
|
83
89
|
conversationContext?: boolean
|
|
84
90
|
/** Cuántos mensajes de usuario recientes incluir. Default 10. */
|
|
85
91
|
conversationMessages?: number
|
|
92
|
+
/**
|
|
93
|
+
* Cuando el advisor responde con su herramienta y acaba el turno, su sesión se
|
|
94
|
+
* marca leída (y se vuelve a archivar) para que no aparezca como "no leída" en
|
|
95
|
+
* la app. Si el turno acaba sin decidir, se deja sin leer: ahí sí hay algo que
|
|
96
|
+
* mirar. Default `true`.
|
|
97
|
+
*/
|
|
98
|
+
markRead?: boolean
|
|
86
99
|
}
|
|
87
100
|
|
|
88
101
|
// ---------------------------------------------------------------------------
|
|
@@ -203,6 +216,29 @@ export function register(
|
|
|
203
216
|
// 2. Única herramienta del advisor
|
|
204
217
|
yield* registerAdvisorTool(ctx)
|
|
205
218
|
|
|
219
|
+
// 2b. Turno del advisor resuelto con su herramienta → sesión leída al acabar.
|
|
220
|
+
if (config.markRead ?? true) {
|
|
221
|
+
yield* ctx.tool.hook("execute.after", (event) =>
|
|
222
|
+
Effect.sync(() => {
|
|
223
|
+
if (event.tool !== ADVISOR_TOOL_NAME) return
|
|
224
|
+
if (event.agent === ADVISOR_AGENT_ID || isAdvisorSession(event.sessionID)) noteAdvisorAnswered(event.sessionID)
|
|
225
|
+
}),
|
|
226
|
+
)
|
|
227
|
+
const call = serverCall(ctx)
|
|
228
|
+
yield* ctx.event.subscribe({ types: ["session.execution.succeeded"] }).pipe(
|
|
229
|
+
Stream.mapEffect((event) =>
|
|
230
|
+
Effect.promise(async () => {
|
|
231
|
+
const sessionID = String((event.data as { sessionID?: unknown })?.sessionID ?? "")
|
|
232
|
+
if (!sessionID || !takeAdvisorAnswered(sessionID)) return
|
|
233
|
+
if (!(await markAdvisorSessionRead(ctx, sessionID, call)))
|
|
234
|
+
console.warn(`[apex.advisor] no se pudo marcar como leída la sesión advisor ${sessionID}`)
|
|
235
|
+
}),
|
|
236
|
+
),
|
|
237
|
+
Stream.runDrain,
|
|
238
|
+
Effect.forkScoped,
|
|
239
|
+
)
|
|
240
|
+
}
|
|
241
|
+
|
|
206
242
|
// 3. Caché de veredictos
|
|
207
243
|
const cache = yield* Effect.promise(() => loadCache(ctx.storage))
|
|
208
244
|
|
|
@@ -228,15 +264,18 @@ export function register(
|
|
|
228
264
|
() => null,
|
|
229
265
|
)
|
|
230
266
|
: null
|
|
267
|
+
const rootID = await resolveRootSessionID(ctx, e.sessionID)
|
|
268
|
+
// El título de la sesión advisor sigue a la objetivo en CADA evaluación,
|
|
269
|
+
// también cuando el veredicto salga del cache: el usuario puede renombrar
|
|
270
|
+
// la sesión en cualquier momento y la lista debe reflejarlo siempre.
|
|
271
|
+
await syncAdvisorTitleForRoot(ctx, rootID, config.location)
|
|
272
|
+
|
|
231
273
|
const conversation = conversationContext
|
|
232
|
-
? await (
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
redact: redactHandler ? (text) => redactHandler!({ text }).redacted : undefined,
|
|
238
|
-
})
|
|
239
|
-
})().catch(() => "")
|
|
274
|
+
? await buildConversationContext(ctx, {
|
|
275
|
+
rootID,
|
|
276
|
+
maxMessages: conversationMessages,
|
|
277
|
+
redact: redactHandler ? (text) => redactHandler!({ text }).redacted : undefined,
|
|
278
|
+
}).catch(() => "")
|
|
240
279
|
: ""
|
|
241
280
|
const cacheKey = generateCacheKey(e.action, e.resources, `${processes?.text ?? ""}\n${conversation}`)
|
|
242
281
|
|
|
@@ -303,6 +342,33 @@ export function register(
|
|
|
303
342
|
})
|
|
304
343
|
}
|
|
305
344
|
|
|
345
|
+
/**
|
|
346
|
+
* Llamadas HTTP del plugin a su propio servidor (Basic `opencode:<password>`).
|
|
347
|
+
* La dirección y el password se resuelven en cada llamada: el servicio puede
|
|
348
|
+
* haber reescrito su registro tras un reinicio.
|
|
349
|
+
*/
|
|
350
|
+
function serverCall(ctx: Plugin.Context): ServerCall {
|
|
351
|
+
return async (path, init) => {
|
|
352
|
+
const endpoint = resolveServerEndpoint({ directory: ctx.location?.directory ?? process.cwd() })
|
|
353
|
+
const password = readServerPassword(endpoint.auth.password)
|
|
354
|
+
if (!endpoint.baseUrl || !password) return false
|
|
355
|
+
try {
|
|
356
|
+
const response = await fetch(`${endpoint.baseUrl.replace(/\/+$/, "")}${path}`, {
|
|
357
|
+
method: init.method,
|
|
358
|
+
headers: {
|
|
359
|
+
authorization: `Basic ${Buffer.from(`${endpoint.auth.username}:${password}`).toString("base64")}`,
|
|
360
|
+
"content-type": "application/json",
|
|
361
|
+
},
|
|
362
|
+
body: JSON.stringify(init.body),
|
|
363
|
+
signal: AbortSignal.timeout(5000),
|
|
364
|
+
})
|
|
365
|
+
return response.ok
|
|
366
|
+
} catch {
|
|
367
|
+
return false
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
306
372
|
/**
|
|
307
373
|
* Aplica la decisión al evento de permiso.
|
|
308
374
|
* - decisive=true → allow/deny sustituyen el efecto (deny deja el motivo).
|
|
@@ -337,5 +403,6 @@ export function createDefaultAdvisorConfig(): AdvisorConfig {
|
|
|
337
403
|
processContext: true,
|
|
338
404
|
conversationContext: true,
|
|
339
405
|
conversationMessages: 10,
|
|
406
|
+
markRead: true,
|
|
340
407
|
}
|
|
341
408
|
}
|
package/browser.ts
CHANGED
|
@@ -455,6 +455,32 @@ export function register(ctx: Plugin.Context, config: BrowserConfigShape): Effec
|
|
|
455
455
|
"keep the current one; pass an empty string to go back to cdpUrl discovery.",
|
|
456
456
|
},
|
|
457
457
|
},
|
|
458
|
+
// Desde plugin 2.4, devolver `{ output }` exige declarar su schema.
|
|
459
|
+
output: {
|
|
460
|
+
type: "object",
|
|
461
|
+
properties: {
|
|
462
|
+
mode: { type: "string", enum: ["external", "in-app", "auto"] },
|
|
463
|
+
source: { type: "string" },
|
|
464
|
+
target: {
|
|
465
|
+
type: "object",
|
|
466
|
+
properties: { cdpUrl: { type: "string" }, profile: { type: ["string", "null"] } },
|
|
467
|
+
additionalProperties: false,
|
|
468
|
+
},
|
|
469
|
+
connected: {
|
|
470
|
+
type: ["object", "null"],
|
|
471
|
+
properties: {
|
|
472
|
+
profile: { type: ["string", "null"] },
|
|
473
|
+
cdp: { type: ["string", "null"] },
|
|
474
|
+
how: { type: ["string", "null"] },
|
|
475
|
+
},
|
|
476
|
+
additionalProperties: true,
|
|
477
|
+
},
|
|
478
|
+
attached: { type: "array", items: { type: "string" } },
|
|
479
|
+
error: { type: ["string", "null"] },
|
|
480
|
+
},
|
|
481
|
+
required: ["mode", "source", "target", "attached"],
|
|
482
|
+
additionalProperties: true,
|
|
483
|
+
},
|
|
458
484
|
options: { namespace: "browser", permission: "browser", codemode: true },
|
|
459
485
|
execute: (input, context) =>
|
|
460
486
|
Effect.gen(function* () {
|
package/core/advisor-session.ts
CHANGED
|
@@ -81,9 +81,11 @@ interface AdvisorCell {
|
|
|
81
81
|
readonly advisorSessions: Set<string>
|
|
82
82
|
/** requestID → resolver de la promesa pendiente */
|
|
83
83
|
readonly pending: Map<string, (decision: AdvisorDecision) => void>
|
|
84
|
+
/** advisor sessionID → último título aplicado (evita updates redundantes) */
|
|
85
|
+
readonly titleApplied: Map<string, string>
|
|
84
86
|
}
|
|
85
87
|
|
|
86
|
-
const CELL_KEY = Symbol.for("apex.advisor.state.
|
|
88
|
+
const CELL_KEY = Symbol.for("apex.advisor.state.v2")
|
|
87
89
|
|
|
88
90
|
function cell(): AdvisorCell {
|
|
89
91
|
const holder = globalThis as Record<symbol, AdvisorCell | undefined>
|
|
@@ -93,6 +95,7 @@ function cell(): AdvisorCell {
|
|
|
93
95
|
sessionCache: new Map(),
|
|
94
96
|
advisorSessions: new Set(),
|
|
95
97
|
pending: new Map(),
|
|
98
|
+
titleApplied: new Map(),
|
|
96
99
|
}
|
|
97
100
|
holder[CELL_KEY] = created
|
|
98
101
|
return created
|
|
@@ -101,6 +104,7 @@ function cell(): AdvisorCell {
|
|
|
101
104
|
const sessionCache = cell().sessionCache
|
|
102
105
|
const advisorSessions = cell().advisorSessions
|
|
103
106
|
const pending = cell().pending
|
|
107
|
+
const titleApplied = cell().titleApplied
|
|
104
108
|
|
|
105
109
|
const STORAGE_KEY = (rootID: string) => `apex:advisor:session:${rootID}`
|
|
106
110
|
const MAX_DEPTH = 25
|
|
@@ -132,6 +136,130 @@ export function isAdvisorSession(sessionID: string): boolean {
|
|
|
132
136
|
return advisorSessions.has(sessionID)
|
|
133
137
|
}
|
|
134
138
|
|
|
139
|
+
// ---------------------------------------------------------------------------
|
|
140
|
+
// Título distintivo de la sesión advisor
|
|
141
|
+
// ---------------------------------------------------------------------------
|
|
142
|
+
|
|
143
|
+
/** Longitud máxima del título de la sesión objetivo que se refleja en el advisor. */
|
|
144
|
+
const MAX_TARGET_TITLE = 60
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Título de la sesión advisor, derivado de la sesión OBJETIVO (la raíz del
|
|
148
|
+
* árbol que atiende). Lleva el título actual de la objetivo —para reconocerla
|
|
149
|
+
* de un vistazo— y su id corto entre corchetes —estable aunque el usuario
|
|
150
|
+
* renombre la sesión, y desambigua dos sesiones con el mismo título—.
|
|
151
|
+
*
|
|
152
|
+
* El prefijo con flecha (`apex advisor → …`) deja claro en la lista de sesiones
|
|
153
|
+
* que es el advisor de esa otra sesión, no una conversación normal.
|
|
154
|
+
*/
|
|
155
|
+
export function advisorTitleFor(rootTitle: string | undefined, rootID: string): string {
|
|
156
|
+
const short = rootID.length > 6 ? rootID.slice(-6) : rootID
|
|
157
|
+
const title = (rootTitle ?? "").trim()
|
|
158
|
+
if (!title) return `apex advisor → sesión ${short}`
|
|
159
|
+
const clipped = title.length > MAX_TARGET_TITLE ? `${title.slice(0, MAX_TARGET_TITLE - 1)}…` : title
|
|
160
|
+
return `apex advisor → ${clipped} [${short}]`
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Título actual de una sesión; undefined si no se puede leer. */
|
|
164
|
+
async function getSessionTitle(ctx: Plugin.Context, sessionID: string): Promise<string | undefined> {
|
|
165
|
+
try {
|
|
166
|
+
const info = (await Effect.runPromise(ctx.session.get({ sessionID: sessionID as never }))) as
|
|
167
|
+
| { title?: string }
|
|
168
|
+
| undefined
|
|
169
|
+
return typeof info?.title === "string" ? info.title : undefined
|
|
170
|
+
} catch {
|
|
171
|
+
return undefined
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Pone (o actualiza) el título de la sesión advisor para que refleje el título
|
|
177
|
+
* ACTUAL de la sesión objetivo. Best-effort e idempotente: si el título ya es
|
|
178
|
+
* el correcto no toca nada (se recuerda el último aplicado por proceso), así
|
|
179
|
+
* que llamarlo en cada petición de permiso recoge los renombrados del usuario
|
|
180
|
+
* sin trabajo redundante. Devuelve el título deseado.
|
|
181
|
+
*/
|
|
182
|
+
export async function ensureAdvisorTitle(
|
|
183
|
+
ctx: Plugin.Context,
|
|
184
|
+
advisorID: string,
|
|
185
|
+
rootID: string,
|
|
186
|
+
rootTitle: string | undefined,
|
|
187
|
+
): Promise<string> {
|
|
188
|
+
const desired = advisorTitleFor(rootTitle, rootID)
|
|
189
|
+
if (titleApplied.get(advisorID) === desired) return desired
|
|
190
|
+
try {
|
|
191
|
+
await Effect.runPromise(
|
|
192
|
+
ctx.session.update({ sessionID: advisorID as never, title: desired as never } as never),
|
|
193
|
+
)
|
|
194
|
+
titleApplied.set(advisorID, desired)
|
|
195
|
+
} catch (error) {
|
|
196
|
+
console.warn(`[apex.advisor] no se pudo renombrar la sesión advisor: ${String(error)}`)
|
|
197
|
+
}
|
|
198
|
+
return desired
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// ---------------------------------------------------------------------------
|
|
202
|
+
// Leída al terminar: la sesión advisor no avisa como "no leída"
|
|
203
|
+
// ---------------------------------------------------------------------------
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Sesiones advisor que han respondido con `apex_advisor_decide` en el turno en
|
|
207
|
+
* curso. Ámbito de proceso, como `cell()` (la herramienta corre en la instancia
|
|
208
|
+
* del location del advisor y el evento puede llegar a otra), con su propia
|
|
209
|
+
* clave para no cambiar la forma de la celda v2.
|
|
210
|
+
*/
|
|
211
|
+
const ANSWERED_KEY = Symbol.for("apex.advisor.answered.v1")
|
|
212
|
+
function answered(): Set<string> {
|
|
213
|
+
const holder = globalThis as Record<symbol, Set<string> | undefined>
|
|
214
|
+
return (holder[ANSWERED_KEY] ??= new Set())
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** La sesión advisor decidió con su herramienta: al acabar el turno se marca leída. */
|
|
218
|
+
export function noteAdvisorAnswered(sessionID: string): void {
|
|
219
|
+
answered().add(sessionID)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** ¿Respondió con su herramienta desde la última vez? Consume la marca. */
|
|
223
|
+
export function takeAdvisorAnswered(sessionID: string): boolean {
|
|
224
|
+
return answered().delete(sessionID)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Llamada HTTP al propio servidor; la API de plugins no expone `session.view` ni `archived`. */
|
|
228
|
+
export interface ServerCall {
|
|
229
|
+
(path: string, init: { method: string; body: unknown }): Promise<boolean>
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Milisegundos de un `time.idle` tal como lo devuelve `session.get` (DateTime, Date o número). */
|
|
233
|
+
export function idleMillis(idle: unknown): number | undefined {
|
|
234
|
+
if (typeof idle === "number" && Number.isFinite(idle)) return idle
|
|
235
|
+
if (idle instanceof Date) return idle.getTime()
|
|
236
|
+
// DateTime.Utc de Effect: `epochMilliseconds`.
|
|
237
|
+
const ms = (idle as { epochMilliseconds?: unknown } | null | undefined)?.epochMilliseconds
|
|
238
|
+
return typeof ms === "number" ? ms : undefined
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Marca la sesión advisor como leída (y la vuelve a archivar: cada `session.prompt`
|
|
243
|
+
* la desarchiva). Sin esto, cada permiso deja la sesión advisor "no leída" en la
|
|
244
|
+
* app, avisando de un turno que el usuario no necesita mirar. Best-effort.
|
|
245
|
+
*/
|
|
246
|
+
export async function markAdvisorSessionRead(ctx: Plugin.Context, sessionID: string, call: ServerCall): Promise<boolean> {
|
|
247
|
+
let idle: number | undefined
|
|
248
|
+
try {
|
|
249
|
+
const info = (await Effect.runPromise(ctx.session.get({ sessionID: sessionID as never }))) as {
|
|
250
|
+
time?: { idle?: unknown }
|
|
251
|
+
}
|
|
252
|
+
idle = idleMillis(info?.time?.idle)
|
|
253
|
+
} catch {
|
|
254
|
+
return false
|
|
255
|
+
}
|
|
256
|
+
if (idle === undefined) return false
|
|
257
|
+
const path = `/api/session/${encodeURIComponent(sessionID)}`
|
|
258
|
+
const viewed = await call(`${path}/view`, { method: "POST", body: { idle } })
|
|
259
|
+
await call(path, { method: "PATCH", body: { archived: true } })
|
|
260
|
+
return viewed
|
|
261
|
+
}
|
|
262
|
+
|
|
135
263
|
/** Llamado por la herramienta del advisor para resolver una decisión pendiente. */
|
|
136
264
|
export function resolvePendingDecision(requestID: string, decision: "allow" | "deny", reason?: string): boolean {
|
|
137
265
|
const resolver = pending.get(requestID)
|
|
@@ -183,8 +311,16 @@ export async function getOrCreateAdvisorSession(
|
|
|
183
311
|
const directory = isAbsolute(rawDir) ? normalize(rawDir) : join(process.cwd(), rawDir)
|
|
184
312
|
const cacheKey = `${rootID}|${directory}`
|
|
185
313
|
|
|
314
|
+
// Título actual de la sesión objetivo: puede haber cambiado desde la última
|
|
315
|
+
// vez (el usuario la renombra), así que se lee en cada petición y se
|
|
316
|
+
// resincroniza el título del advisor abajo.
|
|
317
|
+
const rootTitle = await getSessionTitle(ctx, rootID)
|
|
318
|
+
|
|
186
319
|
const cached = sessionCache.get(cacheKey)
|
|
187
|
-
if (cached)
|
|
320
|
+
if (cached) {
|
|
321
|
+
await ensureAdvisorTitle(ctx, cached, rootID, rootTitle)
|
|
322
|
+
return cached
|
|
323
|
+
}
|
|
188
324
|
|
|
189
325
|
// Persistida entre recargas (se valida que siga existiendo, que el agente sea
|
|
190
326
|
// el advisor y que la location coincida; si no, se recrea).
|
|
@@ -204,6 +340,8 @@ export async function getOrCreateAdvisorSession(
|
|
|
204
340
|
advisorSessions.add(stored)
|
|
205
341
|
// Retrofit: sesiones creadas antes de que existiera el archivado.
|
|
206
342
|
void archiveAdvisorSession(ctx, stored)
|
|
343
|
+
// Retrofit del título distintivo (sesiones creadas con "apex advisor" fijo).
|
|
344
|
+
await ensureAdvisorTitle(ctx, stored, rootID, rootTitle)
|
|
207
345
|
return stored
|
|
208
346
|
}
|
|
209
347
|
}
|
|
@@ -217,10 +355,11 @@ export async function getOrCreateAdvisorSession(
|
|
|
217
355
|
// si no se puede crear, se intenta crear la sesión igualmente
|
|
218
356
|
}
|
|
219
357
|
|
|
358
|
+
const initialTitle = advisorTitleFor(rootTitle, rootID)
|
|
220
359
|
const created = (await Effect.runPromise(
|
|
221
360
|
ctx.session.create({
|
|
222
361
|
agent: ADVISOR_AGENT_ID as never,
|
|
223
|
-
title:
|
|
362
|
+
title: initialTitle,
|
|
224
363
|
metadata: { apexAdvisorFor: rootID, apexAdvisorLocation: directory } as never,
|
|
225
364
|
location: { directory } as never,
|
|
226
365
|
} as never),
|
|
@@ -229,6 +368,7 @@ export async function getOrCreateAdvisorSession(
|
|
|
229
368
|
const advisorID = created.id
|
|
230
369
|
sessionCache.set(cacheKey, advisorID)
|
|
231
370
|
advisorSessions.add(advisorID)
|
|
371
|
+
titleApplied.set(advisorID, initialTitle)
|
|
232
372
|
await Effect.runPromise(ctx.storage.set(STORAGE_KEY(rootID), advisorID as never))
|
|
233
373
|
await archiveAdvisorSession(ctx, advisorID)
|
|
234
374
|
return advisorID
|
|
@@ -362,6 +502,27 @@ export async function buildConversationContext(
|
|
|
362
502
|
].join("\n")
|
|
363
503
|
}
|
|
364
504
|
|
|
505
|
+
/**
|
|
506
|
+
* Pone (o crea) la sesión advisor del árbol y resincroniza su título con el
|
|
507
|
+
* título ACTUAL de la sesión objetivo, sin pedir ninguna decisión.
|
|
508
|
+
*
|
|
509
|
+
* Se llama en cada evaluación de permiso, también cuando el veredicto sale del
|
|
510
|
+
* cache: el usuario puede renombrar la sesión objetivo en cualquier momento y
|
|
511
|
+
* el título del advisor debe seguirlo aunque no haya ida al modelo.
|
|
512
|
+
* Best-effort: un fallo aquí no debe frenar la evaluación.
|
|
513
|
+
*/
|
|
514
|
+
export async function syncAdvisorTitleForRoot(
|
|
515
|
+
ctx: Plugin.Context,
|
|
516
|
+
rootID: string,
|
|
517
|
+
location?: string,
|
|
518
|
+
): Promise<void> {
|
|
519
|
+
try {
|
|
520
|
+
await getOrCreateAdvisorSession(ctx, rootID, location)
|
|
521
|
+
} catch {
|
|
522
|
+
// best-effort: la evaluación del permiso sigue su curso
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
365
526
|
/**
|
|
366
527
|
* Pide una decisión al advisor del árbol.
|
|
367
528
|
* Devuelve null si: la sesión solicitante es la del advisor, no hay sesión
|
package/core/config.ts
CHANGED
|
@@ -108,10 +108,28 @@ export interface CredLlmConfig {
|
|
|
108
108
|
allowRemote: boolean
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
export interface CredKdbxConfig {
|
|
112
|
+
/** Usar un fichero .kdbx como almacén principal (interoperable con KeePassXC). */
|
|
113
|
+
enabled: boolean
|
|
114
|
+
/** Ruta al .kdbx. Soporta ~. */
|
|
115
|
+
path: string
|
|
116
|
+
/** Contraseña del .kdbx: literal | env:VAR | file:/ruta. */
|
|
117
|
+
password: string
|
|
118
|
+
/** Fichero de clave opcional. */
|
|
119
|
+
keyFile: string
|
|
120
|
+
/** Crear el .kdbx si no existe. */
|
|
121
|
+
createIfMissing: boolean
|
|
122
|
+
/** Recargar cuando el fichero cambie en disco (interop con apps externas). */
|
|
123
|
+
watch: boolean
|
|
124
|
+
/** Nombre del grupo KDBX donde se guardan entradas creadas por apex. */
|
|
125
|
+
group: string
|
|
126
|
+
}
|
|
127
|
+
|
|
111
128
|
export interface CredConfig {
|
|
112
129
|
/** Secretos más cortos se rechazan (ver core/cred.ts). */
|
|
113
130
|
minLength: number
|
|
114
131
|
llm: CredLlmConfig
|
|
132
|
+
kdbx: CredKdbxConfig
|
|
115
133
|
}
|
|
116
134
|
|
|
117
135
|
export interface AdvisorConfig {
|
|
@@ -158,6 +176,16 @@ const DEFAULT_CRED_LLM = {
|
|
|
158
176
|
allowRemote: false,
|
|
159
177
|
}
|
|
160
178
|
|
|
179
|
+
const DEFAULT_CRED_KDBX = {
|
|
180
|
+
enabled: false,
|
|
181
|
+
path: "~/.config/opencode/apex-creds.kdbx",
|
|
182
|
+
password: "env:APEX_CRED_KDBX_PASSWORD",
|
|
183
|
+
keyFile: "",
|
|
184
|
+
createIfMissing: true,
|
|
185
|
+
watch: true,
|
|
186
|
+
group: "apex",
|
|
187
|
+
}
|
|
188
|
+
|
|
161
189
|
const credLlmConfigSchema = z.object({
|
|
162
190
|
enabled: z.boolean().default(DEFAULT_CRED_LLM.enabled),
|
|
163
191
|
endpoint: z.string().default(DEFAULT_CRED_LLM.endpoint),
|
|
@@ -166,9 +194,20 @@ const credLlmConfigSchema = z.object({
|
|
|
166
194
|
allowRemote: z.boolean().default(DEFAULT_CRED_LLM.allowRemote),
|
|
167
195
|
})
|
|
168
196
|
|
|
197
|
+
const credKdbxConfigSchema = z.object({
|
|
198
|
+
enabled: z.boolean().default(DEFAULT_CRED_KDBX.enabled),
|
|
199
|
+
path: z.string().default(DEFAULT_CRED_KDBX.path),
|
|
200
|
+
password: z.string().default(DEFAULT_CRED_KDBX.password),
|
|
201
|
+
keyFile: z.string().default(DEFAULT_CRED_KDBX.keyFile),
|
|
202
|
+
createIfMissing: z.boolean().default(DEFAULT_CRED_KDBX.createIfMissing),
|
|
203
|
+
watch: z.boolean().default(DEFAULT_CRED_KDBX.watch),
|
|
204
|
+
group: z.string().default(DEFAULT_CRED_KDBX.group),
|
|
205
|
+
})
|
|
206
|
+
|
|
169
207
|
const credConfigSchema = z.object({
|
|
170
208
|
minLength: z.number().int().positive().default(6),
|
|
171
209
|
llm: credLlmConfigSchema.default(() => ({ ...DEFAULT_CRED_LLM })),
|
|
210
|
+
kdbx: credKdbxConfigSchema.default(() => ({ ...DEFAULT_CRED_KDBX })),
|
|
172
211
|
})
|
|
173
212
|
|
|
174
213
|
const ruleConditionSchema = z.object({
|
|
@@ -246,6 +285,9 @@ const advisorConfigSchema = z.object({
|
|
|
246
285
|
// igual que un agente con el contexto completo (p. ej. Claude Code en modo auto).
|
|
247
286
|
conversationContext: z.boolean().default(true),
|
|
248
287
|
conversationMessages: z.number().int().positive().default(10),
|
|
288
|
+
// Al acabar un turno en el que decidió con su herramienta, la sesión advisor se
|
|
289
|
+
// marca leída (y se re-archiva) para no salir como "no leída" en la app.
|
|
290
|
+
markRead: z.boolean().default(true),
|
|
249
291
|
})
|
|
250
292
|
|
|
251
293
|
const guardRuleSchema = z.object({
|
|
@@ -285,7 +327,7 @@ const browserConfigSchema = z.object({
|
|
|
285
327
|
|
|
286
328
|
export const apexConfigSchema = z.object({
|
|
287
329
|
redact: redactConfigSchema.default(() => ({ mode: "strict" as const, patterns: [], bundles: [...DEFAULT_BUNDLES], minConfidence: "medium" as const, allowlist: [], prefix: "[SECRET:", suffix: "]", key: "", restore: { toolInput: true } })),
|
|
288
|
-
cred: credConfigSchema.default(() => ({ minLength: 6, llm: { ...DEFAULT_CRED_LLM } })),
|
|
330
|
+
cred: credConfigSchema.default(() => ({ minLength: 6, llm: { ...DEFAULT_CRED_LLM }, kdbx: { ...DEFAULT_CRED_KDBX } })),
|
|
289
331
|
events: eventsConfigSchema.default(() => ({ routing: "all" as const, subscriptions: [], server: {}, tools: defaultEventsTools() })),
|
|
290
332
|
advisor: advisorConfigSchema.default(() => ({ actions: [], decisive: false, evaluate: "ask-only" as const, timeoutMs: 10000, processContext: true })),
|
|
291
333
|
guard: guardConfigSchema.default(() => ({
|
|
@@ -317,6 +359,9 @@ export const apexConfigSchema = z.object({
|
|
|
317
359
|
tempAccess: z.boolean().optional(),
|
|
318
360
|
// Activado por defecto: apex_tunnel/webhook/daemon (el daemon solo se lanza al usarlas).
|
|
319
361
|
endpoints: z.boolean().optional(),
|
|
362
|
+
// Activado por defecto (con events y endpoints): servidor MCP `apex` con MCP Events para
|
|
363
|
+
// los triggers de automations de OpenCode. Lanza el daemon al cargar el plugin.
|
|
364
|
+
automations: z.boolean().optional(),
|
|
320
365
|
})
|
|
321
366
|
.default(() => ({})),
|
|
322
367
|
})
|