mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +01:00
Prototype two-way Dot runner bridge over MCP Events
This commit is contained in:
1 parent
887958e45a
commit
cd4739aa9c
12 files changed
+890
-13
No files matched your search
@@ -0,0 +1,162 @@
|
||||
# OpenAI Dot runner prototype
|
||||
|
||||
Built 2026-10-02 on the public MCP foundation from `codex/paperclip-mcp-experimental-setting`
|
||||
(commit `a88448f77`), merged into the fresh `codex/dot-events-prototype` worktree.
|
||||
|
||||
This is a working **local protocol prototype**, not a production-selectable Dot
|
||||
agent. The demo's Dot peer and task authority are synthetic. It does not contact
|
||||
OpenAI, spend model credits, or modify an existing company. The new provider
|
||||
implements the runner's `HarnessDriver` contract and executes through
|
||||
`HarnessDriverBackend`; it does not use the legacy HTTP adapter.
|
||||
|
||||
## Try it
|
||||
|
||||
After installing and building workspace dependencies:
|
||||
|
||||
```sh
|
||||
pnpm prototype:dot
|
||||
```
|
||||
|
||||
The command creates a temporary PostgreSQL database, company, user and task;
|
||||
creates a real OAuth grant through PKCE and consent; starts two loopback HTTP
|
||||
servers; subscribes to a signed event; and drives a runner assignment to
|
||||
completion through authenticated MCP. It prints each successful stage and
|
||||
removes the temporary state. Its synthetic Dot peer deliberately retries a
|
||||
write concurrently to prove there is only one report. No credentials are
|
||||
printed. This is a CLI demo, not a mock UI or a connection to your Dot account.
|
||||
|
||||
Fresh-worktree preparation (use the repository's pinned pnpm version):
|
||||
|
||||
```sh
|
||||
pnpm install --no-frozen-lockfile
|
||||
pnpm --filter '@paperclipai/server^...' --filter '!@paperclipai/paperclip-runner' --filter '!@paperclipai/ui' build
|
||||
```
|
||||
|
||||
The local callback uses an injected transport restricted to one fixed synthetic
|
||||
HTTPS URL and rewrites it to loopback. The production event transport retains
|
||||
its HTTPS, public-IP DNS pinning and no-redirect checks.
|
||||
|
||||
## Two directions, two explicit identities
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Host as Paperclip host
|
||||
participant Runner as Dot runner bridge
|
||||
participant MCP as OAuth MCP + event outbox
|
||||
participant Dot as OpenAI Dot
|
||||
Host->>Runner: Admitted task + explicit grant/agent binding
|
||||
Runner->>MCP: Persist work_available references
|
||||
MCP->>Dot: Signed webhook wakeup
|
||||
Dot-->>MCP: Receipt (does not mean work started)
|
||||
Dot->>MCP: Read inbox and assignment; accept
|
||||
MCP->>Runner: Authenticated, bound commands
|
||||
Runner-->>Host: PRP turn.started
|
||||
Dot->>MCP: Call projected tools / report progress / propose result
|
||||
MCP->>Runner: Check current authority; deduplicate request ID
|
||||
Runner-->>Host: PRP progress and structured result
|
||||
Note over Host: Paperclip decides final task disposition
|
||||
Dot->>MCP: Personal Paperclip reads/writes while idle
|
||||
Note over MCP: These retain the consenting person's identity
|
||||
```
|
||||
|
||||
Dot's always-available personal tools come from the merged public MCP connection.
|
||||
They act as the person who consented. Agent participation is separate: a trusted
|
||||
host binds an already admitted run to one OAuth grant, company, agent, task,
|
||||
session and turn. Connecting or selecting a task never grants impersonation.
|
||||
The registry has no MCP registration tool and no generic API executor.
|
||||
|
||||
## What is implemented
|
||||
|
||||
- `DotHarnessDriver`: one turn per admitted run, explicit acceptance, bounded
|
||||
lifetime, projected tools, progress and validated `paperclip.run_result.v1`
|
||||
completion. Reports normal PRP events consumed by the existing native backend.
|
||||
- `createDotRunnerMcpBridge`: six tools on the existing authenticated endpoint:
|
||||
`paperclip_dot_inbox`, `paperclip_dot_read`, `paperclip_dot_accept`,
|
||||
`paperclip_dot_tool`, `paperclip_dot_progress`, `paperclip_dot_finish`.
|
||||
Bound tools are visible only to the selected grant with write consent.
|
||||
- Optional `paperclip.dot.work_available` event on the existing durable outbox.
|
||||
Its `companyId` and `taskId` identify a designated standing inbox task. Each
|
||||
assignment can concern a different task; the event carries only IDs, and Dot
|
||||
retrieves the current assignment through authenticated tools. Existing
|
||||
authorization, encrypted callback material, signed verification, retry,
|
||||
expiration, rotation and unsubscribe behavior are reused.
|
||||
- Matching duplicate commands share one receipt, including simultaneous writes.
|
||||
A changed retry is rejected. Ambiguous writes remain `unknown` and are not
|
||||
redispatched. Per-run receipts are memory-only in this prototype.
|
||||
- Revocation/expiry prevents further accepted commands and ends event waiting.
|
||||
The live host authority callback runs for each new operation and before
|
||||
returning tool output. The host's tool dispatcher must enforce atomic domain
|
||||
permissions, pause, ownership, approvals and budget checks at the actual write.
|
||||
- Usage and cost remain unknown. Delivery does not fabricate a started turn.
|
||||
Result acceptance proposes a disposition; it does not directly set issue status.
|
||||
|
||||
## Host wiring and the production gap
|
||||
|
||||
The default app does **not** construct the bridge or advertise the Dot event.
|
||||
The host must explicitly pass `enableDotPrototype: true` to
|
||||
`createPublicMcpEvents`, pass the bridge as the fourth argument to
|
||||
`publicMcpIngressRoutes`, and register a driver for a trusted admitted run.
|
||||
The lab demonstrates that composition with synthetic admission and a single
|
||||
synthetic projected tool. There is no production scheduling integration yet.
|
||||
|
||||
Do not enable this by supplying a fake Codex profile to the native execution
|
||||
factory or by creating a heartbeat row from an MCP request. Production needs:
|
||||
|
||||
1. An explicit governed agent binding/consent and a qualified Dot provider in
|
||||
native admission, with task checkout, budgets, pause and policy checks.
|
||||
2. Durable provider mailbox and command receipts, reconnect/recovery and
|
||||
reconciliation of uncertain tool outcomes. The event outbox already persists;
|
||||
this prototype's runner registry does not. After restart it refuses recovery.
|
||||
3. Server-owned runtime tool projection/dispatch with ordinary audit receipts.
|
||||
The lab tool is not the production runner tool authority.
|
||||
4. A stop policy that can handle remote autonomy honestly. Revoking Paperclip
|
||||
access cannot prove that Dot or its child tasks stopped. Active close reports
|
||||
`provider stop is unconfirmed`; interruption, steering and resume are not
|
||||
advertised. `dot-bridge:<session>` identifies this bridge, not an OpenAI task.
|
||||
5. A reachable staging deployment, real Dot plugin onboarding, and a live
|
||||
event-triggered assignment before claiming client compatibility or release
|
||||
readiness. Hosted use also needs the companion Cloud broker deployed.
|
||||
|
||||
An existing in-flight external write can finish after revocation. Do not retry
|
||||
with a fresh request ID to force a result. Inspect authoritative task state.
|
||||
Unregister completed runs to release the bounded in-process registry.
|
||||
|
||||
## Intended live onboarding
|
||||
|
||||
1. Connect the existing Paperclip MCP plugin in developer mode and consent to
|
||||
the team and requested writes.
|
||||
2. Explicitly bind that connection to the chosen Dot agent after the production
|
||||
admission work above. Show the identity and the standing inbox task.
|
||||
3. Give Dot one standing instruction to subscribe to `paperclip.dot.work_available`
|
||||
for that inbox, inspect current assignments, accept intended work, use the
|
||||
projected tools, and finish with a structured result. Treat duplicate events
|
||||
as wakeups, never as another task. Avoid comment-acknowledgement loops.
|
||||
4. Assign work in Paperclip and verify the entire loop with the actual account.
|
||||
|
||||
OpenAI now documents MCP Events for dots. Private developer-mode testing does
|
||||
not require a public directory listing; public distribution is a separate review.
|
||||
See [MCP Events](https://developers.openai.com/plugins/build/mcp-events),
|
||||
[developer mode](https://developers.openai.com/api/docs/guides/developer-mode),
|
||||
and [app review](https://developers.openai.com/plugins/deploy/app-review).
|
||||
|
||||
## Verification
|
||||
|
||||
```sh
|
||||
pnpm --filter @paperclipai/paperclip-runner exec vitest run src/drivers/dot/dot-harness-driver.test.ts
|
||||
pnpm --filter @paperclipai/server exec vitest run src/__tests__/public-mcp.test.ts
|
||||
pnpm prototype:dot
|
||||
```
|
||||
|
||||
Runner tests cover native PRP validation, cross-company/grant/turn rejection,
|
||||
unknown outcomes, concurrent retries, expiry, live authority checks, malformed
|
||||
results, late writes, revocation and unsupported recovery. The MCP suite checks
|
||||
real OAuth, event signatures, the opt-in catalog, personal-tool coexistence and
|
||||
revocation. The CLI demo uses real TCP for both directions.
|
||||
|
||||
Recorded validation: eight runner tests passed; all 37 MCP tests passed; the
|
||||
changed Dot scenario passed again after the final uncertainty-handling fix;
|
||||
runner and server TypeScript checks passed; the loopback CLI demo passed.
|
||||
Shared/server dependency builds and the runner TypeScript build also passed.
|
||||
The repository-wide test/build, Rust provider qualification, hosted Cloud and
|
||||
actual OpenAI Dot acceptance were not run. This is not a PR-ready production
|
||||
provider handoff.
|
||||
@@ -14,6 +14,7 @@
|
||||
"dev:ui": "pnpm --filter @paperclipai/ui dev",
|
||||
"dev:mobile": "pnpm --filter @paperclipai/ui build && pnpm --filter @paperclipai/ui preview",
|
||||
"dev:both": "node scripts/dev-both.mjs",
|
||||
"prototype:dot": "pnpm --filter @paperclipai/server exec tsx scripts/dot-runner-demo.ts",
|
||||
"storybook": "pnpm --filter @paperclipai/ui storybook",
|
||||
"build-storybook": "pnpm --filter @paperclipai/ui build-storybook",
|
||||
"build": "pnpm run preflight:workspace-links && pnpm -r build",
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# Dot runner prototype
|
||||
|
||||
Experimental provider boundary for OpenAI Dot. This is not a qualified production
|
||||
provider and is deliberately absent from the provider picker.
|
||||
|
||||
See `doc/dot-runner-prototype.md` at the repository root for setup and limits.
|
||||
@@ -0,0 +1,133 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { HarnessDriverBackend } from "../../backends/harness-driver-backend.js";
|
||||
import { validatePrpEvent } from "../../protocol/replay-contract.js";
|
||||
import { DotHarnessDriver, type DotCommand, type DotDriverOptions } from "./dot-harness-driver.js";
|
||||
|
||||
const result = { schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", summary: "Research saved.",
|
||||
completionClaim: { contractRevision: "dot-demo-v1", objectiveSatisfied: true, criteria: [], remainingWork: [] },
|
||||
evidence: [], verification: [], attentionRequests: [], artifacts: [] };
|
||||
|
||||
async function fixture(overrides: Partial<DotDriverOptions> = {}) {
|
||||
const identity = { companyId: randomUUID(), agentId: randomUUID(), issueId: randomUUID(), runId: randomUUID(), sessionId: randomUUID() };
|
||||
const principal = { companyId: identity.companyId, grantId: randomUUID() };
|
||||
const publish = vi.fn(async () => {});
|
||||
const executeTool = vi.fn(async () => ({ saved: true }));
|
||||
const assertAuthority = vi.fn(async () => {});
|
||||
const driver = new DotHarnessDriver({ identity, principal, expiresAt: Date.now() + 60_000,
|
||||
tools: [{ name: "write_document", description: "Save the report", inputSchema: { type: "object" } }],
|
||||
publish, executeTool, assertAuthority, ...overrides });
|
||||
const backend = new HarnessDriverBackend(driver);
|
||||
const session = await backend.openSession({ identity });
|
||||
const { turnId } = await session.startTurn({ message: { role: "user", text: "Research competitors and save a report." } });
|
||||
const call = (command: Omit<DotCommand, "turnId" | "requestId"> & Record<string, unknown>, requestId = randomUUID()) =>
|
||||
driver.command(principal, { ...command, turnId, requestId } as DotCommand);
|
||||
return { identity, principal, driver, backend, session, turnId, call, publish, executeTool, assertAuthority };
|
||||
}
|
||||
|
||||
describe("Dot runner provider prototype", () => {
|
||||
it("runs a two-way assignment through the real native backend and valid PRP events", async () => {
|
||||
const f = await fixture();
|
||||
expect(f.publish.mock.calls[0]?.[0]).toMatchObject({ ...f.identity, turnId: f.turnId });
|
||||
expect(JSON.stringify(f.publish.mock.calls)).not.toContain("Research competitors");
|
||||
expect(await f.driver.inbox(f.principal)).toMatchObject({ accepted: false });
|
||||
expect(await f.call({ operation: "read" })).toMatchObject({ message: { text: "Research competitors and save a report." } });
|
||||
await expect(f.call({ operation: "tool", name: "write_document", arguments: {} })).rejects.toThrow("Accept");
|
||||
await f.call({ operation: "accept" });
|
||||
await f.call({ operation: "tool", name: "write_document", arguments: { body: "Report" } });
|
||||
await f.call({ operation: "progress", text: "Saved the report." });
|
||||
const finishId = randomUUID();
|
||||
await f.call({ operation: "finish", result }, finishId);
|
||||
await f.call({ operation: "finish", result }, finishId);
|
||||
const events = [];
|
||||
for await (const event of f.session.events()) {
|
||||
expect(validatePrpEvent(event), JSON.stringify(event)).toMatchObject({ ok: true });
|
||||
events.push(event);
|
||||
}
|
||||
expect(events.filter(e => e.eventType === "turn.started")).toHaveLength(1);
|
||||
expect(events.filter(e => e.eventType === "run.result.proposed")).toHaveLength(1);
|
||||
expect(await f.session.result()).toMatchObject({ result, terminal: { runTerminalState: "succeeded" } });
|
||||
expect(await f.session.usage?.()).toBeNull();
|
||||
await f.session.close({ reason: "finished" });
|
||||
});
|
||||
|
||||
it("deduplicates concurrent writes and rejects changed retries", async () => {
|
||||
const f = await fixture(); await f.call({ operation: "accept" });
|
||||
const id = randomUUID();
|
||||
const command = { operation: "tool", name: "write_document", arguments: { body: "One report" } } as const;
|
||||
const replies = await Promise.all([f.call(command, id), f.call(command, id)]);
|
||||
expect(replies).toEqual([{ saved: true }, { saved: true }]);
|
||||
expect(f.executeTool).toHaveBeenCalledTimes(1);
|
||||
await expect(f.call({ ...command, arguments: { body: "Changed" } }, id)).rejects.toThrow("different arguments");
|
||||
f.driver.revoke();
|
||||
});
|
||||
|
||||
it("does not redispatch a tool with an unknown outcome", async () => {
|
||||
const executeTool = vi.fn(async () => { throw new Error("committed but connection lost"); });
|
||||
const f = await fixture({ executeTool }); await f.call({ operation: "accept" });
|
||||
const id = randomUUID(); const command = { operation: "tool", name: "write_document", arguments: {} } as const;
|
||||
expect(await f.call(command, id)).toMatchObject({ outcome: "unknown" });
|
||||
expect(await f.call(command, id)).toMatchObject({ outcome: "unknown" });
|
||||
expect(executeTool).toHaveBeenCalledTimes(1);
|
||||
f.driver.revoke();
|
||||
});
|
||||
|
||||
it("enforces company, grant, turn, tool, expiry and live admission authority", async () => {
|
||||
let now = Date.now(); const f = await fixture({ now: () => now, expiresAt: now + 1000 });
|
||||
await expect(f.driver.inbox({ ...f.principal, companyId: randomUUID() })).rejects.toThrow("not bound");
|
||||
await expect(f.driver.inbox({ ...f.principal, grantId: randomUUID() })).rejects.toThrow("not bound");
|
||||
await expect(f.driver.command(f.principal, { operation: "accept", requestId: randomUUID(), turnId: randomUUID() })).rejects.toThrow("Stale");
|
||||
await f.call({ operation: "accept" });
|
||||
await expect(f.call({ operation: "tool", name: "arbitrary_admin", arguments: {} })).rejects.toThrow("not projected");
|
||||
f.assertAuthority.mockRejectedValueOnce(new Error("Agent paused"));
|
||||
await expect(f.call({ operation: "read" })).rejects.toThrow("Agent paused");
|
||||
now += 1001;
|
||||
await expect(f.call({ operation: "finish", result })).rejects.toThrow("expired");
|
||||
expect(f.executeTool).not.toHaveBeenCalled(); f.driver.revoke();
|
||||
});
|
||||
|
||||
it("revokes callbacks immediately and does not claim a provider stop or recovery", async () => {
|
||||
const f = await fixture(); await f.call({ operation: "accept" });
|
||||
f.driver.revoke();
|
||||
await expect(f.call({ operation: "progress", text: "late" })).rejects.toThrow("revoked");
|
||||
await expect(f.session.close({ reason: "cancel" })).rejects.toThrow("stop is unconfirmed");
|
||||
expect(await f.backend.descriptor()).toMatchObject({ capabilities: { resume: false, interruption: false, steering: false } });
|
||||
expect(await f.backend.recoverSession(await f.session.snapshot(), { signal: new AbortController().signal })).toMatchObject({ recovered: false });
|
||||
});
|
||||
|
||||
it("rejects a malformed result and cannot execute after completion", async () => {
|
||||
const f = await fixture(); await f.call({ operation: "accept" });
|
||||
await expect(f.call({ operation: "finish", result: { summary: "done" } })).rejects.toThrow("Invalid Paperclip");
|
||||
await f.call({ operation: "finish", result });
|
||||
await expect(f.call({ operation: "tool", name: "write_document", arguments: {} })).rejects.toThrow("already completed");
|
||||
expect(f.executeTool).not.toHaveBeenCalled(); f.driver.revoke();
|
||||
});
|
||||
|
||||
it("settles event waiting when authority expires", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const f = await fixture({ expiresAt: Date.now() + 1000 });
|
||||
const stream = f.session.events()[Symbol.asyncIterator]();
|
||||
await stream.next();
|
||||
const pending = stream.next();
|
||||
await vi.advanceTimersByTimeAsync(1001);
|
||||
// The native backend may synthesize a terminal failure, but cannot hang.
|
||||
await expect(pending).resolves.toBeDefined();
|
||||
await expect(f.call({ operation: "accept" })).rejects.toThrow("revoked");
|
||||
await stream.return?.(); f.driver.revoke();
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
it("reserves admission before awaiting authority and fences concurrent revocation", async () => {
|
||||
let release!: () => void;
|
||||
const identity = { companyId: randomUUID(), agentId: randomUUID(), issueId: randomUUID(), runId: randomUUID(), sessionId: randomUUID() };
|
||||
const driver = new DotHarnessDriver({ identity, principal: { companyId: identity.companyId, grantId: randomUUID() },
|
||||
expiresAt: Date.now() + 10_000, tools: [], publish: async () => {}, executeTool: async () => {},
|
||||
assertAuthority: () => new Promise<void>(resolve => { release = resolve; }) });
|
||||
const input = { runId: identity.runId, normalizedSessionId: identity.sessionId, workingDirectory: "/unused" };
|
||||
const first = driver.openSession(input);
|
||||
await expect(driver.openSession(input)).rejects.toThrow("already opened");
|
||||
driver.revoke(); release();
|
||||
await expect(first).rejects.toThrow("revoked during admission");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,240 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import type { HarnessDriver, HarnessSession, OpenHarnessSessionInput, PersistedHarnessSession } from "../../contracts/harness-driver.js";
|
||||
import type { NativeRunIdentity, NativeUserMessage } from "../../contracts/types.js";
|
||||
import { validatePrpStructuredRunResult, type PrpEvent, type PrpStructuredRunResult } from "../../protocol/replay-contract.js";
|
||||
|
||||
export interface DotPrincipal { companyId: string; grantId: string }
|
||||
export interface DotTool { name: string; description: string; inputSchema: Record<string, unknown> }
|
||||
export interface DotAssignment extends NativeRunIdentity { turnId: string; messageId: string }
|
||||
|
||||
/** All authority comes from the host after normal run admission. Never accept
|
||||
* these bindings or callbacks from an MCP request or an agent configuration. */
|
||||
export interface DotDriverOptions {
|
||||
identity: NativeRunIdentity;
|
||||
principal: DotPrincipal;
|
||||
expiresAt: number;
|
||||
tools: readonly DotTool[];
|
||||
assertAuthority: () => Promise<void>;
|
||||
executeTool: (input: { name: string; arguments: Record<string, unknown>; requestId: string; turnId: string }) => Promise<unknown>;
|
||||
publish: (assignment: DotAssignment) => Promise<void>;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export class DotBoundaryError extends Error {}
|
||||
const canonical = (value: unknown): string => JSON.stringify(value, (_key, v) => v && typeof v === "object" && !Array.isArray(v)
|
||||
? Object.fromEntries(Object.keys(v).sort().map(k => [k, v[k]])) : v);
|
||||
|
||||
/** Experimental, one-run provider. No model API or CLI impersonation: an
|
||||
* authenticated Dot pulls work after an MCP Event and calls back through MCP.
|
||||
* Memory-only: restart loses the session and fails closed; resume is false. */
|
||||
export class DotHarnessDriver implements HarnessDriver {
|
||||
readonly identity: NativeRunIdentity;
|
||||
#options: DotDriverOptions;
|
||||
#session: DotSession | null = null;
|
||||
#opened = false;
|
||||
#revoked = false;
|
||||
|
||||
constructor(options: DotDriverOptions) {
|
||||
if (options.identity.companyId !== options.principal.companyId) throw new DotBoundaryError("Company binding mismatch.");
|
||||
const remaining = options.expiresAt - (options.now ?? Date.now)();
|
||||
if (!Number.isFinite(remaining) || remaining <= 0 || remaining > 24 * 3600_000) throw new DotBoundaryError("Dot authority must expire within 24 hours.");
|
||||
this.identity = structuredClone(options.identity);
|
||||
this.#options = { ...options, identity: this.identity, principal: structuredClone(options.principal), tools: structuredClone(options.tools) };
|
||||
}
|
||||
|
||||
async descriptor() {
|
||||
return {
|
||||
kind: "openai-dot-prototype", displayName: "OpenAI Dot (prototype)", version: "0.1.0", protocolVersion: "prp.v1",
|
||||
capabilities: {
|
||||
resume: false, typedEvents: true, steering: false, interruption: false, structuredResult: true,
|
||||
read: true, reconciliation: true, usage: false, dynamicTools: true,
|
||||
unsupported: ["resume", "steering", "interruption", "usage", "goals", "runtimeRequestResolution"],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async openSession(input: OpenHarnessSessionInput): Promise<HarnessSession> {
|
||||
if (input.runId !== this.identity.runId || input.normalizedSessionId !== this.identity.sessionId || this.#opened || this.#revoked) {
|
||||
throw new DotBoundaryError("Dot session binding mismatch or already opened.");
|
||||
}
|
||||
input.signal?.throwIfAborted();
|
||||
this.#opened = true;
|
||||
await this.#options.assertAuthority();
|
||||
input.signal?.throwIfAborted();
|
||||
if (this.#revoked) throw new DotBoundaryError("Dot driver was revoked during admission.");
|
||||
return this.#session = new DotSession(this.#options);
|
||||
}
|
||||
|
||||
async inbox(principal: DotPrincipal) {
|
||||
return this.#session ? this.#session.inbox(principal) : null;
|
||||
}
|
||||
|
||||
async command(principal: DotPrincipal, input: DotCommand): Promise<unknown> {
|
||||
if (!this.#session) throw new DotBoundaryError("Dot run is unavailable.");
|
||||
return this.#session.command(principal, input);
|
||||
}
|
||||
|
||||
/** Synchronous revocation: future callbacks lose authority immediately.
|
||||
* This does NOT prove that OpenAI stopped the Dot or any child tasks. */
|
||||
revoke() { this.#revoked = true; this.#session?.revoke(); }
|
||||
}
|
||||
|
||||
export type DotCommand = { turnId: string; requestId: string } & (
|
||||
| { operation: "accept" }
|
||||
| { operation: "read" }
|
||||
| { operation: "tool"; name: string; arguments: Record<string, unknown> }
|
||||
| { operation: "progress"; text: string }
|
||||
| { operation: "finish"; result: unknown }
|
||||
);
|
||||
|
||||
class DotSession implements HarnessSession {
|
||||
#turnId: string | null = null;
|
||||
#message: NativeUserMessage | null = null;
|
||||
#messageId = randomUUID();
|
||||
#events: PrpEvent[] = [];
|
||||
#waiters = new Set<() => void>();
|
||||
#revoked = false;
|
||||
#accepted = false;
|
||||
#result: PrpStructuredRunResult | null = null;
|
||||
#tail: Promise<unknown> = Promise.resolve();
|
||||
#receipts = new Map<string, { digest: string; promise: Promise<unknown> }>();
|
||||
#expiry: NodeJS.Timeout;
|
||||
constructor(readonly options: DotDriverOptions) {
|
||||
this.#expiry = setTimeout(() => this.revoke(), Math.max(0, options.expiresAt - this.#now()));
|
||||
this.#expiry.unref();
|
||||
}
|
||||
#now() { return (this.options.now ?? Date.now)(); }
|
||||
ids() { return { driverSessionId: this.options.identity.sessionId, providerSessionId: `dot-bridge:${this.options.identity.sessionId}`, displayId: "OpenAI Dot" }; }
|
||||
|
||||
async #authorize(principal?: DotPrincipal) {
|
||||
if (principal && (principal.companyId !== this.options.principal.companyId || principal.grantId !== this.options.principal.grantId)) {
|
||||
throw new DotBoundaryError("This connection is not bound to this Dot run.");
|
||||
}
|
||||
if (this.#revoked || this.options.expiresAt <= this.#now()) throw new DotBoundaryError("Dot run authority expired or was revoked.");
|
||||
await this.options.assertAuthority();
|
||||
if (this.#revoked || this.options.expiresAt <= this.#now()) throw new DotBoundaryError("Dot run authority expired or was revoked.");
|
||||
}
|
||||
|
||||
async startTurn(input: { message: NativeUserMessage }) {
|
||||
await this.#authorize();
|
||||
if (this.#turnId) throw new DotBoundaryError("This prototype accepts one turn per admitted run.");
|
||||
this.#turnId = randomUUID();
|
||||
this.#message = structuredClone(input.message);
|
||||
this.#emit("session.started", {});
|
||||
// A webhook receipt is not evidence that Dot accepted or started the turn.
|
||||
try { await this.options.publish(this.#assignment()); }
|
||||
catch { this.revoke(); throw new DotBoundaryError("Dot wakeup could not be confirmed. Inspect the assignment before retrying."); }
|
||||
return { turnId: this.#turnId };
|
||||
}
|
||||
|
||||
#assignment(): DotAssignment {
|
||||
return { ...this.options.identity, turnId: this.#turnId!, messageId: this.#messageId };
|
||||
}
|
||||
async inbox(principal: DotPrincipal) {
|
||||
await this.#authorize(principal);
|
||||
return this.#turnId && !this.#result ? { ...this.#assignment(), accepted: this.#accepted, expiresAt: this.options.expiresAt } : null;
|
||||
}
|
||||
|
||||
async command(principal: DotPrincipal, input: DotCommand): Promise<unknown> {
|
||||
await this.#authorize(principal);
|
||||
if (!this.#turnId || input.turnId !== this.#turnId) throw new DotBoundaryError("Stale or unknown Dot turn.");
|
||||
if (!input.requestId || input.requestId.length > 100) throw new DotBoundaryError("A bounded request ID is required.");
|
||||
const encoded = canonical(input);
|
||||
if (Buffer.byteLength(encoded) > 256 * 1024) throw new DotBoundaryError("Dot command exceeds 256 KiB.");
|
||||
const digest = createHash("sha256").update(encoded).digest("hex");
|
||||
const old = this.#receipts.get(input.requestId);
|
||||
if (old) {
|
||||
if (old.digest !== digest) throw new DotBoundaryError("Request ID was reused with different arguments.");
|
||||
return structuredClone(await old.promise);
|
||||
}
|
||||
if (this.#receipts.size >= 1000) throw new DotBoundaryError("Dot run command limit reached.");
|
||||
// Serialize command acceptance with completion. Reserve the promise BEFORE
|
||||
// dispatch so concurrent retries can never execute a tool twice.
|
||||
const promise = this.#tail.then(async () => {
|
||||
await this.#authorize(principal);
|
||||
if (this.#result) throw new DotBoundaryError("Dot turn already completed.");
|
||||
if (input.operation === "accept") {
|
||||
if (!this.#accepted) { this.#accepted = true; this.#emit("turn.started", {}); }
|
||||
return { accepted: true };
|
||||
}
|
||||
if (input.operation === "read") return {
|
||||
assignment: this.#assignment(), message: this.#message, tools: this.options.tools,
|
||||
accounting: { usage: null, cost: null },
|
||||
};
|
||||
if (!this.#accepted) throw new DotBoundaryError("Accept the Dot assignment before writing or finishing.");
|
||||
if (input.operation === "tool") {
|
||||
if (!this.options.tools.some(t => t.name === input.name)) throw new DotBoundaryError("Tool is not projected to this run.");
|
||||
let result: unknown;
|
||||
try {
|
||||
result = await this.options.executeTool({ name: input.name, arguments: input.arguments, requestId: input.requestId, turnId: input.turnId });
|
||||
} catch {
|
||||
// Never replay a possibly committed write after a transport failure.
|
||||
return { outcome: "unknown", message: "Inspect current task state; retry only with the same requestId." };
|
||||
}
|
||||
await this.#authorize(principal);
|
||||
return result;
|
||||
}
|
||||
if (input.operation === "progress") {
|
||||
if (!input.text.trim() || input.text.length > 16_000) throw new DotBoundaryError("Progress must contain 1–16000 characters.");
|
||||
this.#emit("item.started", { kind: "assistant_message" }, input.requestId);
|
||||
this.#emit("item.delta", { text: input.text }, input.requestId);
|
||||
this.#emit("item.completed", { kind: "assistant_message", text: input.text }, input.requestId);
|
||||
return { accepted: true };
|
||||
}
|
||||
const parsed = validatePrpStructuredRunResult(input.result);
|
||||
if (!parsed.ok) throw new DotBoundaryError("Invalid Paperclip structured run result.");
|
||||
this.#result = parsed.result;
|
||||
clearTimeout(this.#expiry);
|
||||
this.#emit("run.result.proposed", this.#result);
|
||||
this.#emit("turn.completed", {});
|
||||
this.#emit("run.terminal", {
|
||||
schema: "paperclip.prp.terminal.v1", turnTerminalState: "completed", runTerminalState: "succeeded",
|
||||
reportedWorkDisposition: this.#result.reportedWorkDisposition,
|
||||
});
|
||||
return { accepted: true, disposition: this.#result.reportedWorkDisposition };
|
||||
});
|
||||
this.#receipts.set(input.requestId, { digest, promise });
|
||||
this.#tail = promise.catch(() => {});
|
||||
return structuredClone(await promise);
|
||||
}
|
||||
|
||||
#emit(eventType: PrpEvent["eventType"], payload: Record<string, unknown>, itemId?: string) {
|
||||
const sequence = this.#events.length + 1;
|
||||
this.#events.push({
|
||||
schema: "paperclip.prp.event.v1", sourceEventId: `${this.options.identity.runId}:${sequence}`,
|
||||
sourceSeq: sequence, sourceInstanceId: `dot:${this.options.identity.sessionId}`, sourceKind: "runner",
|
||||
runId: this.options.identity.runId, normalizedSessionId: this.options.identity.sessionId,
|
||||
...(this.#turnId ? { turnId: this.#turnId } : {}), ...(itemId ? { itemId } : {}),
|
||||
eventType, schemaVersion: 1, priority: eventType.startsWith("run.") ? 0 : 1,
|
||||
emittedAt: new Date(this.#now()).toISOString(), payload: structuredClone(payload),
|
||||
});
|
||||
this.#notify();
|
||||
}
|
||||
#notify() { for (const wake of this.#waiters) wake(); this.#waiters.clear(); }
|
||||
async *events(): AsyncIterable<PrpEvent> {
|
||||
let index = 0;
|
||||
while (true) {
|
||||
while (index < this.#events.length) {
|
||||
const event = this.#events[index++]!;
|
||||
yield structuredClone(event);
|
||||
if (event.eventType === "run.terminal") return;
|
||||
}
|
||||
if (this.#revoked) return;
|
||||
await new Promise<void>(resolve => this.#waiters.add(resolve));
|
||||
}
|
||||
}
|
||||
async read() { return { accepted: this.#accepted, completed: !!this.#result, revoked: this.#revoked }; }
|
||||
async reconcile() { return { ...await this.read(), providerStopConfirmed: false, usage: null, cost: null }; }
|
||||
async usage() { return null; }
|
||||
async snapshot(): Promise<PersistedHarnessSession> {
|
||||
return { driverKind: "openai-dot-prototype", driverSessionId: this.ids().driverSessionId, providerSessionId: this.ids().providerSessionId,
|
||||
runId: this.options.identity.runId, normalizedSessionId: this.options.identity.sessionId,
|
||||
activeTurnId: this.#result || this.#revoked ? null : this.#turnId, lastSourceSequence: this.#events.length,
|
||||
semanticResult: this.#result ? { result: this.#result, turnId: this.#turnId!, fingerprint: canonical(this.#result) } : null };
|
||||
}
|
||||
revoke() { this.#revoked = true; clearTimeout(this.#expiry); this.#notify(); }
|
||||
async close() {
|
||||
this.revoke();
|
||||
if (this.#accepted && !this.#result) throw new DotBoundaryError("Dot authority revoked; provider stop is unconfirmed.");
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ export * from "./contracts/question-set.js";
|
||||
export * from "./contracts/runtime-context.js";
|
||||
export * from "./contracts/types.js";
|
||||
export * from "./backends/harness-driver-backend.js";
|
||||
export * from "./drivers/dot/dot-harness-driver.js";
|
||||
export { createOpenCodeNativeSessionBackend } from "./backends/opencode-native-backend.js";
|
||||
export {
|
||||
createNativeSessionBackend,
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/** Synthetic local lab, not production admission or a real OpenAI Dot.
|
||||
* Uses real OAuth, MCP HTTP, database-backed events, HMAC verification and the
|
||||
* native runner backend. Never reads a user's existing Paperclip database. */
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
||||
import { once } from "node:events";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import express from "express";
|
||||
import { activityLog, authUsers, companies, companyMemberships, createDb, issues, startEmbeddedPostgresTestDatabase } from "@paperclipai/db";
|
||||
import { DotHarnessDriver } from "../../packages/paperclip-runner/src/drivers/dot/dot-harness-driver.js";
|
||||
import { HarnessDriverBackend } from "../../packages/paperclip-runner/src/backends/harness-driver-backend.js";
|
||||
import { publicMcpIngressRoutes } from "../src/routes/public-mcp.js";
|
||||
import { createPublicMcpOAuth } from "../src/services/public-mcp/oauth.js";
|
||||
import { createPublicMcpEvents } from "../src/services/public-mcp/events.js";
|
||||
import { createPublicMcpExecutor, McpApiError, type ApiDispatch } from "../src/services/public-mcp/capabilities.js";
|
||||
import { createDotRunnerMcpBridge } from "../src/services/public-mcp/dot-runner.js";
|
||||
import { instanceSettingsService } from "../src/services/instance-settings.js";
|
||||
|
||||
async function listen(server: Server) {
|
||||
server.listen(0, "127.0.0.1"); await once(server, "listening");
|
||||
const address = server.address(); assert(address && typeof address !== "string");
|
||||
return `http://127.0.0.1:${address.port}`;
|
||||
}
|
||||
async function close(server: Server) {
|
||||
server.closeAllConnections(); if (server.listening) await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
}
|
||||
|
||||
const scratch = await mkdtemp(join(tmpdir(), "paperclip-dot-demo-"));
|
||||
// This process has its own ephemeral encryption key, never the instance key.
|
||||
process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = join(scratch, "master.key");
|
||||
delete process.env.PAPERCLIP_SECRETS_MASTER_KEY;
|
||||
delete process.env.PAPERCLIP_CLOUD_API_ORIGIN;
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
||||
const app = express(); app.use(express.json({ limit: "256kb" }));
|
||||
const http = createServer(app);
|
||||
const receiver = express(); receiver.use(express.raw({ type: "application/json", limit: "256kb" }));
|
||||
const callback = createServer(receiver);
|
||||
const secret = randomBytes(32);
|
||||
const webhookSecret = "whsec_" + secret.toString("base64");
|
||||
const receivedIds = new Set<string>();
|
||||
let service: ReturnType<typeof createPublicMcpEvents> | undefined;
|
||||
let unregister: (() => void) | undefined;
|
||||
let active = true;
|
||||
try {
|
||||
database = await startEmbeddedPostgresTestDatabase("paperclip-dot-demo-");
|
||||
const db = createDb(database.connectionString);
|
||||
const origin = await listen(http);
|
||||
const callbackOrigin = await listen(callback);
|
||||
const oauth = createPublicMcpOAuth(db, { origin, resource: origin + "/mcp/paperclip" });
|
||||
await instanceSettingsService(db).updateExperimental({ enablePublicMcp: true });
|
||||
const userId = randomUUID();
|
||||
await db.insert(authUsers).values({ id: userId, name: "Dot lab operator", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
|
||||
const [company] = await db.insert(companies).values({ name: "Dot prototype lab", issuePrefix: "DOT" }).returning();
|
||||
assert(company);
|
||||
await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: userId, membershipRole: "owner", status: "active" });
|
||||
const [task] = await db.insert(issues).values({ companyId: company.id, title: "Dot runner lab inbox", status: "todo" }).returning();
|
||||
assert(task);
|
||||
const actor = { type: "board" as const, source: "session" as const, userId };
|
||||
const client = await oauth.register({ client_name: "Synthetic Dot test peer", redirect_uris: [origin + "/callback"] });
|
||||
const verifier = randomBytes(32).toString("base64url");
|
||||
const authorization = await oauth.authorize({ client_id: client.client_id, redirect_uri: origin + "/callback", resource: oauth.config.resource,
|
||||
scope: "paperclip:read paperclip:write", response_type: "code", code_challenge_method: "S256", code_challenge: createHash("sha256").update(verifier).digest("base64url") });
|
||||
const consent = await oauth.consent(authorization.split("/").at(-1)!, actor, { decision: "approve", companyId: company.id, allowWrites: true });
|
||||
const tokens = await oauth.token({ grant_type: "authorization_code", client_id: client.client_id, redirect_uri: origin + "/callback",
|
||||
resource: oauth.config.resource, code: new URL(consent.redirectUrl).searchParams.get("code"), code_verifier: verifier });
|
||||
const principal = await oauth.authenticate(tokens.access_token);
|
||||
const api: ApiDispatch = async (p, method, path) => {
|
||||
if (p.grant.companyId !== company.id || method !== "GET" || path !== `/issues/${task.id}`) throw new McpApiError(403);
|
||||
return task;
|
||||
};
|
||||
const bridge = createDotRunnerMcpBridge();
|
||||
service = createPublicMcpEvents(db, oauth, api, { enableDotPrototype: true,
|
||||
// Only the lab receiver bypasses HTTPS/DNS. Production uses eventFetch's
|
||||
// public-address pinning. No CLI option can expand this exact destination.
|
||||
fetch: async (url, init) => {
|
||||
assert.equal(url, "https://dot-demo.invalid/events");
|
||||
return fetch(callbackOrigin + "/events", init);
|
||||
},
|
||||
});
|
||||
app.use(publicMcpIngressRoutes(oauth, createPublicMcpExecutor(db, oauth, api), service, bridge));
|
||||
const rpc = async (method: string, params: Record<string, unknown> = {}) => {
|
||||
const response = await fetch(origin + "/mcp/paperclip", { method: "POST", signal: AbortSignal.timeout(10_000),
|
||||
headers: { Authorization: `Bearer ${tokens.access_token}`, "Content-Type": "application/json", "MCP-Protocol-Version": "2026-07-28", "Mcp-Method": method, "Mcp-Name": String(params.name ?? "") },
|
||||
body: JSON.stringify({ jsonrpc: "2.0", id: randomUUID(), method, params: { ...params, _meta: {
|
||||
"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {},
|
||||
} } }),
|
||||
});
|
||||
const body = await response.json() as { result?: any; error?: unknown };
|
||||
assert(response.ok && !body.error && !body.result?.isError, "MCP operation failed");
|
||||
return body.result;
|
||||
};
|
||||
const tool = async (name: string, args: Record<string, unknown>) => (await rpc("tools/call", { name, arguments: args })).structuredContent;
|
||||
const identity = { companyId: company.id, agentId: randomUUID(), issueId: task.id, runId: randomUUID(), sessionId: randomUUID() };
|
||||
const documents: string[] = [];
|
||||
const driver = new DotHarnessDriver({ identity, principal: { companyId: company.id, grantId: principal.grant.id }, expiresAt: Date.now() + 60_000,
|
||||
assertAuthority: async () => { assert(active, "Lab run has been revoked"); await oauth.authorizeGrant(principal.grant.id); },
|
||||
tools: [{ name: "save_report", description: "Save the synthetic lab report", inputSchema: { type: "object", properties: { body: { type: "string" } }, required: ["body"], additionalProperties: false } }],
|
||||
executeTool: async ({ name, arguments: args }) => { assert.equal(name, "save_report"); assert.equal(typeof args.body, "string"); documents.push(args.body as string); return { saved: true }; },
|
||||
publish: async assignment => {
|
||||
await db.insert(activityLog).values({ companyId: company.id, actorType: "agent", actorId: identity.agentId,
|
||||
action: "dot.work_available", entityType: "issue", entityId: task.id, details: { ...assignment } });
|
||||
},
|
||||
});
|
||||
unregister = bridge.register(driver, principal.grant.id);
|
||||
const native = await new HarnessDriverBackend(driver).openSession({ identity });
|
||||
let resolveWork!: () => void; let rejectWork!: (error: unknown) => void;
|
||||
const completed = new Promise<void>((resolve, reject) => { resolveWork = resolve; rejectWork = reject; });
|
||||
// Avoid an unhandled rejection if a callback fails before the main await.
|
||||
void completed.catch(() => {});
|
||||
const peer = async () => {
|
||||
const { assignments } = await tool("paperclip_dot_inbox", { companyId: company.id });
|
||||
assert.equal(assignments.length, 1);
|
||||
const base = { companyId: company.id, runId: assignments[0].runId, turnId: assignments[0].turnId };
|
||||
const call = (name: string, args = {}, requestId = randomUUID()) => tool(name, { ...base, requestId, ...args });
|
||||
const context = await call("paperclip_dot_read"); assert.match(context.result.message.text, /competitor/);
|
||||
await call("paperclip_dot_accept");
|
||||
const writeId = randomUUID();
|
||||
await Promise.all([0, 1].map(() => call("paperclip_dot_tool", { name: "save_report", arguments: { body: "Synthetic competitor report" } }, writeId)));
|
||||
await call("paperclip_dot_progress", { text: "The lab report is saved." });
|
||||
await call("paperclip_dot_finish", { result: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", summary: "Lab report saved.",
|
||||
completionClaim: { contractRevision: "dot-lab-v1", objectiveSatisfied: true, criteria: [], remainingWork: [] }, evidence: [], verification: [], attentionRequests: [], artifacts: [] } });
|
||||
resolveWork();
|
||||
};
|
||||
receiver.post("/events", (req, res) => {
|
||||
const id = String(req.headers["webhook-id"]);
|
||||
const timestamp = String(req.headers["webhook-timestamp"]);
|
||||
const expected = "v1," + createHmac("sha256", secret).update(`${id}.${timestamp}.${req.body.toString("utf8")}`).digest("base64");
|
||||
const actual = Buffer.from(String(req.headers["webhook-signature"]));
|
||||
if (actual.length !== expected.length || !timingSafeEqual(actual, Buffer.from(expected)) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) { res.sendStatus(401); return; }
|
||||
const body = JSON.parse(req.body.toString("utf8"));
|
||||
if (body.type === "verification") { res.json({ challenge: body.challenge }); return; }
|
||||
res.sendStatus(204);
|
||||
if (receivedIds.has(id)) return;
|
||||
receivedIds.add(id);
|
||||
assert.equal(body.name, "paperclip.dot.work_available");
|
||||
assert(!JSON.stringify(body).includes("competitor"));
|
||||
void peer().catch(rejectWork);
|
||||
});
|
||||
const subscription = { name: "paperclip.dot.work_available", arguments: { companyId: company.id, taskId: task.id },
|
||||
delivery: { mode: "webhook", url: "https://dot-demo.invalid/events", secret: webhookSecret } };
|
||||
await rpc("events/subscribe", subscription);
|
||||
console.log("✓ Real OAuth connection and signed webhook verification");
|
||||
await native.startTurn({ message: { role: "user", text: "Write a synthetic competitor report." } });
|
||||
await service.tick();
|
||||
await Promise.race([completed, new Promise<never>((_, reject) => { const timer = setTimeout(() => reject(new Error("Dot test peer timed out")), 15_000); timer.unref(); completed.finally(() => clearTimeout(timer)).catch(() => {}); })]);
|
||||
const transcript = [];
|
||||
for await (const event of native.events()) transcript.push(event);
|
||||
assert.equal((await native.result())?.result.reportedWorkDisposition, "done");
|
||||
assert.equal(documents.length, 1); assert.equal(receivedIds.size, 1);
|
||||
assert.equal(await native.usage?.(), null);
|
||||
console.log("✓ MCP Event → Dot test peer → native runner acceptance, tool write, progress, structured completion");
|
||||
console.log("✓ Concurrent duplicate write produced one report; usage remains unknown");
|
||||
assert.equal((await tool("paperclip_connection", {})).companyId, company.id);
|
||||
console.log("✓ Personal Paperclip tools remain available when no agent assignment is active");
|
||||
await rpc("events/unsubscribe", { ...subscription, delivery: { mode: "webhook", url: subscription.delivery.url } });
|
||||
await oauth.revokeConnection(principal.grant.id, userId);
|
||||
await assert.rejects(() => rpc("tools/list"));
|
||||
await native.close({ reason: "demo finished" });
|
||||
console.log(`✓ Revoked credentials rejected; ${transcript.length} runner events recorded`);
|
||||
console.log("PASS — synthetic local protocol proof. No real Dot was contacted; production agent admission is not enabled.");
|
||||
} finally {
|
||||
active = false; unregister?.(); await service?.stop();
|
||||
await close(http); await close(callback); await database?.cleanup(); await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
@@ -22,6 +22,9 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro
|
||||
|
||||
import { createPublicMcpEvents, publicMcpEventDefinitions } from "../services/public-mcp/events.js";
|
||||
import { eventFetch, signingKey, type EventFetch } from "../services/public-mcp/event-webhooks.js";
|
||||
import { createDotRunnerMcpBridge } from "../services/public-mcp/dot-runner.js";
|
||||
import { DotHarnessDriver } from "../../../packages/paperclip-runner/src/drivers/dot/dot-harness-driver.js";
|
||||
import { HarnessDriverBackend } from "../../../packages/paperclip-runner/src/backends/harness-driver-backend.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const config = { origin: "https://paperclip.example", resource: "https://paperclip.example/mcp/paperclip" };
|
||||
@@ -358,8 +361,8 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
|
||||
}
|
||||
await expect(oauth.authorize(input)).resolves.toContain("/mcp-connect/");
|
||||
});
|
||||
async function eventFixture(cloudOrigin?: string) {
|
||||
const f = await fixture("member", false);
|
||||
async function eventFixture(cloudOrigin?: string, write = false) {
|
||||
const f = await fixture("member", write);
|
||||
const principal = await oauth.authenticate(f.tokens.access_token);
|
||||
const [task] = await db.insert(issues).values({ companyId: f.company.id, title: "Event fixture", status: "todo" }).returning();
|
||||
let clock = Date.now();
|
||||
@@ -399,6 +402,73 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
|
||||
advance(ms: number) { clock += ms; }, setStatus(value: number) { status = value; }, denyCloud() { cloudAllowed = false; }, duringVerification(fn: () => Promise<void>) { duringVerification = fn; }, badChallenge() { goodChallenge = false; }, now: () => clock };
|
||||
}
|
||||
|
||||
it("Dot prototype: OAuth → signed wakeup → native runner tools → result, with revocation", async () => {
|
||||
const f = await eventFixture(undefined, true);
|
||||
const events = createPublicMcpEvents(db, oauth, f.dispatch, { ...f.options, enableDotPrototype: true });
|
||||
const extension = createDotRunnerMcpBridge();
|
||||
const identity = { companyId: f.company.id, agentId: randomUUID(), issueId: f.task.id, runId: randomUUID(), sessionId: randomUUID() };
|
||||
const documents: string[] = [];
|
||||
const driver = new DotHarnessDriver({
|
||||
identity, principal: { companyId: f.company.id, grantId: f.principal.grant.id }, expiresAt: f.now() + 60_000, now: f.now,
|
||||
assertAuthority: async () => { await oauth.authorizeGrant(f.principal.grant.id); },
|
||||
tools: [{ name: "write_document", description: "Save a report on this assignment", inputSchema: { type: "object", properties: { body: { type: "string" } }, required: ["body"], additionalProperties: false } }],
|
||||
executeTool: async ({ name, arguments: args }) => {
|
||||
if (args.uncertain) throw new Error("Projected tool response was lost");
|
||||
expect(name).toBe("write_document"); documents.push(String(args.body)); return { saved: true };
|
||||
},
|
||||
publish: async assignment => { await f.activity("dot.work_available", { ...assignment, privateText: "MUST NOT LEAVE IN EVENT" }); },
|
||||
});
|
||||
const unregister = extension.register(driver, f.principal.grant.id);
|
||||
const backend = new HarnessDriverBackend(driver);
|
||||
const session = await backend.openSession({ identity });
|
||||
const app = express(); app.use(express.json());
|
||||
app.use(publicMcpIngressRoutes(oauth, createPublicMcpExecutor(db, oauth, f.dispatch), events, extension));
|
||||
const meta = { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {} };
|
||||
const rpc = (method: string, params: Record<string, unknown> = {}, token = f.tokens.access_token) => request(app).post("/mcp/paperclip")
|
||||
.set("Authorization", `Bearer ${token}`).set("MCP-Protocol-Version", "2026-07-28").set("Mcp-Method", method)
|
||||
.set("Mcp-Name", String(params.name ?? "")).send({ jsonrpc: "2.0", id: 1, method, params: { ...params, _meta: meta } });
|
||||
const tool = async (name: string, args: Record<string, unknown>) => (await rpc("tools/call", { name, arguments: args })).body.result;
|
||||
try {
|
||||
expect((await rpc("server/discover")).body.result.capabilities).toHaveProperty("events");
|
||||
expect((await rpc("events/list")).body.result.events.map((e: { name: string }) => e.name)).toContain("paperclip.dot.work_available");
|
||||
const subscription = { ...f.input, name: "paperclip.dot.work_available", arguments: { companyId: f.company.id, taskId: f.task.id } };
|
||||
expect((await rpc("events/subscribe", subscription)).body.result.id).toBeTruthy();
|
||||
const { turnId } = await session.startTurn({ message: { role: "user", text: "Save a competitor research report." } });
|
||||
await events.tick();
|
||||
const deliveries = f.received.filter(r => r.body.eventId);
|
||||
expect(deliveries).toHaveLength(1);
|
||||
expect(deliveries[0]!.body.data).toMatchObject({ runId: identity.runId, agentId: identity.agentId, turnId });
|
||||
expect(JSON.stringify(deliveries)).not.toContain("MUST NOT LEAVE");
|
||||
const base = { companyId: identity.companyId, runId: identity.runId, turnId };
|
||||
const call = (name: string, args = {}, requestId = randomUUID()) => tool(name, { ...base, requestId, ...args });
|
||||
expect((await tool("paperclip_dot_inbox", { companyId: identity.companyId })).structuredContent.assignments).toHaveLength(1);
|
||||
expect((await call("paperclip_dot_read")).structuredContent.result.message.text).toContain("competitor");
|
||||
expect((await call("paperclip_dot_accept")).isError).toBe(false);
|
||||
const writeId = randomUUID();
|
||||
for (let retry = 0; retry < 2; retry++) expect((await call("paperclip_dot_tool", { name: "write_document", arguments: { body: "Competitor report" } }, writeId)).isError).toBe(false);
|
||||
expect(documents).toEqual(["Competitor report"]);
|
||||
const unknown = await call("paperclip_dot_tool", { name: "write_document", arguments: { uncertain: true } });
|
||||
expect(unknown.isError).toBe(true);
|
||||
expect(unknown.structuredContent.outcome).toBe("unknown");
|
||||
expect((await call("paperclip_dot_progress", { text: "Saved the report." })).isError).toBe(false);
|
||||
const other = await fixture();
|
||||
expect((await rpc("tools/call", { name: "paperclip_dot_read", arguments: { ...base, requestId: randomUUID() } }, other.tokens.access_token)).body.result.isError).toBe(true);
|
||||
const result = { schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", summary: "Report saved.",
|
||||
completionClaim: { contractRevision: "dot-prototype-v1", objectiveSatisfied: true, criteria: [], remainingWork: [] },
|
||||
evidence: [], verification: [], attentionRequests: [], artifacts: [] };
|
||||
expect((await call("paperclip_dot_finish", { result })).isError).toBe(false);
|
||||
const transcript = [];
|
||||
for await (const event of session.events()) transcript.push(event);
|
||||
expect(transcript.filter(e => e.eventType === "run.result.proposed")).toHaveLength(1);
|
||||
expect(await session.result()).toMatchObject({ result });
|
||||
expect(await session.usage?.()).toBeNull();
|
||||
// The person's normal tools remain usable while Dot has no active assignment.
|
||||
expect((await tool("paperclip_connection", {})).structuredContent.companyId).toBe(identity.companyId);
|
||||
await oauth.revokeConnection(f.principal.grant.id, f.actor.userId!);
|
||||
expect((await rpc("tools/list")).status).toBe(401);
|
||||
} finally { unregister(); await session.close({ reason: "prototype finished" }).catch(() => {}); await events.stop(); }
|
||||
});
|
||||
|
||||
it("discovers MCP 2.0 events, validates metadata/headers, and preserves legacy tools", async () => {
|
||||
const f = await eventFixture();
|
||||
const app = express(); app.use(express.json());
|
||||
|
||||
@@ -3,8 +3,9 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { z } from "zod";
|
||||
import { publicMcpEventDefinitions, type PublicMcpEvents } from "../services/public-mcp/events.js";
|
||||
import { type PublicMcpEvents } from "../services/public-mcp/events.js";
|
||||
import { McpEventError } from "../services/public-mcp/event-webhooks.js";
|
||||
import type { PublicMcpToolExtension } from "../services/public-mcp/dot-runner.js";
|
||||
import { PUBLIC_MCP_PATH, PUBLIC_MCP_SCOPES, mcpConsentSchema } from "@paperclipai/shared";
|
||||
import { McpOAuthError, type PublicMcpOAuth } from "../services/public-mcp/oauth.js";
|
||||
import { McpApiError, McpCapabilityError, publicMcpCapabilities, type createPublicMcpExecutor } from "../services/public-mcp/capabilities.js";
|
||||
@@ -35,7 +36,7 @@ function authRateLimit(): RequestHandler {
|
||||
};
|
||||
}
|
||||
|
||||
export function publicMcpIngressRoutes(oauth: PublicMcpOAuth, execute: ReturnType<typeof createPublicMcpExecutor>, events?: PublicMcpEvents) {
|
||||
export function publicMcpIngressRoutes(oauth: PublicMcpOAuth, execute: ReturnType<typeof createPublicMcpExecutor>, events?: PublicMcpEvents, extension?: PublicMcpToolExtension) {
|
||||
const router = Router();
|
||||
const { origin, resource } = oauth.config;
|
||||
const prefix = origin + "/mcp/oauth";
|
||||
@@ -79,14 +80,17 @@ export function publicMcpIngressRoutes(oauth: PublicMcpOAuth, execute: ReturnTyp
|
||||
}
|
||||
if (req.method !== "POST") { res.setHeader("Allow", "POST"); res.status(405).end(); return; }
|
||||
const listTools = async () => ({
|
||||
tools: publicMcpCapabilities.map((c) => ({
|
||||
tools: [...publicMcpCapabilities.map((c) => ({
|
||||
name: c.name, description: c.description, inputSchema: z.toJSONSchema(c.schema) as { type: "object"; properties: Record<string, unknown> },
|
||||
annotations: { readOnlyHint: !c.write, destructiveHint: false, idempotentHint: true, openWorldHint: !!c.write },
|
||||
})),
|
||||
})), ...await extension?.listTools(principal!) ?? []],
|
||||
});
|
||||
const callTool = async (request: z.infer<typeof CallToolRequestSchema>) => {
|
||||
try {
|
||||
const result = await execute(token!, request.params.name, request.params.arguments ?? {});
|
||||
const extensionTools = await extension?.listTools(principal!) ?? [];
|
||||
const result = extensionTools.some(t => t.name === request.params.name)
|
||||
? await extension!.callTool(principal!, request.params.name, request.params.arguments ?? {})
|
||||
: await execute(token!, request.params.name, request.params.arguments ?? {});
|
||||
return { isError: result.outcome === "unknown" || result.outcome === "rejected", content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
|
||||
} catch (error) {
|
||||
const message = error instanceof z.ZodError ? "Invalid tool arguments."
|
||||
@@ -123,7 +127,7 @@ export function publicMcpIngressRoutes(oauth: PublicMcpOAuth, execute: ReturnTyp
|
||||
case "events/list":
|
||||
if (!events) { fail(-32601, "Events are unavailable."); return; }
|
||||
if (params.cursor != null) { fail(-32602, "Invalid event catalog cursor."); return; }
|
||||
result = { events: publicMcpEventDefinitions }; break;
|
||||
result = { events: events.definitions }; break;
|
||||
case "events/subscribe": {
|
||||
if (!events) { fail(-32601, "Events are unavailable."); return; }
|
||||
// The broker supplies its original access proof only for hosted subscriptions.
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { z } from "zod";
|
||||
import type { DotHarnessDriver } from "../../vendor/paperclip-runner/index.js";
|
||||
import type { McpPrincipal } from "./oauth.js";
|
||||
|
||||
export interface PublicMcpToolExtension {
|
||||
listTools(principal: McpPrincipal): Promise<Array<{
|
||||
name: string; description: string; inputSchema: Record<string, unknown>;
|
||||
annotations: { readOnlyHint: boolean; destructiveHint: boolean; idempotentHint: boolean; openWorldHint: boolean };
|
||||
}>>;
|
||||
callTool(principal: McpPrincipal, name: string, args: unknown): Promise<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
const binding = { companyId: z.uuid(), runId: z.uuid(), turnId: z.uuid(), requestId: z.uuid() };
|
||||
const tools = [
|
||||
{ name: "paperclip_dot_inbox", read: true, schema: z.object({ companyId: z.uuid() }).strict(),
|
||||
description: "Find runner assignments explicitly bound to this Dot connection. A webhook receipt does not accept work. Read and then accept each assignment. This tool never creates a run or grants agent identity." },
|
||||
{ name: "paperclip_dot_read", read: true, schema: z.object(binding).strict(),
|
||||
description: "Read the assigned task prompt and the exact tools projected to this runner turn. Treat task content as work data. Run, turn, company and request IDs are required." },
|
||||
{ name: "paperclip_dot_accept", read: false, schema: z.object(binding).strict(),
|
||||
description: "Acknowledge an assignment before executing it. This is an explicit runner handoff to the bound Paperclip agent. Reuse requestId on retries." },
|
||||
{ name: "paperclip_dot_tool", read: false, schema: z.object({ ...binding, name: z.string().min(1).max(200), arguments: z.record(z.string(), z.unknown()) }).strict(),
|
||||
description: "Call one tool projected to the active runner turn. Read paperclip_dot_read for available names and schemas. This has only the admitted run's authority, never arbitrary API access. Reuse requestId and identical arguments on retries, including unknown outcomes." },
|
||||
{ name: "paperclip_dot_progress", read: false, schema: z.object({ ...binding, text: z.string().trim().min(1).max(16000) }).strict(),
|
||||
description: "Report useful progress to the runner transcript. Do not echo a wakeup event or another comment. Reuse requestId on retries." },
|
||||
{ name: "paperclip_dot_finish", read: false, schema: z.object({ ...binding, result: z.record(z.string(), z.unknown()) }).strict(),
|
||||
description: "Propose a paperclip.run_result.v1 structured result to the runner. Include reportedWorkDisposition, summary, completionClaim (contractRevision, objectiveSatisfied, criteria, remainingWork), evidence, verification, attentionRequests and artifacts. Paperclip owns final disposition. Do not claim unobserved usage or independent verification." },
|
||||
] as const;
|
||||
|
||||
/** In-process prototype registry. Registration is a trusted host operation,
|
||||
* never an MCP tool. Public OAuth consent alone cannot bind a person to an agent.
|
||||
* A host must supply a normally admitted run and a live authority check. */
|
||||
export function createDotRunnerMcpBridge(): PublicMcpToolExtension & {
|
||||
register(driver: DotHarnessDriver, grantId: string): () => void;
|
||||
} {
|
||||
const runs = new Map<string, { driver: DotHarnessDriver; grantId: string }>();
|
||||
const principalBinding = (p: McpPrincipal) => ({ companyId: p.grant.companyId, grantId: p.grant.id });
|
||||
const owned = (p: McpPrincipal) => [...runs.values()].filter(r => r.grantId === p.grant.id && r.driver.identity.companyId === p.grant.companyId);
|
||||
return {
|
||||
register(driver, grantId) {
|
||||
if (runs.has(driver.identity.runId) || runs.size >= 100) throw new Error("Dot registry already contains the run or is full.");
|
||||
runs.set(driver.identity.runId, { driver, grantId });
|
||||
return () => { driver.revoke(); runs.delete(driver.identity.runId); };
|
||||
},
|
||||
async listTools(p) {
|
||||
if (!p.grant.scopes.includes("paperclip:write") || !owned(p).length) return [];
|
||||
return tools.map(t => ({ name: t.name, description: t.description, inputSchema: z.toJSONSchema(t.schema),
|
||||
annotations: { readOnlyHint: t.read, destructiveHint: false, idempotentHint: true, openWorldHint: !t.read } }));
|
||||
},
|
||||
async callTool(p, name, args) {
|
||||
if (!p.grant.scopes.includes("paperclip:write")) throw new Error("Dot participation requires write consent and an explicit agent binding.");
|
||||
const tool = tools.find(t => t.name === name);
|
||||
if (!tool) throw new Error("Unknown Dot tool.");
|
||||
const a = tool.schema.parse(args);
|
||||
if (a.companyId !== p.grant.companyId) throw new Error("Dot company binding mismatch.");
|
||||
if (name === "paperclip_dot_inbox") {
|
||||
const assignments = [];
|
||||
for (const { driver } of owned(p)) {
|
||||
try { const assignment = await driver.inbox(principalBinding(p)); if (assignment) assignments.push(assignment); }
|
||||
catch { /* Revoked, paused, or expired runs are not offered for work. */ }
|
||||
}
|
||||
return { assignments };
|
||||
}
|
||||
const input = a as z.infer<typeof tools[3]["schema"]> & { result?: unknown; text?: string };
|
||||
const run = runs.get(input.runId);
|
||||
if (!run || run.grantId !== p.grant.id || run.driver.identity.companyId !== p.grant.companyId) throw new Error("Dot run is unavailable.");
|
||||
const common = { turnId: input.turnId, requestId: input.requestId };
|
||||
const command = name === "paperclip_dot_tool" ? { ...common, operation: "tool" as const, name: input.name, arguments: input.arguments }
|
||||
: name === "paperclip_dot_progress" ? { ...common, operation: "progress" as const, text: input.text! }
|
||||
: name === "paperclip_dot_finish" ? { ...common, operation: "finish" as const, result: input.result }
|
||||
: { ...common, operation: name === "paperclip_dot_accept" ? "accept" as const : "read" as const };
|
||||
const result = await run.driver.command(principalBinding(p), command);
|
||||
// Keep uncertainty visible at the MCP envelope, not only inside the
|
||||
// nested provider result. A transport failure must never look successful.
|
||||
const outcome = result && typeof result === "object" && "outcome" in result ? result.outcome : undefined;
|
||||
return { result, ...(outcome === "unknown" || outcome === "rejected" ? { outcome } : {}) };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { type ApiDispatch } from "./capabilities.js";
|
||||
import { PublicMcpDisabledError, type McpPrincipal, type PublicMcpOAuth } from "./oauth.js";
|
||||
import { boundedJson, callbackUrl, eventFetch, McpEventError, postEvent, signingKey, verifyCallback, type EventFetch } from "./event-webhooks.js";
|
||||
|
||||
const names = ["paperclip.task.status_changed", "paperclip.task.comment_created", "paperclip.task.document_updated"] as const;
|
||||
const names = ["paperclip.task.status_changed", "paperclip.task.comment_created", "paperclip.task.document_updated", "paperclip.dot.work_available"] as const;
|
||||
const filters = z.object({ companyId: z.uuid(), taskId: z.uuid(), statuses: z.array(z.enum(ISSUE_STATUSES)).min(1).max(ISSUE_STATUSES.length).optional() }).strict();
|
||||
const common = { name: z.enum(names), arguments: filters, delivery: z.object({ mode: z.literal("webhook"), url: z.string().max(2048), secret: z.string().max(100).optional() }).strict(), _meta: z.record(z.string(), z.unknown()).optional() };
|
||||
const subscribeSchema = z.object({ ...common, ttlMs: z.number().int().positive().nullable().optional(), cursor: z.null().optional() }).strict();
|
||||
@@ -23,7 +23,7 @@ type Subscription = typeof subscriptions.$inferSelect;
|
||||
export type CloudEventAuthority = { token: string; expiresAt: number };
|
||||
type Destination = { url: string; secret: string; previousSecret?: string; previousUntil?: number; cloud?: CloudEventAuthority };
|
||||
|
||||
export const publicMcpEventDefinitions = names.map((name, index) => ({
|
||||
export const publicMcpEventDefinitions = names.slice(0, 3).map((name, index) => ({
|
||||
name,
|
||||
description: [
|
||||
"A Paperclip task changes status, including completion or a blocker. Subscribe only when the user asks to monitor this task; optional statuses restrict delivery. Read the task and deliverables after an event to confirm current state.",
|
||||
@@ -38,7 +38,14 @@ export const publicMcpEventDefinitions = names.map((name, index) => ({
|
||||
}).strict()),
|
||||
}));
|
||||
|
||||
export function createPublicMcpEvents(db: Db, oauth: PublicMcpOAuth, api: ApiDispatch, options: { fetch?: EventFetch; now?: () => number; cloudOrigin?: string } = {}) {
|
||||
const dotEventDefinition = {
|
||||
name: names[3],
|
||||
description: "A runner assignment is available for an explicitly bound Dot. Subscribe to the designated inbox task only when asked to work as this agent. Read paperclip_dot_inbox for current authorized work; duplicate events never imply a second assignment.",
|
||||
delivery: ["webhook"], inputSchema: z.toJSONSchema(filters.omit({ statuses: true })),
|
||||
payloadSchema: z.toJSONSchema(z.object({ companyId: z.uuid(), taskId: z.uuid(), url: z.url(), runId: z.uuid(), agentId: z.uuid(), turnId: z.uuid(), messageId: z.uuid() }).strict()),
|
||||
};
|
||||
|
||||
export function createPublicMcpEvents(db: Db, oauth: PublicMcpOAuth, api: ApiDispatch, options: { fetch?: EventFetch; now?: () => number; cloudOrigin?: string; enableDotPrototype?: boolean } = {}) {
|
||||
const fetcher = options.fetch ?? eventFetch;
|
||||
const now = options.now ?? Date.now;
|
||||
const cloudOrigin = options.cloudOrigin ?? process.env.PAPERCLIP_CLOUD_API_ORIGIN;
|
||||
@@ -70,6 +77,7 @@ export function createPublicMcpEvents(db: Db, oauth: PublicMcpOAuth, api: ApiDis
|
||||
return "sub_" + createHash("sha256").update(canonical([principal.grant.id, callbackUrl(input.delivery.url), input.name, input.arguments])).digest("hex");
|
||||
}
|
||||
function validate(input: z.infer<typeof unsubscribeSchema>) {
|
||||
if (input.name === names[3] && !options.enableDotPrototype) throw new McpEventError(-32602, "Dot prototype events are disabled.");
|
||||
if (input.name !== names[0] && input.arguments.statuses) throw new McpEventError(-32602, "Only status events accept statuses.");
|
||||
if (input.arguments.statuses) input.arguments.statuses = [...new Set(input.arguments.statuses)].sort();
|
||||
}
|
||||
@@ -151,9 +159,12 @@ export function createPublicMcpEvents(db: Db, oauth: PublicMcpOAuth, api: ApiDis
|
||||
const changedStatus = changes ? Object.hasOwn(changes, "status") : previous?.status !== details.status;
|
||||
const wanted = s.name === names[0] ? ["issue.updated", "issue.checked_out", "issue.released"].includes(activity.action) && changedStatus && ISSUE_STATUSES.includes(details.status as typeof ISSUE_STATUSES[number]) && (!Array.isArray(s.arguments.statuses) || s.arguments.statuses.includes(details.status))
|
||||
: s.name === names[1] ? activity.action === "issue.comment_added" && z.uuid().safeParse(details.commentId).success
|
||||
: ["issue.document_created", "issue.document_updated"].includes(activity.action) && typeof details.key === "string" && typeof details.revisionNumber === "number";
|
||||
: s.name === names[2] ? ["issue.document_created", "issue.document_updated"].includes(activity.action) && typeof details.key === "string" && typeof details.revisionNumber === "number"
|
||||
: options.enableDotPrototype && activity.action === "dot.work_available" && [details.runId, details.agentId, details.turnId, details.messageId].every(v => z.uuid().safeParse(v).success);
|
||||
const data = { companyId: s.companyId, taskId: s.taskId, url: oauth.config.origin + "/" + encodeURIComponent(company.prefix) + "/issues/" + s.taskId,
|
||||
...(s.name === names[0] ? { status: details.status } : s.name === names[1] ? { commentId: details.commentId } : { documentKey: details.key, revisionNumber: details.revisionNumber }) };
|
||||
...(s.name === names[0] ? { status: details.status } : s.name === names[1] ? { commentId: details.commentId }
|
||||
: s.name === names[2] ? { documentKey: details.key, revisionNumber: details.revisionNumber }
|
||||
: { runId: details.runId, agentId: details.agentId, turnId: details.turnId, messageId: details.messageId }) };
|
||||
// Nonmatching activity also gets a receipt, so it cannot starve later matches.
|
||||
await db.insert(deliveries).values({ subscriptionId: s.id, activityId: activity.id,
|
||||
event: wanted ? { eventId: "evt_" + activity.id, name: s.name, timestamp: activity.createdAt.toISOString(), data, cursor: null } : {},
|
||||
@@ -178,6 +189,7 @@ export function createPublicMcpEvents(db: Db, oauth: PublicMcpOAuth, api: ApiDis
|
||||
const finish = (outcome: string) => db.update(deliveries).set({ finishedAt: new Date(now()), outcome }).where(eq(deliveries.id, claim.id));
|
||||
const [s] = await db.select().from(subscriptions).where(eq(subscriptions.id, claim.subscriptionId));
|
||||
if (!s || s.stoppedAt || s.expiresAt.getTime() <= now()) { await finish("inactive"); return true; }
|
||||
if (s.name === names[3] && !options.enableDotPrototype) { await finish("dot_prototype_disabled"); return true; }
|
||||
let destination: Destination;
|
||||
try {
|
||||
const principal = await oauth.authorizeGrant(s.grantId);
|
||||
@@ -221,6 +233,7 @@ export function createPublicMcpEvents(db: Db, oauth: PublicMcpOAuth, api: ApiDis
|
||||
})().finally(() => { running = null; }));
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
return { subscribe, unsubscribe, tick,
|
||||
definitions: [...publicMcpEventDefinitions, ...(options.enableDotPrototype ? [dotEventDefinition] : [])],
|
||||
start() { if (!timer) { timer = setInterval(() => { void tick().catch(() => logger.warn("Public MCP event delivery tick failed")); }, 2000); timer.unref(); } },
|
||||
async stop() { if (timer) clearInterval(timer); timer = undefined; await running?.catch(() => {}); },
|
||||
};
|
||||
|
||||
+2
@@ -10,6 +10,8 @@
|
||||
type RunnerModule = typeof import("@paperclipai/paperclip-runner");
|
||||
|
||||
export type {
|
||||
DotHarnessDriver,
|
||||
DotAssignment,
|
||||
PaperclipJsonValue,
|
||||
PaperclipQuestionResponse,
|
||||
PaperclipSemanticActionBinding,
|
||||
|
||||
Reference in new issue
Block a user