mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Environment plugins can run agent tasks on remote computers, and can run the provider sign-in for those computers > - Core decides which adapters can sign in on a plugin environment from a fixed Claude and Codex rule and a `supportsCodexLogin` flag > - A plugin cannot say which adapters it supports, so Grok has no sign-in on a plugin computer, and a plugin can run an adapter that it cannot sign in > - This pull request lets a Runner task driver declare its supported adapters, and makes support mean the full adapter lifecycle: runs and, where Paperclip offers one, sign-in > - The benefit is one extensible support contract per driver, with no partial matrix, and Grok subscription sign-in on plugin computers ## Linked Issues or Issue Description **Subsystem affected** Plugin SDK environment drivers, plugin sign-in (login pseudo-terminal), plugin Runner task credentials, and agent Runner selection. **Problem or motivation** Core allows plugin-computer sign-in only for Claude, and for Codex when the plugin can read back a credential file. The flag for that is named `supportsCodexLogin`, which does not describe what it does. A plugin cannot advertise which adapters it supports. Grok has a device sign-in in Core, but it has no sign-in on a plugin computer, and a Grok subscription cannot reach a plugin task. A plugin can also run an adapter that has no sign-in on that plugin. This gives a partial support matrix. **Proposed solution** A Runner task driver declares `supportedAdapters`. Support for an adapter means the full lifecycle. The driver must run the adapter, and it must run the Paperclip sign-in when the adapter has one. Core validates the declaration in the manifest, and Core checks it again against the methods of the running worker. An adapter that fails either check is not offered for sign-in, for save, or for runs. The sign-in contract moves to one shared map, so a new adapter sign-in is one entry in that map. **Alternatives considered** A separate per-capability table (runs, sign-in, credential read-back) was rejected. It permits the partial matrix that this change removes. The existing sign-in map and credential sets already contain the necessary data. **Additional context** Related open pull requests: Refs #14001 (Kubernetes plugin login pseudo-terminal), Refs #21327 (Grok device link in the sign-in UI). ## What Changed - Environment drivers can declare `supportedAdapters`. The manifest is rejected when the list has duplicates, when the driver is not a Runner task driver, or when it lists an adapter that has a Paperclip sign-in and the driver does not declare the login pseudo-terminal with `creationOperationVersion: 1`. - Core removes a listed adapter when the running worker does not implement the methods it needs (task methods, and sign-in methods with credential read-back for file sign-ins). Core logs a warning one time for each removed adapter. - `supportsCodexLogin` is replaced by `loginAdapters`, the adapters that can sign in on that environment. Drivers without `supportedAdapters` keep the current behaviour: Claude, and Codex when the worker reads back credentials. - A new shared sign-in map holds the adapters that Paperclip signs in and where each sign-in leaves its credential (terminal output or a file). Manifest validation, server admission, environment presentation, and the Connections sign-in step use this map. Two hard-coded Claude and Codex lists are removed. - Credential read-back accepts any file sign-in key and returns `{ kind: "auth-file", content }`. - The plugin task credential `codex-auth-json` becomes `{ type: "auth-file", provider: "codex" | "grok", content }`. - A Grok subscription is delivered to plugin tasks as an `auth-file` credential. A refreshed Grok file returns to the account through the existing write-back. The write-back record now stores its provider. - On a driver that lists adapters, Core refuses to save, offer, or submit a Runner harness that is not on the list. The error is `agent_runner_unavailable`. - The SDK README and the plugin environment task and AI connection docs describe the contract. ## Verification - `pnpm --filter @paperclipai/server typecheck`, `pnpm --filter @paperclipai/plugin-sdk typecheck`, and `pnpm --filter @paperclipai/ui typecheck` pass. - Targeted server tests pass: plugin environment driver capabilities, plugin login credential, plugin Runner credentials, plugin task credential write-back (Codex and Grok, with a provider mismatch case), environment task runtime submit gating, agent Runner selection, login environment, login session runtime, device login routes and service, setup token, login command, and adapter routes. - Plugin Runner probe and integration tests pass (run from the repository root). - Shared tests (77) and plugin SDK tests (129) pass, including the new manifest validation cases. - UI AI connection tests (67) pass. - Not run locally: the full suite (CI runs it), a render test for the Connections credential step, and an end-to-end route test for computer device sign-in admission. Unit tests cover that admission. ## Risks - Breaking change for plugins that use the plugin SDK task credential or credential read-back. `codex-auth-json` becomes `auth-file`, and the read-back result kind changes. A plugin must update to the new SDK shapes in the same release. - Plugins that do not declare `supportedAdapters` keep the current behaviour. No warning is logged for them. - `supportedAdapters` applies to Runner task drivers only. Sandbox providers reject the field. Support for sandbox providers is a separate change. - The new-agent screen does not offer sign-in on a plugin computer. That sign-in needs a target computer, and the Connections flow selects it. This is the current behaviour for Claude and Codex. - No migration. The write-back record treats a missing provider as Codex, so records written before this change still work. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs) and extended thinking. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Paperclip <noreply@paperclip.ing>
319 lines
19 KiB
TypeScript
319 lines
19 KiB
TypeScript
import { z } from "zod";
|
|
import type { PluginEnvironmentDriverBaseParams, PluginEnvironmentLease } from "./protocol.js";
|
|
import type { PluginAgentRuntimeIdentity } from "./types.js";
|
|
|
|
export const MAX_ENVIRONMENT_TASK_FILE_BYTES = 10 * 1024 * 1024;
|
|
const taskFilePath = z.string().min(1).max(2000).refine(value =>
|
|
!/[\\\u0000-\u001f\u007f]/u.test(value) && !/^[a-z][a-z0-9+.-]*:/iu.test(value) &&
|
|
value.replace(/^\//u, "").split("/").every(part => part !== "" && part !== "." && part !== ".."), "Expected a canonical task file path");
|
|
// Provider IDs are opaque; providers validate their own addressing constraints.
|
|
const providerId = z.string().min(1);
|
|
// PRP identity.schema.json stableId.
|
|
const runnerIdentity = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/);
|
|
const durableIdentity = z.object({ runnerInstanceId: runnerIdentity, environmentLeaseId: runnerIdentity,
|
|
runId: runnerIdentity, normalizedSessionId: runnerIdentity, turnId: runnerIdentity, itemId: runnerIdentity }).strict();
|
|
const identifier = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/);
|
|
const secureUrl = z.string().url().refine(value => {
|
|
const url = new URL(value);
|
|
return url.protocol === "wss:" && !url.username && !url.password && !url.search && !url.hash;
|
|
}, "Expected a credential-free WSS URL");
|
|
|
|
const credentialValue = z.string().min(1).max(65_536).refine(value => !value.includes("\0"));
|
|
const githubBroker = z.object({ url: z.string().url().max(2000).refine(value => {
|
|
try {
|
|
const url = new URL(value);
|
|
return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash;
|
|
} catch { return false; }
|
|
}, "Expected a credential-free HTTP broker URL"), token: credentialValue }).strict();
|
|
const claudeCredentialEnvironment = z.object({
|
|
CLAUDE_CODE_OAUTH_TOKEN: credentialValue.optional(), ANTHROPIC_API_KEY: credentialValue.optional(),
|
|
}).strict().refine(env => Object.values(env).filter(Boolean).length === 1, "Select one Claude credential");
|
|
export const MAX_CONFIGURED_ENVIRONMENT_KEYS = 128;
|
|
export const MAX_CONFIGURED_ENVIRONMENT_ENTRY_BYTES = 65_536;
|
|
export const MAX_CONFIGURED_ENVIRONMENT_BYTES = 262_144;
|
|
const utf8 = new TextEncoder();
|
|
const utf8Bytes = (value: string) => utf8.encode(value).byteLength;
|
|
export const environmentTaskConfiguredEnvironmentSchema = z.record(
|
|
z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/),
|
|
z.string().refine(value => !value.includes("\0"), "Expected a NUL-free value"),
|
|
).superRefine((environment, ctx) => {
|
|
const entries = Object.entries(environment);
|
|
if (entries.length > MAX_CONFIGURED_ENVIRONMENT_KEYS) {
|
|
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Too many configured environment variables" });
|
|
return;
|
|
}
|
|
let total = 0;
|
|
for (const [name, value] of entries) {
|
|
const size = utf8Bytes(name) + utf8Bytes(value);
|
|
total += size;
|
|
if (size > MAX_CONFIGURED_ENVIRONMENT_ENTRY_BYTES) {
|
|
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Configured environment variable is too large", path: [name] });
|
|
}
|
|
}
|
|
if (total > MAX_CONFIGURED_ENVIRONMENT_BYTES) {
|
|
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Configured environment is too large" });
|
|
}
|
|
});
|
|
export type PluginEnvironmentTaskConfiguredEnvironment = z.infer<typeof environmentTaskConfiguredEnvironmentSchema>;
|
|
|
|
export const ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS = {
|
|
grok: [["XAI_API_KEY"]],
|
|
copilot: [["COPILOT_GITHUB_TOKEN"]],
|
|
opencode: [["OPENROUTER_API_KEY"], ["PAPERCLIP_AI_PROVIDER_URL", "PAPERCLIP_AI_PROVIDER_KEY"]],
|
|
antigravity: [["GEMINI_API_KEY"], ["PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"]],
|
|
} as const satisfies Record<string, readonly (readonly string[])[]>;
|
|
export type PluginEnvironmentTaskCredentialProvider = keyof typeof ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS;
|
|
const providerNames = Object.keys(ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS) as [PluginEnvironmentTaskCredentialProvider, ...PluginEnvironmentTaskCredentialProvider[]];
|
|
const providerCredential = z.object({
|
|
type: z.literal("provider-env"),
|
|
provider: z.enum(providerNames),
|
|
environment: z.record(z.string(), credentialValue),
|
|
}).strict().superRefine((credential, ctx) => {
|
|
const names = Object.keys(credential.environment).sort();
|
|
const sets: readonly (readonly string[])[] = ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS[credential.provider];
|
|
if (!sets.some(set => set.length === names.length && [...set].sort().every((name, index) => name === names[index]))) {
|
|
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Select one complete credential for the provider", path: ["environment"] });
|
|
}
|
|
});
|
|
|
|
export const ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS = ["codex", "grok"] as const;
|
|
export type PluginEnvironmentTaskAuthFileProvider = typeof ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS[number];
|
|
|
|
/** Only provider authentication is transferred. Paths and executable settings remain provider-owned. */
|
|
export const environmentTaskCredentialSchema = z.discriminatedUnion("type", [
|
|
z.object({ type: z.literal("auth-file"), provider: z.enum(ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS), content: credentialValue }).strict(),
|
|
z.object({ type: z.literal("claude-env"), environment: claudeCredentialEnvironment }).strict(),
|
|
providerCredential,
|
|
]);
|
|
export type PluginEnvironmentTaskCredential = z.infer<typeof environmentTaskCredentialSchema>;
|
|
|
|
/** Runner owns this versioned data contract. The plugin resolves its execution-host locations. */
|
|
export const environmentRunnerLaunchRequirementsSchema = z.object({
|
|
schema: z.literal("paperclip.runner.launch-requirements.v1"),
|
|
identity: durableIdentity,
|
|
provider: z.enum(["codex", "opencode", "acpx", "claude_managed", "aws_agentcore"]),
|
|
model: z.string().min(1).nullable(), instructions: z.string().max(1024 * 1024),
|
|
runtimeContext: z.record(z.string(), z.unknown()).nullable(),
|
|
settings: z.object({ acpxAgent: identifier.optional(), acpxMode: z.string().optional(),
|
|
acpxPermissionMode: z.enum(["approve-all", "approve-paperclip", "approve-reads", "deny-all"]).optional(),
|
|
acpxPermissionModePinned: z.boolean().optional(), piThinkingLevel: z.enum(["off", "low", "high", "max"]).optional(),
|
|
claudeEffort: z.enum(["low", "medium", "high", "xhigh", "max"]).optional(),
|
|
grokEffort: z.enum(["minimal", "low", "medium", "high", "xhigh"]).optional(),
|
|
grokDisableWebSearch: z.boolean().optional(),
|
|
opencodePermissionMode: z.enum(["allow", "ask", "deny"]).optional(),
|
|
disableCodexWebSearch: z.literal(true).optional(),
|
|
disableCodexProjectInstructions: z.literal(true).optional(),
|
|
managedProfile: z.record(z.string(), z.unknown()).optional(), agentCoreProfile: z.record(z.string(), z.unknown()).optional(),
|
|
}).strict(),
|
|
approvalPolicy: z.enum(["never", "on-request", "untrusted"]), readOnly: z.boolean(),
|
|
preparedConversation: z.boolean(), includeCollaborationModeInstructions: z.boolean(),
|
|
}).strict();
|
|
const preparedLaunch = z.object({ configurationId: providerId.max(1024),
|
|
requirementsDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),
|
|
provider: z.record(z.string(), z.unknown()),
|
|
}).strict();
|
|
|
|
/** One plugin-provided Runner execution attempt with a PRP connection. Secrets are transient RPC input. */
|
|
export const environmentTaskOperationSchema = z.discriminatedUnion("kind", [
|
|
z.object({ kind: z.literal("describe") }).strict(),
|
|
z.object({ kind: z.literal("copilot_metadata"), token: credentialValue, model: z.string().min(1).max(1024).optional() }).strict(),
|
|
z.object({ kind: z.literal("prepare"), requirements: environmentRunnerLaunchRequirementsSchema,
|
|
githubBroker: githubBroker.optional(),
|
|
recovery: preparedLaunch.optional(), resumeFrom: providerId.optional(),
|
|
priorIdentity: durableIdentity.optional(), accountIdentity: z.string().min(1).max(1024).optional(),
|
|
preparationDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(),
|
|
runDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(),
|
|
projectIds: z.array(z.string().uuid()).max(64).refine(ids => new Set(ids).size === ids.length, "Duplicate project IDs"),
|
|
}).strict(),
|
|
z.object({
|
|
kind: z.literal("submit"),
|
|
projectIds: z.array(z.string().uuid()).max(64).refine(ids => new Set(ids).size === ids.length, "Duplicate project IDs"),
|
|
runner: z.object({
|
|
/** Inclusive PRP version range supported by the submitting client. */
|
|
protocolMin: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
|
|
protocolMax: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
|
|
harness: identifier,
|
|
runnerId: runnerIdentity, leaseId: runnerIdentity, runId: runnerIdentity,
|
|
sessionId: runnerIdentity, turnId: runnerIdentity, itemId: runnerIdentity,
|
|
}).strict().refine(value => value.protocolMin <= value.protocolMax, "Invalid PRP version range"),
|
|
bootstrapTicket: z.string().min(1).max(65_536),
|
|
/** Opaque prior provider task; Core authorizes the saved session before supplying it. */
|
|
resumeFrom: z.string().min(1).optional(),
|
|
preparedLaunchId: providerId.max(1024).optional(),
|
|
/** Require the externally installed account to match this Core-selected credential revision. */
|
|
credentialIdentity: z.string().min(1).max(1024).optional(),
|
|
/** Stable account selection; distinct from its current credential revision. */
|
|
accountIdentity: z.string().min(1).max(1024).optional(),
|
|
credential: environmentTaskCredentialSchema.optional(),
|
|
configuredEnvironment: environmentTaskConfiguredEnvironmentSchema.optional(),
|
|
/** Core supplies these protected launch inputs for native agent runs. */
|
|
launch: z.object({
|
|
runnerVersion: z.string().min(1), runnerDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),
|
|
maxOutboxBytes: z.number().int().positive(), p0ReserveBytes: z.number().int().positive(),
|
|
maxRuntimeMs: z.number().int().nonnegative().optional(), maxLifetimeMs: z.number().int().nonnegative().optional(),
|
|
reconnectGraceMs: z.number().int().nonnegative().optional(),
|
|
lifecyclePolicy: z.discriminatedUnion("mode", [
|
|
z.object({ mode: z.literal("per_turn"), idleTimeoutMs: z.null() }).strict(),
|
|
z.object({ mode: z.literal("warm"), idleTimeoutMs: z.number().int().positive().max(86_400_000) }).strict(),
|
|
]),
|
|
}).strict().optional(),
|
|
}).strict(),
|
|
z.object({ kind: z.literal("check_project_auth"), configurationId: providerId.max(1024),
|
|
provider: identifier, projectIds: z.array(z.string().uuid()).max(64)
|
|
.refine(ids => new Set(ids).size === ids.length, "Duplicate project IDs") }).strict(),
|
|
z.object({ kind: z.literal("read_file"), identity: durableIdentity,
|
|
path: taskFilePath, maxBytes: z.number().int().positive().max(MAX_ENVIRONMENT_TASK_FILE_BYTES),
|
|
projectIds: z.array(z.string().uuid()).max(64).refine(ids => new Set(ids).size === ids.length, "Duplicate project IDs"),
|
|
}).strict(),
|
|
z.object({ kind: z.literal("read_state"), identity: durableIdentity, resumeFrom: providerId.optional() }).strict(),
|
|
z.object({ kind: z.literal("archive_state"), priorIdentity: durableIdentity,
|
|
archiveKey: z.string().regex(/^[a-f0-9]{24}$/), resumeFrom: providerId }).strict(),
|
|
z.object({ kind: z.literal("credentials"), accountIdentity: z.string().min(1).max(1024) }).strict(),
|
|
z.object({ kind: z.literal("status") }).strict(),
|
|
z.object({ kind: z.literal("connection") }).strict(),
|
|
z.object({ kind: z.literal("release"), identity: durableIdentity }).strict(),
|
|
z.object({ kind: z.literal("resume"), identity: durableIdentity, bootstrapTicket: credentialValue,
|
|
handoffCredential: z.object({ accountIdentity: z.string().min(1).max(1024), environment: claudeCredentialEnvironment }).strict().optional(),
|
|
credential: environmentTaskCredentialSchema.optional(),
|
|
configuredEnvironment: environmentTaskConfiguredEnvironmentSchema.optional(),
|
|
relaunchedRunnerVersion: z.literal(1).optional(),
|
|
runner: z.object({ runId: runnerIdentity, turnId: runnerIdentity, itemId: runnerIdentity }).strict().optional(),
|
|
}).strict(),
|
|
z.object({
|
|
kind: z.literal("ensure_ownership"),
|
|
operationId: z.string().uuid(),
|
|
identity: durableIdentity,
|
|
sourceTaskId: providerId.max(1024),
|
|
sourceGeneration: providerId.max(1024),
|
|
targetGeneration: providerId.max(1024),
|
|
policy: z.enum(["ordinary", "reclaim_if_needed"]),
|
|
}).strict(),
|
|
z.object({ kind: z.literal("complete") }).strict(),
|
|
z.object({ kind: z.literal("stop") }).strict(),
|
|
]);
|
|
|
|
const runnerArtifact = z.object({ version: z.string().min(1), digest: z.string().regex(/^sha256:[a-f0-9]{64}$/) }).strict();
|
|
|
|
export const environmentTaskResultSchema = z.discriminatedUnion("kind", [
|
|
z.object({ kind: z.literal("accepted"), taskId: providerId }).strict(),
|
|
z.object({ kind: z.literal("admission_rejected"), taskId: providerId,
|
|
reason: z.enum(["session_state_unavailable", "account_binding_mismatch"]) }).strict(),
|
|
z.object({ kind: z.literal("released"), taskId: providerId }).strict(),
|
|
z.object({ kind: z.literal("resume"), taskId: providerId, outcome: z.enum(["resumed", "unavailable"]), runner: runnerArtifact.optional() }).strict(),
|
|
z.object({
|
|
kind: z.literal("ownership"),
|
|
taskId: providerId,
|
|
operationId: z.string().uuid(),
|
|
targetGeneration: providerId.max(1024),
|
|
status: z.enum(["pending", "ready"]),
|
|
checkpointUnavailable: z.literal(true).optional(),
|
|
}).strict(),
|
|
z.object({ kind: z.literal("copilot_metadata"), taskId: providerId, metadata: z.record(z.string(), z.unknown()),
|
|
executionStopped: z.literal(true) }).strict(),
|
|
z.object({ kind: z.literal("project_auth"), taskId: providerId, configurationId: providerId.max(1024),
|
|
provider: identifier, allowed: z.boolean() }).strict(),
|
|
z.object({ kind: z.literal("file"), taskId: providerId,
|
|
base64: z.string().max(4 * Math.ceil(MAX_ENVIRONMENT_TASK_FILE_BYTES / 3)),
|
|
byteSize: z.number().int().nonnegative().max(MAX_ENVIRONMENT_TASK_FILE_BYTES),
|
|
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
|
}).strict(),
|
|
z.object({ kind: z.literal("state"), taskId: providerId, state: z.record(z.string(), z.unknown()) }).strict(),
|
|
z.object({ kind: z.literal("prepared"), taskId: providerId, launch: preparedLaunch, projectAuthCheckAtSubmit: z.literal(true).optional(),
|
|
projectAuthChecked: z.literal(true).optional() }).strict(),
|
|
z.object({ kind: z.literal("credentials"), taskId: providerId, /** Null proves that cancellation fenced admission before the task could start. It must not mean an unavailable export. */
|
|
credential: environmentTaskCredentialSchema.nullable() }).strict(),
|
|
z.object({ kind: z.literal("description"), taskId: providerId,
|
|
runner: runnerArtifact,
|
|
warmTaskVersion: z.literal(1).optional(),
|
|
releaseResumeVersion: z.literal(1).optional(),
|
|
sessionHandoffVersion: z.literal(1).optional(),
|
|
launchPreparationVersion: z.literal(1).optional(),
|
|
executionContextVersion: z.literal(1).optional(),
|
|
/** Each version attests stopped-source recovery for its provider independently. */
|
|
codexSourceRecoveryVersion: z.literal(1).optional(),
|
|
acpxSourceRecoveryVersion: z.literal(1).optional(),
|
|
freshWorkspaceVersion: z.literal(1).optional(),
|
|
projectAuthCheckVersion: z.literal(1).optional(),
|
|
workspaceFileReadVersion: z.literal(1).optional(),
|
|
githubCredentialBrokerVersion: z.literal(1).optional(),
|
|
configuredEnvironmentVersion: z.literal(1).optional(),
|
|
resumeLaunchInputsVersion: z.literal(1).optional(),
|
|
resumeRelaunchedRunnerVersion: z.literal(1).optional(),
|
|
resumeIdentityVersion: z.literal(1).optional(),
|
|
launchDigestVersion: z.literal(1).optional(),
|
|
}).strict(),
|
|
z.object({
|
|
kind: z.literal("status"), taskId: providerId,
|
|
phase: z.enum(["preparing", "running", "completed", "failed", "cancelled", "interrupted"]),
|
|
exitCode: z.number().int().optional(),
|
|
/** Provider observed the task and all descendants stopped; terminal phase alone is insufficient. */
|
|
executionStopped: z.boolean().optional(),
|
|
preparationStopped: z.boolean().optional(),
|
|
/** The provider retains this task's recoverable session state for a later launch. */
|
|
sessionStateAvailable: z.boolean().optional(),
|
|
}).strict(),
|
|
z.object({
|
|
kind: z.literal("connection"), taskId: providerId,
|
|
endpoint: z.object({
|
|
kind: z.literal("authenticated_websocket"), websocketUrl: secureUrl,
|
|
generation: providerId,
|
|
secretHeaders: z.array(z.object({
|
|
name: z.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/),
|
|
value: z.string().min(1).max(65_536).regex(/^[^\r\n]+$/),
|
|
}).strict()).max(16),
|
|
}).strict(),
|
|
}).strict(),
|
|
]);
|
|
|
|
export type PluginEnvironmentRunnerLaunchRequirements = z.infer<typeof environmentRunnerLaunchRequirementsSchema>;
|
|
export type PluginEnvironmentPreparedLaunch = z.infer<typeof preparedLaunch>;
|
|
|
|
export type PluginEnvironmentTaskOperation = z.infer<typeof environmentTaskOperationSchema>;
|
|
export type PluginEnvironmentTaskResult = z.infer<typeof environmentTaskResultSchema>;
|
|
|
|
export interface PluginEnvironmentTaskExecutionContext {
|
|
id: string;
|
|
deadlineAtMs: number;
|
|
transport: {
|
|
instanceSecrets: PluginAgentRuntimeIdentity["instanceSecrets"];
|
|
configuration: Record<string, unknown>;
|
|
};
|
|
}
|
|
|
|
export interface PluginEnvironmentTaskParams extends Omit<PluginEnvironmentDriverBaseParams, "environmentId"> {
|
|
/** Null during cleanup after the environment is deleted. */
|
|
environmentId: string | null;
|
|
lease: PluginEnvironmentLease;
|
|
/** Provider-issued task identifier persisted in the lease, stable across ambiguous submission retries. */
|
|
taskId: string;
|
|
/** Null during cleanup after the associated run is deleted. */
|
|
runId: string | null;
|
|
agentId: string | null;
|
|
/** Company-validated projects to prepare on submit; empty during cleanup. */
|
|
projectIds: string[];
|
|
workspace?: import("@paperclipai/shared").WorkspaceProviderBinding;
|
|
fresh?: import("./workspace-provider.js").PluginFreshWorkspace;
|
|
operation: PluginEnvironmentTaskOperation;
|
|
executionContextSupported?: 1;
|
|
executionContext?: PluginEnvironmentTaskExecutionContext;
|
|
}
|
|
|
|
/** An accepted stop is not proof of process termination. */
|
|
export function parseEnvironmentTaskResult(operation: PluginEnvironmentTaskOperation, taskId: string, value: unknown): PluginEnvironmentTaskResult {
|
|
const result = environmentTaskResultSchema.parse(value);
|
|
if (operation.kind === "ensure_ownership") {
|
|
if (result.kind !== "ownership" || result.taskId !== taskId || result.operationId !== operation.operationId ||
|
|
result.targetGeneration !== operation.targetGeneration) {
|
|
throw new Error("Invalid plugin-provided session ownership response");
|
|
}
|
|
return result;
|
|
}
|
|
const expected = operation.kind === "release" ? "released" : operation.kind === "resume" ? "resume" : operation.kind === "read_file" ? "file" : operation.kind === "describe" ? "description" : operation.kind === "prepare" ? "prepared" : operation.kind === "check_project_auth" ? "project_auth" : ["read_state", "archive_state"].includes(operation.kind) ? "state" : ["status", "connection", "credentials", "copilot_metadata"].includes(operation.kind) ? operation.kind : "accepted";
|
|
const rejectedSubmit = operation.kind === "submit" && result.kind === "admission_rejected";
|
|
if (result.taskId !== taskId || (result.kind !== expected && !rejectedSubmit)) throw new Error("Invalid plugin-provided Runner execution response");
|
|
if (operation.kind === "resume" && result.kind === "resume" && operation.runner && result.outcome === "resumed" && !result.runner) {
|
|
throw new Error("Invalid plugin-provided Runner execution response");
|
|
}
|
|
return result;
|
|
}
|