Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .muse-plugin/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"schemaVersion": 1,
"name": "acp",
"displayName": "Agentic Control Plane",
"version": "0.1.1",
"version": "0.1.2",
"description": "Policy-check every tool call against your Agentic Control Plane workspace before it runs.",
"compat": { "source": "native", "manifestDir": ".muse-plugin" },
"capabilities": {
Expand Down
69 changes: 64 additions & 5 deletions hook.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import { homedir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'

export const HOOK_VERSION = '0.1.0'
export const HOOK_VERSION = '0.1.2'

/** 200 KB ceiling on tool output sent for post-hoc scanning (matches the backend). */
const POST_HOOK_PAYLOAD_CEILING = 200 * 1024
Expand All @@ -60,16 +60,46 @@ function readToken(env = process.env) {
return null
}

function lapseLine(fields) {
function lapseLine(fields, env = process.env) {
try {
mkdirSync(ACP_DIR, { recursive: true })
const dir = acpDir(env)
mkdirSync(dir, { recursive: true })
appendFileSync(
join(ACP_DIR, 'lapse.log'),
join(dir, 'lapse.log'),
JSON.stringify({ at: new Date().toISOString(), client: 'muse-code-hook', ...fields }) + '\n',
)
} catch { /* the lapse log is best-effort — never block a call on it */ }
}

// True the first time the workspace-deleted notice is asked for in a session,
// false after (gatewaystack-connect#1693, ported from claude-code-acp-plugin
// 0.29.3). With no session id, at most once per 24h via a timestamp marker.
// Fails toward showing the notice: an unwritable marker means it repeats,
// not vanishes.
const DELETED_NOTICE_WINDOW_MS = 24 * 60 * 60 * 1000
function firstDeletedNoticeThisSession(sessionId, env = process.env) {
const dir = join(acpDir(env), 'notices')
const id = String(sessionId ?? '').replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120)
try {
mkdirSync(dir, { recursive: true })
if (!id || id === 'unknown') {
const marker = join(dir, 'workspace-deleted.no-session')
let last = 0
try { last = Date.parse(readFileSync(marker, 'utf8').trim()) || 0 } catch { /* absent */ }
if (Date.now() - last < DELETED_NOTICE_WINDOW_MS) return false
writeFileSync(marker, new Date().toISOString())
return true
}
writeFileSync(join(dir, `workspace-deleted.${id}`), new Date().toISOString(), { flag: 'wx' })
return true
} catch (e) {
return e?.code !== 'EEXIST'
}
}

const KEY_FIX = 'Fix: re-run the installer (curl -sf https://agenticcontrolplane.com/install.sh | bash) or create a key at https://cloud.agenticcontrolplane.com/settings/api-keys and save it: echo \'gsk_...\' > ~/.acp/credentials'
const DELETED_FIX = 'The ACP workspace this machine was connected to has been deleted. To remove ACP from this machine: acp-uninstall (older installs without it: curl -sf https://agenticcontrolplane.com/uninstall.sh | bash). To keep using ACP, re-run the installer: curl -sf https://agenticcontrolplane.com/install.sh | bash'

/**
* Tier resolution, in trust order: explicit env, config file, CI markers,
* then the payload's own permission_mode — `never` means no human is
Expand Down Expand Up @@ -160,6 +190,11 @@ async function post(base, headers, path, payload, timeoutMs) {
// limit it is reporting.
const err = new Error(`HTTP ${res.status}${res.statusText ? ` ${res.statusText}` : ''}`)
err.httpStatus = res.status
if (res.status >= 400 && res.status < 500) {
// A 4xx body may carry a machine-readable `code` (workspace_deleted).
const errBody = await res.json().catch(() => null)
if (typeof errBody?.code === 'string') err.acpCode = errBody.code
}
throw err
}
return await res.json()
Expand Down Expand Up @@ -280,9 +315,33 @@ export async function decide(payload, env = process.env) {
data = await post(govern, headers, '/govern/tool-use', base, timeoutMs)
}
} catch (error) {
// A 401/403 is NOT the gateway being down — it is this machine's key being
// revoked, mistyped, or from a deleted workspace. Reading it as "gateway
// unreachable" left a user running ungoverned for hours believing it was
// our outage. Same tier posture as an outage (interactive fails open,
// unattended stays blocked), but the message names the cause and the fix.
// `code: "workspace_deleted"`: the owner deleted the workspace on purpose —
// say so once per session with how to remove ACP, then proceed silently.
// (gatewaystack-connect#1693, ported from claude-code-acp-plugin 0.29.3.)
const status = error?.httpStatus
if (status === 401 || status === 403) {
const deleted = error.acpCode === 'workspace_deleted'
const fix = deleted ? DELETED_FIX : KEY_FIX
if (tier === 'interactive') {
lapseLine({ kind: 'UNGOVERNED', tool: call.toolName, tier, detail: `key rejected (HTTP ${status})` }, env)
if (deleted && !firstDeletedNoticeThisSession(call.sessionId, env)) return { out: {} }
const warn = `[ACP] ⚠ KEY REJECTED (HTTP ${status}): the key in ~/.acp/credentials is revoked or invalid — this call proceeded UNGOVERNED and unlogged, and every call will until it is fixed. ${fix}`
return { out: { systemMessage: warn }, warn }
}
return {
out: encodeDecision('deny',
`[ACP] Key rejected (HTTP ${status}) — the key in ~/.acp/credentials is revoked or invalid; ${tier} tier stays blocked until it is fixed. ${fix}`,
call.event),
}
}
const detail = error?.name === 'AbortError' ? 'request timed out' : (error?.message ?? 'network error')
if (tier === 'interactive') {
lapseLine({ kind: 'UNGOVERNED', tool: call.toolName, tier, detail })
lapseLine({ kind: 'UNGOVERNED', tool: call.toolName, tier, detail }, env)
const warn = `[ACP] ⚠ UNGOVERNED: gateway unreachable (${detail}) — ${call.toolName} proceeded WITHOUT policy check. Lapse logged to ~/.acp/lapse.log.`
return { out: { systemMessage: warn }, warn }
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@agenticcontrolplane/muse-code",
"version": "0.1.1",
"version": "0.1.2",
"description": "Agentic Control Plane hook for Meta Muse Code — allow/ask/deny before every tool call, output scanning after it, one receipt per session.",
"type": "module",
"bin": {
Expand Down
133 changes: 133 additions & 0 deletions test/key-rejected.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// A 401/403 from the gateway is a credential failure, not an outage, and a
// 401 with `code: "workspace_deleted"` says so once per session
// (gatewaystack-connect#1693; mirrors codex-acp-plugin
// test/key-rejected.test.mjs).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createServer } from 'node:http'
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'

import { decide } from '../hook.mjs'

async function withGateway(status, reply, fn) {
const server = createServer((req, res) => {
req.resume()
req.on('end', () => {
res.statusCode = status
res.setHeader('content-type', 'application/json')
res.end(reply === undefined ? '' : JSON.stringify(reply))
})
})
await new Promise((r) => server.listen(0, '127.0.0.1', r))
try { return await fn(`http://127.0.0.1:${server.address().port}`) } finally { server.close() }
}

function tmpHome() {
const home = mkdtempSync(join(tmpdir(), 'acp-keyrej-'))
mkdirSync(join(home, '.acp'), { recursive: true })
writeFileSync(join(home, '.acp', 'credentials'), 'test-token')
return home
}

function runPre(base, home, extra = {}) {
const payload = {
hook_event_name: 'PreToolUse',
tool_name: 'Bash',
tool_input: { command: 'echo hi' },
permission_mode: 'default',
...extra,
}
return decide(payload, { HOME: home, ACP_GOVERN_BASE: base })
}

const decision = (r) => r.out.hookSpecificOutput?.permissionDecision ?? 'allow'
const reason = (r) => r.out.hookSpecificOutput?.permissionDecisionReason
const DELETED = { error: 'workspace deleted', code: 'workspace_deleted' }

test('interactive 401 proceeds with KEY REJECTED naming the key and the fix, and logs the lapse', async () => {
const home = tmpHome()
const r = await withGateway(401, { error: 'invalid key' }, (b) => runPre(b, home, { session_id: 's1' }))
assert.equal(decision(r), 'allow')
assert.match(r.out.systemMessage, /^\[ACP\] ⚠ KEY REJECTED \(HTTP 401\): the key in ~\/\.acp\/credentials is revoked or invalid/)
assert.match(r.out.systemMessage, /install\.sh/)
assert.match(r.out.systemMessage, /settings\/api-keys/)
assert.doesNotMatch(r.out.systemMessage, /unreachable/i)
assert.match(readFileSync(join(home, '.acp', 'lapse.log'), 'utf8'), /key rejected \(HTTP 401\)/)
})

test('interactive 401 with no body still reads as KEY REJECTED', async () => {
const r = await withGateway(401, undefined, (b) => runPre(b, tmpHome()))
assert.equal(decision(r), 'allow')
assert.match(r.out.systemMessage, /KEY REJECTED \(HTTP 401\)/)
})

test('unattended 401 stays denied with the cause named', async () => {
const r = await withGateway(401, { error: 'invalid key' }, (b) => runPre(b, tmpHome(), { permission_mode: 'never' }))
assert.equal(decision(r), 'deny')
assert.match(reason(r), /Key rejected \(HTTP 401\)/)
assert.match(reason(r), /~\/\.acp\/credentials/)
assert.doesNotMatch(reason(r), /unreachable/i)
})

test('403 is treated like 401', async () => {
const i = await withGateway(403, { error: 'forbidden' }, (b) => runPre(b, tmpHome()))
assert.equal(decision(i), 'allow')
assert.match(i.out.systemMessage, /KEY REJECTED \(HTTP 403\)/)
const u = await withGateway(403, { error: 'forbidden' }, (b) => runPre(b, tmpHome(), { permission_mode: 'never' }))
assert.equal(decision(u), 'deny')
assert.match(reason(u), /Key rejected \(HTTP 403\)/)
})

test('5xx keeps the outage posture', async () => {
const i = await withGateway(503, { error: 'down' }, (b) => runPre(b, tmpHome()))
assert.equal(decision(i), 'allow')
assert.match(i.out.systemMessage, /UNGOVERNED: gateway unreachable \(HTTP 503/)
const u = await withGateway(503, { error: 'down' }, (b) => runPre(b, tmpHome(), { permission_mode: 'never' }))
assert.equal(decision(u), 'deny')
assert.match(reason(u), /Gateway unreachable/)
})

test('interactive workspace_deleted: one notice per session, then silent; lapse logged every call', async () => {
const home = tmpHome()
await withGateway(401, DELETED, async (b) => {
const first = await runPre(b, home, { session_id: 'sess-a' })
assert.equal(decision(first), 'allow')
assert.match(first.out.systemMessage, /workspace this machine was connected to has been deleted/)
assert.match(first.out.systemMessage, /acp-uninstall/)
assert.match(first.out.systemMessage, /uninstall\.sh/)
assert.ok(existsSync(join(home, '.acp', 'notices', 'workspace-deleted.sess-a')))

const second = await runPre(b, home, { session_id: 'sess-a' })
assert.deepEqual(second.out, {})
assert.equal(second.warn, undefined)

const otherSession = await runPre(b, home, { session_id: 'sess-b' })
assert.match(otherSession.out.systemMessage, /has been deleted/)
})
const lapses = readFileSync(join(home, '.acp', 'lapse.log'), 'utf8').trim().split('\n')
assert.equal(lapses.length, 3)
})

test('interactive workspace_deleted with no session id: at most once per 24h', async () => {
const home = tmpHome()
await withGateway(401, DELETED, async (b) => {
const first = await runPre(b, home)
assert.match(first.out.systemMessage, /has been deleted/)
const second = await runPre(b, home)
assert.deepEqual(second.out, {})
})
})

test('unattended workspace_deleted denies every call with the deleted message', async () => {
const home = tmpHome()
await withGateway(401, DELETED, async (b) => {
for (let i = 0; i < 2; i++) {
const r = await runPre(b, home, { permission_mode: 'never', session_id: 'sess-u' })
assert.equal(decision(r), 'deny')
assert.match(reason(r), /has been deleted/)
assert.match(reason(r), /acp-uninstall/)
}
})
})
Loading