Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
64 changes: 56 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,14 @@ Add the plugin to your [OpenCode config](https://opencode.ai/docs/config/):

### OpenCode V2

OpenCode V2 uses the new plugin API. You can load `opencode-pty/v2` and optionally configure options (such as a fixed web UI port):
OpenCode V2 uses the new plugin API. Load the package by its bare npm ref — the `.` entrypoint is a dual-mode export that serves both runtimes — and optionally configure options (such as a fixed web UI port):

```json
{
"$schema": "https://opencode.ai/config.json",
"plugin": [
"plugins": [
{
"package": "opencode-pty/v2",
"package": "opencode-pty",
"options": {
"port": 4200,
"hostname": "127.0.0.1",
Expand All @@ -61,6 +61,34 @@ OpenCode V2 uses the new plugin API. You can load `opencode-pty/v2` and optional
}
```

Notes for V2:

- V2 reads the `plugins` array (object form). The V1 `plugin` field is silently ignored — a V1-shaped array produces zero plugin loads.
- The previous `opencode-pty/v2` subpath ref does not install: the V2 loader parses subpath refs as npm install specs ([#67](https://github.com/shekohex/opencode-pty/issues/67)). The bare ref works via the dual-mode default export; the `./v2` subpath remains valid for direct-import consumers.
- A plugin must export a default definition with an `id` and a `setup` (or `effect`) function. The `.` entrypoint now exports exactly that alongside the V1 `server` entrypoint.
- If the npm ref fails to install through OpenCode's bundled npm with `<git dep preparation failed>`, use a local clone (below). That failure happens for any package with dependencies, not just this one.

#### Install from a local clone

```bash
git clone https://github.com/shekohex/opencode-pty.git
cd opencode-pty
npm install --legacy-peer-deps # plain npm fails on react@18 vs @opentui/keymap peer
```

Then point a directory entry at the clone:

```json
{
"$schema": "https://opencode.ai/config.json",
"plugins": ["/absolute/path/to/opencode-pty"]
}
```

A directory entry resolves a root `server` file, else `index`, with a `.ts`, `.tsx`, or `.js`
extension; `package.json` `main` and `exports` are not followed for a path entry. This
repository's root `index.ts` is that entrypoint, so the clone loads without a build step.

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `port` | `number` | `0` (ephemeral) | Fixed port for the PTY Web UI observer server |
Expand Down Expand Up @@ -297,7 +325,27 @@ This eliminates the need for polling—perfect for long-running processes like b

### Permissions

This plugin respects OpenCode's [permission settings](https://opencode.ai/docs/permissions/) for the `bash` tool. Commands spawned via `pty_spawn` are checked against your `permission.bash` configuration.
This plugin respects OpenCode's [permission settings](https://opencode.ai/docs/permissions/). Commands spawned via `pty_spawn`, and command lines sent with `pty_write`, are checked with the same permission surface the host's own shell tool uses.

On **V2** that surface is `ctx.permission.assert`: the plugin asks the host to evaluate the session's rules and only spawns once the check resolves. A `deny` rule blocks the spawn, and an `ask` rule raises OpenCode's normal permission prompt — the answer is honoured, including saved approvals. V2 names the shell action `shell`:

```json
{
"$schema": "https://opencode.ai/config.json",
"permissions": [
{ "action": "shell", "resource": "npm *", "effect": "allow" },
{ "action": "shell", "resource": "git push", "effect": "deny" },
{ "action": "shell", "resource": "terraform *", "effect": "deny" }
]
}
```

Two V2 edge cases are deliberate:

- A check that cannot be attributed to a session is **denied** rather than allowed. Every PTY tool call carries its session, so this only affects calls made outside a tool invocation, and denying keeps a configured `deny` rule from being bypassed.
- A host that exposes no `ctx.permission` domain gets a startup warning and no checks, matching the pre-2.0 fallback below. This plugin cannot read `permissions` itself on V2 — the plugin context has no config reader — so the host is the only authority.

On **V1** the plugin reads `permission.bash` from the host config:

```json
{
Expand All @@ -313,12 +361,12 @@ This plugin respects OpenCode's [permission settings](https://opencode.ai/docs/p
```

> [!IMPORTANT]
> **Limitations compared to built-in bash tool:**
> **V1 limitations compared to the built-in bash tool:**
>
> - **"ask" permissions are treated as "deny"**: Since plugins cannot trigger OpenCode's permission prompt UI, commands matching an "ask" pattern will be denied. A toast notification will inform you when this happens. Configure explicit "allow" or "deny" for commands you want to use with PTY.
> - **"external_directory" with "ask" is treated as "allow"**: When the working directory is outside the project and `permission.external_directory` is set to "ask", this plugin allows it (with a log message). Set to "deny" explicitly if you want to block external directories.
> - **"ask" permissions are treated as "deny"**: Since the V1 plugin API cannot trigger OpenCode's permission prompt UI, commands matching an "ask" pattern will be denied. A toast notification will inform you when this happens. Configure explicit "allow" or "deny" for commands you want to use with PTY. (V2 does not have this limitation — `ctx.permission.assert` prompts.)
> - **"external_directory" with "ask" is treated as "allow"**: When the working directory is outside the project and `permission.external_directory` is set to "ask", the V1 path allows it (with a log message). Set to "deny" explicitly if you want to block external directories.

#### Example: Allow specific commands for PTY
#### Example: Allow specific commands for PTY (V1)

```json
{
Expand Down
15 changes: 15 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,17 @@
import { Plugin } from './src/v2/index.ts'
import { PTYPlugin } from './src/plugin.ts'

export { PTYPlugin } from './src/plugin.ts'
export { PTYPlugin as server } from './src/plugin.ts'
export { Plugin } from './src/v2/index.ts'

// Dual-mode default export: opencode V1 (>= 1.18.29) resolves the object entrypoint and
// calls `server()`; V2 validates `{ id, setup }` and calls `setup()`. The bare npm ref
// therefore loads on both runtimes — necessary because the V2 loader parses the
// documented `opencode-pty/v2` subpath ref as an npm install spec and cannot install it
// (#67), and the previous `.` entrypoint carried no default export at all.
export default {
id: Plugin.id,
server: PTYPlugin,
setup: Plugin.setup,
}
1 change: 1 addition & 0 deletions src/adapters/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { HostAdapter } from './types.ts'

export * from './types.ts'
export * from './v1/index.ts'
export * from './v2/index.ts'

/**
* Installs a host adapter by connecting its notifier and permission authorizer
Expand Down
19 changes: 17 additions & 2 deletions src/adapters/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,27 @@ export interface SessionNotifier {
sendExitNotification(session: PTYSession, exitCode: number): Promise<void> | void
}

/**
* The tool invocation a permission check belongs to.
*
* Hosts that evaluate permissions per session need this to attribute the check
* to a session, an agent and a tool call. It is optional because a check can be
* made outside a tool call; hosts that require it decide what an absent value
* means (the V2 adapter denies, see `V2PermissionAuthorizer`).
*/
export interface PermissionRequestContext {
sessionID?: string
agent?: string
messageID?: string
callID?: string
}

/**
* Host-agnostic authorizer for validating command and workdir execution permissions.
*/
export interface PermissionAuthorizer {
checkCommand(command: string, args: string[]): Promise<void>
checkWorkdir(workdir: string): Promise<void>
checkCommand(command: string, args: string[], context?: PermissionRequestContext): Promise<void>
checkWorkdir(workdir: string, context?: PermissionRequestContext): Promise<void>
}

/**
Expand Down
153 changes: 153 additions & 0 deletions src/adapters/v2/permissions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import type { PermissionAuthorizer, PermissionRequestContext } from '../types.ts'

/**
* The subset of opencode V2's `ctx.permission` the authorizer needs.
*
* Typed structurally rather than imported so the adapter stays decoupled from
* the `@opencode/plugin` package version pinned by the host, and so tests can
* supply a recording double without a whole V2 server context.
*/
export interface V2PermissionDomain {
assert(input: V2PermissionAssertInput): Promise<void>
}

export interface V2PermissionAssertInput {
sessionID: string
agent?: string
/** Permission action: V2 names the shell action `shell` (V1 called it `bash`). */
action: string
resources: string[]
/** Patterns saved when the user answers "always allow". */
save?: string[]
source?: { type: 'tool'; messageID: string; id: string }
}

export interface V2PermissionAuthorizerOptions {
permission: V2PermissionDomain
/** The location directory; a workdir outside it is an external directory. */
directory?: string
}

/**
* V2 permission authorizer built on `ctx.permission.assert`.
*
* opencode V2 has no `config.get()` on the plugin context, so the configured
* `permissions` rules cannot be read and re-implemented here: `assert` is the
* only documented surface that evaluates them (including saved approvals and
* agent rules) and prompts when a rule resolves to `ask`. Delegating keeps the
* plugin's answer identical to the host's own shell tool.
*
* Safe default: when `assert` is present but the check cannot be attributed to
* a session, the check **denies**. Allowing instead would reintroduce #80 —
* a `deny` rule silently bypassed — while denying only affects calls made
* outside a tool invocation, which the plugin does not make.
*/
export class V2PermissionAuthorizer implements PermissionAuthorizer {
private readonly permission: V2PermissionDomain
private readonly directory?: string

constructor(options: V2PermissionAuthorizerOptions) {
this.permission = options.permission
this.directory = options.directory
}

async checkCommand(
command: string,
args: string[],
context?: PermissionRequestContext
): Promise<void> {
const commandLine = [command, ...args].join(' ').trim()
if (!commandLine) {
return
}

// `save` proposes the exact command so "always allow" cannot widen a rule
// to a prefix the user never approved. The host decides whether to store it.
await this.assert(context, 'shell', [commandLine], [commandLine])
}

async checkWorkdir(workdir: string, context?: PermissionRequestContext): Promise<void> {
if (!this.directory || isInside(workdir, this.directory)) {
return
}

const normalized = normalizeSegments(workdir)
await this.assert(context, 'external_directory', [normalized, `${normalized}/*`])
}

private async assert(
context: PermissionRequestContext | undefined,
action: string,
resources: string[],
save?: string[]
): Promise<void> {
const sessionID = context?.sessionID
if (!sessionID) {
throw new Error(
`PTY: ${action} permission for "${resources.join(', ')}" cannot be evaluated without a session, so it is denied.`
)
}

const source =
context.messageID && context.callID
? { type: 'tool' as const, messageID: context.messageID, id: context.callID }
: undefined

await this.permission.assert({
sessionID,
...(context.agent ? { agent: context.agent } : {}),
action,
resources,
...(save ? { save } : {}),
...(source ? { source } : {}),
})
}
}

/**
* True when `path` is the same as, or below, `root`.
*
* Both sides are resolved lexically first, so `/workspace/app/../etc` is not
* mistaken for a path inside `/workspace/app`, and the comparison is
* segment-wise so `/workspace/app-evil` is not inside `/workspace/app` either.
*/
function isInside(path: string, root: string): boolean {
const normalizedRoot = normalizeSegments(root)
const normalizedPath = normalizeSegments(path)
return normalizedPath === normalizedRoot || normalizedPath.startsWith(`${normalizedRoot}/`)
}

/**
* Collapses `.` and `..` segments without touching the filesystem.
*
* `..` never climbs above the first segment: a path that escapes its own root
* then simply fails the prefix comparison above.
*/
function normalizeSegments(path: string): string {
const absolute = path.startsWith('/')
const segments: string[] = []
for (const segment of path.split('/')) {
if (!segment || segment === '.') {
continue
}
if (segment === '..') {
if (segments.length > 0) {
segments.pop()
}
continue
}
segments.push(segment)
}
const joined = segments.join('/')
return absolute ? `/${joined}` : joined || '.'
}

export function createV2PermissionAuthorizer(
permission: V2PermissionDomain | undefined,
directory?: string
): V2PermissionAuthorizer | undefined {
if (!permission || typeof permission.assert !== 'function') {
return undefined
}
return new V2PermissionAuthorizer({ permission, directory })
}
53 changes: 45 additions & 8 deletions src/plugin/pty/permissions.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { PluginClient } from '../types.ts'
import type { PermissionAuthorizer } from '../../adapters/types.ts'
import type { PermissionAuthorizer, PermissionRequestContext } from '../../adapters/types.ts'
import { V1PermissionAuthorizer } from '../../adapters/v1/permissions.ts'

export type { PermissionAuthorizer }
export type { PermissionAuthorizer, PermissionRequestContext }

let _authorizer: PermissionAuthorizer | null = null

Expand All @@ -27,22 +27,59 @@ export function initPermissions(client: PluginClient, directory: string): void {
_authorizer = new V1PermissionAuthorizer(client, directory)
}

/**
* Extracts what a host needs to attribute a permission check to a tool call.
*
* The V1 tool context and the V2 tool context carry overlapping but different
* fields (`id` only exists on V2), and a tool may be invoked without a context
* in tests, so every field is read defensively instead of being trusted.
*/
export function permissionRequestContext(toolContext: unknown): PermissionRequestContext {
const source = (toolContext ?? {}) as Record<string, unknown>
const context: PermissionRequestContext = {}
for (const key of ['sessionID', 'agent', 'messageID'] as const) {
const value = source[key]
if (typeof value === 'string') context[key] = value
}
if (typeof source.id === 'string') context.callID = source.id
return context
}

/**
* Checks command execution permission against the active authorizer.
* Defaults to allowing if no authorizer is set.
*/
export async function checkCommandPermission(command: string, args: string[]): Promise<void> {
if (_authorizer) {
await _authorizer.checkCommand(command, args)
export async function checkCommandPermission(
command: string,
args: string[],
context?: PermissionRequestContext
): Promise<void> {
if (!_authorizer) {
return
}
// Pass the context only when there is one: a context-less check keeps the
// two-argument call shape existing authorizers and tests already observe.
if (context) {
await _authorizer.checkCommand(command, args, context)
return
}
await _authorizer.checkCommand(command, args)
}

/**
* Checks working directory access permission against the active authorizer.
* Defaults to allowing if no authorizer is set.
*/
export async function checkWorkdirPermission(workdir: string): Promise<void> {
if (_authorizer) {
await _authorizer.checkWorkdir(workdir)
export async function checkWorkdirPermission(
workdir: string,
context?: PermissionRequestContext
): Promise<void> {
if (!_authorizer) {
return
}
if (context) {
await _authorizer.checkWorkdir(workdir, context)
return
}
await _authorizer.checkWorkdir(workdir)
}
Loading