feat(runner): add experimental Grok Bot agent participation (#16219)

## Thinking Path

> - Paperclip manages AI agents that perform work for a company.
> - The shared Runner owns task admission, authority, receipts and
finalization.
> - An existing Grok Bot needs to receive assignments and return results
through that Runner.
> - The Bot also needs governed access when it starts work from its own
conversation.
> - This PR adds agent-purpose MCP access and routine webhook dispatch.
> - It reuses the external-agent Rust Runner and keeps Grok capabilities
explicit.
> - The provider stays experimental until the real-client managed
journeys pass.

## Linked Issues or Issue Description

**Agent or provider**
Grok Bot, distinct from the Grok Build coding runtime in #13882.

**Why this adapter is useful**
Users can assign work to an existing Bot, receive progress, questions,
documents and files in Paperclip, and let the Bot initiate work under
its agent permissions.

**How the agent is invoked**
A webhook-only routine delivers bounded references. Dedicated
named-agent OAuth and MCP provide inbound calls. Setup follows [Grok
routines](https://cursor.com/help/grok-bot/routines) and [custom
plugins](https://cursor.com/help/grok-bot/connect-plugins). The current
desktop app needs its Bot-generated Webhook URL navigation link when
routine-row clicks fail.

The GitHub search found related Grok Build runtime work, but no existing
Grok Bot agent provider. This extends the roadmap’s existing agent,
Runner, governance and artifact foundations.

## What Changed

- Add default-off Grok Bot participation through the shared real Rust
external backend, preserving native provider identity guarantees and
distinguishing session closure from remote termination.
- Bind agent OAuth to company, agent, client, gateway and authorizer;
recheck permissions and task-bound execution authority without
manufacturing a native identity.
- Persist routine configuration, dispatch intents, authenticated
acknowledgement and recovery holds. Store URL/key together in encrypted
secret storage, use guarded public egress, and never automatically
replay ambiguous HTTP delivery.
- Reuse native tools, durable waiting, completion assessment and review.
Add task-bound file grants through existing artifact storage; suppress
proactive echo dispatch and synchronous result wake loops.
- Enforce the current native deliverable work-mode policy at file-ticket
issuance and use. Add operator retries for confirmed rejected wakes,
with retained receipts, stable retry intent and current-authority
checks. Recovery locks bindings before routine rows. Thread Stop
resolves the selected run and its agent.
- Cancel queued and preparing Stop targets before assignment creation,
restore saved setup after a failed request and successful retry, and
publish the Grok provider descriptor schema. Advance the versioned
Copilot source declaration for the shared schema change; its
qualification remains pending.
- Filter task summaries with the shared privacy policy, preserve
feedback admission when wake delivery is blocked, reconcile settled
delivery receipts without restoring work authority, and bind every Stop
control to its displayed run. Recovery records distinguish dispatch
uncertainty from a revoked session.
- Add resumable guided setup, credential replacement, consent,
management, observed work status and stop/recovery controls, plus an
interactive Storybook journey using the production task thread, question
form and report card. Grok’s own apps remain available; Paperclip
workspace and third-party tools are deferred.

## Verification

- Five focused protocol, authorization, person MCP and Runner files: 192
tests pass. The Grok assigned-work case executes the actual Rust Runner,
saves a document, uploads/deduplicates a file and reaches ordinary
finalization.
- Proactive intake/deduplication and renewed-session recovery pass.
These use scripted clients and synthetic storage; they are not
real-provider acceptance.
- Repository typecheck, production build, token gates, map checks and
Storybook build/catalog checks pass. The local full-suite campaign was
stopped after macOS shared-memory exhaustion repeatedly prevented
embedded PostgreSQL startup. No local aggregate pass is claimed. The
first clean-worker CI run identified avatar fixture/configuration, flag
defaults, feature-card ordering and OpenAPI route-coverage gaps; all
four focused regressions pass after correction. Those regressions pass.
The latest clean-worker CI run also found a Copilot source-hash
declaration mismatch after the shared descriptor update; the corrected
declaration passes all 28 integrity tests. The next review corrections
pass 144 rendered UI tests, 21 OpenAPI tests and 82 Runner
contract/integrity/history tests. The latest database fixtures were
blocked at startup by host shared-memory exhaustion; clean-worker CI
must execute their new regressions. Full current-head CI now passes: 54
successful checks and four intentional skips. The database regression
uses the PostgreSQL driver result shape; file-policy, rejected-feedback
and lock-order cases pass on clean workers. Current-head Greptile is 5/5
with no unresolved findings.
- Rendered setup steps and outbound-only verification were walked
through in Storybook. Simulation cannot enable Done without an
authenticated-reply state.
- Actual client OAuth, continued access, reconnect and one routine wake
with an exact chat acknowledgement were observed separately. This
candidate’s live authenticated challenge, assigned/proactive workflows,
Linux managed artifact, restart and cleanup are not yet qualified. The
provider stays disabled by default.
- The separate Cloud ingress change forwards only exact task-bound
upload/download paths and preserves host identity and header stripping.
- Current Cloud policy reserves Test for pre-merge app/harness
experiments; Staging accepts only master-derived revisions. Real-client
qualification needs a supported, authorized deployment target and
remains outstanding.

## Risks

One append-only migration adds routine/dispatch state and extends shared
bindings and file tickets. The unshipped migrations were regenerated
after upstream consumed their original numbers. Rolling back code
retains the durable rows; revoke grants and inspect unknown remote
activity before resuming dispatch. Grok cannot confirm remote
termination, stream its complete transcript or report spending. Plugins
are account-wide and do not isolate credentials between Bots.
Real-client managed acceptance remains required before enabling the
experimental provider.

## Model Used

OpenAI Codex based on GPT-6, with reasoning, code execution and
browser/native UI tools. The exact deployment model ID and
context-window size are not exposed by this runtime.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-10-13 20:57:42 -05:00
1 parent f6608f382f
commit b8ffeb973a
99 files changed
+3976 -331

No files matched your search

@@ -71,7 +71,7 @@ export interface BuildNativeExecutionInput {
branchName: string | null;
};
normalizedSessionId: string | null;
provider?: "codex" | "opencode" | "claude_managed" | "aws_agentcore" | "acpx" | "openai_dot";
provider?: "codex" | "opencode" | "claude_managed" | "aws_agentcore" | "acpx" | "openai_dot" | "grok_bot";
dotBinding?: DotBindingSnapshot;
acpxAgent?: NativeAcpxAgent;
codexApprovalPolicy?: NativeCodexApprovalPolicy;
@@ -108,8 +108,8 @@ export interface BuildNativeExecutionInput {
};
runtimeContext: NativeRuntimeContextSnapshot;
}
export function buildNativeExecutionInput(input: BuildNativeExecutionInput & { provider: "openai_dot"; dotBinding: DotBindingSnapshot }): NativeExecutionInputV6;
export function buildNativeExecutionInput(input: BuildNativeExecutionInput & { provider?: Exclude<BuildNativeExecutionInput["provider"], "openai_dot"> }): NativeExecutionInputV5;
export function buildNativeExecutionInput(input: BuildNativeExecutionInput & { provider: "openai_dot" | "grok_bot"; dotBinding: DotBindingSnapshot }): NativeExecutionInputV6;
export function buildNativeExecutionInput(input: BuildNativeExecutionInput & { provider?: Exclude<BuildNativeExecutionInput["provider"], "openai_dot" | "grok_bot"> }): NativeExecutionInputV5;
export function buildNativeExecutionInput(input: BuildNativeExecutionInput): NativeExecutionInputV5 | NativeExecutionInputV6;
export function buildNativeExecutionInput(input: BuildNativeExecutionInput): NativeExecutionInputV5 | NativeExecutionInputV6 {
if (input.issue.workMode !== "standard" && input.issue.workMode !== "planning" && input.issue.workMode !== "ask") {
@@ -330,10 +330,10 @@ export function buildNativeExecutionInput(input: BuildNativeExecutionInput): Nat
credentialBindings: [],
runtimeContext: input.runtimeContext,
};
return parseNativeExecutionInput(input.provider === "openai_dot" ? { ...prepared,
schema: "paperclip.native-execution-input.v6", provider: { kind: "openai_dot", model: null, binding: input.dotBinding },
return parseNativeExecutionInput(["openai_dot", "grok_bot"].includes(input.provider ?? "") ? { ...prepared,
schema: "paperclip.native-execution-input.v6", provider: { kind: input.provider, model: null, binding: input.dotBinding },
workspace: { access: "none", cwd: null, repoUrl: null, repoRef: null, branchName: null },
session: { ...prepared.session, driverKind: "openai_dot_mcp", lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }
session: { ...prepared.session, driverKind: input.provider === "grok_bot" ? "grok_bot_mcp" : "openai_dot_mcp", lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }
} : prepared) as NativeExecutionInputV5 | NativeExecutionInputV6;
}
@@ -1681,7 +1681,8 @@ export function nativeSessionWorkspaceScope(execution: { binding: Pick<NativeExe
function nativeProviderSessionScope(execution: NativeExecutionInput) {
switch (execution.provider.kind) {
case "openai_dot": return { kind: "openai_dot", bindingId: execution.provider.binding.bindingId, generation: execution.provider.binding.bindingGeneration };
case "grok_bot":
case "openai_dot": return { kind: execution.provider.kind, bindingId: execution.provider.binding.bindingId, generation: execution.provider.binding.bindingGeneration };
case "claude_managed":
return {
kind: execution.provider.kind,
@@ -5549,6 +5550,7 @@ function canonicalJson(value: unknown): string {
function runnerProviderStateFilename(execution: NativeExecutionInput): string {
switch (execution.provider.kind) {
case "grok_bot":
case "openai_dot":
return "dot-provider-state.json";
case "codex":
@@ -5583,6 +5585,7 @@ export function providerSessionIdentityFromDurableProviderState(input: {
providerSessionIdentity: null,
});
switch (input.execution.provider.kind) {
case "grok_bot":
case "openai_dot":
// Dot checkpoints recover the bridge only; there is no native provider thread.
return emptyIdentity();
@@ -7531,7 +7534,7 @@ export async function executePaperclipNativeSession(input: {
await retireSupersededWarmNativeSessions(
ownerScope, nativeSessionScopeKey(input.execution),
);
if (input.execution.provider.kind === "openai_dot" && isCloudManagedInstance()
if (input.execution.schema === "paperclip.native-execution-input.v6" && isCloudManagedInstance()
&& (!input.useRunnerd || input.runnerExecutionTarget?.kind !== "remote"
|| input.runnerExecutionTarget.transport !== "sandbox")) {
throw new Error("dot_cloud_requires_managed_runner");
@@ -7556,7 +7559,7 @@ export async function executePaperclipNativeSession(input: {
// a later sweep from closing an owner this turn is about to acquire.
await closingWarmNativeSessions.get(sessionScopeId);
if (input.execution.provider.kind === "openai_dot") {
if (input.execution.schema === "paperclip.native-execution-input.v6") {
return await executePaperclipNativeSessionWithinScope(input);
}
const workspaceRoot = input.execution.workspace.cwd;
@@ -7662,7 +7665,7 @@ async function executePaperclipNativeSessionWithinScope(
input.execution.provider.kind !== "claude_managed" &&
input.execution.provider.kind !== "aws_agentcore" &&
input.execution.provider.kind !== "acpx" &&
input.execution.provider.kind !== "openai_dot"
input.execution.schema !== "paperclip.native-execution-input.v6"
) {
throw new Error("paperclip_runner_provider_unsupported");
}
@@ -8609,7 +8612,7 @@ async function executePaperclipNativeSessionWithinScope(
controller,
});
try {
if (input.managedGitHub && input.execution.provider.kind !== "openai_dot") {
if (input.managedGitHub && input.execution.schema !== "paperclip.native-execution-input.v6") {
if (!input.execution.workspace.cwd) throw new Error("native_workspace_required");
githubAccess ??= await createNativeGitHubAccess({
scope: input.execution.binding,
@@ -9594,7 +9597,7 @@ async function executePaperclipNativeSessionWithinScope(
resultJson: {
nativeResult: native.result as unknown as Record<string, unknown>,
nativeTerminal: native.terminal as unknown as Record<string, unknown>,
...(input.execution.provider.kind === "openai_dot" ? { providerAccounting: { usage: null, cost: null, externallyBilled: true }, externalStopConfirmed: false } : {}),
...(input.execution.schema === "paperclip.native-execution-input.v6" ? { providerAccounting: { usage: null, cost: null, externallyBilled: true }, externalStopConfirmed: false } : {}),
...(providerFailure ? { nativeProviderFailure: providerFailure.diagnostic } : {}),
...(native.goalRolloverRequired ? { goalRolloverRequired: true } : {}),
planSynchronizations,
@@ -9605,7 +9608,7 @@ async function executePaperclipNativeSessionWithinScope(
...resolveNativeBilling(input.execution.provider, input.runnerEnvironment, input.billingIdentity),
model: input.execution.provider.model,
usage: normalizeNativeUsage(native.usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" }),
costUsd: input.execution.provider.kind !== "openai_dot" && normalizeNativeUsage(native.usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" })
costUsd: input.execution.schema !== "paperclip.native-execution-input.v6" && normalizeNativeUsage(native.usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" })
? nativeUsageCostUsd(native.usage, input.execution.provider) ?? null : null,
costUsdExact: typeof native.usage?.accountingCostUsdExact === "string" ? native.usage.accountingCostUsdExact : undefined,
costStatus: nativeAccountingComplete && native.usage?.accountingCostIncomplete !== true
@@ -9775,6 +9778,7 @@ export function nativeUsageCostUsd(
/** Billing identity follows the selected runtime and resolved credentials.
* Unknown authentication remains unknown; a provider name does not prove billing mode. */
export function resolveNativeBilling(provider: NativeExecutionInput["provider"], env: NodeJS.ProcessEnv = {}, identity?: Pick<AdapterExecutionResult, "provider" | "biller" | "billingType">): Pick<AdapterExecutionResult, "provider" | "biller" | "billingType"> {
if (provider.kind === "grok_bot") return { provider: "grok_bot", biller: "unknown", billingType: "unknown" };
if (identity) return identity.provider === "openai" && identity.billingType === "metered_api"
? { ...identity, biller: inferOpenAiCompatibleBiller(env, identity.biller ?? "unknown") }
: identity;
@@ -10143,7 +10147,7 @@ function readRemoteProviderPackIdentity(packRoot: string, verifyControllerFiles:
export function assertRemoteRunnerBuildMetadata(
value: unknown,
requiredMode: "dial_wss" | "listen_ws",
requiredExternalProvider?: "openai_dot_mcp",
requiredExternalProvider?: "openai_dot_mcp" | "grok_bot_mcp",
): void {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("runner_remote_artifact_metadata_invalid");
@@ -11244,7 +11248,7 @@ async function prepareRemoteDotRunner({ input, target, runner, root, identity }:
}
const metadata = await runner.execute({ command: remoteBinary, args: ["--build-metadata"], bypassSession: true, timeoutMs: 30000 });
if (metadata.exitCode !== 0 || metadata.timedOut) throw new Error("runner_remote_artifact_verification_failed");
assertRemoteRunnerBuildMetadata(JSON.parse(metadata.stdout), requiredMode, "openai_dot_mcp");
assertRemoteRunnerBuildMetadata(JSON.parse(metadata.stdout), requiredMode, input.execution.provider.kind === "grok_bot" ? "grok_bot_mcp" : "openai_dot_mcp");
const checksum = await runner.execute({ command: "sh", args: ["-c",
'if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1"; else shasum -a 256 "$1"; fi', "paperclip-dot-artifact", remoteBinary],
bypassSession: true, timeoutMs: 10000 });
@@ -11377,7 +11381,7 @@ async function createRunnerdBackendWithinSessionClaim(
// Remote Codex already sends dynamic tool calls over authenticated PRP. Keep
// the assigned gateway on the control plane instead of asking the sandbox to
// reach the host's HTTP origin (which may be private or loopback-only).
const relayAssignedMcp = (remoteTarget !== null && input.execution.provider.kind === "codex") || input.execution.provider.kind === "openai_dot";
const relayAssignedMcp = (remoteTarget !== null && input.execution.provider.kind === "codex") || input.execution.schema === "paperclip.native-execution-input.v6";
const assignedMcpUrl = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_URL;
const assignedMcpToken = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_TOKEN;
const assignedMcpName = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_NAME;
@@ -11399,7 +11403,7 @@ async function createRunnerdBackendWithinSessionClaim(
workMode: input.execution.task.workMode,
})
: undefined;
const dotAttachmentActor = input.execution.provider.kind === "openai_dot"
const dotAttachmentActor = input.execution.schema === "paperclip.native-execution-input.v6"
? await input.db.select({ config: agents.adapterConfig }).from(agents).where(and(
eq(agents.id, input.execution.binding.agentId), eq(agents.companyId, input.execution.binding.companyId),
)).limit(1).then(rows => rows[0]) : undefined;
@@ -11418,10 +11422,11 @@ async function createRunnerdBackendWithinSessionClaim(
: undefined,
workMode: input.execution.task.workMode,
runtimeContext: "runtimeContext" in input.execution ? input.execution.runtimeContext : undefined,
workspaceBridge: input.execution.provider.kind === "openai_dot" && !!input.dotWorkspaceRoot,
workspaceBridge: input.execution.schema === "paperclip.native-execution-input.v6" && !!input.dotWorkspaceRoot,
taskAttachmentRead: dotAttachmentActor?.config.dotAttachmentAccess === true,
dotRuntime: input.execution.provider.kind === "openai_dot",
assertBridgeAuthority: input.execution.provider.kind === "openai_dot" ? () => dotRunnerBroker(input.db).assertRunAuthority(input.execution as import("../../vendor/paperclip-runner/index.js").NativeExecutionInputV6) : undefined,
dotRuntime: input.execution.schema === "paperclip.native-execution-input.v6",
firstPartyOnly: input.execution.provider.kind === "grok_bot",
assertBridgeAuthority: input.execution.schema === "paperclip.native-execution-input.v6" ? () => dotRunnerBroker(input.db).assertRunAuthority(input.execution as import("../../vendor/paperclip-runner/index.js").NativeExecutionInputV6) : undefined,
workspaceRoot: input.dotWorkspaceRoot ?? remoteTarget?.remoteCwd ?? input.execution.workspace.cwd ?? undefined,
executionTargetKind: target.kind,
readRemoteWorkspaceFile: remoteTarget && remoteCommandRunner
@@ -110,6 +110,7 @@ import {
type NativeChatAttachmentReadScope,
} from "./chat-attachment-read.js";
const EXTERNAL_WORKSPACE_OPERATIONS = new Set(["get_workspace", "list_workspaces", "select_workspace", "prepare_repository", "register_deliverable"]);
const IMPLEMENTED_OPERATIONS = new Set([
"submit_complaint", "submit_suggestion",
"read_agent_instructions", "update_agent_instructions", "get_agent_instruction_history", "restore_agent_instructions",
@@ -146,6 +147,8 @@ type Binding = {
workspaceBridge?: boolean;
/** Pinned provider identity; configuration edits cannot remove API file guards. */
dotRuntime?: boolean;
/** Grok retains its provider apps; this release exposes first-party Paperclip tools only. */
firstPartyOnly?: boolean;
/** Operator-approved Dot attachment access, pinned when the turn opens. */
taskAttachmentRead?: boolean;
runtimeContext?: NativeRuntimeContextSnapshot;
@@ -241,6 +244,7 @@ export class PaperclipRunnerToolAuthority {
CAPABILITY_SEMANTIC_TOOL_CATALOG.filter(
(descriptor) =>
IMPLEMENTED_OPERATIONS.has(descriptor.operationId) &&
(!this.binding.firstPartyOnly || !EXTERNAL_WORKSPACE_OPERATIONS.has(descriptor.operationId)) &&
(runnerApiToolsEnabled(
this.binding.companyId,
this.binding.apiToolsEnabled,
@@ -289,10 +293,10 @@ export class PaperclipRunnerToolAuthority {
definitions.push(REUSE_CHAT_ATTACHMENT_TOOL_DEFINITION);
if (this.binding.chatAttachmentReadScope) definitions.push(READ_CHAT_ATTACHMENT_TOOL_DEFINITION);
if (this.binding.taskAttachmentRead) definitions.push(...TASK_ATTACHMENT_DEFINITIONS);
definitions.push(...runnerBridgeDefinitions({ workspace: !!this.binding.workspaceRoot && this.binding.workspaceBridge === true, skills: !!this.binding.runtimeContext, api: runnerApiToolsEnabled(this.binding.companyId, this.binding.apiToolsEnabled), mode: workMode }));
const connectionTools = [...RUNTIME_CONNECTION_TOOL_DEFINITIONS,
definitions.push(...runnerBridgeDefinitions({ workspace: !this.binding.firstPartyOnly && !!this.binding.workspaceRoot && this.binding.workspaceBridge === true, skills: !!this.binding.runtimeContext, api: runnerApiToolsEnabled(this.binding.companyId, this.binding.apiToolsEnabled), mode: workMode }));
const connectionTools = this.binding.firstPartyOnly ? [] : [...RUNTIME_CONNECTION_TOOL_DEFINITIONS,
...(this.binding.connectorAssignments ?? []).flatMap((assignment) => assignment.tools)];
const assignedTools = this.binding.assignedMcpTools?.definitions((tools) =>
const assignedTools = this.binding.firstPartyOnly ? [] : this.binding.assignedMcpTools?.definitions((tools) =>
runnerCodexDynamicToolsFit([...connectionTools, ...tools, ...definitions])) ?? [];
return [...connectionTools, ...assignedTools, ...definitions];
}
@@ -302,6 +306,7 @@ export class PaperclipRunnerToolAuthority {
callId: string;
arguments: unknown;
}): Promise<unknown> {
if (this.binding.firstPartyOnly && (EXTERNAL_WORKSPACE_OPERATIONS.has(call.tool) || call.tool.startsWith("workspace_"))) throw forbidden("Paperclip workspace access is unavailable to this Grok Bot session.");
if (this.binding.nativeReview) {
if (call.tool === "resolve_review") return this.#resolveReview(call.arguments);
if (!NATIVE_REVIEW_READ_TOOLS.has(call.tool)) {
@@ -374,6 +379,8 @@ export class PaperclipRunnerToolAuthority {
const { operationId, ...response } = record(await this.#callApi(call.callId, { operationId: operation.operationId, pathParams: { id: input.taskId, ...(input.key ? { key: input.key } : {}) }, ...(body ? { body } : {}) }));
return { ...response, apiOperationId: operationId };
}
if (this.binding.firstPartyOnly && (this.binding.assignedMcpTools?.has(call.tool) || isConnectorTool(call.tool)
|| RUNTIME_CONNECTION_TOOL_DEFINITIONS.some(tool => tool.name === call.tool))) throw forbidden("This Grok Bot connection exposes first-party Paperclip operations. Use your own provider apps under their existing permissions.");
if (this.binding.assignedMcpTools?.has(call.tool)) {
const current = await this.#boundContext();
return this.binding.assignedMcpTools.execute(call, current.issue.workMode as "standard" | "planning" | "ask");
@@ -743,6 +750,7 @@ export class PaperclipRunnerToolAuthority {
const bound = await this.#boundContext();
const context = { ...this.binding, issueIdentifier: bound.issue.identifier, workMode: bound.issue.workMode };
const { input, operation } = validateRunnerApiCall(value, context);
if (this.binding.firstPartyOnly && /\/(?:workspaces|workspace-runtime|repositories|tool-gateway|tool-connections|tool-profiles|tools|connection-intents|connections|plugins)(?:\/|$)/.test(operation.path)) throw forbidden("Third-party tools through Paperclip are unavailable for this Grok Bot connection.");
const sensitiveResponse = runnerApiSensitiveResponse(operation.method, operation.path);
await this.#assertDotApiFileAccess(operation.path, input);
const apiUrl = this.binding.apiUrl ?? process.env.PAPERCLIP_API_URL;
@@ -928,6 +936,9 @@ export class PaperclipRunnerToolAuthority {
}
async #assertDotApiFileAccess(path: string, input: { pathParams?: Record<string, string>; files?: RunnerApiFile[] }) {
if (this.binding.firstPartyOnly && (input.files?.length || /\/(?:attachments|assets)\/[^/]+\/content$/.test(path) || /\/file-resources\/content$/.test(path))) {
throw forbidden("Use this Grok work session's bounded upload or download grant; direct file API access is unavailable.");
}
if (!this.binding.dotRuntime) return;
const current = await this.#boundContext();
await this.binding.assertBridgeAuthority?.();
@@ -38,6 +38,7 @@ export type QualifiedPaperclipRunnerAcpxAgent =
type AdmittedPaperclipRunnerAcpxAgent = QualifiedPaperclipRunnerAcpxAgent | AcpxQualificationCandidate;
export type PaperclipRunnerProviderProfile =
| { provider: "grok_bot"; backend: "grok_bot_mcp"; model: null; externalBindingId: string }
| { provider: "openai_dot"; backend: "openai_dot_mcp"; model: null; dotBindingId: string }
| {
provider: "codex";
@@ -71,6 +72,7 @@ export type PaperclipRunnerProviderProfile =
};
export type PaperclipRunnerNativeProviderInput =
| { provider: "grok_bot"; model: null; dotBinding: import("../../vendor/paperclip-runner/index.js").DotBindingSnapshot }
| { provider: "openai_dot"; model: null; dotBinding: import("../../vendor/paperclip-runner/index.js").DotBindingSnapshot }
| {
provider: "codex";
@@ -165,6 +167,17 @@ export function validatePaperclipRunnerDotConfig(config: Record<string, unknown>
return bindingId;
}
export function validatePaperclipRunnerGrokConfig(config: Record<string, unknown>, requireBinding = true): string | null {
const bindingId = optionalString(config.externalBindingId);
if ((requireBinding && !bindingId) || (bindingId && !/^[0-9a-f-]{36}$/i.test(bindingId))
|| config.allowUnmeteredProvider !== true || (config.lifecycleMode && config.lifecycleMode !== "per_turn")
|| optionalString(config.model) || config.dotWorkspaceAccess === true || config.dotAttachmentAccess === true
|| optionalString(config.cwd) || optionalString(config.command)) {
throw new PaperclipRunnerProviderProfileError("paperclip_runner_grok_config_invalid", "Grok Bot requires a bound per-turn work session and an explicit acknowledgement of unreported provider spending. Paperclip workspace, shell and third-party app tools are unavailable.");
}
return bindingId;
}
/** A task may change a local Runner model (and Codex effort), but not provider identity. */
export function projectPaperclipRunnerTaskConfig(
backend: "codex_app_server" | "opencode_server",
@@ -370,6 +383,9 @@ export function resolvePaperclipRunnerProviderProfile(
);
}
if (candidate === "grok_bot") {
return { provider: "grok_bot", backend: "grok_bot_mcp", model: null, externalBindingId: validatePaperclipRunnerGrokConfig(config)! };
}
if (candidate === "openai_dot") {
const bindingId = validatePaperclipRunnerDotConfig(config)!;
return { provider: "openai_dot", backend: "openai_dot_mcp", model: null, dotBindingId: bindingId };
@@ -554,6 +570,10 @@ export function resolvePaperclipRunnerNativeProviderInput(input: {
"Paperclip Runner provider changed after this run selected its native backend.",
);
}
if (profile.provider === "grok_bot") {
if (!input.dotBinding || input.dotBinding.bindingId !== profile.externalBindingId) throw new PaperclipRunnerProviderProfileError("paperclip_runner_grok_binding_unavailable", "The Grok binding must be resolved by the server after normal admission.");
return { provider: "grok_bot", model: null, dotBinding: input.dotBinding };
}
if (profile.provider === "openai_dot") {
if (!input.dotBinding || input.dotBinding.bindingId !== profile.dotBindingId) throw new PaperclipRunnerProviderProfileError("paperclip_runner_dot_binding_unavailable", "Dot binding must be resolved by the server after normal admission.");
return { provider: "openai_dot", model: null, dotBinding: input.dotBinding };
@@ -51,7 +51,7 @@ export type NativeRuntimeResolution =
| "claude_managed_agents_api"
| "aws_agentcore_harness_api"
| "acpx_runtime"
| "openai_dot_mcp";
| "openai_dot_mcp" | "grok_bot_mcp";
protocolVersion: 1;
};
authorityDecision: NativeStatusDecision;
@@ -98,6 +98,7 @@ function ineligible(
export function resolveNativeRuntimeMode(input: {
enabled: boolean;
dotEnabled?: boolean;
grokEnabled?: boolean;
runtimeConfig: unknown;
adapterConfig?: unknown;
agent: { id?: string; status: string; adapterType: string | null };
@@ -129,6 +130,8 @@ export function resolveNativeRuntimeMode(input: {
// Dot has its own rollout; enabling it does not opt in other Runner providers.
if (runnerProfile.provider === "openai_dot") {
if (input.dotEnabled !== true) throw ineligible("paperclip_runner_dot_disabled", "Enable OpenAI Dot and Assistant connections (MCP) in experimental settings before assigning new work.");
} else if (runnerProfile.provider === "grok_bot" && (input.grokEnabled !== true || !input.enabled)) {
throw ineligible("paperclip_runner_grok_disabled", "Enable Grok Bot, Paperclip Runner, and Assistant connections (MCP) before assigning new work.");
} else if (!input.enabled) {
throw ineligible(
"paperclip_runner_rollout_disabled",
@@ -187,6 +190,7 @@ export function resolveHeartbeatRuntimeMode(input: {
};
enabled: boolean;
dotEnabled?: boolean;
grokEnabled?: boolean;
adapterType: string | null;
adapterConfig: unknown;
agentStatus: string;
@@ -214,6 +218,7 @@ export function resolveHeartbeatRuntimeMode(input: {
resolution = resolveNativeRuntimeMode({
enabled: input.enabled,
dotEnabled: input.dotEnabled,
grokEnabled: input.grokEnabled,
runtimeConfig: {},
adapterConfig: input.adapterConfig,
agent: {
@@ -249,6 +254,7 @@ export function resolveHeartbeatRuntimeMode(input: {
? "claude_managed"
: resolution.profile.backend === "aws_agentcore_harness_api"
? "aws_agentcore"
: resolution.profile.backend === "grok_bot_mcp" ? "grok_bot"
: resolution.profile.backend === "openai_dot_mcp" ? "openai_dot"
: resolution.profile.backend === "acpx_runtime"
? "acpx"
@@ -270,6 +276,7 @@ export function resolveHeartbeatNativeRuntimeMode(input: {
};
enabled: boolean;
dotEnabled?: boolean;
grokEnabled?: boolean;
runtimeConfig: unknown;
adapterConfig?: unknown;
agent: { id?: string; status: string; adapterType: string | null };
@@ -301,6 +308,7 @@ export function resolveHeartbeatNativeRuntimeMode(input: {
? "claude_managed_agents_api"
: driverKind === "aws_agentcore_harness_api"
? "aws_agentcore_harness_api"
: driverKind === "grok_bot_mcp" ? "grok_bot_mcp"
: driverKind === "openai_dot_mcp" ? "openai_dot_mcp"
: driverKind === "acpx_runtime"
? "acpx_runtime"