Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/en/docs/integrations/opencode.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ traffic goes through the gateway, turn prompt-time recall off so the gateway pre
Named `pc_*` tools expose curated Memory, Handoff, Experience, Skill, and read-only Candidate operations. OpenCode
asks for confirmation before a durable mutation. Candidate approval and rejection remain explicit human CLI actions.

The confirmation is OpenCode's `powercontext` permission, which the plugin sets to `ask`. A rule you configure that
matches it, such as `"*": "allow"` in `permission` or in an agent's `permission`, takes precedence. Each request uses
the operation as its pattern, so `"permission": {"powercontext": {"remember_memory": "allow"}}` saves memories
without asking while other writes still ask. Answering "Allow always" approves only that call.

In `opencode run`, OpenCode rejects each permission request and ends the turn, so a non-interactive run stops at its
first PowerContext write. Allow the operations such a run needs, for example with
`"permission": {"powercontext": "allow"}`, rather than approving every permission for the run.

## Configure the connection

Set variables before starting OpenCode:
Expand Down
8 changes: 8 additions & 0 deletions docs/zh/docs/integrations/opencode.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ opencode
具名 `pc_*` 工具提供精选的 Memory、Handoff、Experience、Skill 和只读 Candidate 操作。持久化变更前
OpenCode 会要求确认;Candidate 的批准和拒绝仍由用户通过 CLI 显式执行。

这项确认对应 OpenCode 的 `powercontext` 权限,插件将它设为 `ask`。你配置的匹配规则优先,例如 `permission` 或某个
agent 的 `permission` 中的 `"*": "allow"`。每次请求以操作名作为模式,因此
`"permission": {"powercontext": {"remember_memory": "allow"}}` 会让保存 Memory 时不再询问,其他写入仍会询问。
选择 “Allow always” 只批准当前这一次调用。

在 `opencode run` 中,OpenCode 会拒绝每个权限请求并结束当前回合,因此非交互运行会停在第一次 PowerContext 写入。
请为这类运行允许它需要的操作,例如 `"permission": {"powercontext": "allow"}`,而不是批准这次运行的所有权限。

## 配置连接

启动 OpenCode 前设置环境变量:
Expand Down
4 changes: 3 additions & 1 deletion integrations/opencode/plugins/powercontext/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ opencode
For each normal user turn, the plugin recalls bounded project context and independently captures the prompt as Source
evidence. Recalled content is inserted transiently before model dispatch and is labelled as untrusted history. It is
not persisted into the OpenCode transcript. Curated `pc_*` tools expose Memory, Handoff, Experience, Skill, and
read-only Candidate operations. OpenCode asks before a named durable mutation.
read-only Candidate operations. OpenCode asks before a named durable mutation: the plugin sets OpenCode's
`powercontext` permission to `ask`, and a `permission` rule you configure that matches it, including `*`, takes
precedence.

The package also installs a TUI plugin. Run `/pc` in interactive OpenCode to open the PowerContext command prompt,
then use the same subcommands as the DSH plugin: `doctor`, `search`, `remember`, `flush`, `review`, `stats`,
Expand Down
13 changes: 12 additions & 1 deletion integrations/opencode/plugins/powercontext/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2469,6 +2469,8 @@ Use pc_review_list / pc_review_get for requested candidate inspection. Generatio
Memory correction requires the requested change, exact current Atomic Memory artifact and real content ETag from pc_memory_get. pc_memory_retire sets recoverable forgotten state using the exact artifact and state_version from search, list or pc_memory_state. Follow next_cursor for later inventory pages. Empty retrieval is normal. On failure, denial, or missing Scope, report the operation and safe returned reason without guessing causes or claiming saved/restored context. Avoid repeated failed calls and continue ordinary work.
Use powercontext-project-context for a relevant detailed workflow if that Skill is available; no Skill detour is needed before every response.`;
const CONTEXT_PREFIX = "PowerContext host-supplied context.";
const PERMISSION = "powercontext";
const DEFAULT_PERMISSION_RULE = `${PERMISSION.slice(0, -1)}?`;
const MAX_SOURCE_BYTES = 2e5;
const MAX_SESSION_CACHE = 256;
function promptText(parts, transportEncoded) {
Expand Down Expand Up @@ -2737,7 +2739,7 @@ function operationTool(runtime, definition) {
args: definition.args,
async execute(args, context) {
if (operationMutates(definition.operationId)) await context.ask({
permission: "powercontext",
permission: PERMISSION,
patterns: [definition.operationId],
always: [],
metadata: { operation: definition.operationId }
Expand Down Expand Up @@ -3039,6 +3041,15 @@ const PowerContextPlugin = async (input) => {
return {};
}
const hooks = {
config: async (config) => {
const settings = config;
const permission = settings.permission;
if (typeof permission === "string" || permission && DEFAULT_PERMISSION_RULE in permission) return;
settings.permission = {
[DEFAULT_PERMISSION_RULE]: "ask",
...permission
};
},
tool: createTools(runtime),
"chat.message": async (event, output) => {
const messageID = event.messageID ?? output.message.id;
Expand Down
16 changes: 15 additions & 1 deletion integrations/opencode/plugins/powercontext/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ Memory correction requires the requested change, exact current Atomic Memory art
Use powercontext-project-context for a relevant detailed workflow if that Skill is available; no Skill detour is needed before every response.`

