@microvac/plugin-sdk 0.0.0-stage → 0.1.0-rc.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1630 -2
  3. package/dist/.paperclip-build-complete +1 -0
  4. package/dist/bundlers.d.ts +57 -0
  5. package/dist/bundlers.d.ts.map +1 -0
  6. package/dist/bundlers.js +106 -0
  7. package/dist/bundlers.js.map +1 -0
  8. package/dist/define-plugin.d.ts +444 -0
  9. package/dist/define-plugin.d.ts.map +1 -0
  10. package/dist/define-plugin.js +37 -0
  11. package/dist/define-plugin.js.map +1 -0
  12. package/dist/dev-cli.d.ts +3 -0
  13. package/dist/dev-cli.d.ts.map +1 -0
  14. package/dist/dev-cli.js +49 -0
  15. package/dist/dev-cli.js.map +1 -0
  16. package/dist/dev-server.d.ts +34 -0
  17. package/dist/dev-server.d.ts.map +1 -0
  18. package/dist/dev-server.js +194 -0
  19. package/dist/dev-server.js.map +1 -0
  20. package/dist/environment-acquire-error.d.ts +19 -0
  21. package/dist/environment-acquire-error.d.ts.map +1 -0
  22. package/dist/environment-acquire-error.js +44 -0
  23. package/dist/environment-acquire-error.js.map +1 -0
  24. package/dist/environment-creation-cleanup.d.ts +45 -0
  25. package/dist/environment-creation-cleanup.d.ts.map +1 -0
  26. package/dist/environment-creation-cleanup.js +105 -0
  27. package/dist/environment-creation-cleanup.js.map +1 -0
  28. package/dist/environment-resume-error.d.ts +35 -0
  29. package/dist/environment-resume-error.d.ts.map +1 -0
  30. package/dist/environment-resume-error.js +67 -0
  31. package/dist/environment-resume-error.js.map +1 -0
  32. package/dist/environment-runner-ingress-error.d.ts +13 -0
  33. package/dist/environment-runner-ingress-error.d.ts.map +1 -0
  34. package/dist/environment-runner-ingress-error.js +39 -0
  35. package/dist/environment-runner-ingress-error.js.map +1 -0
  36. package/dist/environment-stop-error.d.ts +14 -0
  37. package/dist/environment-stop-error.d.ts.map +1 -0
  38. package/dist/environment-stop-error.js +44 -0
  39. package/dist/environment-stop-error.js.map +1 -0
  40. package/dist/environment-sync-error.d.ts +25 -0
  41. package/dist/environment-sync-error.d.ts.map +1 -0
  42. package/dist/environment-sync-error.js +125 -0
  43. package/dist/environment-sync-error.js.map +1 -0
  44. package/dist/environment-task-error.d.ts +25 -0
  45. package/dist/environment-task-error.d.ts.map +1 -0
  46. package/dist/environment-task-error.js +73 -0
  47. package/dist/environment-task-error.js.map +1 -0
  48. package/dist/environment-tasks.d.ts +565 -0
  49. package/dist/environment-tasks.d.ts.map +1 -0
  50. package/dist/environment-tasks.js +269 -0
  51. package/dist/environment-tasks.js.map +1 -0
  52. package/dist/host-client-factory.d.ts +336 -0
  53. package/dist/host-client-factory.d.ts.map +1 -0
  54. package/dist/host-client-factory.js +754 -0
  55. package/dist/host-client-factory.js.map +1 -0
  56. package/dist/idle-drain.d.ts +14 -0
  57. package/dist/idle-drain.d.ts.map +1 -0
  58. package/dist/idle-drain.js +72 -0
  59. package/dist/idle-drain.js.map +1 -0
  60. package/dist/idle-drain.test.d.ts +2 -0
  61. package/dist/idle-drain.test.d.ts.map +1 -0
  62. package/dist/idle-drain.test.js +52 -0
  63. package/dist/idle-drain.test.js.map +1 -0
  64. package/dist/index.d.ts +110 -0
  65. package/dist/index.d.ts.map +1 -0
  66. package/dist/index.js +97 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/invocation-tracer.d.ts +10 -0
  69. package/dist/invocation-tracer.d.ts.map +1 -0
  70. package/dist/invocation-tracer.js +61 -0
  71. package/dist/invocation-tracer.js.map +1 -0
  72. package/dist/protocol.d.ts +2519 -0
  73. package/dist/protocol.d.ts.map +1 -0
  74. package/dist/protocol.duplex-channel.test.d.ts +2 -0
  75. package/dist/protocol.duplex-channel.test.d.ts.map +1 -0
  76. package/dist/protocol.duplex-channel.test.js +229 -0
  77. package/dist/protocol.duplex-channel.test.js.map +1 -0
  78. package/dist/protocol.js +368 -0
  79. package/dist/protocol.js.map +1 -0
  80. package/dist/testing.d.ts +258 -0
  81. package/dist/testing.d.ts.map +1 -0
  82. package/dist/testing.js +2624 -0
  83. package/dist/testing.js.map +1 -0
  84. package/dist/types.d.ts +2028 -0
  85. package/dist/types.d.ts.map +1 -0
  86. package/dist/types.js +23 -0
  87. package/dist/types.js.map +1 -0
  88. package/dist/ui/clipboard.d.ts +8 -0
  89. package/dist/ui/clipboard.d.ts.map +1 -0
  90. package/dist/ui/clipboard.js +12 -0
  91. package/dist/ui/clipboard.js.map +1 -0
  92. package/dist/ui/components.d.ts +518 -0
  93. package/dist/ui/components.d.ts.map +1 -0
  94. package/dist/ui/components.js +135 -0
  95. package/dist/ui/components.js.map +1 -0
  96. package/dist/ui/hooks.d.ts +155 -0
  97. package/dist/ui/hooks.d.ts.map +1 -0
  98. package/dist/ui/hooks.js +195 -0
  99. package/dist/ui/hooks.js.map +1 -0
  100. package/dist/ui/index.d.ts +55 -0
  101. package/dist/ui/index.d.ts.map +1 -0
  102. package/dist/ui/index.js +52 -0
  103. package/dist/ui/index.js.map +1 -0
  104. package/dist/ui/runtime.d.ts +3 -0
  105. package/dist/ui/runtime.d.ts.map +1 -0
  106. package/dist/ui/runtime.js +30 -0
  107. package/dist/ui/runtime.js.map +1 -0
  108. package/dist/ui/types.d.ts +423 -0
  109. package/dist/ui/types.d.ts.map +1 -0
  110. package/dist/ui/types.js +17 -0
  111. package/dist/ui/types.js.map +1 -0
  112. package/dist/worker-rpc-host.d.ts +93 -0
  113. package/dist/worker-rpc-host.d.ts.map +1 -0
  114. package/dist/worker-rpc-host.js +2086 -0
  115. package/dist/worker-rpc-host.js.map +1 -0
  116. package/dist/workspace-operation-error.d.ts +46 -0
  117. package/dist/workspace-operation-error.d.ts.map +1 -0
  118. package/dist/workspace-operation-error.js +78 -0
  119. package/dist/workspace-operation-error.js.map +1 -0
  120. package/dist/workspace-provider.d.ts +395 -0
  121. package/dist/workspace-provider.d.ts.map +1 -0
  122. package/dist/workspace-provider.js +182 -0
  123. package/dist/workspace-provider.js.map +1 -0
  124. package/package.json +85 -4