const CONTEXT_PREFIX = 'PowerContext host-supplied context.'
const PERMISSION = 'powercontext'
// OpenCode matches permission names against rule keys as wildcards, where `?` stands for one character. This key
// matches only the plugin's permission, yet it differs from a `powercontext` key the user writes.
const DEFAULT_PERMISSION_RULE = `${PERMISSION.slice(0, -1)}?`
const MAX_SOURCE_BYTES = 200_000
const MAX_SESSION_CACHE = 256

Expand Down Expand Up @@ -331,7 +335,7 @@ function operationTool(
async execute(args, context) {
if (operationMutates(definition.operationId)) {
await context.ask({
permission: 'powercontext',
permission: PERMISSION,
patterns: [definition.operationId],
always: [],
metadata: { operation: definition.operationId },
Expand Down Expand Up @@ -650,6 +654,16 @@ export const PowerContextPlugin: Plugin = async (input) => {
}

const hooks: Awaited<ReturnType<Plugin>> = {
// OpenCode's agents allow every permission their defaults do not name, so a durable mutation would run without
// the confirmation it requests. OpenCode applies the last matching rule, and the default comes before every rule
// the user configures, so those rules still decide each operation they match.
config: async (config) => {
// The SDK's Config type predates permissions keyed by name.
const settings = config as { permission?: string | Record<string, unknown> }
const permission = settings.permission
if (typeof permission === 'string' || (permission && DEFAULT_PERMISSION_RULE in permission)) return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve the fallback when its wildcard key contains user rules

The presence check also matches a user-owned per-operation rule, not just the scalar fallback installed by this hook. With {"permission":{"powercontex?":{"commit_handoff":"allow"}}}, it returns before installing an ask fallback. Using the exact bundle on real OpenCode 1.18.21 with a real Server, pc_remember then falls through to the built-in * = allow, emits no permission request, and persists the Memory even though no user rule covers remember_memory. Please retain ask for unmatched operations when this key is already configured, while preserving the user's matching rules.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9bdb6d1. When the configuration already uses powercontex?, the hook now adds its ask rule under the next key of the same form (powerconte?t, then powercont?xt, …), still ahead of every user rule. With {"permission": {"powercontex?": {"commit_handoff": "allow"}}}, commit_handoff stays allowed and every other operation asks.

Verified with the exact bundle on OpenCode 1.19.5 against a real Server: under that configuration, pc_remember now raises a powercontext request for remember_memory, a rejected request stores nothing, and an approved one stores the Memory. c57a603's bundle fails the same case without a request. GET /agent lists powerconte?t:*=ask before powercontex?:commit_handoff=allow for build, plan, and general. plugin.spec.ts covers this configuration and a repeated run of the hook. I did not run 1.18.21.

settings.permission = { [DEFAULT_PERMISSION_RULE]: 'ask', ...permission }
},
tool: createTools(runtime),
'chat.message': async (event, output) => {
const messageID = event.messageID ?? output.message.id
Expand Down
16 changes: 16 additions & 0 deletions integrations/opencode/plugins/powercontext/tests/plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,22 @@ describe('PowerContextPlugin', () => {
expect(JSON.parse(String(result))).toMatchObject({ ok: true })
})

it('puts an ask rule for its permission ahead of the user permission rules', async () => {
const hooks = await PowerContextPlugin(pluginInput())
const configure = async (permission?: unknown) => {
const config: any = permission === undefined ? {} : { permission }
await hooks.config?.(config)
return config.permission
}
// OpenCode applies the last matching rule, so each rule the user configures still decides what it matches.
expect(await configure()).toEqual({ 'powercontex?': 'ask' })
const rules = { bash: 'ask', powercontext: { commit_handoff: 'allow' }, '*': 'deny' }
expect(Object.entries(await configure(rules))).toEqual([['powercontex?', 'ask'], ...Object.entries(rules)])
const configured = await configure({ powercontext: 'allow' })
expect(Object.entries(await configure(configured))).toEqual([['powercontex?', 'ask'], ['powercontext', 'allow']])
expect(await configure('allow')).toBe('allow')
})

it('captures a Working Note through the scoped operation', async () => {
process.env.POWERCONTEXT_OPENCODE_SCOPE_ID = 'project:test'
const calls: Array<{ url: string; body: any }> = []
Expand Down
Loading