@@ -0,0 +1,2028 @@
1
+ /**
2
+ * Core types for the Paperclip plugin worker-side SDK.
3
+ *
4
+ * These types define the stable public API surface that plugin workers import
5
+ * from `@paperclipai/plugin-sdk`. The host provides a concrete implementation
6
+ * of `PluginContext` to the plugin at initialisation time.
7
+ *
8
+ * @see PLUGIN_SPEC.md §14 — SDK Surface
9
+ * @see PLUGIN_SPEC.md §29.2 — SDK Versioning
10
+ */
11
+ import type { RunStartupStage, PaperclipPluginManifestV1, PluginStateScopeKind, PluginEventType, PluginEntityQuery, PluginToolDeclaration, PluginLauncherDeclaration, Company, Project, Issue, IssueComment, IssueDocument, IssueDocumentSummary, IssueRelationIssueSummary, IssueAssigneeAdapterOverrides, IssueAttachment, IssueThreadInteraction, Approval, SuggestTasksInteraction, AskUserQuestionsInteraction, RequestConfirmationInteraction, RequestCheckboxConfirmationInteraction, CreateIssueThreadInteractionInput, PluginIssueOriginKind, IssueSurfaceVisibility, PluginManagedAgentResolution, PluginManagedProjectResolution, PluginManagedRoutineResolution, PluginManagedSkillResolution, Routine, RoutineRun, Agent, Goal, HumanCompanyMembershipRole, InviteJoinType, MembershipStatus, PermissionKey, PrincipalPermissionGrant, PrincipalType, EnvSecretRefBinding } from "@paperclipai/shared";
12
+ import type { PluginPerformActionContext } from "./protocol.js";
13
+ export type { PaperclipPluginManifestV1, PluginEntityQuery, PluginJobDeclaration, PluginWebhookDeclaration, PluginToolDeclaration, PluginEnvironmentDriverDeclaration, PluginEnvironmentTemplateConfigBinding, PluginManagedAgentDeclaration, PluginManagedAgentResolution, PluginManagedProjectDeclaration, PluginManagedProjectResolution, PluginManagedRoutineDeclaration, PluginManagedRoutineResolution, PluginManagedSkillDeclaration, PluginManagedSkillFileDeclaration, PluginManagedSkillResolution, CompanySkill, Routine, RoutineRun, PluginLocalFolderDeclaration, PluginCompanySettings, PluginManagedResourceKind, PluginManagedResourceRef, PluginUiSlotDeclaration, PluginUiDeclaration, PluginLauncherActionDeclaration, PluginLauncherRenderDeclaration, PluginLauncherDeclaration, PluginMinimumHostVersion, PluginDatabaseDeclaration, PluginApiRouteDeclaration, PluginApiRouteCompanyResolution, PluginObjectReferenceRefreshPolicy, PluginObjectReferenceProviderDeclaration, PluginRecord, PluginDatabaseNamespaceRecord, PluginMigrationRecord, PluginConfig, JsonSchema, PluginStatus, PluginCategory, PluginCapability, PluginUiSlotType, PluginUiSlotEntityType, PluginLauncherPlacementZone, PluginLauncherAction, PluginLauncherBounds, PluginLauncherRenderEnvironment, PluginStateScopeKind, PluginJobStatus, PluginJobRunStatus, PluginJobRunTrigger, PluginWebhookDeliveryStatus, PluginDatabaseCoreReadTable, PluginDatabaseMigrationStatus, PluginDatabaseNamespaceMode, PluginDatabaseNamespaceStatus, PluginApiRouteAuthMode, PluginApiRouteCheckoutPolicy, PluginApiRouteMethod, PluginEventType, PluginBridgeErrorCode, Company, Project, Issue, IssueComment, IssueDocument, IssueDocumentSummary, IssueRelationIssueSummary, IssueThreadInteraction, ConnectionIntentInteraction, ConnectionIntentPayload, ConnectionIntentResult, ConnectionIntentSetupOptions, ConnectionRequestResult, ConnectionsSearchResult, SuggestTasksInteraction, AskUserQuestionsInteraction, RequestConfirmationInteraction, RequestCheckboxConfirmationInteraction, CreateIssueThreadInteraction, CreateIssueThreadInteractionInput, PluginIssueOriginKind, IssueSurfaceVisibility, Agent, Goal, HumanCompanyMembershipRole, InviteJoinType, MembershipStatus, PermissionKey, PrincipalPermissionGrant, PrincipalType, EnvSecretRefBinding, } from "@paperclipai/shared";
14
+ /**
15
+ * A scope key identifies the exact location where plugin state is stored.
16
+ * Scope is partitioned by `scopeKind` and optional `scopeId`.
17
+ *
18
+ * Examples:
19
+ * - `{ scopeKind: "instance" }` — single global value for the whole instance
20
+ * - `{ scopeKind: "project", scopeId: "proj-uuid" }` — per-project state
21
+ * - `{ scopeKind: "issue", scopeId: "iss-uuid" }` — per-issue state
22
+ *
23
+ * @see PLUGIN_SPEC.md §21.3 `plugin_state`
24
+ */
25
+ export interface ScopeKey {
26
+ /** What kind of Paperclip object this state is scoped to. */
27
+ scopeKind: PluginStateScopeKind;
28
+ /** UUID or text identifier for the scoped object. Omit for `instance` scope. */
29
+ scopeId?: string;
30
+ /** Optional sub-namespace within the scope to avoid key collisions. Defaults to `"default"`. */
31
+ namespace?: string;
32
+ /** The state key within the namespace. */
33
+ stateKey: string;
34
+ }
35
+ /**
36
+ * Optional filter applied when subscribing to an event. The host evaluates
37
+ * the filter server-side so filtered-out events never cross the process boundary.
38
+ *
39
+ * All filter fields are optional. If omitted the plugin receives every event
40
+ * of the subscribed type.
41
+ *
42
+ * @see PLUGIN_SPEC.md §16.1 — Event Filtering
43
+ */
44
+ export interface EventFilter {
45
+ /** Only receive events for this project. */
46
+ projectId?: string;
47
+ /** Only receive events for this company. */
48
+ companyId?: string;
49
+ /** Only receive events for this agent. */
50
+ agentId?: string;
51
+ /** Additional arbitrary filter fields. */
52
+ [key: string]: unknown;
53
+ }
54
+ /**
55
+ * Envelope wrapping every domain event delivered to a plugin worker.
56
+ *
57
+ * @see PLUGIN_SPEC.md §16 — Event System
58
+ */
59
+ export interface PluginEvent<TPayload = unknown> {
60
+ /** Unique event identifier (UUID). */
61
+ eventId: string;
62
+ /** The event type (e.g. `"issue.created"`). */
63
+ eventType: PluginEventType | `plugin.${string}`;
64
+ /** ISO 8601 timestamp when the event occurred. */
65
+ occurredAt: string;
66
+ /** ID of the actor that caused the event, if applicable. */
67
+ actorId?: string;
68
+ /** Type of actor: `"user"`, `"agent"`, `"system"`, or `"plugin"`. */
69
+ actorType?: "user" | "agent" | "system" | "plugin";
70
+ /** Primary entity involved in the event. */
71
+ entityId?: string;
72
+ /** Type of the primary entity. */
73
+ entityType?: string;
74
+ /** UUID of the company this event belongs to. */
75
+ companyId: string;
76
+ /** Typed event payload. */
77
+ payload: TPayload;
78
+ }
79
+ /**
80
+ * Context passed to a plugin job handler when the host triggers a scheduled run.
81
+ *
82
+ * @see PLUGIN_SPEC.md §13.6 — `runJob`
83
+ */
84
+ export interface PluginJobContext {
85
+ /** Stable job key matching the declaration in the manifest. */
86
+ jobKey: string;
87
+ /** UUID for this specific job run instance. */
88
+ runId: string;
89
+ /** What triggered this run. */
90
+ trigger: "schedule" | "manual" | "retry";
91
+ /** ISO 8601 timestamp when the run was scheduled to start. */
92
+ scheduledAt: string;
93
+ }
94
+ /**
95
+ * Run context passed to a plugin tool handler when an agent invokes the tool.
96
+ *
97
+ * @see PLUGIN_SPEC.md §13.10 — `executeTool`
98
+ */
99
+ export interface ToolRunContext {
100
+ /** UUID of the agent invoking the tool. */
101
+ agentId: string;
102
+ /** UUID of the current agent run. */
103
+ runId: string;
104
+ /** UUID of the company the run belongs to. */
105
+ companyId: string;
106
+ /**
107
+ * UUID of the project the run belongs to, or an empty string when the run
108
+ * has no project. Check the value before you use it as a project ID.
109
+ */
110
+ projectId: string;
111
+ /**
112
+ * The connection this call runs on. Present only for tools of a plugin
113
+ * connector (`ctx.connectors.register`). The host resolves it from the
114
+ * gateway session; tool arguments can never change it.
115
+ */
116
+ connection?: ToolRunConnection;
117
+ }
118
+ /**
119
+ * A credential the host resolved for one connector call. It is valid for
120
+ * that call only; the worker never reads the vault and never sees another
121
+ * connection's credential.
122
+ */
123
+ export interface ConnectionCredential {
124
+ kind: "api_key";
125
+ value: string;
126
+ }
127
+ /** The connection a plugin connector tool runs on. */
128
+ export interface ToolRunConnection {
129
+ /** Connection id. */
130
+ id: string;
131
+ /** The app slug as declared in the manifest (not namespaced). */
132
+ appSlug: string;
133
+ /** The connection method key from the manifest. */
134
+ methodKey: string;
135
+ /** The grant whose credential the host resolved for this call. */
136
+ grantId: string;
137
+ /** Per-connection settings, validated against the method's `settingsSchema`. */
138
+ settings: Record<string, unknown>;
139
+ /** Present when the method authenticates. */
140
+ credential?: ConnectionCredential;
141
+ }
142
+ /** The connection passed to `ctx.connectors.listTools`. */
143
+ export type ConnectorToolListConnection = Omit<ToolRunConnection, "grantId"> & {
144
+ grantId?: string;
145
+ };
146
+ /** One tool a dynamic plugin connector offers for a connection. */
147
+ export interface ConnectorToolDescriptor {
148
+ /** Lowercase letters, digits and underscores. */
149
+ name: string;
150
+ displayName?: string;
151
+ description?: string;
152
+ risk: "read" | "write" | "destructive";
153
+ parametersSchema: Record<string, unknown>;
154
+ }
155
+ /** Tool run context for a plugin connector tool: `connection` is always present. */
156
+ export type ConnectorToolRunContext = ToolRunContext & {
157
+ connection: ToolRunConnection;
158
+ };
159
+ /**
160
+ * Result returned from a plugin tool handler.
161
+ *
162
+ * @see PLUGIN_SPEC.md §13.10 — `executeTool`
163
+ */
164
+ export interface ToolResult {
165
+ /** String content returned to the agent. Required for success responses. */
166
+ content?: string;
167
+ /** Structured data returned alongside or instead of string content. */
168
+ data?: unknown;
169
+ /** If present, indicates the tool call failed. */
170
+ error?: string;
171
+ }
172
+ /**
173
+ * Input for creating or updating a plugin-owned entity.
174
+ *
175
+ * @see PLUGIN_SPEC.md §21.3 `plugin_entities`
176
+ */
177
+ export interface PluginEntityUpsert {
178
+ /** Plugin-defined entity type (e.g. `"linear-issue"`, `"github-pr"`). */
179
+ entityType: string;
180
+ /** Scope where this entity lives. */
181
+ scopeKind: PluginStateScopeKind;
182
+ /** Optional scope ID. */
183
+ scopeId?: string;
184
+ /** External identifier in the remote system (e.g. Linear issue ID). */
185
+ externalId?: string;
186
+ /** Human-readable title for display in the Paperclip UI. */
187
+ title?: string;
188
+ /** Optional status string. */
189
+ status?: string;
190
+ /** Full entity data blob. Must be JSON-serializable. */
191
+ data: Record<string, unknown>;
192
+ }
193
+ /**
194
+ * A plugin-owned entity record as returned by `ctx.entities.list()`.
195
+ *
196
+ * @see PLUGIN_SPEC.md §21.3 `plugin_entities`
197
+ */
198
+ export interface PluginEntityRecord {
199
+ /** UUID primary key. */
200
+ id: string;
201
+ /** Plugin-defined entity type. */
202
+ entityType: string;
203
+ /** Scope kind. */
204
+ scopeKind: PluginStateScopeKind;
205
+ /** Scope ID, if any. */
206
+ scopeId: string | null;
207
+ /** External identifier, if any. */
208
+ externalId: string | null;
209
+ /** Human-readable title. */
210
+ title: string | null;
211
+ /** Status string. */
212
+ status: string | null;
213
+ /** Full entity data. */
214
+ data: Record<string, unknown>;
215
+ /** ISO 8601 creation timestamp. */
216
+ createdAt: string;
217
+ /** ISO 8601 last-updated timestamp. */
218
+ updatedAt: string;
219
+ }
220
+ /**
221
+ * Workspace metadata provided by the host. Plugins use this to resolve local
222
+ * filesystem paths for file browsing, git, terminal, and process operations.
223
+ *
224
+ * @see PLUGIN_SPEC.md §7 — Project Workspaces
225
+ * @see PLUGIN_SPEC.md §20 — Local Tooling
226
+ */
227
+ export interface PluginWorkspace {
228
+ /** UUID primary key. */
229
+ id: string;
230
+ /** UUID of the parent project. */
231
+ projectId: string;
232
+ /** Display name for this workspace. */
233
+ name: string;
234
+ /** Absolute filesystem path to the workspace directory. */
235
+ path: string;
236
+ /** Repository URL, when known. */
237
+ repoUrl: string | null;
238
+ /** Checkout/ref requested for the workspace, when known. */
239
+ repoRef: string | null;
240
+ /** Default comparison ref for workspace tooling, when known. */
241
+ defaultRef: string | null;
242
+ /** Whether this is the project's primary workspace. */
243
+ isPrimary: boolean;
244
+ /** ISO 8601 creation timestamp. */
245
+ createdAt: string;
246
+ /** ISO 8601 last-updated timestamp. */
247
+ updatedAt: string;
248
+ }
249
+ /**
250
+ * Plugin-safe execution workspace metadata provided by the host. This exposes
251
+ * the local/repository coordinates plugins need for workspace tooling without
252
+ * giving the SDK a host-owned diff engine.
253
+ */
254
+ export interface PluginExecutionWorkspaceMetadata {
255
+ /** UUID primary key. */
256
+ id: string;
257
+ /** UUID of the owning company. */
258
+ companyId: string;
259
+ projectId: string | null;
260
+ /** UUID of the backing project workspace, when present. */
261
+ projectWorkspaceId: string | null;
262
+ /** Absolute filesystem path to the workspace when locally realized. */
263
+ path: string | null;
264
+ /** Current working directory for local workspace tooling. */
265
+ cwd: string | null;
266
+ /** Repository URL, when known. */
267
+ repoUrl: string | null;
268
+ /** Base ref configured for the workspace, when known. */
269
+ baseRef: string | null;
270
+ /** Branch name configured for the workspace, when known. */
271
+ branchName: string | null;
272
+ /** Host provider type for the realized workspace. */
273
+ providerType: string | null;
274
+ /** Provider metadata already safe for plugin consumption. */
275
+ providerMetadata: Record<string, unknown> | null;
276
+ }
277
+ /**
278
+ * `ctx.config` — read resolved operator configuration for this plugin.
279
+ *
280
+ * Plugin workers receive the resolved config at initialisation. Use `get()`
281
+ * to access the current configuration at any time. The host calls
282
+ * `configChanged` on the worker when the operator updates config at runtime.
283
+ *
284
+ * @see PLUGIN_SPEC.md §13.3 — `validateConfig`
285
+ * @see PLUGIN_SPEC.md §13.4 — `configChanged`
286
+ */
287
+ export interface PluginConfigClient {
288
+ /**
289
+ * Returns the resolved operator configuration for this plugin in a company.
290
+ * When called during a host-scoped invocation, the host may derive the
291
+ * companyId; otherwise callers must pass it explicitly.
292
+ */
293
+ get(companyId?: string): Promise<Record<string, unknown>>;
294
+ }
295
+ export interface PluginLocalFolderProblem {
296
+ code: "not_configured" | "not_absolute" | "missing" | "not_directory" | "not_readable" | "not_writable" | "missing_directory" | "missing_file" | "path_traversal" | "symlink_escape" | "atomic_write_failed";
297
+ message: string;
298
+ path?: string;
299
+ }
300
+ export interface PluginLocalFolderStatus {
301
+ folderKey: string;
302
+ configured: boolean;
303
+ path: string | null;
304
+ realPath: string | null;
305
+ access: "read" | "readWrite";
306
+ readable: boolean;
307
+ writable: boolean;
308
+ requiredDirectories: string[];
309
+ requiredFiles: string[];
310
+ missingDirectories: string[];
311
+ missingFiles: string[];
312
+ healthy: boolean;
313
+ problems: PluginLocalFolderProblem[];
314
+ checkedAt: string;
315
+ }
316
+ export interface PluginLocalFolderConfigureInput {
317
+ companyId: string;
318
+ folderKey: string;
319
+ path: string;
320
+ access?: "read" | "readWrite";
321
+ requiredDirectories?: string[];
322
+ requiredFiles?: string[];
323
+ }
324
+ export interface PluginLocalFolderListOptions {
325
+ relativePath?: string | null;
326
+ recursive?: boolean;
327
+ maxEntries?: number;
328
+ }
329
+ export interface PluginLocalFolderEntry {
330
+ path: string;
331
+ name: string;
332
+ kind: "file" | "directory";
333
+ size: number | null;
334
+ modifiedAt: string | null;
335
+ }
336
+ export interface PluginLocalFolderListing {
337
+ folderKey: string;
338
+ relativePath: string | null;
339
+ entries: PluginLocalFolderEntry[];
340
+ truncated: boolean;
341
+ }
342
+ export interface PluginLocalFoldersClient {
343
+ /** Manifest-declared local folders for this plugin. */
344
+ declarations(): import("@paperclipai/shared").PluginLocalFolderDeclaration[];
345
+ /** Persist a company-scoped local folder path after validating it. */
346
+ configure(input: PluginLocalFolderConfigureInput): Promise<PluginLocalFolderStatus>;
347
+ /** Check the stored folder readiness for a company and folder key. */
348
+ status(companyId: string, folderKey: string): Promise<PluginLocalFolderStatus>;
349
+ /** List entries below a configured folder after containment checks. */
350
+ list(companyId: string, folderKey: string, options?: PluginLocalFolderListOptions): Promise<PluginLocalFolderListing>;
351
+ /** Read a UTF-8 text file below a configured folder after containment checks. */
352
+ readText(companyId: string, folderKey: string, relativePath: string): Promise<string>;
353
+ /** Write a UTF-8 text file below a configured folder using atomic rename. */
354
+ writeTextAtomic(companyId: string, folderKey: string, relativePath: string, contents: string): Promise<PluginLocalFolderStatus>;
355
+ /** Delete a file below a configured folder after containment checks. Missing files are treated as already deleted. */
356
+ deleteFile(companyId: string, folderKey: string, relativePath: string): Promise<PluginLocalFolderStatus>;
357
+ }
358
+ /**
359
+ * `ctx.events` — subscribe to and emit Paperclip domain events.
360
+ *
361
+ * Requires `events.subscribe` capability for `on()`.
362
+ * Requires `events.emit` capability for `emit()`.
363
+ *
364
+ * @see PLUGIN_SPEC.md §16 — Event System
365
+ */
366
+ export interface PluginEventsClient {
367
+ /** Read durable resource hooks. Requires events.subscribe and a company scope.
368
+ * Creation is delivered first, then the remaining events in id order.
369
+ * Prefer manifest resourceLifecycle + onResourceLifecycle for automatic delivery.
370
+ * Manual consumers page using afterId and restart pagination to revisit unacknowledged events.
371
+ * Events repeat until acknowledged; use a company-scoped provider idempotency key.
372
+ */
373
+ listLifecycle(companyId: string, limit?: number, afterId?: string): Promise<ResourceLifecycleEvent[]>;
374
+ /** Acknowledge only after the provider operation succeeds. */
375
+ acknowledgeLifecycle(companyId: string, eventId: string): Promise<void>;
376
+ /**
377
+ * Subscribe to a core Paperclip domain event or a plugin-namespaced event.
378
+ *
379
+ * @param name - Event type, e.g. `"issue.created"` or `"plugin.@acme/linear.sync-done"`
380
+ * @param fn - Async event handler
381
+ */
382
+ on(name: PluginEventType | `plugin.${string}`, fn: (event: PluginEvent) => Promise<void>): () => void;
383
+ /**
384
+ * Subscribe to an event with an optional server-side filter.
385
+ *
386
+ * @param name - Event type
387
+ * @param filter - Server-side filter evaluated before dispatching to the worker
388
+ * @param fn - Async event handler
389
+ * @returns An unsubscribe function that removes the handler
390
+ */
391
+ on(name: PluginEventType | `plugin.${string}`, filter: EventFilter, fn: (event: PluginEvent) => Promise<void>): () => void;
392
+ /**
393
+ * Emit a plugin-namespaced event. Other plugins with `events.subscribe` can
394
+ * subscribe to it using `"plugin.<pluginId>.<eventName>"`.
395
+ *
396
+ * Requires the `events.emit` capability.
397
+ *
398
+ * Plugin-emitted events are automatically namespaced: if the plugin ID is
399
+ * `"acme.linear"` and the event name is `"sync-done"`, the full event type
400
+ * becomes `"plugin.acme.linear.sync-done"`.
401
+ *
402
+ * @see PLUGIN_SPEC.md §16.2 — Plugin-to-Plugin Events
403
+ *
404
+ * @param name - Bare event name (e.g. `"sync-done"`)
405
+ * @param companyId - UUID of the company this event belongs to
406
+ * @param payload - JSON-serializable event payload
407
+ */
408
+ emit(name: string, companyId: string, payload: unknown): Promise<void>;
409
+ }
410
+ export type ResourceLifecycleEvent = {
411
+ /** Native private credentials for this plugin/project. Only supplied to automatic
412
+ * project lifecycle callbacks with projects.instance-secrets. Never expose to UI. */
413
+ instanceSecrets?: Record<string, string>;
414
+ id: string;
415
+ companyId: string;
416
+ resourceId: string;
417
+ createdAt: string;
418
+ } & ({
419
+ resourceType: "agent";
420
+ action: "create" | "pause" | "resume" | "terminate";
421
+ } | {
422
+ resourceType: "project";
423
+ action: "create" | "update" | "archive" | "delete";
424
+ } | {
425
+ resourceType: "agent_runtime";
426
+ action: "update" | "delete";
427
+ });
428
+ /** Return acknowledged only after durable effects finish. Retry unfinished work;
429
+ * defer when configuration is missing (replayed on configuration changes or startup).
430
+ * Both retry and deferred leave the event unacknowledged.
431
+ */
432
+ export interface ResourceLifecycleResult {
433
+ eventId: string;
434
+ status: "acknowledged" | "retry" | "deferred";
435
+ /** Project-only patch, saved atomically with acknowledgment. Null removes a key.
436
+ * Up to 16 lowercase snake_case keys, each value at most 128 KiB. */
437
+ instanceSecrets?: Record<string, string | null>;
438
+ }
439
+ /**
440
+ * `ctx.jobs` — register handlers for scheduled jobs declared in the manifest.
441
+ *
442
+ * Requires `jobs.schedule` capability.
443
+ *
444
+ * @see PLUGIN_SPEC.md §17 — Scheduled Jobs
445
+ */
446
+ export interface PluginJobsClient {
447
+ /**
448
+ * Register a handler for a scheduled job.
449
+ *
450
+ * The `key` must match a `jobKey` declared in the plugin manifest.
451
+ * The host calls this handler according to the job's declared `schedule`.
452
+ *
453
+ * @param key - Job key matching the manifest declaration
454
+ * @param fn - Async job handler
455
+ */
456
+ register(key: string, fn: (job: PluginJobContext) => Promise<void>): void;
457
+ }
458
+ /**
459
+ * A runtime launcher registration uses the same declaration shape as a
460
+ * manifest launcher entry.
461
+ */
462
+ export type PluginLauncherRegistration = PluginLauncherDeclaration;
463
+ /**
464
+ * `ctx.launchers` — register launcher declarations at runtime.
465
+ */
466
+ export interface PluginLaunchersClient {
467
+ /**
468
+ * Register launcher metadata for host discovery.
469
+ *
470
+ * If a launcher with the same id is registered more than once, the latest
471
+ * declaration replaces the previous one.
472
+ */
473
+ register(launcher: PluginLauncherRegistration): void;
474
+ }
475
+ export interface PluginDatabaseClient {
476
+ /** Host-derived PostgreSQL schema name for this plugin's namespace. */
477
+ namespace: string;
478
+ /** Run a restricted SELECT against the plugin namespace and whitelisted core tables. */
479
+ query<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T[]>;
480
+ /** Run a restricted INSERT, UPDATE, or DELETE against the plugin namespace. */
481
+ execute(sql: string, params?: unknown[]): Promise<{
482
+ rowCount: number;
483
+ }>;
484
+ }
485
+ /**
486
+ * `ctx.http` — make outbound HTTP requests.
487
+ *
488
+ * Requires `http.outbound` capability.
489
+ *
490
+ * @see PLUGIN_SPEC.md §15.1 — Capabilities: Runtime/Integration
491
+ */
492
+ export interface PluginHttpClient {
493
+ /**
494
+ * Perform an outbound HTTP request.
495
+ *
496
+ * The host enforces `http.outbound` capability before allowing the call.
497
+ * Plugins may also use standard Node `fetch` or other libraries directly —
498
+ * this client exists for host-managed tracing and audit logging.
499
+ *
500
+ * @param url - Target URL
501
+ * @param init - Standard `RequestInit` options
502
+ * @returns The response
503
+ */
504
+ fetch(url: string, init?: RequestInit): Promise<Response>;
505
+ }
506
+ /**
507
+ * `ctx.secrets` — resolve secret references.
508
+ *
509
+ * Requires `secrets.read-ref` capability.
510
+ *
511
+ * Plugins store shared `{ type: "secret_ref", secretId, version? }` bindings in
512
+ * company-scoped config. This client resolves a bound ref through the
513
+ * Paperclip secret provider system at execution time.
514
+ *
515
+ * @see PLUGIN_SPEC.md §22 — Secrets
516
+ */
517
+ export interface PluginSecretsClient {
518
+ /**
519
+ * Resolve a secret reference to its current value.
520
+ *
521
+ * The reference must be the shared `secret_ref` object shape from plugin
522
+ * config. Legacy string UUID references fail closed.
523
+ *
524
+ * Secret values are resolved at call time and must never be cached or
525
+ * written to logs, config, or other persistent storage.
526
+ *
527
+ * @param secretRef - The secret reference object from plugin config
528
+ * @returns The resolved secret value
529
+ */
530
+ resolve(secretRef: string | EnvSecretRefBinding, options?: {
531
+ companyId?: string;
532
+ configPath?: string;
533
+ }): Promise<string>;
534
+ }
535
+ /**
536
+ * Input for writing a plugin activity log entry.
537
+ *
538
+ * @see PLUGIN_SPEC.md §21.4 — Activity Log Changes
539
+ */
540
+ export interface PluginActivityLogEntry {
541
+ /** UUID of the company this activity belongs to. Required for auditing. */
542
+ companyId: string;
543
+ /** Human-readable description of the activity. */
544
+ message: string;
545
+ /** Optional entity type this activity relates to. */
546
+ entityType?: string;
547
+ /** Optional entity ID this activity relates to. */
548
+ entityId?: string;
549
+ /** Optional additional metadata. */
550
+ metadata?: Record<string, unknown>;
551
+ }
552
+ /**
553
+ * `ctx.activity` — write plugin-originated activity log entries.
554
+ *
555
+ * Requires `activity.log.write` capability.
556
+ *
557
+ * @see PLUGIN_SPEC.md §21.4 — Activity Log Changes
558
+ */
559
+ export interface PluginActivityClient {
560
+ /**
561
+ * Write an activity log entry attributed to this plugin.
562
+ *
563
+ * The host writes the entry with `actor_type = plugin` and
564
+ * `actor_id = <pluginId>`.
565
+ *
566
+ * @param entry - The activity log entry to write
567
+ */
568
+ log(entry: PluginActivityLogEntry): Promise<void>;
569
+ }
570
+ /**
571
+ * `ctx.environmentTasks` — status reporting for this plugin's Runner tasks.
572
+ *
573
+ * Requires `environment.drivers.register`.
574
+ */
575
+ export interface PluginEnvironmentTasksClient {
576
+ /**
577
+ * Report the startup stage of one of this plugin's Runner tasks while the
578
+ * host waits for an environment task operation on that task (for example
579
+ * `starting_environment` while a stopped machine starts during `submit`).
580
+ *
581
+ * The board shows the reported stage only for the rest of that operation.
582
+ * When it returns, the host's own stage for the run shows again. The host
583
+ * ignores a report outside such an operation, for another plugin's task, or
584
+ * after the run's agent turn has started. It never fails the operation.
585
+ */
586
+ reportStartupStage(input: {
587
+ taskId: string;
588
+ stage: RunStartupStage;
589
+ }): Promise<void>;
590
+ }
591
+ /**
592
+ * `ctx.state` — read and write plugin-scoped key-value state.
593
+ *
594
+ * Each plugin gets an isolated namespace: state written by plugin A can never
595
+ * be read or overwritten by plugin B. Within a plugin, state is partitioned by
596
+ * a five-part composite key: `(pluginId, scopeKind, scopeId, namespace, stateKey)`.
597
+ *
598
+ * **Scope kinds**
599
+ *
600
+ * | `scopeKind` | `scopeId` | Typical use |
601
+ * |-------------|-----------|-------------|
602
+ * | `"instance"` | omit | Global flags, last full-sync timestamps |
603
+ * | `"company"` | company UUID | Per-company sync cursors |
604
+ * | `"project"` | project UUID | Per-project settings, branch tracking |
605
+ * | `"project_workspace"` | workspace UUID | Per-workspace state |
606
+ * | `"agent"` | agent UUID | Per-agent memory |
607
+ * | `"issue"` | issue UUID | Idempotency keys, linked external IDs |
608
+ * | `"goal"` | goal UUID | Per-goal progress |
609
+ * | `"run"` | run UUID | Per-run checkpoints |
610
+ *
611
+ * **Namespaces**
612
+ *
613
+ * The optional `namespace` field (default: `"default"`) lets you group related
614
+ * keys within a scope without risking collisions between different logical
615
+ * subsystems inside the same plugin.
616
+ *
617
+ * **Security**
618
+ *
619
+ * Never store resolved secret values. Store only secret references and resolve
620
+ * them at call time via `ctx.secrets.resolve()`.
621
+ *
622
+ * @example
623
+ * ```ts
624
+ * // Instance-global flag
625
+ * await ctx.state.set({ scopeKind: "instance", stateKey: "schema-version" }, 2);
626
+ *
627
+ * // Idempotency key per issue
628
+ * const synced = await ctx.state.get({ scopeKind: "issue", scopeId: issueId, stateKey: "synced-to-linear" });
629
+ * if (!synced) {
630
+ * await syncToLinear(issueId);
631
+ * await ctx.state.set({ scopeKind: "issue", scopeId: issueId, stateKey: "synced-to-linear" }, true);
632
+ * }
633
+ *
634
+ * // Per-project, namespaced for two integrations
635
+ * await ctx.state.set({ scopeKind: "project", scopeId: projectId, namespace: "linear", stateKey: "cursor" }, cursor);
636
+ * await ctx.state.set({ scopeKind: "project", scopeId: projectId, namespace: "github", stateKey: "last-event" }, eventId);
637
+ * ```
638
+ *
639
+ * `plugin.state.read` capability required for `get()`.
640
+ * `plugin.state.write` capability required for `set()` and `delete()`.
641
+ *
642
+ * @see PLUGIN_SPEC.md §21.3 `plugin_state`
643
+ */
644
+ export interface PluginStateClient {
645
+ /**
646
+ * Read a state value.
647
+ *
648
+ * Returns the stored JSON value as-is, or `null` if no entry has been set
649
+ * for this scope+key combination. Falsy values (`false`, `0`, `""`) are
650
+ * returned correctly and are not confused with "not set".
651
+ *
652
+ * @param input - Scope key identifying the entry to read
653
+ * @returns The stored JSON value, or `null` if no value has been set
654
+ */
655
+ get(input: ScopeKey): Promise<unknown>;
656
+ /**
657
+ * Write a state value. Creates the row if it does not exist; replaces it
658
+ * atomically (upsert) if it does. Safe to call concurrently.
659
+ *
660
+ * Any JSON-serializable value is accepted: objects, arrays, strings,
661
+ * numbers, booleans, and `null`.
662
+ *
663
+ * @param input - Scope key identifying the entry to write
664
+ * @param value - JSON-serializable value to store
665
+ */
666
+ set(input: ScopeKey, value: unknown): Promise<void>;
667
+ /**
668
+ * Delete a state value. No-ops silently if the entry does not exist
669
+ * (idempotent by design — safe to call without prior `get()`).
670
+ *
671
+ * @param input - Scope key identifying the entry to delete
672
+ */
673
+ delete(input: ScopeKey): Promise<void>;
674
+ }
675
+ /**
676
+ * `ctx.entities` — create and query plugin-owned entity records.
677
+ *
678
+ * @see PLUGIN_SPEC.md §21.3 `plugin_entities`
679
+ */
680
+ export interface PluginEntitiesClient {
681
+ /**
682
+ * Create or update a plugin entity record (upsert by `externalId` within
683
+ * the given scope, or by `id` if provided).
684
+ *
685
+ * @param input - Entity data to upsert
686
+ */
687
+ upsert(input: PluginEntityUpsert): Promise<PluginEntityRecord>;
688
+ /**
689
+ * Query plugin entity records.
690
+ *
691
+ * @param query - Filter criteria
692
+ * @returns Matching entity records
693
+ */
694
+ list(query: PluginEntityQuery): Promise<PluginEntityRecord[]>;
695
+ }
696
+ /**
697
+ * `ctx.projects` — read project and workspace metadata.
698
+ *
699
+ * Requires `projects.read` capability.
700
+ * Requires `project.workspaces.read` capability for workspace operations.
701
+ *
702
+ * @see PLUGIN_SPEC.md §7 — Project Workspaces
703
+ */
704
+ export interface PluginProjectSnapshot {
705
+ projectId: string;
706
+ workspaces: PluginWorkspace[];
707
+ entity: PluginEntityRecord | null;
708
+ instanceSecrets: Record<string, string>;
709
+ }
710
+ export interface PluginProjectsClient {
711
+ /** Transient GitHub credential for a stored repository in the current host-issued
712
+ * lifecycle/workspace invocation. Requires projects.git-credentials. Never persist or log. */
713
+ resolveGitCredential(projectId: string, workspaceId: string, companyId: string): Promise<string | null>;
714
+ /** Trusted worker access to this plugin’s native project credentials.
715
+ * Requires projects.instance-secrets; never expose via UI/data handlers. */
716
+ getInstanceSecrets(projectId: string, companyId: string): Promise<Record<string, string>>;
717
+ /** Read authorized project workspaces, instance secrets and one plugin-owned entity per project.
718
+ * Missing or changing projects reject the batch. Null means the host does not support this method.
719
+ * Keep the result in the trusted worker. */
720
+ readSnapshots(projectIds: string[], companyId: string, entityType: string): Promise<PluginProjectSnapshot[] | null>;
721
+ /**
722
+ * List projects visible to the plugin.
723
+ *
724
+ * Requires the `projects.read` capability.
725
+ */
726
+ list(input: {
727
+ companyId: string;
728
+ limit?: number;
729
+ offset?: number;
730
+ }): Promise<Project[]>;
731
+ /**
732
+ * Get a single project by ID.
733
+ *
734
+ * Requires the `projects.read` capability.
735
+ */
736
+ get(projectId: string, companyId: string): Promise<Project | null>;
737
+ /**
738
+ * List all workspaces attached to a project.
739
+ *
740
+ * @param projectId - UUID of the project
741
+ * @param companyId - UUID of the company that owns the project
742
+ * @returns All workspaces for the project, ordered with primary first
743
+ */
744
+ listWorkspaces(projectId: string, companyId: string): Promise<PluginWorkspace[]>;
745
+ /**
746
+ * Get the primary workspace for a project.
747
+ *
748
+ * @param projectId - UUID of the project
749
+ * @param companyId - UUID of the company that owns the project
750
+ * @returns The primary workspace, or `null` if no workspace is configured
751
+ */
752
+ getPrimaryWorkspace(projectId: string, companyId: string): Promise<PluginWorkspace | null>;
753
+ /**
754
+ * Resolve the primary workspace for an issue by looking up the issue's
755
+ * project and returning its primary workspace.
756
+ *
757
+ * This is a convenience method that combines `issues.get()` and
758
+ * `getPrimaryWorkspace()` in a single RPC call.
759
+ *
760
+ * @param issueId - UUID of the issue
761
+ * @param companyId - UUID of the company that owns the issue
762
+ * @returns The primary workspace for the issue's project, or `null` if
763
+ * the issue has no project or the project has no workspace
764
+ *
765
+ * @see PLUGIN_SPEC.md §20 — Local Tooling
766
+ */
767
+ getWorkspaceForIssue(issueId: string, companyId: string): Promise<PluginWorkspace | null>;
768
+ /** Resolve and reconcile manifest-declared plugin-managed projects by stable key. Requires `projects.managed`. */
769
+ managed: {
770
+ get(projectKey: string, companyId: string): Promise<PluginManagedProjectResolution>;
771
+ reconcile(projectKey: string, companyId: string): Promise<PluginManagedProjectResolution>;
772
+ reset(projectKey: string, companyId: string): Promise<PluginManagedProjectResolution>;
773
+ };
774
+ }
775
+ /**
776
+ * `ctx.executionWorkspaces` — read execution workspace metadata.
777
+ *
778
+ * Requires `execution.workspaces.read`.
779
+ */
780
+ export interface PluginExecutionWorkspacesClient {
781
+ /**
782
+ * Return plugin-safe metadata for an execution workspace. The host enforces
783
+ * company access before returning any workspace coordinates.
784
+ */
785
+ get(workspaceId: string, companyId: string): Promise<PluginExecutionWorkspaceMetadata | null>;
786
+ }
787
+ /**
788
+ * `ctx.routines` — resolve and reconcile plugin-managed Paperclip routines.
789
+ *
790
+ * Requires `routines.managed` capability.
791
+ */
792
+ export interface PluginRoutinesClient {
793
+ managed: {
794
+ get(routineKey: string, companyId: string): Promise<PluginManagedRoutineResolution>;
795
+ reconcile(routineKey: string, companyId: string, overrides?: {
796
+ assigneeAgentId?: string | null;
797
+ projectId?: string | null;
798
+ }): Promise<PluginManagedRoutineResolution>;
799
+ reset(routineKey: string, companyId: string, overrides?: {
800
+ assigneeAgentId?: string | null;
801
+ projectId?: string | null;
802
+ }): Promise<PluginManagedRoutineResolution>;
803
+ update(routineKey: string, companyId: string, patch: {
804
+ status?: string;
805
+ }): Promise<Routine>;
806
+ run(routineKey: string, companyId: string, overrides?: {
807
+ assigneeAgentId?: string | null;
808
+ projectId?: string | null;
809
+ }): Promise<RoutineRun>;
810
+ };
811
+ }
812
+ /**
813
+ * `ctx.skills` — resolve and reconcile plugin-managed company skills.
814
+ *
815
+ * Requires `skills.managed` capability.
816
+ */
817
+ export interface PluginSkillsClient {
818
+ managed: {
819
+ get(skillKey: string, companyId: string): Promise<PluginManagedSkillResolution>;
820
+ reconcile(skillKey: string, companyId: string): Promise<PluginManagedSkillResolution>;
821
+ reset(skillKey: string, companyId: string): Promise<PluginManagedSkillResolution>;
822
+ };
823
+ }
824
+ /**
825
+ * `ctx.data` — register `getData` handlers that back `usePluginData()` in the
826
+ * plugin's frontend components.
827
+ *
828
+ * The plugin's UI calls `usePluginData(key, params)` which routes through the
829
+ * host bridge to the worker's registered handler.
830
+ *
831
+ * @see PLUGIN_SPEC.md §13.8 — `getData`
832
+ */
833
+ export interface PluginDataClient {
834
+ /**
835
+ * Register a handler for a plugin-defined data key.
836
+ *
837
+ * @param key - Stable string identifier for this data type (e.g. `"sync-health"`)
838
+ * @param handler - Async function that receives request params and returns JSON-serializable data
839
+ */
840
+ register(key: string, handler: (params: Record<string, unknown>) => Promise<unknown>): void;
841
+ }
842
+ /**
843
+ * `ctx.actions` — register `performAction` handlers that back
844
+ * `usePluginAction()` in the plugin's frontend components.
845
+ *
846
+ * @see PLUGIN_SPEC.md §13.9 — `performAction`
847
+ */
848
+ export interface PluginActionsClient {
849
+ /**
850
+ * Register a handler for a plugin-defined action key.
851
+ *
852
+ * @param key - Stable string identifier for this action (e.g. `"resync"`)
853
+ * @param handler - Async function that receives action params plus immutable host actor context and returns a result
854
+ */
855
+ register(key: string, handler: (params: Record<string, unknown>, context: PluginPerformActionContext) => Promise<unknown>): void;
856
+ }
857
+ /**
858
+ * `ctx.tools` — register handlers for agent tools declared in the manifest.
859
+ *
860
+ * Requires `agent.tools.register` capability.
861
+ *
862
+ * Tool names are automatically namespaced by plugin ID at runtime.
863
+ *
864
+ * @see PLUGIN_SPEC.md §11 — Agent Tools
865
+ */
866
+ export interface PluginToolsClient {
867
+ /**
868
+ * Register a handler for a plugin-contributed agent tool.
869
+ *
870
+ * @param name - Tool name matching the manifest declaration (without namespace prefix)
871
+ * @param declaration - Tool metadata (displayName, description, parametersSchema)
872
+ * @param fn - Async handler that executes the tool
873
+ */
874
+ register(name: string, declaration: Pick<PluginToolDeclaration, "displayName" | "description" | "parametersSchema">, fn: (params: unknown, runCtx: ToolRunContext) => Promise<ToolResult>): void;
875
+ }
876
+ /**
877
+ * `ctx.connectors` — serve the tools of connectors this plugin declares in
878
+ * `apps` with `transport: "plugin"`.
879
+ *
880
+ * Requires the `connectors.provide` capability. Declaring a connector grants
881
+ * no tools: agents get them only from a connection installed for them or for
882
+ * the whole company, exactly like built-in connectors.
883
+ */
884
+ export interface PluginConnectorsClient {
885
+ /**
886
+ * Register the handler for one tool of a plugin connector. Every static
887
+ * tool in the manifest needs a handler before `setup` returns, or the worker
888
+ * fails to start.
889
+ *
890
+ * @param appSlug - App slug as declared in the manifest
891
+ * @param toolName - Tool name (`[a-z0-9_]`)
892
+ * @param fn - Handler. `runCtx.connection` identifies the connection, its
893
+ * settings and the credential the host resolved for this call.
894
+ */
895
+ register(appSlug: string, toolName: string, fn: (params: unknown, runCtx: ConnectorToolRunContext) => Promise<ToolResult>): void;
896
+ /**
897
+ * Provide the tool list of a `tools: { kind: "dynamic" }` connector for one
898
+ * connection. The host caches the result in the connection's catalog and
899
+ * refreshes it on connect, on settings change and on request.
900
+ */
901
+ listTools(appSlug: string, fn: (connection: ConnectorToolListConnection) => Promise<ConnectorToolDescriptor[]>): void;
902
+ }
903
+ /**
904
+ * `ctx.logger` — structured logging from the plugin worker.
905
+ *
906
+ * Log output is captured by the host, stored, and surfaced in the plugin
907
+ * health dashboard.
908
+ *
909
+ * @see PLUGIN_SPEC.md §26.1 — Logging
910
+ */
911
+ export interface PluginLogger {
912
+ /** Log an informational message. */
913
+ info(message: string, meta?: Record<string, unknown>): void;
914
+ /** Log a warning. */
915
+ warn(message: string, meta?: Record<string, unknown>): void;
916
+ /** Log an error. */
917
+ error(message: string, meta?: Record<string, unknown>): void;
918
+ /** Log a debug message (may be suppressed in production). */
919
+ debug(message: string, meta?: Record<string, unknown>): void;
920
+ }
921
+ /**
922
+ * `ctx.tracer` — a minimal, OpenTelemetry-free span contract. The plugin worker
923
+ * builds a real span through this surface; the host records it through the real
924
+ * tracer. The shape is a subset of the `@opentelemetry/api` `Span` shape, so the
925
+ * plugin SDK never imports `@opentelemetry/api`.
926
+ *
927
+ * A span with no active host trace context is a no-op: it accepts the calls and
928
+ * ends without an effect. So a lifecycle hook can always open a span, and the
929
+ * span records nothing until tracing is on.
930
+ */
931
+ export interface PluginSpan {
932
+ /** Set one bounded attribute. The host re-clamps every attribute at its trust
933
+ * boundary, so an out-of-allowlist attribute never reaches a recorded span. */
934
+ setAttribute(key: string, value: string | number | boolean): void;
935
+ /** Set the span status. The host maps it onto the recorded span. */
936
+ setStatus(status: {
937
+ code: number;
938
+ message?: string;
939
+ }): void;
940
+ /** End the span. The worker sends the span data to the host once, here. */
941
+ end(): void;
942
+ }
943
+ /**
944
+ * `ctx.tracer` — a minimal, OpenTelemetry-free tracer contract. The plugin uses
945
+ * it the same way as `ctx.logger`. The default is a no-op that never throws, so
946
+ * a plugin span changes nothing until the host injects a live tracer and an
947
+ * active host trace context.
948
+ */
949
+ export interface PluginTracer {
950
+ /** Invocation-wide monotonic clock anchored to epoch milliseconds. */
951
+ now?(): number;
952
+ isRecording?(): boolean;
953
+ /** Completed bounded timing receipt; the host validates times and parentage. */
954
+ recordSpan?(span: import("./protocol.js").PluginSpanRecord): void;
955
+ /** Invocation-scoped nesting; absent on older hosts. No additional IPC per child. */
956
+ withSpan?<T>(name: string, work: () => T | Promise<T>, attributes?: Record<string, string | number | boolean>): Promise<T>;
957
+ /** Start one span. `options.attributes` seeds the span attributes. */
958
+ startSpan(name: string, options?: {
959
+ attributes?: Record<string, string | number | boolean>;
960
+ }): PluginSpan;
961
+ }
962
+ /** A shared no-op span. It satisfies the span contract and does nothing, so a
963
+ * plugin with no injected tracer changes no behavior. */
964
+ export declare const NOOP_PLUGIN_SPAN: PluginSpan;
965
+ /** The default tracer. It opens no real span, so a lifecycle hook that wraps
966
+ * work in a span behaves exactly as before when no live tracer is injected. */
967
+ export declare const NOOP_PLUGIN_TRACER: PluginTracer;
968
+ /**
969
+ * `ctx.metrics` — write plugin-contributed metrics.
970
+ *
971
+ * Requires `metrics.write` capability.
972
+ *
973
+ * @see PLUGIN_SPEC.md §15.1 — Capabilities: Data Write
974
+ */
975
+ export interface PluginMetricsClient {
976
+ /**
977
+ * Write a numeric metric data point.
978
+ *
979
+ * @param name - Metric name (plugin-namespaced by the host)
980
+ * @param value - Numeric value
981
+ * @param tags - Optional key-value tags for filtering
982
+ */
983
+ write(name: string, value: number, tags?: Record<string, string>): Promise<void>;
984
+ }
985
+ /**
986
+ * `ctx.telemetry` — emit plugin-scoped telemetry to the host's external
987
+ * telemetry pipeline.
988
+ *
989
+ * Requires `telemetry.track` capability.
990
+ */
991
+ export interface PluginTelemetryClient {
992
+ /**
993
+ * Track a plugin telemetry event.
994
+ *
995
+ * The host prefixes the final event name as `plugin.<pluginId>.<eventName>`
996
+ * before forwarding it to the shared telemetry client.
997
+ *
998
+ * @param eventName - Bare plugin event slug (for example `"sync_completed"`)
999
+ * @param dimensions - Optional structured dimensions
1000
+ */
1001
+ track(eventName: string, dimensions?: Record<string, string | number | boolean>): Promise<void>;
1002
+ }
1003
+ /**
1004
+ * `ctx.companies` — read company metadata.
1005
+ *
1006
+ * Requires `companies.read` capability.
1007
+ */
1008
+ export interface PluginCompaniesClient {
1009
+ /**
1010
+ * List companies visible to this plugin.
1011
+ */
1012
+ list(input?: {
1013
+ limit?: number;
1014
+ offset?: number;
1015
+ }): Promise<Company[]>;
1016
+ /**
1017
+ * Get one company by ID.
1018
+ */
1019
+ get(companyId: string): Promise<Company | null>;
1020
+ }
1021
+ /**
1022
+ * `ctx.issues.documents` — read and write issue documents.
1023
+ *
1024
+ * Requires:
1025
+ * - `issue.documents.read` for `list` and `get`
1026
+ * - `issue.documents.write` for `upsert` and `delete`
1027
+ *
1028
+ * @see PLUGIN_SPEC.md §14 — SDK Surface
1029
+ */
1030
+ export interface PluginIssueDocumentsClient {
1031
+ /**
1032
+ * List all documents attached to an issue.
1033
+ *
1034
+ * Returns summary metadata (id, key, title, format, timestamps) without
1035
+ * the full document body. Use `get()` to fetch a specific document's body.
1036
+ *
1037
+ * Requires the `issue.documents.read` capability.
1038
+ */
1039
+ list(issueId: string, companyId: string): Promise<IssueDocumentSummary[]>;
1040
+ /**
1041
+ * Get a single document by key, including its full body content.
1042
+ *
1043
+ * Returns `null` if no document exists with the given key.
1044
+ *
1045
+ * Requires the `issue.documents.read` capability.
1046
+ *
1047
+ * @param issueId - UUID of the issue
1048
+ * @param key - Document key (e.g. `"plan"`, `"design-spec"`)
1049
+ * @param companyId - UUID of the company
1050
+ */
1051
+ get(issueId: string, key: string, companyId: string): Promise<IssueDocument | null>;
1052
+ /**
1053
+ * Create or update a document on an issue.
1054
+ *
1055
+ * If a document with the given key already exists, it is updated and a new
1056
+ * revision is created. If it does not exist, it is created.
1057
+ *
1058
+ * Requires the `issue.documents.write` capability.
1059
+ *
1060
+ * @param input - Document data including issueId, key, body, and optional title/format/changeSummary
1061
+ */
1062
+ upsert(input: {
1063
+ issueId: string;
1064
+ key: string;
1065
+ body: string;
1066
+ companyId: string;
1067
+ title?: string;
1068
+ format?: string;
1069
+ changeSummary?: string;
1070
+ }): Promise<IssueDocument>;
1071
+ /**
1072
+ * Delete a document and all its revisions.
1073
+ *
1074
+ * No-ops silently if the document does not exist (idempotent).
1075
+ *
1076
+ * Requires the `issue.documents.write` capability.
1077
+ *
1078
+ * @param issueId - UUID of the issue
1079
+ * @param key - Document key to delete
1080
+ * @param companyId - UUID of the company
1081
+ */
1082
+ delete(issueId: string, key: string, companyId: string): Promise<void>;
1083
+ }
1084
+ export interface PluginIssueMutationActor {
1085
+ /** Agent that initiated the plugin operation, when the plugin is acting from an agent run. */
1086
+ actorAgentId?: string | null;
1087
+ /** Board/user that initiated the plugin operation, when known. */
1088
+ actorUserId?: string | null;
1089
+ /** Heartbeat run that initiated the operation. Required for checkout-aware agent actions. */
1090
+ actorRunId?: string | null;
1091
+ }
1092
+ export interface PluginIssueRelationSummary {
1093
+ blockedBy: IssueRelationIssueSummary[];
1094
+ blocks: IssueRelationIssueSummary[];
1095
+ }
1096
+ export interface PluginIssueRelationsClient {
1097
+ /** Read blocker relationships for an issue. Requires `issue.relations.read`. */
1098
+ get(issueId: string, companyId: string): Promise<PluginIssueRelationSummary>;
1099
+ /** Replace the issue's blocked-by relation set. Requires `issue.relations.write`. */
1100
+ setBlockedBy(issueId: string, blockedByIssueIds: string[], companyId: string, actor?: PluginIssueMutationActor): Promise<PluginIssueRelationSummary>;
1101
+ /** Add one or more blockers while preserving existing blockers. Requires `issue.relations.write`. */
1102
+ addBlockers(issueId: string, blockerIssueIds: string[], companyId: string, actor?: PluginIssueMutationActor): Promise<PluginIssueRelationSummary>;
1103
+ /** Remove one or more blockers while preserving all other blockers. Requires `issue.relations.write`. */
1104
+ removeBlockers(issueId: string, blockerIssueIds: string[], companyId: string, actor?: PluginIssueMutationActor): Promise<PluginIssueRelationSummary>;
1105
+ }
1106
+ export interface PluginIssueCheckoutOwnership {
1107
+ issueId: string;
1108
+ status: Issue["status"];
1109
+ assigneeAgentId: string | null;
1110
+ checkoutRunId: string | null;
1111
+ adoptedFromRunId: string | null;
1112
+ }
1113
+ export interface PluginIssueWakeupResult {
1114
+ queued: boolean;
1115
+ runId: string | null;
1116
+ }
1117
+ export interface PluginIssueWakeupBatchResult {
1118
+ issueId: string;
1119
+ queued: boolean;
1120
+ runId: string | null;
1121
+ }
1122
+ export interface PluginIssueRunSummary {
1123
+ id: string;
1124
+ issueId: string | null;
1125
+ agentId: string;
1126
+ status: string;
1127
+ invocationSource: string;
1128
+ triggerDetail: string | null;
1129
+ startedAt: string | null;
1130
+ finishedAt: string | null;
1131
+ error: string | null;
1132
+ createdAt: string;
1133
+ }
1134
+ export interface PluginIssueApprovalSummary {
1135
+ issueId: string;
1136
+ id: string;
1137
+ type: string;
1138
+ status: string;
1139
+ requestedByAgentId: string | null;
1140
+ requestedByUserId: string | null;
1141
+ decidedByUserId: string | null;
1142
+ decidedAt: string | null;
1143
+ createdAt: string;
1144
+ }
1145
+ export interface PluginIssueCostSummary {
1146
+ costCents: number;
1147
+ inputTokens: number;
1148
+ cachedInputTokens: number;
1149
+ outputTokens: number;
1150
+ billingCode: string | null;
1151
+ }
1152
+ export interface PluginBudgetIncidentSummary {
1153
+ id: string;
1154
+ scopeType: string;
1155
+ scopeId: string;
1156
+ metric: string;
1157
+ windowKind: string;
1158
+ thresholdType: string;
1159
+ amountLimit: number;
1160
+ amountObserved: number;
1161
+ status: string;
1162
+ approvalId: string | null;
1163
+ createdAt: string;
1164
+ }
1165
+ export interface PluginIssueInvocationBlockSummary {
1166
+ issueId: string;
1167
+ agentId: string;
1168
+ scopeType: "company" | "agent" | "project";
1169
+ scopeId: string;
1170
+ scopeName: string;
1171
+ reason: string;
1172
+ }
1173
+ export interface PluginIssueOrchestrationSummary {
1174
+ issueId: string;
1175
+ companyId: string;
1176
+ subtreeIssueIds: string[];
1177
+ relations: Record<string, PluginIssueRelationSummary>;
1178
+ approvals: PluginIssueApprovalSummary[];
1179
+ runs: PluginIssueRunSummary[];
1180
+ costs: PluginIssueCostSummary;
1181
+ openBudgetIncidents: PluginBudgetIncidentSummary[];
1182
+ invocationBlocks: PluginIssueInvocationBlockSummary[];
1183
+ }
1184
+ export interface PluginIssueSubtreeOptions {
1185
+ /** Include the root issue in the result. Defaults to true. */
1186
+ includeRoot?: boolean;
1187
+ /** Include blocker relationship summaries keyed by issue ID. */
1188
+ includeRelations?: boolean;
1189
+ /** Include issue document summaries keyed by issue ID. */
1190
+ includeDocuments?: boolean;
1191
+ /** Include queued/running heartbeat runs keyed by issue ID. */
1192
+ includeActiveRuns?: boolean;
1193
+ /** Include assignee summaries keyed by agent ID. */
1194
+ includeAssignees?: boolean;
1195
+ }
1196
+ export interface PluginIssueAssigneeSummary {
1197
+ id: string;
1198
+ name: string;
1199
+ role: string;
1200
+ title: string | null;
1201
+ status: Agent["status"];
1202
+ }
1203
+ export interface PluginIssueSubtree {
1204
+ rootIssueId: string;
1205
+ companyId: string;
1206
+ issueIds: string[];
1207
+ issues: Issue[];
1208
+ relations?: Record<string, PluginIssueRelationSummary>;
1209
+ documents?: Record<string, IssueDocumentSummary[]>;
1210
+ activeRuns?: Record<string, PluginIssueRunSummary[]>;
1211
+ assignees?: Record<string, PluginIssueAssigneeSummary>;
1212
+ }
1213
+ export interface PluginIssueSummariesClient {
1214
+ /**
1215
+ * Read the compact orchestration inputs a workflow plugin needs for an
1216
+ * issue or issue subtree. Requires `issues.orchestration.read`.
1217
+ */
1218
+ getOrchestration(input: {
1219
+ issueId: string;
1220
+ companyId: string;
1221
+ includeSubtree?: boolean;
1222
+ billingCode?: string | null;
1223
+ }): Promise<PluginIssueOrchestrationSummary>;
1224
+ }
1225
+ /**
1226
+ * Attachment content bytes returned by `ctx.issues.getAttachmentContent`.
1227
+ * Bytes are base64-encoded; there is no URL surface.
1228
+ */
1229
+ export interface PluginIssueAttachmentContent {
1230
+ attachmentId: string;
1231
+ contentType: string;
1232
+ byteSize: number;
1233
+ sha256: string;
1234
+ originalFilename: string | null;
1235
+ /** The attachment's raw bytes, base64-encoded. */
1236
+ contentBase64: string;
1237
+ }
1238
+ /**
1239
+ * `ctx.issues` — read and mutate issues plus comments.
1240
+ *
1241
+ * Requires:
1242
+ * - `issues.read` for read operations
1243
+ * - `issues.create` for create
1244
+ * - `issues.update` for update
1245
+ * - `issues.checkout` for checkout ownership assertions
1246
+ * - `issues.wakeup` for assignment wakeup requests
1247
+ * - `issues.orchestration.read` for orchestration summaries
1248
+ * - `issue.comments.read` for `listComments`
1249
+ * - `issue.comments.create` for `createComment`
1250
+ * - `issue.comments.create_human_attributed` for `createComment` calls that pass `actorUserId`
1251
+ * - `issue.interactions.create` for `createInteraction`, `suggestTasks`, `askUserQuestions`, `requestConfirmation`, and `requestCheckboxConfirmation`
1252
+ * - `issue.interactions.read` for `listInteractions`
1253
+ * - `issue.interactions.respond` for `respondInteraction`
1254
+ * - `issue.attachments.read` for `listAttachments` and `getAttachmentContent`
1255
+ * - `issue.documents.read` for `documents.list` and `documents.get`
1256
+ * - `issue.documents.write` for `documents.upsert` and `documents.delete`
1257
+ */
1258
+ export interface PluginIssuesClient {
1259
+ list(input: {
1260
+ companyId: string;
1261
+ projectId?: string;
1262
+ assigneeAgentId?: string;
1263
+ originKind?: PluginIssueOriginKind;
1264
+ originKindPrefix?: string;
1265
+ originId?: string;
1266
+ status?: Issue["status"];
1267
+ includePluginOperations?: boolean;
1268
+ limit?: number;
1269
+ offset?: number;
1270
+ }): Promise<Issue[]>;
1271
+ get(issueId: string, companyId: string): Promise<Issue | null>;
1272
+ create(input: {
1273
+ companyId: string;
1274
+ projectId?: string;
1275
+ goalId?: string;
1276
+ parentId?: string;
1277
+ /** Inherit this issue's project and workspace strategy. The new issue always gets its own workspace. */
1278
+ inheritExecutionWorkspaceFromIssueId?: string;
1279
+ title: string;
1280
+ description?: string;
1281
+ status?: Issue["status"];
1282
+ priority?: Issue["priority"];
1283
+ assigneeAgentId?: string;
1284
+ assigneeUserId?: string | null;
1285
+ requestDepth?: number;
1286
+ billingCode?: string | null;
1287
+ assigneeAdapterOverrides?: IssueAssigneeAdapterOverrides | null;
1288
+ surfaceVisibility?: IssueSurfaceVisibility;
1289
+ originKind?: PluginIssueOriginKind;
1290
+ originId?: string | null;
1291
+ originRunId?: string | null;
1292
+ blockedByIssueIds?: string[];
1293
+ labelIds?: string[];
1294
+ executionWorkspaceId?: string | null;
1295
+ executionWorkspacePreference?: string | null;
1296
+ executionWorkspaceSettings?: Record<string, unknown> | null;
1297
+ actor?: PluginIssueMutationActor;
1298
+ }): Promise<Issue>;
1299
+ update(issueId: string, patch: Partial<Pick<Issue, "title" | "description" | "status" | "priority" | "assigneeAgentId" | "assigneeUserId" | "billingCode" | "originKind" | "originId" | "originRunId" | "requestDepth" | "executionWorkspaceId" | "executionWorkspacePreference">> & {
1300
+ blockedByIssueIds?: string[];
1301
+ labelIds?: string[];
1302
+ executionWorkspaceSettings?: Record<string, unknown> | null;
1303
+ }, companyId: string, actor?: PluginIssueMutationActor): Promise<Issue>;
1304
+ assertCheckoutOwner(input: {
1305
+ issueId: string;
1306
+ companyId: string;
1307
+ actorAgentId: string;
1308
+ actorRunId: string;
1309
+ }): Promise<PluginIssueCheckoutOwnership>;
1310
+ /**
1311
+ * Read a root issue's descendants with optional relation/document/run/assignee
1312
+ * summaries. Requires `issue.subtree.read`.
1313
+ */
1314
+ getSubtree(issueId: string, companyId: string, options?: PluginIssueSubtreeOptions): Promise<PluginIssueSubtree>;
1315
+ requestWakeup(issueId: string, companyId: string, options?: {
1316
+ reason?: string;
1317
+ contextSource?: string;
1318
+ idempotencyKey?: string | null;
1319
+ } & PluginIssueMutationActor): Promise<PluginIssueWakeupResult>;
1320
+ requestWakeups(issueIds: string[], companyId: string, options?: {
1321
+ reason?: string;
1322
+ contextSource?: string;
1323
+ idempotencyKeyPrefix?: string | null;
1324
+ } & PluginIssueMutationActor): Promise<PluginIssueWakeupBatchResult[]>;
1325
+ listComments(issueId: string, companyId: string): Promise<IssueComment[]>;
1326
+ /**
1327
+ * Post a comment on an issue.
1328
+ *
1329
+ * Pass `authorAgentId` to attribute the comment to the plugin's own agent
1330
+ * identity (requires `issue.comments.create`, the default).
1331
+ *
1332
+ * Pass `actorUserId` to attribute the comment to a real human instead —
1333
+ * for example, relaying a paired chat user's reply back into the issue
1334
+ * thread. Requires the additional `issue.comments.create_human_attributed`
1335
+ * capability. The host independently verifies that `actorUserId` is an
1336
+ * active human member of the issue's company before applying the
1337
+ * attribution — a plugin can only ever attribute comments to identities
1338
+ * that could have posted them in the web app. A human-attributed comment
1339
+ * also participates in the normal wake-the-assignee behavior a board
1340
+ * user's comment gets in the web app (subject to the same closed-issue /
1341
+ * no-assignee exclusions) — unlike a plugin's own agent-attributed
1342
+ * comments, which never wake anyone.
1343
+ */
1344
+ createComment(issueId: string, body: string, companyId: string, options?: {
1345
+ authorAgentId?: string;
1346
+ actorUserId?: string;
1347
+ }): Promise<IssueComment>;
1348
+ createInteraction(issueId: string, interaction: CreateIssueThreadInteractionInput, companyId: string, options?: {
1349
+ authorAgentId?: string;
1350
+ }): Promise<IssueThreadInteraction>;
1351
+ suggestTasks(issueId: string, interaction: Omit<Extract<CreateIssueThreadInteractionInput, {
1352
+ kind: "suggest_tasks";
1353
+ }>, "kind">, companyId: string, options?: {
1354
+ authorAgentId?: string;
1355
+ }): Promise<SuggestTasksInteraction>;
1356
+ askUserQuestions(issueId: string, interaction: Omit<Extract<CreateIssueThreadInteractionInput, {
1357
+ kind: "ask_user_questions";
1358
+ }>, "kind">, companyId: string, options?: {
1359
+ authorAgentId?: string;
1360
+ }): Promise<AskUserQuestionsInteraction>;
1361
+ requestConfirmation(issueId: string, interaction: Omit<Extract<CreateIssueThreadInteractionInput, {
1362
+ kind: "request_confirmation";
1363
+ }>, "kind">, companyId: string, options?: {
1364
+ authorAgentId?: string;
1365
+ }): Promise<RequestConfirmationInteraction>;
1366
+ requestCheckboxConfirmation(issueId: string, interaction: Omit<Extract<CreateIssueThreadInteractionInput, {
1367
+ kind: "request_checkbox_confirmation";
1368
+ }>, "kind">, companyId: string, options?: {
1369
+ authorAgentId?: string;
1370
+ }): Promise<RequestCheckboxConfirmationInteraction>;
1371
+ /**
1372
+ * List the issue-thread interactions (decision cards) on an issue.
1373
+ * Requires `issue.interactions.read`.
1374
+ */
1375
+ listInteractions(issueId: string, companyId: string): Promise<IssueThreadInteraction[]>;
1376
+ /**
1377
+ * Resolve (accept/reject) a pending issue-thread interaction on behalf of a
1378
+ * paired board user. Requires `issue.interactions.respond`.
1379
+ *
1380
+ * `actorUserId` is the human company member the decision is attributed to.
1381
+ * The host independently re-verifies that this user is an active human
1382
+ * member of the issue's company before applying the decision — a plugin can
1383
+ * only ever resolve interactions as an identity that could have resolved
1384
+ * them in the web app (whose interaction-resolve routes are board-only).
1385
+ *
1386
+ * Returns the (possibly already-resolved) interaction and `applied`, which is
1387
+ * `true` when this call performed the resolution and `false` when the
1388
+ * interaction had already converged to a resolved state (idempotent replays).
1389
+ */
1390
+ respondInteraction(issueId: string, interactionId: string, input: {
1391
+ action: "accept" | "reject";
1392
+ actorUserId?: string;
1393
+ reason?: string | null;
1394
+ }, companyId: string): Promise<{
1395
+ interaction: IssueThreadInteraction;
1396
+ applied: boolean;
1397
+ }>;
1398
+ /** List attachment metadata for an issue. Requires `issue.attachments.read`. */
1399
+ listAttachments(issueId: string, companyId: string): Promise<IssueAttachment[]>;
1400
+ /**
1401
+ * Read an attachment's content bytes (base64) through the capability-scoped
1402
+ * host bridge. Requires `issue.attachments.read`.
1403
+ *
1404
+ * Company-scoped and audit-logged host-side; there is no URL surface. Returns
1405
+ * `null` for an unknown or cross-company attachment id (indistinguishable by
1406
+ * design). Pass `maxBytes` to refuse over-cap assets — the host throws rather
1407
+ * than partially reading when the stored size exceeds the cap.
1408
+ */
1409
+ getAttachmentContent(attachmentId: string, companyId: string, options?: {
1410
+ maxBytes?: number | null;
1411
+ }): Promise<PluginIssueAttachmentContent | null>;
1412
+ /** Read and write issue documents. Requires `issue.documents.read` / `issue.documents.write`. */
1413
+ documents: PluginIssueDocumentsClient;
1414
+ /** Read and write blocker relationships. */
1415
+ relations: PluginIssueRelationsClient;
1416
+ /** Read compact orchestration summaries. */
1417
+ summaries: PluginIssueSummariesClient;
1418
+ }
1419
+ /**
1420
+ * `ctx.approvals` — read and decide company approvals.
1421
+ *
1422
+ * Requires `approvals.read` for `list` / `get`; `approvals.respond` for
1423
+ * `decide`. Approval payloads returned by `list` / `get` are redacted host-side
1424
+ * to match the web app's own approval read surface (no secret leakage through
1425
+ * the bridge).
1426
+ */
1427
+ export interface PluginApprovalsClient {
1428
+ list(input: {
1429
+ companyId: string;
1430
+ status?: string | null;
1431
+ }): Promise<Approval[]>;
1432
+ get(approvalId: string, companyId: string): Promise<Approval | null>;
1433
+ /**
1434
+ * Approve or reject an approval on behalf of a paired board user.
1435
+ *
1436
+ * `actorUserId` is the human company member the decision is attributed to.
1437
+ * The host independently re-verifies that this user is an active human member
1438
+ * of the approval's company before applying the decision — a plugin can only
1439
+ * ever decide approvals as an identity that could have decided them in the
1440
+ * web app (whose approval-decision routes are board-only).
1441
+ *
1442
+ * `applied` is `true` when this call performed the decision and `false` when
1443
+ * the approval had already converged to a decided state (idempotent replays).
1444
+ */
1445
+ decide(approvalId: string, input: {
1446
+ action: "approve" | "reject";
1447
+ actorUserId?: string;
1448
+ decisionNote?: string | null;
1449
+ }, companyId: string): Promise<{
1450
+ approval: Approval;
1451
+ applied: boolean;
1452
+ }>;
1453
+ }
1454
+ /**
1455
+ * `ctx.agents` — read and manage agents.
1456
+ *
1457
+ * Requires `agents.read` for reads; `agents.pause` / `agents.resume` /
1458
+ * `agents.invoke` for write operations.
1459
+ */
1460
+ export interface PluginAgentRuntimeSkill {
1461
+ key: string;
1462
+ runtimeName: string;
1463
+ source: string;
1464
+ versionId?: string | null;
1465
+ currentVersionId?: string | null;
1466
+ sourceStatus?: "available" | "missing";
1467
+ missingDetail?: string | null;
1468
+ }
1469
+ export interface PluginAgentConnectionAssignments {
1470
+ features: {
1471
+ publicMcp: boolean;
1472
+ chatConnectors: boolean;
1473
+ };
1474
+ connections: Array<{
1475
+ id: string;
1476
+ name: string;
1477
+ transport: string;
1478
+ enabled: boolean;
1479
+ status: string;
1480
+ }>;
1481
+ profileIds: string[];
1482
+ }
1483
+ export interface PluginAgentRuntimeState {
1484
+ connectionAssignments: PluginAgentConnectionAssignments;
1485
+ skills: PluginAgentRuntimeSkill[];
1486
+ /** Selected company skills omitted because the environment requires the same skill name. */
1487
+ shadowedSkills?: Array<{
1488
+ key: string;
1489
+ shadowedBy: string;
1490
+ }>;
1491
+ revision: string;
1492
+ agent: Agent;
1493
+ instructionsRootPath: string | null;
1494
+ instructionsEntryFile: string;
1495
+ /** Default entry content when the agent has no instruction directory. */
1496
+ instructionsEntryContent?: string;
1497
+ instanceSecrets: Record<string, string>;
1498
+ }
1499
+ export type PluginAgentRuntimeIdentity = Pick<PluginAgentRuntimeState, "revision" | "instanceSecrets"> & {
1500
+ agent: Pick<Agent, "id" | "companyId" | "status" | "lifecycleState" | "lifecycleVersion">;
1501
+ };
1502
+ export interface PluginAgentsClient {
1503
+ getRuntimeIdentity(agentId: string, companyId: string): Promise<PluginAgentRuntimeIdentity | null>;
1504
+ /** Lifecycle reconciliation can install missing environment skills; task and recovery reads leave this false. */
1505
+ getRuntime(agentId: string, companyId: string, environmentId?: string, installEnvironmentSkills?: boolean): Promise<PluginAgentRuntimeState | null>;
1506
+ list(input: {
1507
+ companyId: string;
1508
+ status?: Agent["status"];
1509
+ limit?: number;
1510
+ offset?: number;
1511
+ }): Promise<Agent[]>;
1512
+ get(agentId: string, companyId: string): Promise<Agent | null>;
1513
+ /** Pause an agent. Throws if agent is terminated or not found. Requires `agents.pause`. */
1514
+ pause(agentId: string, companyId: string): Promise<Agent>;
1515
+ /** Resume a paused agent (sets status to idle). Throws if terminated, pending_approval, or not found. Requires `agents.resume`. */
1516
+ resume(agentId: string, companyId: string): Promise<Agent>;
1517
+ /** Invoke (wake up) an agent with a prompt payload. Throws if paused, terminated, pending_approval, or not found. Requires `agents.invoke`. */
1518
+ invoke(agentId: string, companyId: string, opts: {
1519
+ prompt: string;
1520
+ reason?: string;
1521
+ }): Promise<{
1522
+ runId: string;
1523
+ }>;
1524
+ /** Resolve and reconcile manifest-declared plugin-managed agents by stable key. Requires `agents.managed`. */
1525
+ managed: {
1526
+ get(agentKey: string, companyId: string): Promise<PluginManagedAgentResolution>;
1527
+ reconcile(agentKey: string, companyId: string): Promise<PluginManagedAgentResolution>;
1528
+ reset(agentKey: string, companyId: string): Promise<PluginManagedAgentResolution>;
1529
+ };
1530
+ /** Create, message, and close agent chat sessions. Requires `agent.sessions.*` capabilities. */
1531
+ sessions: PluginAgentSessionsClient;
1532
+ }
1533
+ /**
1534
+ * Represents an active conversational session with an agent.
1535
+ * Maps to an `AgentTaskSession` row on the host.
1536
+ */
1537
+ export interface AgentSession {
1538
+ sessionId: string;
1539
+ agentId: string;
1540
+ companyId: string;
1541
+ status: "active" | "closed";
1542
+ createdAt: string;
1543
+ }
1544
+ /**
1545
+ * A streaming event received during a session's `sendMessage` call.
1546
+ * Delivered via JSON-RPC notifications from host to worker.
1547
+ */
1548
+ export interface AgentSessionEvent {
1549
+ sessionId: string;
1550
+ runId: string;
1551
+ seq: number;
1552
+ /** The kind of event: "chunk" for output data, "status" for run state changes, "done" for end-of-stream, "error" for failures. */
1553
+ eventType: "chunk" | "status" | "done" | "error";
1554
+ stream: "stdout" | "stderr" | "system" | null;
1555
+ /**
1556
+ * Event text. On a successful `done` event this is the canonical final
1557
+ * user-facing assistant reply, or null when the run produced no reply text.
1558
+ */
1559
+ message: string | null;
1560
+ payload: Record<string, unknown> | null;
1561
+ }
1562
+ /**
1563
+ * Result of sending a message to a session.
1564
+ */
1565
+ export interface AgentSessionSendResult {
1566
+ runId: string;
1567
+ }
1568
+ /**
1569
+ * `ctx.agents.sessions` — create, message, and close agent chat sessions.
1570
+ *
1571
+ * Requires `agent.sessions.create` for create, `agent.sessions.list` for list,
1572
+ * `agent.sessions.send` for sendMessage, `agent.sessions.close` for close.
1573
+ */
1574
+ export interface PluginAgentSessionsClient {
1575
+ /** Create a new conversational session with an agent. Requires `agent.sessions.create`. */
1576
+ create(agentId: string, companyId: string, opts?: {
1577
+ taskKey?: string;
1578
+ reason?: string;
1579
+ }): Promise<AgentSession>;
1580
+ /** List active sessions for an agent owned by this plugin. Requires `agent.sessions.list`. */
1581
+ list(agentId: string, companyId: string): Promise<AgentSession[]>;
1582
+ /**
1583
+ * Send a message to a session and receive streaming events via the `onEvent` callback.
1584
+ * Returns immediately with `{ runId }`. Events are delivered asynchronously.
1585
+ * Requires `agent.sessions.send`.
1586
+ */
1587
+ sendMessage(sessionId: string, companyId: string, opts: {
1588
+ prompt: string;
1589
+ reason?: string;
1590
+ onEvent?: (event: AgentSessionEvent) => void;
1591
+ }): Promise<AgentSessionSendResult>;
1592
+ /** Close a session, releasing resources. Requires `agent.sessions.close`. */
1593
+ close(sessionId: string, companyId: string): Promise<void>;
1594
+ }
1595
+ /**
1596
+ * `ctx.goals` — read and mutate goals.
1597
+ *
1598
+ * Requires:
1599
+ * - `goals.read` for read operations
1600
+ * - `goals.create` for create
1601
+ * - `goals.update` for update
1602
+ */
1603
+ export interface PluginGoalsClient {
1604
+ list(input: {
1605
+ companyId: string;
1606
+ level?: Goal["level"];
1607
+ status?: Goal["status"];
1608
+ limit?: number;
1609
+ offset?: number;
1610
+ }): Promise<Goal[]>;
1611
+ get(goalId: string, companyId: string): Promise<Goal | null>;
1612
+ create(input: {
1613
+ companyId: string;
1614
+ title: string;
1615
+ description?: string;
1616
+ level?: Goal["level"];
1617
+ status?: Goal["status"];
1618
+ parentId?: string;
1619
+ ownerAgentId?: string;
1620
+ }): Promise<Goal>;
1621
+ update(goalId: string, patch: Partial<Pick<Goal, "title" | "description" | "level" | "status" | "parentId" | "ownerAgentId">>, companyId: string): Promise<Goal>;
1622
+ }
1623
+ export interface PluginAccessMember {
1624
+ id: string;
1625
+ companyId: string;
1626
+ principalType: PrincipalType;
1627
+ principalId: string;
1628
+ status: MembershipStatus;
1629
+ membershipRole: string | null;
1630
+ grants: PrincipalPermissionGrant[];
1631
+ createdAt: Date | string;
1632
+ updatedAt: Date | string;
1633
+ }
1634
+ export interface PluginAccessInvite {
1635
+ id: string;
1636
+ companyId: string | null;
1637
+ inviteType: string;
1638
+ allowedJoinTypes: InviteJoinType;
1639
+ defaultsPayload: Record<string, unknown> | null;
1640
+ expiresAt: Date | string;
1641
+ invitedByUserId: string | null;
1642
+ revokedAt: Date | string | null;
1643
+ acceptedAt: Date | string | null;
1644
+ createdAt: Date | string;
1645
+ updatedAt: Date | string;
1646
+ state: "active" | "revoked" | "accepted" | "expired";
1647
+ }
1648
+ export interface PluginAccessMembersClient {
1649
+ list(input: {
1650
+ companyId: string;
1651
+ includeArchived?: boolean;
1652
+ }): Promise<PluginAccessMember[]>;
1653
+ get(memberId: string, companyId: string): Promise<PluginAccessMember | null>;
1654
+ update(memberId: string, patch: {
1655
+ membershipRole?: HumanCompanyMembershipRole | null;
1656
+ status?: Extract<MembershipStatus, "pending" | "active" | "suspended">;
1657
+ }, companyId: string): Promise<PluginAccessMember>;
1658
+ }
1659
+ export interface PluginAccessInvitesClient {
1660
+ list(input: {
1661
+ companyId: string;
1662
+ state?: PluginAccessInvite["state"];
1663
+ limit?: number;
1664
+ offset?: number;
1665
+ }): Promise<{
1666
+ invites: PluginAccessInvite[];
1667
+ nextOffset: number | null;
1668
+ }>;
1669
+ create(input: {
1670
+ companyId: string;
1671
+ allowedJoinTypes?: InviteJoinType;
1672
+ humanRole?: HumanCompanyMembershipRole | null;
1673
+ defaultsPayload?: Record<string, unknown> | null;
1674
+ agentMessage?: string | null;
1675
+ }): Promise<PluginAccessInvite & {
1676
+ token: string;
1677
+ }>;
1678
+ revoke(inviteId: string, companyId: string): Promise<PluginAccessInvite>;
1679
+ }
1680
+ export interface PluginAccessClient {
1681
+ /** Read and update company memberships. Requires `access.members.*`. */
1682
+ members: PluginAccessMembersClient;
1683
+ /** Read, create, and revoke company invites. Requires `access.invites.*`. */
1684
+ invites: PluginAccessInvitesClient;
1685
+ }
1686
+ export interface PluginAuthorizationPolicySummary {
1687
+ companyId: string;
1688
+ permissionsMode: "simple";
1689
+ memberCount: number;
1690
+ activeMemberCount: number;
1691
+ grantCount: number;
1692
+ advancedPolicyAvailable: false;
1693
+ }
1694
+ export interface PluginAuthorizationPolicyRecord {
1695
+ resourceType: "company" | "agent" | "project" | "issue";
1696
+ resourceId: string;
1697
+ companyId: string;
1698
+ policy: Record<string, unknown> | null;
1699
+ updatedAt: Date | string | null;
1700
+ }
1701
+ export interface PluginAssignmentPreviewInput {
1702
+ companyId: string;
1703
+ actor: {
1704
+ type: "board";
1705
+ userId?: string | null;
1706
+ companyIds?: string[];
1707
+ isInstanceAdmin?: boolean;
1708
+ } | {
1709
+ type: "agent";
1710
+ agentId: string;
1711
+ companyId: string;
1712
+ };
1713
+ target: {
1714
+ issueId?: string | null;
1715
+ projectId?: string | null;
1716
+ parentIssueId?: string | null;
1717
+ assigneeAgentId?: string | null;
1718
+ assigneeUserId?: string | null;
1719
+ status?: string | null;
1720
+ };
1721
+ }
1722
+ export interface PluginAuthorizationDecisionResult {
1723
+ allowed: boolean;
1724
+ action: string;
1725
+ explanation: string;
1726
+ reason: string;
1727
+ grant?: {
1728
+ principalType: PrincipalType;
1729
+ principalId: string;
1730
+ permissionKey: PermissionKey;
1731
+ scope: Record<string, unknown> | null;
1732
+ };
1733
+ }
1734
+ export interface PluginAuthorizationAuditEntry {
1735
+ id: string;
1736
+ companyId: string;
1737
+ actorType: string;
1738
+ actorId: string;
1739
+ action: string;
1740
+ entityType: string;
1741
+ entityId: string;
1742
+ details: Record<string, unknown> | null;
1743
+ createdAt: Date | string;
1744
+ }
1745
+ export interface PluginAuthorizationClient {
1746
+ grants: {
1747
+ list(input: {
1748
+ companyId: string;
1749
+ principalType?: PrincipalType;
1750
+ principalId?: string;
1751
+ }): Promise<PrincipalPermissionGrant[]>;
1752
+ set(input: {
1753
+ companyId: string;
1754
+ principalType: PrincipalType;
1755
+ principalId: string;
1756
+ grants: Array<{
1757
+ permissionKey: PermissionKey;
1758
+ scope?: Record<string, unknown> | null;
1759
+ }>;
1760
+ grantedByUserId?: string | null;
1761
+ }): Promise<PrincipalPermissionGrant[]>;
1762
+ };
1763
+ policies: {
1764
+ summary(companyId: string): Promise<PluginAuthorizationPolicySummary>;
1765
+ get(input: {
1766
+ companyId: string;
1767
+ resourceType: PluginAuthorizationPolicyRecord["resourceType"];
1768
+ resourceId: string;
1769
+ }): Promise<PluginAuthorizationPolicyRecord | null>;
1770
+ update(input: {
1771
+ companyId: string;
1772
+ resourceType: PluginAuthorizationPolicyRecord["resourceType"];
1773
+ resourceId: string;
1774
+ policy: Record<string, unknown> | null;
1775
+ }): Promise<PluginAuthorizationPolicyRecord>;
1776
+ previewAssignment(input: PluginAssignmentPreviewInput): Promise<PluginAuthorizationDecisionResult>;
1777
+ explainAssignment(input: PluginAssignmentPreviewInput): Promise<PluginAuthorizationDecisionResult>;
1778
+ };
1779
+ audit: {
1780
+ search(input: {
1781
+ companyId: string;
1782
+ action?: string;
1783
+ actorType?: string;
1784
+ actorId?: string;
1785
+ entityType?: string;
1786
+ entityId?: string;
1787
+ decision?: string;
1788
+ limit?: number;
1789
+ offset?: number;
1790
+ }): Promise<PluginAuthorizationAuditEntry[]>;
1791
+ };
1792
+ }
1793
+ /**
1794
+ * `ctx.streams` — push real-time events from the worker to the plugin UI.
1795
+ *
1796
+ * The worker opens a named channel, emits events on it, and closes it when
1797
+ * done. On the UI side, `usePluginStream(channel)` receives these events in
1798
+ * real time via SSE.
1799
+ *
1800
+ * Streams are scoped to `(pluginId, channel, companyId)`. Multiple UI clients
1801
+ * can subscribe to the same channel concurrently.
1802
+ *
1803
+ * @example
1804
+ * ```ts
1805
+ * // Worker: stream chat tokens to the UI
1806
+ * ctx.streams.open("chat", companyId);
1807
+ * for await (const token of tokenStream) {
1808
+ * ctx.streams.emit("chat", { type: "token", text: token });
1809
+ * }
1810
+ * ctx.streams.close("chat");
1811
+ * ```
1812
+ *
1813
+ * @see usePluginStream in `@paperclipai/plugin-sdk/ui`
1814
+ */
1815
+ export interface PluginStreamsClient {
1816
+ /**
1817
+ * Open a named stream channel. Optional — `emit()` implicitly opens if needed.
1818
+ * Sends a `stream:open` event to connected UI clients.
1819
+ */
1820
+ open(channel: string, companyId: string): void;
1821
+ /**
1822
+ * Push an event to all UI clients subscribed to this channel.
1823
+ *
1824
+ * @param channel - Stream channel name (e.g. `"chat"`, `"logs"`)
1825
+ * @param event - JSON-serializable event payload
1826
+ */
1827
+ emit(channel: string, event: unknown): void;
1828
+ /**
1829
+ * Close a stream channel. Sends a `stream:close` event to connected UI
1830
+ * clients so they know no more events will arrive.
1831
+ */
1832
+ close(channel: string): void;
1833
+ }
1834
+ /**
1835
+ * `ctx.execution` — deliver incremental command output from an environment
1836
+ * driver's active `execute` call to the host runner log sink.
1837
+ *
1838
+ * A sandbox provider that streams a long-lived command's output calls
1839
+ * `ctx.execution.log(stream, chunk)` for each new chunk while the execute call
1840
+ * runs. The host correlates the chunk to the active execute invocation by the
1841
+ * host-issued invocation id on the message envelope, and delivers it to that
1842
+ * call's log callback before the final result. The default is a no-op that
1843
+ * never throws, so a provider that does not stream keeps its current behavior.
1844
+ *
1845
+ * The `chunk` is a text string, not raw bytes. The host drops a chunk with an
1846
+ * unknown stream name or a chunk that is empty or too large.
1847
+ */
1848
+ export interface PluginExecutionClient {
1849
+ /**
1850
+ * Deliver one incremental output chunk of the active execute call.
1851
+ *
1852
+ * @param stream - Either `"stdout"` or `"stderr"`.
1853
+ * @param chunk - The new output text for that stream.
1854
+ */
1855
+ log(stream: "stdout" | "stderr", chunk: string): void;
1856
+ }
1857
+ /**
1858
+ * `ctx.loginPty` — stream one live login pseudo-terminal's output and exit
1859
+ * from a sandbox provider worker to the host.
1860
+ *
1861
+ * The worker opener registers the output listener on the session and forwards
1862
+ * each raw chunk through `output(hostRouteId, workerSessionId, chunk)`. It
1863
+ * forwards the child exit through `exit(hostRouteId, workerSessionId,
1864
+ * exitCode)`. Each call carries the host route identifier the open request
1865
+ * carried and the worker session identifier the open reply returned, so the
1866
+ * host can hold more than one concurrent login pseudo-terminal per worker and
1867
+ * bind each chunk to its own route. The host drops a chunk or an exit that
1868
+ * carries an unknown, a stale, or a mismatched identifier, and it never logs
1869
+ * the raw bytes. The default is a no-op that never throws.
1870
+ */
1871
+ export interface PluginLoginPtyClient {
1872
+ /**
1873
+ * Deliver one raw output chunk of a live login pseudo-terminal.
1874
+ *
1875
+ * @param hostRouteId - The host route identifier the open request carried. The worker echoes it, so the host routes the chunk to its own route.
1876
+ * @param workerSessionId - The worker session identifier the open reply returned.
1877
+ * @param chunk - The raw terminal output text.
1878
+ */
1879
+ output(hostRouteId: string, workerSessionId: string, chunk: string): void;
1880
+ /**
1881
+ * Deliver the child exit of a live login pseudo-terminal.
1882
+ *
1883
+ * @param hostRouteId - The host route identifier the open request carried. The worker echoes it, so the host resolves the exit against its own route.
1884
+ * @param workerSessionId - The worker session identifier the open reply returned.
1885
+ * @param exitCode - The child exit code, or null when the child ended with no code.
1886
+ */
1887
+ exit(hostRouteId: string, workerSessionId: string, exitCode: number | null): void;
1888
+ }
1889
+ /**
1890
+ * `ctx.duplexChannel` — stream one persistent duplex channel's data and exit from
1891
+ * a sandbox provider worker to the host.
1892
+ *
1893
+ * The worker registers the data listener on the channel and forwards each raw
1894
+ * chunk through `data(workerSessionId, chunk)`. It forwards the child exit through
1895
+ * `exit(workerSessionId, exitCode)`. Each call carries the worker session
1896
+ * identifier the open reply returned, so the host binds the data to the open route
1897
+ * by that identifier while the route is open. The host drops a chunk or an exit
1898
+ * that carries an unknown or a mismatched identifier, and it never logs the raw
1899
+ * bytes. The default is a no-op that never throws. This client models the
1900
+ * `loginPty` client, but it carries no login command allowlist.
1901
+ */
1902
+ export interface PluginDuplexChannelClient {
1903
+ /**
1904
+ * Deliver one raw data chunk of a persistent duplex channel.
1905
+ *
1906
+ * @param hostRouteId - The host route identifier the open request carried. The worker echoes it, so the host routes the exact pair.
1907
+ * @param workerSessionId - The worker session identifier the open reply returned.
1908
+ * @param chunk - The raw channel output bytes.
1909
+ */
1910
+ data(hostRouteId: string, workerSessionId: string, chunk: Uint8Array): void;
1911
+ /**
1912
+ * Deliver the child exit of a persistent duplex channel.
1913
+ *
1914
+ * @param hostRouteId - The host route identifier the open request carried. The worker echoes it, so the host routes the exact pair.
1915
+ * @param workerSessionId - The worker session identifier the open reply returned.
1916
+ * @param exitCode - The child exit code, or null when the child ended with no code.
1917
+ * @param transportClosed - True when the transport closed with no exit data, so the exit is a reason-less transport close, not a process exit. Absent marks a real process exit.
1918
+ */
1919
+ exit(hostRouteId: string, workerSessionId: string, exitCode: number | null, transportClosed?: boolean): void;
1920
+ }
1921
+ /**
1922
+ * The full plugin context object passed to the plugin worker at initialisation.
1923
+ *
1924
+ * This is the central interface plugin authors use to interact with the host.
1925
+ * Every client is capability-gated: calling a client method without the
1926
+ * required capability declared in the manifest results in a runtime error.
1927
+ *
1928
+ * @example
1929
+ * ```ts
1930
+ * import { definePlugin } from "@paperclipai/plugin-sdk";
1931
+ *
1932
+ * export default definePlugin({
1933
+ * async setup(ctx) {
1934
+ * ctx.events.on("issue.created", async (event) => {
1935
+ * ctx.logger.info("Issue created", { issueId: event.entityId });
1936
+ * });
1937
+ *
1938
+ * ctx.data.register("sync-health", async ({ companyId }) => {
1939
+ * const state = await ctx.state.get({ scopeKind: "company", scopeId: String(companyId), stateKey: "last-sync" });
1940
+ * return { lastSync: state };
1941
+ * });
1942
+ * },
1943
+ * });
1944
+ * ```
1945
+ *
1946
+ * @see PLUGIN_SPEC.md §14 — SDK Surface
1947
+ */
1948
+ export interface PluginContext {
1949
+ /** The plugin's manifest as validated at install time. */
1950
+ manifest: PaperclipPluginManifestV1;
1951
+ /** Read resolved operator configuration. */
1952
+ config: PluginConfigClient;
1953
+ /** Configure and safely access trusted company-scoped local folders. */
1954
+ localFolders: PluginLocalFoldersClient;
1955
+ /** Subscribe to and emit domain events. Requires `events.subscribe` / `events.emit`. */
1956
+ events: PluginEventsClient;
1957
+ /** Register handlers for scheduled jobs. Requires `jobs.schedule`. */
1958
+ jobs: PluginJobsClient;
1959
+ /** Register launcher metadata that the host can surface in plugin UI entry points. */
1960
+ launchers: PluginLaunchersClient;
1961
+ /** Restricted plugin-owned database namespace. Requires database namespace capabilities. */
1962
+ db: PluginDatabaseClient;
1963
+ /** Make outbound HTTP requests. Requires `http.outbound`. */
1964
+ http: PluginHttpClient;
1965
+ /** Resolve secret references. Requires `secrets.read-ref`. */
1966
+ secrets: PluginSecretsClient;
1967
+ /** Write activity log entries. Requires `activity.log.write`. */
1968
+ activity: PluginActivityClient;
1969
+ /** Report Runner task startup stages. Requires `environment.drivers.register`. */
1970
+ environmentTasks: PluginEnvironmentTasksClient;
1971
+ /** Read and write scoped plugin state. Requires `plugin.state.read` / `plugin.state.write`. */
1972
+ state: PluginStateClient;
1973
+ /** Create and query plugin-owned entity records. */
1974
+ entities: PluginEntitiesClient;
1975
+ /** Read project and workspace metadata. Requires `projects.read` / `project.workspaces.read`. */
1976
+ projects: PluginProjectsClient;
1977
+ /** Read execution workspace metadata. Requires `execution.workspaces.read`. */
1978
+ executionWorkspaces: PluginExecutionWorkspacesClient;
1979
+ /** Resolve and reconcile plugin-managed routines. Requires `routines.managed`. */
1980
+ routines: PluginRoutinesClient;
1981
+ /** Resolve and reconcile plugin-managed company skills. Requires `skills.managed`. */
1982
+ skills: PluginSkillsClient;
1983
+ /** Read company metadata. Requires `companies.read`. */
1984
+ companies: PluginCompaniesClient;
1985
+ /** Read and write issues, comments, and documents. Requires issue capabilities. */
1986
+ issues: PluginIssuesClient;
1987
+ /** Read and decide company approvals. Requires `approvals.read` / `approvals.respond`. */
1988
+ approvals: PluginApprovalsClient;
1989
+ /** Read and manage agents. Requires `agents.read` for reads; `agents.pause` / `agents.resume` / `agents.invoke` for write ops. */
1990
+ agents: PluginAgentsClient;
1991
+ /** Read and mutate goals. Requires `goals.read` for reads; `goals.create` / `goals.update` for write ops. */
1992
+ goals: PluginGoalsClient;
1993
+ /** Read and manage access memberships and invites. Requires `access.*` capabilities. */
1994
+ access: PluginAccessClient;
1995
+ /** Read and manage authorization grants, policy summaries, previews, and audit entries. Requires `authorization.*` capabilities. */
1996
+ authorization: PluginAuthorizationClient;
1997
+ /** Register getData handlers for the plugin's UI components. */
1998
+ data: PluginDataClient;
1999
+ /** Register performAction handlers for the plugin's UI components. */
2000
+ actions: PluginActionsClient;
2001
+ /** Push real-time events from the worker to the plugin UI via SSE. */
2002
+ streams: PluginStreamsClient;
2003
+ /** Deliver incremental command output from the active execute call to the
2004
+ * host runner log sink. The default is a no-op for a provider that does not
2005
+ * stream. */
2006
+ execution: PluginExecutionClient;
2007
+ /** Stream one live login pseudo-terminal's output and exit to the host.
2008
+ * The default is a no-op for a provider that opens no login
2009
+ * pseudo-terminal. */
2010
+ loginPty: PluginLoginPtyClient;
2011
+ /** Stream one persistent duplex channel's data and exit to the host. The
2012
+ * default is a no-op for a provider that opens no duplex channel. */
2013
+ duplexChannel: PluginDuplexChannelClient;
2014
+ /** Register agent tool handlers. Requires `agent.tools.register`. */
2015
+ tools: PluginToolsClient;
2016
+ /** Serve plugin connector tools. Requires `connectors.provide`. */
2017
+ connectors: PluginConnectorsClient;
2018
+ /** Write plugin metrics. Requires `metrics.write`. */
2019
+ metrics: PluginMetricsClient;
2020
+ /** Emit plugin-scoped external telemetry. Requires `telemetry.track`. */
2021
+ telemetry: PluginTelemetryClient;
2022
+ /** Structured logger. Output is captured and surfaced in the plugin health dashboard. */
2023
+ logger: PluginLogger;
2024
+ /** Tracer for provider spans. The default is a no-op; the host records a span
2025
+ * only when tracing is on and an active host trace context is present. */
2026
+ tracer: PluginTracer;
2027
+ }
2028
+ //# sourceMappingURL=types.d.ts.map