@hachej/boring-agent 0.1.95 → 0.1.97

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 (45) hide show
  1. package/dist/DebugDrawer-2TO5SE2D.js +7 -0
  2. package/dist/{chunk-NITBKFG6.js → chunk-3OEDBRKY.js} +93 -58
  3. package/dist/{chunk-BOIV2I3N.js → chunk-46HJK2ES.js} +31 -16
  4. package/dist/{chunk-AQBXNPMD.js → chunk-4IQ4HHBG.js} +4 -0
  5. package/dist/{chunk-2EMAKBVR.js → chunk-CXMM24NW.js} +9039 -7788
  6. package/dist/{chunk-OFQ7J6SI.js → chunk-LSO2AO6Q.js} +57 -1
  7. package/dist/{chunk-2GBHYJVC.js → chunk-VXF5DWS6.js} +34 -0
  8. package/dist/{chunk-2TMS2RU2.js → chunk-WC5KBGP2.js} +518 -165
  9. package/dist/chunk-YGRQ4Q5P.js +20 -0
  10. package/dist/core/index.d.ts +5 -5
  11. package/dist/core/index.js +604 -7
  12. package/dist/{createHarness-UCD74XXK.js → createHarness-PW3A2MRB.js} +3 -3
  13. package/dist/{errors-G6T6S7PQ.d.ts → errors-cNC4HMpV.d.ts} +14 -7
  14. package/dist/eval/index.d.ts +5 -3
  15. package/dist/eval/index.js +31 -23
  16. package/dist/file-search-QxnanNjO.d.ts +87 -0
  17. package/dist/front/index.d.ts +86 -16
  18. package/dist/front/index.js +839 -343
  19. package/dist/front/styles.css +1171 -2129
  20. package/dist/{harness-Cc48o6uS.d.ts → harness-DS8jLKIx.d.ts} +4 -2
  21. package/dist/{lease-CusB-uLg.d.ts → lease-D8WC6pQl.d.ts} +10 -89
  22. package/dist/{middleware-CzW8n7B7.d.ts → middleware-Cq_cYHjJ.d.ts} +1 -1
  23. package/dist/piChatEvent-B3ehh9V0.d.ts +384 -0
  24. package/dist/{piChatSessionService-C0KbcGw9.d.ts → piChatSessionService-xnv8rcdh.d.ts} +1 -1
  25. package/dist/{sandbox-DAD8cWQR.d.ts → sandbox-KQiEdz4W.d.ts} +12 -1
  26. package/dist/server/agent-host/testing/compositionRouteProof.d.ts +8 -0
  27. package/dist/server/agent-host/testing/compositionRouteProof.js +78 -0
  28. package/dist/server/agent-host/testing/gatewayConformance.d.ts +6 -6
  29. package/dist/server/agent-host/testing/gatewayConformance.js +17 -9
  30. package/dist/server/index.d.ts +572 -370
  31. package/dist/server/index.js +69 -17
  32. package/dist/server/worker/index.d.ts +2 -2
  33. package/dist/server/worker/index.js +9 -9
  34. package/dist/shared/index.d.ts +212 -56
  35. package/dist/shared/index.js +43 -7
  36. package/dist/{types-C-Eroi__.d.ts → types-D_SD-7_l.d.ts} +304 -87
  37. package/docs/AGENT_GATEWAY_V0.md +6 -3
  38. package/docs/AGENT_PACKAGES.md +80 -0
  39. package/docs/ERROR_CODES.md +58 -0
  40. package/docs/README.md +1 -0
  41. package/docs/runtime.md +19 -2
  42. package/package.json +34 -29
  43. package/dist/DebugDrawer-RYEBQ6CO.js +0 -6
  44. package/dist/chunk-EOMY2HDT.js +0 -619
  45. package/dist/piChatEvent-BsMp3MSo.d.ts +0 -368
@@ -1,25 +1,32 @@
1
- import { P as ProvisionWorkspaceRuntimeOptions, W as WorkspaceProvisioningResult, R as RuntimeModeAdapter, a as RuntimeModeId, B as BuiltinRuntimeModeId, b as AgentRuntimeHostOperations, c as RuntimeBashStrategy, d as RuntimeFilesystemStrategy, M as ModeContext, e as WorkspaceProvisioningAdapter, f as RuntimeBundle, g as PiHarnessOptions, h as AgentMeteringSink, i as RuntimeFilesystemBinding, j as MeteringErrorLogger, k as ReadyStatusTracker, l as ResolvedAgentRuntimeScope, C as CreateAgentHostOptions, m as CompiledAgentHostAgentSpec, n as AgentRequestLedger, o as AgentEffectAdmission, p as AgentRequestKey, q as CreatedAgentHost, r as AgentFleetCompiler, A as AgentGatewayEffect, s as AgentRequestTarget, t as AgentRequestLedgerRecord, u as AgentRequestFailure, v as AgentHostLegacyRoutePolicy } from '../types-C-Eroi__.js';
2
- export { w as AgentHostAddressedHttpProjectionOptions, x as AgentHostAgentSpec, y as AgentHostDescription, z as AgentHostHandle, D as AgentHostHttpProjectionOptions, E as AgentHostLegacyHttpProjectionOptions, F as AgentHostLegacyProjectionComposition, G as AgentHostLegacyProjectionLifecycle, H as AgentHostLegacyProjectionRuntime, I as AgentHostLegacyRoutePolicyMountInput, J as ConfiguredAgentHostAgentSpec, L as LegacyDefaultAgentHostSpec, K as MeteringReleaseInput, N as MeteringReleaseReason, O as MeteringReservationResult, Q as MeteringReserveInput, S as MeteringRunKind, T as MeteringRunScope, U as MeteringRunStatus, V as MeteringSettleInput, X as MeteringUsage, Y as MeteringUsageInput, Z as PI_PACKAGE_RESOURCE_FILTERS, _ as PiExtensionFactory, $ as PiPackageSource, a0 as PluginSkillSource, a1 as ResolvedEnvironmentScope, a2 as RuntimeFilesystemBindingOperations, a3 as RuntimeNodePackageSpec, a4 as RuntimeProvisioningContribution, a5 as RuntimePythonSpec, a6 as RuntimeTemplateContribution, a7 as WorkspaceProvisioningExecResult, a8 as compactPiPackages, a9 as createResourceSettingsManager, aa as mergePiPackageSources, ab as normalizeMeteringUsage, ac as piPackageSourceKey } from '../types-C-Eroi__.js';
3
- import { E as ExecOptions, a as ExecResult, W as WorkspaceChangeEvent, b as Workspace, S as Sandbox } from '../sandbox-DAD8cWQR.js';
4
- import { R as RemoteWorkerWorkspaceOp, a as RemoteWorkerWorkspaceResult, b as RemoteWorkerExecRequest } from '../middleware-CzW8n7B7.js';
5
- export { c as REMOTE_WORKER_PROVIDER, d as REMOTE_WORKER_RUNTIME_CWD, e as RemoteWorkerErrorPayload, f as RemoteWorkerExecResponse, g as RemoteWorkerFsEventEnvelope, W as WORKER_INTERNAL_TOKEN_HEADER, h as WORKER_REQUEST_ID_HEADER, i as WORKER_WORKSPACE_ID_HEADER, j as createAgentAuthMiddleware } from '../middleware-CzW8n7B7.js';
1
+ import { P as ProvisionWorkspaceRuntimeOptions, W as WorkspaceProvisioningResult, a as PiPackageSource, R as RuntimeModeAdapter, b as RuntimeModeId, B as BuiltinRuntimeModeId, c as AgentRuntimeHostOperations, d as RuntimeBashStrategy, e as RuntimeFilesystemStrategy, M as ModeContext, f as WorkspaceProvisioningAdapter, g as AgentInstructionFileRef, C as ConfiguredAgentHostAgentSpec, h as AgentHostAgentSpec, i as RuntimeBundle, j as PiHarnessOptions, k as AgentMeteringSink, l as RuntimeFilesystemBinding, m as CreatedAgentHost, n as MeteringErrorLogger, o as ReadyStatusTracker, p as ResolvedAgentRuntimeScope, q as CreateAgentHostOptions, r as CompiledAgentHostAgentSpec, s as AgentRequestLedger, t as AgentEffectAdmission, u as AuthorizedEnvironmentIntent, v as AgentHostEnvironmentScope, w as AgentRequestKey, x as AgentRequestLedgerPrepareResult, y as AgentRequestFailure, z as AgentRequestLedgerRecord, D as AgentFleetCompiler, E as AgentRequestTarget, F as RuntimeFilesystemAccessDecision } from '../types-D_SD-7_l.js';
2
+ export { A as AgentGatewayEffect, G as AgentHostDescription, H as AgentHostDirectProjectionOptions, I as AgentHostDispatcherRunInput, J as AgentHostEnvironmentLease, K as AgentHostHandle, L as LegacyDefaultAgentHostSpec, N as MeteringReleaseInput, O as MeteringReleaseReason, Q as MeteringReservationResult, S as MeteringReserveInput, T as MeteringRunKind, U as MeteringRunScope, V as MeteringRunStatus, X as MeteringSettleInput, Y as MeteringUsage, Z as MeteringUsageInput, _ as PI_PACKAGE_RESOURCE_FILTERS, $ as PiExtensionFactory, a0 as PluginSkillSource, a1 as ResolvedEnvironmentScope, a2 as RuntimeFilesystemBindingOperations, a3 as RuntimeNodePackageSpec, a4 as RuntimeProvisioningContribution, a5 as RuntimePythonSpec, a6 as RuntimeTemplateContribution, a7 as WorkspaceProvisioningExecResult, a8 as compactPiPackages, a9 as mergePiPackageSources, aa as normalizeMeteringUsage, ab as piPackageSourceKey } from '../types-D_SD-7_l.js';
3
+ import { E as ExecOptions, a as ExecResult, W as WorkspaceChangeEvent, b as Workspace, S as Sandbox } from '../sandbox-KQiEdz4W.js';
4
+ export { R as RuntimeFilesystemCapability } from '../sandbox-KQiEdz4W.js';
5
+ import { R as RemoteWorkerWorkspaceOp, a as RemoteWorkerWorkspaceResult, b as RemoteWorkerExecRequest } from '../middleware-Cq_cYHjJ.js';
6
+ export { c as REMOTE_WORKER_PROVIDER, d as REMOTE_WORKER_RUNTIME_CWD, e as RemoteWorkerErrorPayload, f as RemoteWorkerExecResponse, g as RemoteWorkerFsEventEnvelope, W as WORKER_INTERNAL_TOKEN_HEADER, h as WORKER_REQUEST_ID_HEADER, i as WORKER_WORKSPACE_ID_HEADER, j as createAgentAuthMiddleware } from '../middleware-Cq_cYHjJ.js';
6
7
  import { SandboxProviderV1, WorkspaceSandboxPairV1 } from '@hachej/boring-sandbox/shared';
7
- import { S as SandboxHandleStore, C as CompiledAgentBundle, a as Sha256Digest, A as AgentDeployment, b as ShareEntryStore, P as PluginRestartWarning, W as WorkspaceAgentDispatcherContext, c as WorkspaceAgentDispatcher, d as ProviderId, e as CredentialFieldId, R as ResolvedCredentialMaterialV1, f as AuthorizedWorkspaceCredentialScopeV1, V as VerifiedWorkspaceCredentialAuthorityV1, g as WorkspaceCredentialAuthorityVerifierV1, h as CredentialConsumerBindingRegistryV1, i as ProviderRegistryV1, j as WorkspaceCredentialResolverV1, k as ProviderCredentialRefV1, l as ResolvedCredentialLeaseV1 } from '../lease-CusB-uLg.js';
8
- import { s as AgentConfig, b as Agent, d as AgentActor, j as AgentEvent, t as AgentTool, u as AgentHarnessFactory, T as TelemetrySink, A as AgentHarness } from '../harness-Cc48o6uS.js';
9
- export { v as AgentHarnessFactoryInput } from '../harness-Cc48o6uS.js';
10
- import { b as PiChatEvent, E as ErrorCode, l as SessionCtx, S as SessionStore, m as SessionListOptions, k as SessionSummary, n as PiChatSnapshot, c as PromptPayload, d as PromptReceipt, F as FollowUpPayload, e as FollowUpReceipt, f as QueueClearPayload, g as QueueClearReceipt, I as InterruptPayload, i as StopPayload, j as StopReceipt } from '../piChatEvent-BsMp3MSo.js';
11
- import { A as AgentGateway, a as AuthorizedAgentScope, b as AgentSessionRef, c as AgentSessionActivity, V as VerifiedAgentScopeClaim, d as AgentSessionSummary, e as AgentSessionStateSnapshot, f as AgentSessionConnection, J as JsonValue, g as AgentGatewayErrorDTO } from '../errors-G6T6S7PQ.js';
8
+ import { S as SandboxHandleStore, C as CompiledAgentBundle, a as Sha256Digest, A as AgentDeployment, b as ShareEntryStore, P as ProviderId, c as CredentialFieldId, R as ResolvedCredentialMaterialV1, d as AuthorizedWorkspaceCredentialScopeV1, V as VerifiedWorkspaceCredentialAuthorityV1, W as WorkspaceCredentialAuthorityVerifierV1, e as CredentialConsumerBindingRegistryV1, f as ProviderRegistryV1, g as WorkspaceCredentialResolverV1, h as ProviderCredentialRefV1, i as ResolvedCredentialLeaseV1 } from '../lease-D8WC6pQl.js';
9
+ import { E as ErrorCode, l as SessionCtx, b as PiChatEvent, S as SessionStore, m as SessionListOptions, k as SessionSummary, n as PiChatSnapshot, c as PromptPayload, d as PromptReceipt, F as FollowUpPayload, e as FollowUpReceipt, f as QueueClearPayload, g as QueueClearReceipt, I as InterruptPayload, i as StopPayload, j as StopReceipt } from '../piChatEvent-B3ehh9V0.js';
10
+ import { J as JsonValue, b as AgentGateway, c as AuthorizedAgentScope, d as AgentSessionRef, e as AgentSessionActivity, V as VerifiedAgentScopeClaim, f as AgentGatewayErrorDTO, g as AgentSessionSummary, h as AgentSessionStateSnapshot, i as AgentSessionConnection } from '../errors-cNC4HMpV.js';
11
+ import { d as AgentActor, j as AgentEvent, T as TelemetrySink, s as AgentTool, t as AgentHarnessFactory, A as AgentHarness } from '../harness-DS8jLKIx.js';
12
+ export { u as AgentConfig, v as AgentHarnessFactoryInput } from '../harness-DS8jLKIx.js';
12
13
  import { IncomingMessage, ServerResponse } from 'node:http';
13
14
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
14
- import { FastifyRequest, FastifyInstance, FastifyPluginAsync } from 'fastify';
15
- import { i as PiSessionRequestContext, g as PiChatSessionService, h as PiSessionCreateInit, e as PiChatEventSubscriber, P as PiChatEventStreamResult, a as AgentEffectAdmission$1 } from '../piChatSessionService-C0KbcGw9.js';
16
- import { BoringAgentRuntimePaths } from '@hachej/boring-sandbox/providers/node-workspace';
15
+ import { FastifyRequest, FastifyInstance, FastifyPluginCallback } from 'fastify';
16
+ import { i as PiSessionRequestContext, g as PiChatSessionService, h as PiSessionCreateInit, e as PiChatEventSubscriber, P as PiChatEventStreamResult } from '../piChatSessionService-xnv8rcdh.js';
17
+ import { W as WorkspaceAgentDirectRunInput, a as WorkspaceAgentDirectRunCallback, b as WorkspaceAgentDispatcherContext, c as WorkspaceAgentDispatcher, d as WorkspaceAgentGatewayBinding } from '../file-search-QxnanNjO.js';
18
+ export { L as LeaseBoundWorkspaceAgent } from '../file-search-QxnanNjO.js';
19
+ import { SettingsManager } from '@mariozechner/pi-coding-agent';
17
20
  import '@hachej/boring-bash/agent';
18
- import '@mariozechner/pi-coding-agent';
21
+ import '@hachej/boring-sandbox/providers/node-workspace';
19
22
  import 'zod';
20
23
 
21
24
  declare function provisionWorkspaceRuntime(opts: ProvisionWorkspaceRuntimeOptions): Promise<WorkspaceProvisioningResult>;
22
25
 
26
+ declare function createResourceSettingsManager(cwd: string, agentDir: string, piPackages: PiPackageSource[], options?: {
27
+ includePackage?: (source: PiPackageSource) => boolean;
28
+ }): SettingsManager;
29
+
23
30
  /**
24
31
  * uv setup for Python-family runtimes (e.g. Vercel `python3.13`), which already
25
32
  * ship `pip` and usually `uv`. Verify-or-install via the on-PATH `uv`.
@@ -190,8 +197,13 @@ declare function createVercelSandboxModeAdapter(options: {
190
197
  workspaceRoot: string;
191
198
  }): RuntimeModeAdapter;
192
199
 
200
+ declare function createBlaxelSandboxModeAdapter(options: {
201
+ provider: SandboxProviderV1;
202
+ runtimeHost: AgentRuntimeHostOperations;
203
+ }): RuntimeModeAdapter;
204
+
193
205
  interface ProviderRuntimeModeAdapterOptions {
194
- id: 'direct' | 'local' | 'vercel-sandbox';
206
+ id: BuiltinRuntimeModeId;
195
207
  provider: SandboxProviderV1;
196
208
  runtimeHost: AgentRuntimeHostOperations;
197
209
  workspaceFsCapability: 'strong' | 'best-effort';
@@ -214,39 +226,7 @@ interface SandboxRuntimeModeOptions {
214
226
  declare function resolveBuiltinRuntimeLayoutRoot(mode: BuiltinRuntimeModeId, workspaceRoot: string): string;
215
227
  declare function createSandboxRuntimeModeAdapter(mode: BuiltinRuntimeModeId, options?: SandboxRuntimeModeOptions): RuntimeModeAdapter;
216
228
 
217
- interface EventStreamReadResult {
218
- events: Array<{
219
- data: unknown;
220
- offset: string;
221
- }>;
222
- nextOffset: string;
223
- upToDate: boolean;
224
- closed: boolean;
225
- }
226
- interface EventStreamMeta {
227
- nextOffset: string;
228
- closed: boolean;
229
- }
230
- interface EventStreamStore {
231
- createStream(path: string): Promise<void>;
232
- appendEvent(path: string, event: unknown): Promise<string>;
233
- appendEventOnce(path: string, key: string, event: unknown): Promise<string>;
234
- appendAgentEvent(sessionId: string, chunk: PiChatEvent, opts?: {
235
- idempotencyKey?: string;
236
- streamPath?: string;
237
- }): Promise<string>;
238
- readEvents(path: string, opts?: {
239
- offset?: string;
240
- limit?: number;
241
- }): Promise<EventStreamReadResult>;
242
- closeStream(path: string): Promise<void>;
243
- getStreamMeta(path: string): Promise<EventStreamMeta | null>;
244
- subscribe(path: string, listener: () => void): () => void;
245
- }
246
-
247
- declare function createAgent(config: AgentConfig): Agent;
248
-
249
- type AgentDirectoryCompilerErrorCode = 'AGENT_DIRECTORY_NOT_FOUND' | 'AGENT_DIRECTORY_NOT_DIRECTORY' | 'AGENT_MANIFEST_NOT_FOUND' | 'AGENT_MANIFEST_NOT_FILE' | 'AGENT_MANIFEST_INVALID_UTF8' | 'AGENT_MANIFEST_INVALID_JSON' | 'AGENT_ASSET_NOT_FOUND' | 'AGENT_ASSET_NOT_FILE' | 'AGENT_ASSET_INVALID_UTF8' | 'AGENT_PATH_SYMLINK_ESCAPE' | 'AGENT_PATH_CHANGED_DURING_READ' | 'AGENT_DIRECTORY_IO_FAILED';
229
+ type AgentDirectoryCompilerErrorCode = 'AGENT_DIRECTORY_NOT_FOUND' | 'AGENT_DIRECTORY_NOT_DIRECTORY' | 'AGENT_MANIFEST_NOT_FOUND' | 'AGENT_MANIFEST_NOT_FILE' | 'AGENT_MANIFEST_INVALID_UTF8' | 'AGENT_MANIFEST_INVALID_JSON' | 'AGENT_MANIFEST_MISSING_BORING_AGENT' | 'AGENT_ASSET_NOT_FOUND' | 'AGENT_ASSET_NOT_FILE' | 'AGENT_ASSET_INVALID_UTF8' | 'AGENT_PATH_SYMLINK_ESCAPE' | 'AGENT_PATH_CHANGED_DURING_READ' | 'AGENT_DIRECTORY_IO_FAILED';
250
230
  type AgentDirectoryCompilerPublicErrorCode = Extract<ErrorCode, 'CONFIG_INVALID' | 'PATH_NOT_FOUND' | 'PATH_SYMLINK_ESCAPE'>;
251
231
  declare class AgentDirectoryCompilerError extends Error {
252
232
  readonly code: AgentDirectoryCompilerPublicErrorCode;
@@ -261,6 +241,12 @@ declare class AgentDirectoryCompilerError extends Error {
261
241
  });
262
242
  }
263
243
  declare function compileAgentDirectory(directory: string): Promise<CompiledAgentBundle>;
244
+ /**
245
+ * Compiles a persona authored as a plugin-shaped package: `package.json`'s
246
+ * `boring.agent` block stands in for `agent.json`, `instructions.md` is
247
+ * unchanged. Used for `.agents/personas/<seat>` fleet packages.
248
+ */
249
+ declare function compilePersonaPackageDirectory(directory: string): Promise<CompiledAgentBundle>;
264
250
 
265
251
  type AuthoredAgentMaterializationErrorCode = Extract<ErrorCode, 'AUTHORED_AGENT_ID_INVALID' | 'AUTHORED_AGENT_TYPE_MISMATCH' | 'AUTHORED_AGENT_REFERENCE_UNSUPPORTED'>;
266
252
  type AuthoredAgentSourceV1 = Readonly<{
@@ -270,10 +256,23 @@ type AuthoredAgentSourceV1 = Readonly<{
270
256
  label?: string;
271
257
  description?: string;
272
258
  instructions: string;
259
+ /**
260
+ * Computed identity of the compiled definition (instructions + knowledge
261
+ * bytes). The digest, not the version string, is the definition identity.
262
+ */
263
+ definitionDigest?: string;
264
+ /** Host path of the package's optional `knowledge/` folder, when present. */
265
+ knowledgeDir?: string;
273
266
  }>;
274
267
  interface MaterializeAgentDirectoryInput {
275
268
  directory: string;
276
269
  expectedAgentTypeId?: string;
270
+ /**
271
+ * Manifest shape to compile. Defaults to `agent.json` for backward
272
+ * compatibility. `package.json` reads the `boring.agent` block, used by
273
+ * plugin-shaped personas (`.agents/personas/<seat>`).
274
+ */
275
+ manifest?: 'agent.json' | 'package.json';
277
276
  }
278
277
  declare class AuthoredAgentMaterializationError extends Error {
279
278
  readonly code: AuthoredAgentMaterializationErrorCode;
@@ -290,6 +289,189 @@ declare class AuthoredAgentMaterializationError extends Error {
290
289
  */
291
290
  declare function materializeAgentDirectory(input: MaterializeAgentDirectoryInput): Promise<AuthoredAgentSourceV1>;
292
291
 
292
+ interface TrustedAgentInstructionAppendix {
293
+ readonly name: string;
294
+ readonly content: string;
295
+ readonly digest: Sha256Digest;
296
+ }
297
+ interface TrustedAuthoredAgentPolicy {
298
+ readonly fallbackLabel?: string;
299
+ /**
300
+ * Workspace-relative authored instruction sources for this agent, supplied
301
+ * by the trusted composer that actually knows where they live.
302
+ */
303
+ readonly instructionFiles?: readonly AgentInstructionFileRef[];
304
+ readonly instructionAppendices?: readonly TrustedAgentInstructionAppendix[];
305
+ readonly plugins?: readonly {
306
+ readonly name: string;
307
+ readonly config?: JsonValue;
308
+ }[];
309
+ readonly preferredModel?: string;
310
+ }
311
+ interface CreateConfiguredAgentHostAgentSpecInput {
312
+ readonly source: AuthoredAgentSourceV1;
313
+ readonly policy?: TrustedAuthoredAgentPolicy;
314
+ }
315
+ declare class TrustedAgentCompositionError extends Error {
316
+ readonly code: "CONFIG_INVALID";
317
+ readonly field: string;
318
+ constructor(field: string, message: string);
319
+ }
320
+ /**
321
+ * Maps identity-only authored data into AgentHost configuration. Every behavior
322
+ * input is supplied separately by trusted host composition.
323
+ */
324
+ declare function createConfiguredAgentHostAgentSpec(input: CreateConfiguredAgentHostAgentSpecInput): Promise<ConfiguredAgentHostAgentSpec>;
325
+
326
+ interface ModelTierCandidate {
327
+ readonly provider: string;
328
+ readonly id: string;
329
+ readonly envVar: string;
330
+ }
331
+ interface FleetSkillBinding {
332
+ readonly name: string;
333
+ readonly digest: Sha256Digest;
334
+ }
335
+ interface FleetSeatBinding {
336
+ readonly seat: string;
337
+ readonly agentTypeId: string;
338
+ readonly skills: readonly FleetSkillBinding[];
339
+ }
340
+ interface DiscoveredAgentPackageDescriptor {
341
+ readonly rootDir: string;
342
+ readonly manifest: {
343
+ readonly boring: {
344
+ readonly agent: {
345
+ readonly definitionId: string;
346
+ readonly version: string;
347
+ readonly label?: string;
348
+ readonly description?: string;
349
+ readonly instructionsRef: string;
350
+ };
351
+ };
352
+ readonly pi?: {
353
+ readonly skills?: readonly string[];
354
+ };
355
+ };
356
+ readonly preflight: {
357
+ readonly ok: boolean;
358
+ readonly errors?: readonly {
359
+ readonly code: string;
360
+ readonly message: string;
361
+ }[];
362
+ };
363
+ }
364
+ interface LoadConfiguredAgentFleetOptions {
365
+ /** Plugin-manager scan descriptors injected by the workspace/CLI boot layer. */
366
+ readonly discoveredPackages: readonly DiscoveredAgentPackageDescriptor[];
367
+ /**
368
+ * Root of the workspace the `user` filesystem serves, or `null` when the
369
+ * host resolves a DIFFERENT root per request (core, the CLI hub) and so has
370
+ * no single one at fleet-composition time.
371
+ *
372
+ * Required, because published `instructionFiles` are addressed relative to
373
+ * it and only the caller knows it. It is NOT derivable from the discovered
374
+ * package roots: a fleet can be composed from packages that live outside
375
+ * the workspace root, and guessing produced well-formed paths that
376
+ * resolved to nothing.
377
+ *
378
+ * `null` is not a soft option — it makes the host structurally unable to
379
+ * publish a ref it cannot guarantee, which is the honest answer for
380
+ * per-workspace roots.
381
+ */
382
+ readonly workspaceRoot: string | null;
383
+ /** Path to `.agents/factory/fleet.yaml`. */
384
+ readonly fleetConfigPath: string;
385
+ /** Path to `.agents/factory/policy.yaml` (read for `models.seats` tiers). */
386
+ readonly policyPath: string;
387
+ /**
388
+ * Directory containing `<skill>/SKILL.md` canonical skill sources.
389
+ * This root is host-owned because shared skill names are not package paths.
390
+ */
391
+ readonly skillsRoot: string;
392
+ /** Overridable for tests; defaults to `process.env`. */
393
+ readonly env?: NodeJS.ProcessEnv;
394
+ }
395
+ type FleetLoaderDiagnosticCode = Extract<ErrorCode, 'AGENT_FLEET_SEAT_PERSONA_INVALID' | 'AGENT_FLEET_SEAT_SKILL_DIGEST_MISMATCH' | 'AGENT_DEFINITION_ID_CONFLICT' | 'AGENT_DEFINITION_UNSEATED' | 'AGENT_FLEET_SEAT_INSTRUCTIONS_PATH_UNPUBLISHABLE'>;
396
+ interface FleetLoaderDiagnostic {
397
+ readonly seat?: string;
398
+ readonly agentTypeId: string;
399
+ readonly code: FleetLoaderDiagnosticCode;
400
+ readonly message: string;
401
+ }
402
+ interface LoadConfiguredAgentFleetResult {
403
+ readonly agents: readonly ConfiguredAgentHostAgentSpec[];
404
+ readonly diagnostics: readonly FleetLoaderDiagnostic[];
405
+ }
406
+ type FleetConfigErrorCode = Extract<ErrorCode, 'AGENT_FLEET_CONFIG_FILE_INVALID'>;
407
+ /** Thrown for whole-fleet configuration failures (not per-seat, fail-closed). */
408
+ declare class FleetConfigError extends Error {
409
+ readonly code: FleetConfigErrorCode;
410
+ readonly field: string;
411
+ constructor(input: {
412
+ field: string;
413
+ message: string;
414
+ cause?: unknown;
415
+ });
416
+ }
417
+ /**
418
+ * Loads the config-driven production/CLI agent fleet: `.agents/factory/fleet.yaml`
419
+ * seat → skill-digest bindings, boot-injected plugin-shaped persona package
420
+ * descriptors, `.agents/factory/policy.yaml` `models.seats` tiers, and the
421
+ * priority-ordered `models.tiers` candidates declared in fleet.yaml.
422
+ *
423
+ * Fails closed per seat: a persona that fails materialization, digest
424
+ * verification, or spec composition is excluded with a stable diagnostic —
425
+ * the remaining valid seats still compose. Whole-fleet config errors (an
426
+ * unreadable/malformed fleet.yaml or policy.yaml) throw `FleetConfigError`,
427
+ * since there is no seat set to fail closed against.
428
+ */
429
+ declare function loadConfiguredAgentFleet(options: LoadConfiguredAgentFleetOptions): Promise<LoadConfiguredAgentFleetResult>;
430
+
431
+ declare const LEGACY_DEFAULT_AGENT_FLEET: readonly AgentHostAgentSpec[];
432
+ interface ResolveDefaultAgentFleetOptions {
433
+ /**
434
+ * Repository root used to resolve `.agents/{factory,skills}` when
435
+ * `BORING_AGENT_FLEET=1` composes the fleet. Defaults to `process.cwd()`.
436
+ */
437
+ readonly repositoryRoot?: string;
438
+ /** Asset-manager scan results supplied by the workspace/CLI boot layer. */
439
+ readonly discoveredPackages?: readonly DiscoveredAgentPackageDescriptor[];
440
+ /**
441
+ * Root of the workspace the `user` filesystem serves, or `null` when the
442
+ * host resolves one per request. Explicit rather than defaulted, because it
443
+ * is a DIFFERENT root from `repositoryRoot` in every multi-workspace host —
444
+ * the two only coincide in the single-root dogfood/playground case.
445
+ * Personas outside it are not published as openable instruction refs (see
446
+ * `loadConfiguredAgentFleet`): a well-formed path the workbench cannot open
447
+ * is worse than no link.
448
+ */
449
+ readonly workspaceRoot: string | null;
450
+ /** Overridable for tests; defaults to `process.env`. */
451
+ readonly env?: NodeJS.ProcessEnv;
452
+ }
453
+ /**
454
+ * `BORING_AGENT_FLEET=1` composes the config-driven production fleet
455
+ * from boot-injected plugin scan descriptors plus `.agents/factory` under `repositoryRoot`
456
+ * alongside the default agent; flag absent preserves the legacy
457
+ * single-default-agent boot byte-identically. Shared by
458
+ * `createWorkspaceAgentServer`, `createCoreWorkspaceAgentServer`, and the CLI
459
+ * hub — one composition path for every production/CLI entry point.
460
+ *
461
+ * Fails closed at two levels:
462
+ * - Per seat: `loadConfiguredAgentFleet` excludes an individual invalid
463
+ * persona/skill with a stable diagnostic; the remaining seats still boot
464
+ * (see its own docstring).
465
+ * - Whole fleet: a missing/malformed `fleet.yaml` or `policy.yaml` would
466
+ * otherwise throw `FleetConfigError` out of the boot path. That throw is
467
+ * preserved for direct/programmatic callers of `loadConfiguredAgentFleet`
468
+ * (e.g. the playground, tests), but this boot-seam wrapper catches it and
469
+ * degrades to the legacy default-agent-only fleet plus a logged
470
+ * diagnostic — a container with the flag on and no `.agents/` tree must
471
+ * still boot.
472
+ */
473
+ declare function resolveDefaultAgentFleet(options: ResolveDefaultAgentFleetOptions): Promise<readonly AgentHostAgentSpec[]>;
474
+
293
475
  interface ResolvedAgentDigestInput {
294
476
  readonly workspaceId: string;
295
477
  readonly defaultDeploymentId: string;
@@ -412,7 +594,7 @@ interface ManagedAgentCollectArtifactsInput {
412
594
  }
413
595
  interface ManagedAgentMcpDelegateOptions {
414
596
  gateway?: AgentGateway;
415
- agentTypeId?: string;
597
+ agentTypeId: string;
416
598
  resolveGatewayScope?(input: {
417
599
  brief: string;
418
600
  ctx: SessionCtx;
@@ -527,23 +709,6 @@ declare function shareResourceUri(id: string): string;
527
709
  */
528
710
  declare function registerShareEntryResources(server: McpServer, options: ShareEntryMcpResourceOptions): void;
529
711
 
530
- interface ReloadHookDiagnostic {
531
- source: string;
532
- message: string;
533
- pluginId?: string;
534
- }
535
- interface ReloadHookResult {
536
- /**
537
- * One per plugin that loaded successfully but whose server-side
538
- * surfaces (routes, agentTools) still hold pre-reload code. The
539
- * /api/v1/agent/reload response surfaces these so the chat UI can
540
- * render a "restart needed" banner without subscribing to SSE.
541
- */
542
- restart_warnings?: ReadonlyArray<PluginRestartWarning>;
543
- /** Non-fatal plugin reload diagnostics to surface to the caller/UI. */
544
- diagnostics?: ReadonlyArray<ReloadHookDiagnostic>;
545
- }
546
-
547
712
  interface RuntimeEnvContributionContext {
548
713
  workspaceId: string;
549
714
  workspaceRoot: string;
@@ -554,6 +719,17 @@ interface RuntimeEnvContribution {
554
719
  id: string;
555
720
  getEnv(ctx: RuntimeEnvContributionContext): Record<string, string> | Promise<Record<string, string>>;
556
721
  }
722
+ declare function withRuntimeEnvContributions(runtimeBundle: RuntimeBundle, baseContext: RuntimeEnvContributionContext, contributions: RuntimeEnvContribution[], telemetry?: TelemetrySink): RuntimeBundle;
723
+
724
+ interface AuthorizedSessionRunDetails {
725
+ runId: string;
726
+ terminalEntryId: string;
727
+ state: 'success' | 'error' | 'aborted' | 'interrupted';
728
+ createdAt?: string;
729
+ details: readonly unknown[];
730
+ }
731
+ /** Redact a session snapshot to terminal run identity and allowlisted structured details. */
732
+ declare function projectAuthorizedSessionRunDetails(messages: readonly unknown[], detailKinds: readonly string[]): AuthorizedSessionRunDetails[];
557
733
 
558
734
  interface WorkspaceAgentDispatcherResolveOptions {
559
735
  request?: FastifyRequest;
@@ -593,47 +769,48 @@ interface WorkspaceAgentDispatcherBinding {
593
769
  }): Promise<BoundPiSession>;
594
770
  }
595
771
  interface WorkspaceAgentDispatcherResolver {
772
+ /** Callback-scoped canonical Host operation; no dispatcher or Workspace escapes. */
773
+ runWithWorkspaceAgent(input: WorkspaceAgentDirectRunInput & {
774
+ request?: FastifyRequest;
775
+ }, run: WorkspaceAgentDirectRunCallback): Promise<void>;
596
776
  resolve(ctx: WorkspaceAgentDispatcherContext, options?: WorkspaceAgentDispatcherResolveOptions): Promise<WorkspaceAgentDispatcher>;
597
777
  resolveWithWorkspace?(ctx: WorkspaceAgentDispatcherContext, options?: WorkspaceAgentDispatcherResolveOptions): Promise<WorkspaceAgentDispatcherBinding>;
778
+ /** Authorize one exact addressed native session without exposing transcript data. */
779
+ authorizeSession?(ctx: WorkspaceAgentDispatcherContext, ref: AgentSessionRef, options?: WorkspaceAgentDispatcherResolveOptions): Promise<void>;
780
+ /** Authorized transcript-redacted projection of allowlisted structured run details. */
781
+ readSessionRunDetails?(ctx: WorkspaceAgentDispatcherContext, ref: AgentSessionRef, detailKinds: readonly string[], options?: WorkspaceAgentDispatcherResolveOptions): Promise<readonly AuthorizedSessionRunDetails[]>;
598
782
  }
783
+ /**
784
+ * Bind the compatibility dispatcher surface to one addressed AgentGateway
785
+ * capability. The gateway, scope, and agent type are supplied only by the
786
+ * trusted composition root.
787
+ */
788
+ declare function createBoundWorkspaceAgentDispatcher(binding: WorkspaceAgentGatewayBinding, ctx: WorkspaceAgentDispatcherContext): WorkspaceAgentDispatcher;
599
789
 
600
- interface CreateAgentAppOptions {
790
+ interface CreateStandaloneAgentHostAppOptions {
601
791
  workspaceRoot?: string;
602
792
  sessionId?: string;
603
793
  templatePath?: string;
604
794
  mode?: RuntimeModeId;
605
- /** Supply a custom runtime adapter to plug in non-built-in sandbox/workspace modes. */
606
795
  runtimeModeAdapter?: RuntimeModeAdapter;
607
- /** Provider/runtime values supplied by the embedding host. */
608
796
  runtimeHost?: AgentRuntimeHostOperations;
609
797
  authToken?: string;
610
798
  version?: string;
611
799
  logger?: boolean;
800
+ /** Standalone defaults to a warm runtime; readiness smokes may keep binding lazy. */
801
+ initializeRuntime?: boolean;
612
802
  extraTools?: AgentTool[];
613
- /** When true, omit the six filesystem tools (read/write/edit/find/grep/ls). */
614
803
  disableDefaultFileTools?: boolean;
615
- /**
616
- * Append-only addendum to the underlying agent's system prompt. Cannot
617
- * replace the base prompt — host apps EXTEND it (e.g. document app-
618
- * specific tools, panes, data conventions). Plumbed to pi-coding-agent
619
- * via DefaultResourceLoader's `appendSystemPromptSource`.
620
- */
621
804
  systemPromptAppend?: string;
622
- /** Override the default pi-backed harness with a custom agent runtime. */
623
805
  harnessFactory?: AgentHarnessFactory;
624
- /** Optional pi adapter/runtime knobs used by the default harness. */
625
806
  pi?: PiHarnessOptions;
626
- /** Optional runtime provisioning result used to wire generated PATH/env/skills into tools and Pi. */
807
+ /** Additional host roots allowed to contribute local Pi resource bytes. */
808
+ piResourceAuthorizedRoots?: string[];
627
809
  runtimeProvisioning?: WorkspaceProvisioningResult;
628
- /** Optional dynamic runtime provisioning source used after /reload refreshes generated env/PATH. */
629
810
  getRuntimeProvisioning?: () => WorkspaceProvisioningResult | undefined;
630
- /** Optional stable namespace for file-backed session storage. */
631
811
  sessionNamespace?: string;
632
- /** Optional best-effort telemetry sink supplied by an embedding host. */
633
812
  telemetry?: TelemetrySink;
634
- /** Optional billing sink for native Pi usage (see AgentMeteringSink). */
635
813
  metering?: AgentMeteringSink;
636
- /** Generic filesystem binding seam for standalone embeddings. */
637
814
  getFilesystemBindings?: (ctx: {
638
815
  request?: FastifyRequest;
639
816
  sessionId?: string;
@@ -644,47 +821,40 @@ interface CreateAgentAppOptions {
644
821
  userEmailVerified?: boolean;
645
822
  requestId?: string;
646
823
  }) => RuntimeFilesystemBinding[] | undefined | Promise<RuntimeFilesystemBinding[] | undefined>;
647
- /**
648
- * Trusted host seam for resolving Pi HTTP session scope. The default keeps
649
- * unauthenticated requests workspace-only and authenticated requests user-scoped.
650
- */
651
824
  resolvePiSessionRequestContext?: (request: FastifyRequest, defaultContext: PiSessionRequestContext) => PiSessionRequestContext | Promise<PiSessionRequestContext>;
652
- /** Generic runtime env contributors. Agent stays workspace-neutral; hosts decide env names/values. */
653
825
  runtimeEnvContributions?: RuntimeEnvContribution[];
654
- /** Runtime-aware provisioning hook. Runs after Workspace/Sandbox creation and before tools/harness. */
655
826
  runtimeProvisioner?: (ctx: {
656
827
  workspaceRoot: string;
657
828
  runtimeMode: RuntimeModeId;
658
829
  runtimeBundle: RuntimeBundle;
659
830
  }) => Promise<void>;
660
- /** Optional explicit file-backed session directory. Mostly for tests/hosts. */
661
831
  sessionDir?: string;
662
- /** Optional explicit root for file-backed session directories. */
663
832
  sessionRoot?: string;
664
- /**
665
- * Enable user/global Pi extension auto-discovery from .pi/ and ~/.pi.
666
- * App/internal plugins should be passed through extraTools/pi instead.
667
- * Defaults to true for standalone agent compatibility.
668
- */
669
833
  externalPlugins?: boolean;
670
- /**
671
- * Called BEFORE the harness reloads its session. May return a
672
- * `ReloadHookResult` (with `restart_warnings` and/or diagnostics) —
673
- * surfaced verbatim on the /api/v1/agent/reload response. `void` /
674
- * undefined return = no warnings (backwards compatible).
675
- */
676
- beforeReload?: () => void | ReloadHookResult | undefined | Promise<void | ReloadHookResult | undefined>;
677
- /**
678
- * Optional dynamic system-prompt source forwarded to the harness. The
679
- * harness calls it whenever it builds or rebuilds a session prompt. Used by
680
- * the workspace plugin layer.
681
- */
834
+ beforeReload?: () => void | {
835
+ readonly diagnostics?: ReadonlyArray<{
836
+ source: string;
837
+ message: string;
838
+ pluginId?: string;
839
+ }>;
840
+ readonly restart_warnings?: ReadonlyArray<{
841
+ id: string;
842
+ surfaces: readonly string[];
843
+ message: string;
844
+ }>;
845
+ } | undefined | Promise<void | {
846
+ readonly diagnostics?: ReadonlyArray<{
847
+ source: string;
848
+ message: string;
849
+ pluginId?: string;
850
+ }>;
851
+ readonly restart_warnings?: ReadonlyArray<{
852
+ id: string;
853
+ surfaces: readonly string[];
854
+ message: string;
855
+ }>;
856
+ } | undefined>;
682
857
  systemPromptDynamic?: () => string | undefined | Promise<string | undefined>;
683
- /**
684
- * Optional host callback returning current plugin/skill load diagnostics
685
- * for this workspace. Surfaced by the `plugin_diagnostics` agent tool so the
686
- * model can iterate on plugin/skill load errors after a /reload.
687
- */
688
858
  getPluginDiagnostics?: (args: {
689
859
  workspaceId: string;
690
860
  workspaceRoot: string;
@@ -693,13 +863,52 @@ interface CreateAgentAppOptions {
693
863
  message: string;
694
864
  pluginId?: string;
695
865
  }>>;
696
- /**
697
- * Trusted in-process host composition seam. The resolver trusts caller-supplied
698
- * workspace/user context; callers must authorize that context before resolving.
699
- */
700
866
  onWorkspaceAgentDispatcher?: (resolver: WorkspaceAgentDispatcherResolver) => void;
701
867
  }
702
- declare function createAgentApp(opts?: CreateAgentAppOptions): Promise<FastifyInstance>;
868
+ /** Thin standalone HTTP shell over one directly composed CreatedAgentHost. */
869
+ declare function createStandaloneAgentHostApp(options?: CreateStandaloneAgentHostAppOptions): Promise<FastifyInstance>;
870
+
871
+ interface AgentHostEnvironmentHttpProjectionOptions {
872
+ readonly created: CreatedAgentHost;
873
+ readonly authorizeAgentRequest: (request: FastifyRequest) => Promise<AuthorizedAgentScope>;
874
+ readonly runtimeHost?: AgentRuntimeHostOperations;
875
+ readonly getWorkspaceHostRoot?: (request: FastifyRequest) => string | undefined | Promise<string | undefined>;
876
+ }
877
+ /**
878
+ * Mount application-owned filesystem routes over finite Host Environment leases.
879
+ * The FS event stream explicitly retains its lease until the transport closes.
880
+ */
881
+ declare function registerAgentHostEnvironmentRoutes(app: FastifyInstance, options: AgentHostEnvironmentHttpProjectionOptions): Promise<void>;
882
+
883
+ interface EventStreamReadResult {
884
+ events: Array<{
885
+ data: unknown;
886
+ offset: string;
887
+ }>;
888
+ nextOffset: string;
889
+ upToDate: boolean;
890
+ closed: boolean;
891
+ }
892
+ interface EventStreamMeta {
893
+ nextOffset: string;
894
+ closed: boolean;
895
+ }
896
+ interface EventStreamStore {
897
+ createStream(path: string): Promise<void>;
898
+ appendEvent(path: string, event: unknown): Promise<string>;
899
+ appendEventOnce(path: string, key: string, event: unknown): Promise<string>;
900
+ appendAgentEvent(sessionId: string, chunk: PiChatEvent, opts?: {
901
+ idempotencyKey?: string;
902
+ streamPath?: string;
903
+ }): Promise<string>;
904
+ readEvents(path: string, opts?: {
905
+ offset?: string;
906
+ limit?: number;
907
+ }): Promise<EventStreamReadResult>;
908
+ closeStream(path: string): Promise<void>;
909
+ getStreamMeta(path: string): Promise<EventStreamMeta | null>;
910
+ subscribe(path: string, listener: () => void): () => void;
911
+ }
703
912
 
704
913
  interface HarnessPiChatServiceOptions {
705
914
  harness: AgentHarness;
@@ -718,6 +927,15 @@ interface HarnessPiChatServiceOptions {
718
927
  onEvent?: (sessionId: string, event: PiChatEvent) => void;
719
928
  /** Receives non-fatal metering pipeline failures (default: console.warn). */
720
929
  meteringLogger?: MeteringErrorLogger;
930
+ /** Canonical HTTP projection for lazily loaded persisted attachment bytes. */
931
+ attachmentUrl?: (input: {
932
+ readonly sessionId: string;
933
+ readonly messageId: string;
934
+ readonly index: number;
935
+ readonly data?: string;
936
+ readonly mediaType?: string;
937
+ readonly filename?: string;
938
+ }) => string;
721
939
  }
722
940
  declare class HarnessPiChatService implements PiChatSessionService {
723
941
  private readonly harness;
@@ -726,12 +944,15 @@ declare class HarnessPiChatService implements PiChatSessionService {
726
944
  private readonly workspace?;
727
945
  private readonly eventStore?;
728
946
  private readonly onEvent?;
947
+ private readonly attachmentUrl?;
729
948
  private readonly channels;
730
949
  private readonly channelCreations;
950
+ private readonly sessionGenerations;
731
951
  private readonly messageMetadata;
732
952
  private readonly activePromptRuns;
733
953
  private readonly syntheticPromptFailures;
734
954
  private readonly activeSyntheticPromptErrors;
955
+ private readonly liveAttachments;
735
956
  private readonly lifecycle;
736
957
  private readonly metering?;
737
958
  private disposePromise?;
@@ -745,14 +966,25 @@ declare class HarnessPiChatService implements PiChatSessionService {
745
966
  deleteSession(ctx: PiSessionRequestContext, sessionId: string): Promise<void>;
746
967
  private deleteSessionBeforeDispose;
747
968
  readAttachment(ctx: PiSessionRequestContext, sessionId: string, messageId: string, index: number): Promise<{
748
- data: Uint8Array;
749
- mediaType: string;
750
- filename?: string;
969
+ readonly data: Uint8Array;
970
+ readonly mediaType: string;
971
+ readonly filename?: string;
751
972
  }>;
752
973
  readState(ctx: PiSessionRequestContext, sessionId: string): Promise<PiChatSnapshot>;
753
974
  private readStateBeforeDispose;
975
+ /**
976
+ * The persisted transcript can lag the live adapter: transcript writes are
977
+ * asynchronous, and some harnesses never persist transcripts at all. A
978
+ * persisted refresh whose seq fences the live replay buffer while its
979
+ * messages are missing would permanently hide those turns from a hydrating
980
+ * client (it starts "caught up" at that seq with an empty timeline), so
981
+ * refresh from persisted state only when it carries at least as much
982
+ * rendered history as the live adapter.
983
+ */
984
+ private persistedStateDropsLiveMessages;
754
985
  private canRefreshFromPersistedState;
755
986
  private harnessMayHaveLiveSession;
987
+ private attachmentUrlFor;
756
988
  private readPersistedState;
757
989
  subscribe(ctx: PiSessionRequestContext, sessionId: string, cursor: number, subscriber: PiChatEventSubscriber): Promise<PiChatEventStreamResult>;
758
990
  private subscribeBeforeDispose;
@@ -788,8 +1020,23 @@ declare class HarnessPiChatService implements PiChatSessionService {
788
1020
  private ensureChannel;
789
1021
  /** Coalesce concurrent cold callers so only one adapter subscription wins. */
790
1022
  private createChannelOnce;
1023
+ private generationOf;
1024
+ private assertSessionIncarnation;
791
1025
  private buildChannel;
1026
+ /** Cheap cold-snapshot seq lookup (no buffer hydration) — see {@link hydrateDurableReplayBuffer} for the live-channel path. */
792
1027
  private readDurableLatestPiChatSeq;
1028
+ /**
1029
+ * On cold channel construction, rehydrate a fresh {@link PiChatReplayBuffer}
1030
+ * from the durable event store (when present) so resuming clients replay
1031
+ * genuinely — not merely resume seq counting from a high-water-mark with an
1032
+ * empty buffer, which forces every behind-the-tip cursor into
1033
+ * `PI_CHAT_REPLAY_GAP`. Reads at most the buffer's own retention window
1034
+ * (`DEFAULT_REPLAY_BUFFER_MAX_EVENTS`) worth of trailing entries — older
1035
+ * history is already outside what the in-memory buffer would retain even
1036
+ * across a live process, so this preserves prior semantics for very long
1037
+ * streams while fixing the common "just restarted" resume case.
1038
+ */
1039
+ private hydrateDurableReplayBuffer;
793
1040
  /**
794
1041
  * Validate the persisted session identity and instantiate its lazily-created
795
1042
  * Pi adapter under the same full cache key. This is intentionally a narrow
@@ -815,7 +1062,6 @@ interface EnvironmentLease {
815
1062
  }
816
1063
 
817
1064
  interface BuiltAgentComposition {
818
- readonly agent: Agent;
819
1065
  readonly harness: AgentHarness;
820
1066
  readonly sessionStore: SessionStore;
821
1067
  readonly service: HarnessPiChatService;
@@ -831,17 +1077,27 @@ interface AgentSessionRuntimeAuthority {
831
1077
  /** Absent only for a pre-AH0 transcript created before runtime pins existed. */
832
1078
  readonly runtimeScopeIdentity?: string;
833
1079
  }
1080
+ interface AgentSessionActivityUpdate {
1081
+ readonly ref: AgentSessionRef;
1082
+ readonly status: AgentSessionActivity;
1083
+ }
834
1084
  /** Process-lifetime live-turn projection. Reads never create activity rows. */
835
1085
  declare class AgentSessionActivityIndex {
836
1086
  private readonly activity;
1087
+ private readonly subscribers;
837
1088
  get(workspaceScopeId: string, ref: AgentSessionRef): AgentSessionActivity;
838
- set(workspaceScopeId: string, ref: AgentSessionRef, activity: AgentSessionActivity): void;
1089
+ set(workspaceScopeId: string, ref: AgentSessionRef, status: AgentSessionActivity): void;
1090
+ snapshot(workspaceScopeId: string): AgentSessionActivityUpdate[];
1091
+ subscribe(workspaceScopeId: string, subscriber: (update: AgentSessionActivityUpdate) => void): () => void;
839
1092
  delete(workspaceScopeId: string, ref: AgentSessionRef): void;
840
1093
  observe(workspaceScopeId: string, ref: AgentSessionRef, event: PiChatEvent): void;
841
1094
  }
842
1095
 
843
1096
  interface RuntimeBinding {
844
1097
  readonly key: string;
1098
+ readonly agentTypeId: string;
1099
+ readonly workspaceScopeId: string;
1100
+ readonly generation: number;
845
1101
  readonly scope: ResolvedAgentRuntimeScope;
846
1102
  readonly environmentLease: EnvironmentLease;
847
1103
  readonly composition: BuiltAgentComposition;
@@ -853,21 +1109,45 @@ interface AgentHostRuntime {
853
1109
  readonly ledger: AgentRequestLedger;
854
1110
  readonly effectAdmission: AgentEffectAdmission;
855
1111
  readonly activity: AgentSessionActivityIndex;
1112
+ readonly shutdownGraceMs: number;
856
1113
  listSessionSummaries(agentTypeId: string, scope: AuthorizedAgentScope, claim: VerifiedAgentScopeClaim): Promise<readonly SessionSummary[]>;
857
1114
  isDraining(): boolean;
858
1115
  assertOpen(): void;
859
1116
  verify(scope: AuthorizedAgentScope): Promise<VerifiedAgentScopeClaim>;
1117
+ resolveEnvironmentScope(scope: AuthorizedAgentScope, claim: VerifiedAgentScopeClaim, intent: AuthorizedEnvironmentIntent): Promise<AgentHostEnvironmentScope>;
1118
+ acquireEnvironment(scope: AuthorizedAgentScope, claim: VerifiedAgentScopeClaim, intent: AuthorizedEnvironmentIntent): Promise<EnvironmentLease>;
1119
+ acquireResolvedEnvironment(workspaceScopeId: string, environment: AgentHostEnvironmentScope): Promise<EnvironmentLease>;
860
1120
  resolveSessionRuntime(agentTypeId: string, scope: AuthorizedAgentScope, claim: VerifiedAgentScopeClaim, sessionId: string): Promise<AgentSessionRuntimeAuthority | undefined>;
861
- resolveBinding(agentTypeId: string, scope: AuthorizedAgentScope, claim: VerifiedAgentScopeClaim, resolvedRuntimeScope?: ResolvedAgentRuntimeScope): Promise<RuntimeBinding>;
1121
+ resolveAgentRuntimeScope(agentTypeId: string, scope: AuthorizedAgentScope, claim: VerifiedAgentScopeClaim, operation: 'new-binding' | 'existing-session' | 'reload', requestId: string, sessionId?: string): Promise<ResolvedAgentRuntimeScope>;
1122
+ resolveBinding(agentTypeId: string, scope: AuthorizedAgentScope, claim: VerifiedAgentScopeClaim, resolvedRuntimeScope?: ResolvedAgentRuntimeScope, purpose?: 'current' | 'pinned'): Promise<RuntimeBinding>;
1123
+ findPublishedBinding(agentTypeId: string, workspaceScopeId: string, runtimeScopeIdentity?: string, physicalBindingIdentity?: string, provisioningFingerprint?: string): RuntimeBinding | undefined;
1124
+ findPublishedCurrentBinding(agentTypeId: string, workspaceScopeId: string, physicalBindingIdentity: string, runtimeScopeIdentity?: string, provisioningFingerprint?: string): RuntimeBinding | undefined;
862
1125
  startDrain(): void;
863
1126
  drainRuntime(): Promise<void>;
864
1127
  registerSubscription(close: () => void | Promise<void>): () => void;
865
- trackEffect<T>(effect: Promise<T>, key: AgentRequestKey): Promise<T>;
866
- retireCompatibilityComposition(composition: BuiltAgentComposition): Promise<void>;
1128
+ startPreparedEffect<T>(key: AgentRequestKey, effect: () => Promise<T>): Promise<T>;
1129
+ runBindingOperation<T>(bindingKey: string, operation: () => Promise<T>): Promise<T>;
867
1130
  closeRuntime(): Promise<void>;
868
1131
  }
869
1132
  declare function createAgentHost(options: CreateAgentHostOptions): Promise<CreatedAgentHost>;
870
1133
 
1134
+ /** SQLite-backed atomic ownership/CAS ledger for direct and production projections. */
1135
+ declare class SqliteAgentRequestLedger implements AgentRequestLedger {
1136
+ readonly durability: "durable-transactional";
1137
+ private readonly database;
1138
+ constructor(path: string);
1139
+ prepare(key: AgentRequestKey, digest: string): Promise<AgentRequestLedgerPrepareResult>;
1140
+ acceptAdmission(key: AgentRequestKey, admissionReceipt: string): Promise<void>;
1141
+ beginEffect(key: AgentRequestKey): Promise<void>;
1142
+ reject(key: AgentRequestKey, failure: AgentRequestFailure): Promise<void>;
1143
+ complete(key: AgentRequestKey, receipt: JsonValue): Promise<void>;
1144
+ markOutcomeUnknown(key: AgentRequestKey, error: AgentGatewayErrorDTO): Promise<void>;
1145
+ read(key: AgentRequestKey): Promise<AgentRequestLedgerRecord | undefined>;
1146
+ close(): void;
1147
+ private readSync;
1148
+ private transition;
1149
+ }
1150
+
871
1151
  declare const AgentFleetCompilationErrorCode: {
872
1152
  readonly AGENT_FLEET_PLUGIN_UNKNOWN: "AGENT_FLEET_PLUGIN_UNKNOWN";
873
1153
  readonly AGENT_FLEET_CONFIG_BINDING_UNKNOWN: "AGENT_FLEET_CONFIG_BINDING_UNKNOWN";
@@ -898,20 +1178,44 @@ interface CreateValidatingAgentFleetCompilerOptions {
898
1178
  */
899
1179
  declare function createValidatingAgentFleetCompiler(options: CreateValidatingAgentFleetCompilerOptions): AgentFleetCompiler;
900
1180
 
901
- type RetryableSessionGuard = () => Promise<AgentGatewayErrorDTO | undefined>;
902
1181
  declare class EmbeddedAgentGateway implements AgentGateway {
903
1182
  private readonly runtime;
904
1183
  private readonly cursorSecret;
905
1184
  private readonly connections;
906
- private readonly effects;
907
1185
  private readonly pins;
1186
+ private readonly unpinnedSessionFallbackPins;
908
1187
  private readonly writerTails;
909
1188
  private sessionRuntimeResolutionObserver?;
910
1189
  private closed;
911
1190
  constructor(runtime: AgentHostRuntime);
1191
+ /** Host-owned addressed runtime-capability effect seam. */
1192
+ runHostEffect(input: {
1193
+ readonly scope: AuthorizedAgentScope;
1194
+ readonly operation: 'agent.reload' | 'session.command.execute';
1195
+ readonly target: AgentRequestTarget;
1196
+ readonly requestId: string;
1197
+ readonly payload: JsonValue;
1198
+ readonly action: () => Promise<JsonValue>;
1199
+ readonly classify?: () => Promise<{
1200
+ readonly kind: 'execute';
1201
+ } | {
1202
+ readonly kind: 'reject';
1203
+ readonly error: AgentGatewayErrorDTO;
1204
+ }>;
1205
+ }): Promise<JsonValue>;
1206
+ /** Host-internal resolver shared by every session-bearing capability route. */
1207
+ resolveHostSessionBinding(scope: AuthorizedAgentScope, ref: AgentSessionRef): Promise<{
1208
+ claim: VerifiedAgentScopeClaim;
1209
+ binding: RuntimeBinding;
1210
+ }>;
1211
+ /** Side-effect-free reload lookup: validates persisted existence/pin and requires an already-published binding. */
1212
+ inspectPublishedSessionBinding(scope: AuthorizedAgentScope, ref: AgentSessionRef): Promise<{
1213
+ claim: VerifiedAgentScopeClaim;
1214
+ binding: RuntimeBinding;
1215
+ }>;
912
1216
  /** Server-only test observer for distinguishing runtime pin resolution paths. */
913
1217
  setSessionRuntimeResolutionObserverForTesting(observer: (input: {
914
- readonly source: 'pre-ah0-compatibility-fallback' | 'persisted-runtime-pin';
1218
+ readonly source: 'unpinned-session-fallback' | 'persisted-runtime-pin';
915
1219
  readonly runtimeScopeIdentity: string;
916
1220
  }) => void): void;
917
1221
  /** Test-only activity seam used by the shared implementation conformance. */
@@ -925,6 +1229,7 @@ declare class EmbeddedAgentGateway implements AgentGateway {
925
1229
  version: string;
926
1230
  digest: string;
927
1231
  } | undefined;
1232
+ pluginIds?: string[] | undefined;
928
1233
  agentTypeId: string;
929
1234
  label: string;
930
1235
  }[]>;
@@ -942,20 +1247,12 @@ declare class EmbeddedAgentGateway implements AgentGateway {
942
1247
  private bindingForSession;
943
1248
  private loadSummary;
944
1249
  private sessionEffect;
945
- /** Internal legacy-alias seam; never exposed through the public Gateway contract. */
946
- runLegacyCompatibilityEffect(input: {
947
- readonly scope: AuthorizedAgentScope;
948
- readonly operation: AgentGatewayEffect;
949
- readonly target: AgentRequestTarget;
950
- readonly requestId: string;
951
- readonly payload: JsonValue;
952
- readonly action: () => Promise<unknown>;
953
- readonly retryableGuard?: RetryableSessionGuard;
954
- }): Promise<unknown>;
955
1250
  private effect;
1251
+ private applyClassification;
956
1252
  private replayReceipt;
957
1253
  private failure;
958
1254
  private promptAdmission;
1255
+ private queueClearAdmission;
959
1256
  private withWriter;
960
1257
  private encodeCursor;
961
1258
  private decodeCursor;
@@ -963,8 +1260,9 @@ declare class EmbeddedAgentGateway implements AgentGateway {
963
1260
 
964
1261
  /** Process-lifetime Level-B ledger with the exact published state machine. */
965
1262
  declare class InMemoryAgentRequestLedger implements AgentRequestLedger {
1263
+ readonly durability: "in-memory";
966
1264
  private readonly records;
967
- prepare(key: AgentRequestKey, digest: string): Promise<AgentRequestLedgerRecord>;
1265
+ prepare(key: AgentRequestKey, digest: string): Promise<AgentRequestLedgerPrepareResult>;
968
1266
  acceptAdmission(key: AgentRequestKey, admissionReceipt: string): Promise<void>;
969
1267
  beginEffect(key: AgentRequestKey): Promise<void>;
970
1268
  reject(key: AgentRequestKey, failure: AgentRequestFailure): Promise<void>;
@@ -981,10 +1279,12 @@ interface RuntimeScopeIdentityInput {
981
1279
  }[];
982
1280
  readonly validatedConfig: JsonValue;
983
1281
  readonly grants: readonly string[];
984
- readonly placementIdentity: string;
1282
+ /** Stable semantic placement class; never an absolute root or lease key. */
1283
+ readonly placementClassIdentity: string;
985
1284
  readonly isolationMode: string;
986
1285
  readonly toolContractDigests: readonly string[];
987
- readonly provisioningGeneration: string;
1286
+ /** Stable semantic provisioning contract. */
1287
+ readonly provisioningIdentity: string;
988
1288
  readonly bindingInputs?: JsonValue;
989
1289
  }
990
1290
  interface EnvironmentProvisioningIdentityInput {
@@ -1014,247 +1314,149 @@ declare function applyCspHeaders(response: HeaderLike, opts?: {
1014
1314
  dev?: boolean;
1015
1315
  }): void;
1016
1316
 
1017
- interface AgentModelSelection {
1018
- provider: string;
1019
- id: string;
1317
+ interface DeepLinkRoutesOptions {
1318
+ /** Workspace-agnostic store: entries carry their own `workspaceId`. */
1319
+ store: ShareEntryStore;
1320
+ workspace?: Workspace;
1321
+ /**
1322
+ * Resolves the `Workspace` already authorized for the request's scoped
1323
+ * workspace (the same `getWorkspace` shape used by fileRoutes/treeRoutes —
1324
+ * membership for this workspace is enforced upstream, before this route's
1325
+ * handler runs, by the host's existing `onRequest` seam).
1326
+ */
1327
+ getWorkspace?: (request: FastifyRequest) => Workspace | Promise<Workspace>;
1328
+ }
1329
+ declare const deepLinkRoutes: FastifyPluginCallback<DeepLinkRoutesOptions>;
1330
+
1331
+ interface SkillMetadataFrontmatter {
1332
+ readonly name?: string;
1333
+ readonly description?: string;
1020
1334
  }
1335
+ declare function parseSkillMetadataFrontmatter(content: string): SkillMetadataFrontmatter;
1336
+
1337
+ interface PiResourceDigestLimits {
1338
+ readonly maxDepth: number;
1339
+ readonly maxFiles: number;
1340
+ readonly maxFileBytes: number;
1341
+ readonly maxTotalBytes: number;
1342
+ }
1343
+ declare const DEFAULT_PI_RESOURCE_DIGEST_LIMITS: PiResourceDigestLimits;
1344
+ interface PiResourceDigestInput {
1345
+ /** Cwd passed to Pi. Explicit skills/extensions resolve from here. */
1346
+ readonly piCwd: string;
1347
+ /** Pi user agent directory. User settings/package sources resolve from here. */
1348
+ readonly piAgentDir: string;
1349
+ /** User home Pi uses for ~/.agents skill discovery. */
1350
+ readonly piUserHome: string;
1351
+ /** Mirrors Pi's noSkills resource-loader option. */
1352
+ readonly noSkills: boolean;
1353
+ readonly promptParts?: readonly (string | undefined)[];
1354
+ readonly additionalSkillPaths?: readonly string[];
1355
+ readonly packages?: readonly PiPackageSource[];
1356
+ readonly extensionPaths?: readonly string[];
1357
+ /** Lexical roots explicitly authorized by the embedding Workspace/CLI. */
1358
+ readonly authorizedRoots: readonly string[];
1359
+ /** CLI workspaces may contain repo-managed symlinks (e.g. .pi/skills/*). */
1360
+ readonly allowInternalSymlinks?: boolean;
1361
+ readonly limits?: Partial<PiResourceDigestLimits>;
1362
+ }
1363
+ interface PiResourceSet {
1364
+ readonly promptParts?: readonly (string | undefined)[];
1365
+ readonly additionalSkillPaths?: readonly string[];
1366
+ readonly packages?: readonly PiPackageSource[];
1367
+ readonly extensionPaths?: readonly string[];
1368
+ }
1369
+ /** Canonical normalization shared by Workspace and CLI resource resolvers. */
1370
+ declare function createPiResourceDigestInput(input: {
1371
+ readonly piCwd: string;
1372
+ readonly piAgentDir?: string;
1373
+ readonly piUserHome?: string;
1374
+ readonly noSkills?: boolean;
1375
+ readonly resourceSets: readonly PiResourceSet[];
1376
+ readonly authorizedRoots: readonly string[];
1377
+ readonly allowInternalSymlinks?: boolean;
1378
+ readonly limits?: Partial<PiResourceDigestLimits>;
1379
+ }): PiResourceDigestInput;
1380
+ /** Bounded asynchronous content identity for the exact Pi resources considered by a reload candidate. */
1381
+ declare function digestPiResourceInputs(input: PiResourceDigestInput): Promise<string>;
1382
+ /** Immutable digest plus the reload fences that defend that exact snapshot. */
1383
+ declare function createPiResourceDigestFence(resolveInput: () => PiResourceDigestInput | Promise<PiResourceDigestInput>): Promise<{
1384
+ readonly resourceInputDigest: string;
1385
+ readonly revalidateResourceInputs: () => Promise<void>;
1386
+ }>;
1021
1387
 
1022
1388
  /**
1023
- * GET /api/v1/agent/models
1389
+ * `plugin_diagnostics` built-in agent tool.
1024
1390
  *
1025
- * Returns the list of models pi-coding-agent has auth for (i.e. where
1026
- * the corresponding provider API key is present in the environment or
1027
- * `~/.pi/agent/auth.json`). Consumers — including the shadcn example
1028
- * ChatPanel — fetch this endpoint to populate the model-selector dropdown
1029
- * instead of hardcoding a short alias list.
1391
+ * Surfaces current plugin/skill loading errors to the agent so it can iterate
1392
+ * on them without the failures being silently swallowed. It merges three
1393
+ * sources:
1030
1394
  *
1031
- * Shape:
1032
- * {
1033
- * models: [
1034
- * { provider: "anthropic", id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6", available: true },
1035
- * ...
1036
- * ]
1037
- * }
1395
+ * - `lastReloadDiagnostics`: diagnostics captured by the most recent
1396
+ * /api/v1/agents/:agentTypeId/reload (hook + harness resource diagnostics).
1397
+ * - `resourceDiagnostics`: live Pi skill/extension load diagnostics for the
1398
+ * current session, read straight from the harness.
1399
+ * - `pluginErrors`: host-provided plugin load/preflight errors for the
1400
+ * workspace (wired by the embedding host).
1038
1401
  *
1039
- * Safe to call unauthenticated — we only report {provider, id, label,
1040
- * available}, never any key material.
1402
+ * The tool is informational: it returns the diagnostics as data and never
1403
+ * reports `isError`, even when diagnostics exist.
1041
1404
  */
1042
1405
 
1043
- interface ModelSummary {
1044
- provider: string;
1045
- id: string;
1046
- label: string;
1047
- available: boolean;
1048
- }
1049
- interface ModelFilterContext {
1050
- request: FastifyRequest;
1051
- workspaceId?: string;
1406
+ interface PluginDiagnostic {
1407
+ source: string;
1408
+ message: string;
1409
+ pluginId?: string;
1052
1410
  }
1053
- type ModelFilterResult = {
1054
- models: readonly ModelSummary[];
1055
- defaultModel?: AgentModelSelection;
1056
- };
1057
- interface ModelsRoutesOptions {
1058
- filterModels?: (ctx: ModelFilterContext, models: readonly ModelSummary[], defaultModel: AgentModelSelection | undefined) => ModelFilterResult | Promise<ModelFilterResult>;
1411
+ interface PluginDiagnosticsToolDeps {
1412
+ /** Diagnostics stashed by the last /reload. Read via a thunk because the
1413
+ * runtime binding is assigned after the tool catalog is built. */
1414
+ getLastReloadDiagnostics: () => ReadonlyArray<PluginDiagnostic>;
1415
+ /** Live harness, used to read per-session resource diagnostics. */
1416
+ getHarness: () => AgentHarness | undefined;
1417
+ /** Optional host callback returning workspace plugin load/preflight errors. */
1418
+ getPluginErrors?: () => Promise<ReadonlyArray<PluginDiagnostic>>;
1059
1419
  }
1420
+ declare function createPluginDiagnosticsTool(deps: PluginDiagnosticsToolDeps): AgentTool;
1060
1421
 
1061
- type PiSessionRequestContextResolver = (request: FastifyRequest, defaultContext: PiSessionRequestContext) => PiSessionRequestContext | Promise<PiSessionRequestContext>;
1062
-
1063
- interface PrebuiltAgentHostRoutePolicy {
1064
- /** The sole Host instance constructed by the embedding composition root. */
1065
- readonly created: CreatedAgentHost;
1066
- /** Default Agent used by the legacy unaddressed route family. */
1067
- readonly defaultAgentTypeId: string;
1068
- /**
1069
- * App-owned capability issuer. The app may replace workspaceScopeId with its
1070
- * canonical workspace/storage partition while retaining the normalized
1071
- * runtime scope as private issuer context.
1072
- */
1073
- issueScope(input: {
1074
- readonly claim: VerifiedAgentScopeClaim;
1075
- readonly runtimeScope: ResolvedAgentRuntimeScope;
1076
- }): AuthorizedAgentScope;
1422
+ declare const RUNTIME_FILESYSTEM_BINDING_DUPLICATE_CODE: "RUNTIME_FILESYSTEM_BINDING_DUPLICATE";
1423
+ declare class RuntimeFilesystemBindingConfigurationError extends Error {
1424
+ readonly code: "RUNTIME_FILESYSTEM_BINDING_DUPLICATE";
1425
+ readonly filesystem: string;
1426
+ constructor(filesystem: string);
1077
1427
  }
1078
- interface RegisterAgentRoutesOptions {
1079
- /**
1080
- * Reuse a Host created by the embedding composition root. Omission preserves
1081
- * the historical wrapper behavior and constructs one legacy default Host.
1082
- */
1083
- agentHost?: PrebuiltAgentHostRoutePolicy;
1084
- workspaceRoot?: string;
1085
- sessionId?: string;
1086
- templatePath?: string;
1087
- getTemplatePath?: (ctx: {
1088
- workspaceId: string;
1089
- workspaceRoot: string;
1090
- request?: FastifyRequest;
1091
- }) => string | undefined | Promise<string | undefined>;
1092
- mode?: RuntimeModeId;
1093
- /** Supply a custom runtime adapter to plug in non-built-in sandbox/workspace modes. */
1094
- runtimeModeAdapter?: RuntimeModeAdapter;
1095
- /** Provider/runtime values supplied by the embedding host. */
1096
- runtimeHost?: AgentRuntimeHostOperations;
1097
- version?: string;
1098
- extraTools?: AgentTool[];
1099
- /** When true, omit the six filesystem tools (read/write/edit/find/grep/ls). */
1100
- disableDefaultFileTools?: boolean;
1101
- getExtraTools?: (ctx: {
1102
- workspaceId: string;
1103
- workspaceRoot: string;
1104
- runtimeMode: RuntimeModeId;
1105
- workspaceFsCapability?: Workspace['fsCapability'];
1106
- authSubject?: string;
1107
- }) => AgentTool[] | Promise<AgentTool[]>;
1108
- systemPromptAppend?: string;
1109
- /** Optional dynamic system-prompt source forwarded to the harness. */
1110
- systemPromptDynamic?: () => string | undefined | Promise<string | undefined>;
1111
- getSystemPromptDynamic?: (ctx: {
1112
- workspaceId: string;
1113
- workspaceRoot: string;
1114
- }) => string | undefined | Promise<string | undefined>;
1115
- /** Immutable host contribution captured once in the runtime binding scope. */
1116
- getRuntimeScopeContribution?: (ctx: {
1117
- workspaceId: string;
1118
- workspaceRoot: string;
1119
- request?: FastifyRequest;
1120
- }) => Readonly<{
1121
- identity: string;
1122
- loadSystemPromptAppend?: () => Promise<string | undefined>;
1123
- }> | Promise<Readonly<{
1124
- identity: string;
1125
- loadSystemPromptAppend?: () => Promise<string | undefined>;
1126
- }>>;
1127
- /** Override the default pi-backed harness with a custom agent runtime. */
1128
- harnessFactory?: AgentHarnessFactory;
1129
- /** Optional pi adapter/runtime knobs used by the default harness. */
1130
- pi?: PiHarnessOptions;
1131
- getPi?: (ctx: {
1132
- workspaceId: string;
1133
- workspaceRoot: string;
1134
- request?: FastifyRequest;
1135
- }) => PiHarnessOptions | undefined | Promise<PiHarnessOptions | undefined>;
1136
- sessionNamespace?: string;
1137
- /** Optional explicit root for file-backed Pi chat transcript storage. */
1138
- sessionRoot?: string;
1139
- /** Trusted host seam for resolving Pi HTTP session scope. */
1140
- resolvePiSessionRequestContext?: PiSessionRequestContextResolver;
1141
- /** Optional best-effort telemetry sink supplied by an embedding host. */
1142
- telemetry?: TelemetrySink;
1143
- /** Optional host admission called immediately before each agent effect. */
1144
- admitEffect?: AgentEffectAdmission$1;
1145
- /** Generic request-aware model filtering seam. Hosts may filter per user/workspace. */
1146
- filterModels?: ModelsRoutesOptions['filterModels'];
1147
- /** Generic per-request/per-run filesystem binding seam. Hosts may return user/session-filtered bindings. */
1148
- getFilesystemBindings?: (ctx: {
1149
- request?: FastifyRequest;
1150
- workspaceId: string;
1151
- workspaceRoot: string;
1152
- sessionId?: string;
1153
- userId?: string;
1154
- userEmail?: string;
1155
- userEmailVerified?: boolean;
1156
- requestId?: string;
1157
- }) => RuntimeFilesystemBinding[] | undefined | Promise<RuntimeFilesystemBinding[] | undefined>;
1158
- /**
1159
- * Optional billing sink for native Pi usage. Reserve happens before
1160
- * accepted prompt/follow-up execution (fail closed), usage is recorded from
1161
- * native assistant message_end events, and runs settle/release from native
1162
- * terminal lifecycle. See AgentMeteringSink.
1163
- */
1164
- metering?: AgentMeteringSink;
1165
- /**
1166
- * Enable user/global Pi extension auto-discovery from .pi/ and ~/.pi.
1167
- * App/internal plugins should be passed through extraTools/pi instead.
1168
- * Defaults to true for standalone agent compatibility.
1169
- */
1170
- externalPlugins?: boolean;
1171
- getSessionNamespace?: (ctx: {
1172
- workspaceId: string;
1173
- workspaceRoot: string;
1174
- request?: FastifyRequest;
1175
- /** Verified actor id for trusted requestless dispatcher resolution. */
1176
- userId?: string;
1177
- }) => string | undefined | Promise<string | undefined>;
1178
- registerHealthRoute?: boolean;
1179
- /**
1180
- * Optional Lane W share-entry store (AR1-002/AR1-003, same-workspace
1181
- * shareable links, `docs/issues/391/runtime-refactor/work/
1182
- * AR1-shareable-artifacts/AR1-001-SPEC.md` §3). When supplied, mounts the
1183
- * membership-gated `GET /a/:id` deep-link route. Omit to leave Lane W
1184
- * entirely unmounted (no widening for hosts that don't use it yet).
1185
- */
1186
- shareEntryStore?: ShareEntryStore;
1187
- getWorkspaceId?: (request: FastifyRequest) => string | Promise<string>;
1188
- getWorkspaceRoot?: (workspaceId: string, request: FastifyRequest) => string | Promise<string>;
1189
- getTrustedWorkspaceRoot?: (ctx: WorkspaceAgentDispatcherContext) => string | Promise<string>;
1190
- /** Generic runtime env contributors. Agent stays workspace-neutral; hosts decide env names/values. */
1191
- runtimeEnvContributions?: RuntimeEnvContribution[];
1192
- /**
1193
- * Optional runtime reconciliation hook. Callers own plugin discovery and may
1194
- * call provisionWorkspaceRuntime() with the normalized structural inputs.
1195
- * registerAgentRoutes only consumes the returned env/PATH/skill paths.
1196
- */
1197
- provisionRuntime?: (ctx: {
1198
- workspaceId: string;
1199
- workspaceRoot: string;
1200
- runtimeMode: RuntimeModeId;
1201
- runtimeLayout: BoringAgentRuntimePaths;
1202
- provisioningAdapter?: WorkspaceProvisioningAdapter;
1203
- /** Already-created paired Workspace/Sandbox runtime for this binding. */
1204
- runtimeBundle: RuntimeBundle;
1205
- request?: FastifyRequest;
1206
- /** Aborted when this binding retires; retirement still drains the task before provider disposal. */
1207
- signal: AbortSignal;
1208
- }) => WorkspaceProvisioningResult | undefined | Promise<WorkspaceProvisioningResult | undefined>;
1209
- provisionWorkspace?: boolean;
1210
- /** Optional hook called before /api/v1/agent/reload reloads the harness. */
1211
- beforeReload?: (ctx: {
1212
- workspaceId: string;
1213
- workspaceRoot: string;
1214
- request: FastifyRequest;
1215
- }) => void | ReloadHookResult | undefined | Promise<void | ReloadHookResult | undefined>;
1216
- /**
1217
- * Optional host callback returning current plugin/skill load diagnostics
1218
- * for a workspace. Surfaced by the `plugin_diagnostics` agent tool so the
1219
- * model can iterate on plugin/skill load errors after a /reload.
1220
- */
1221
- getPluginDiagnostics?: (args: {
1222
- workspaceId: string;
1223
- workspaceRoot: string;
1224
- }) => Promise<Array<{
1225
- source: string;
1226
- message: string;
1227
- pluginId?: string;
1228
- }>>;
1229
- /**
1230
- * Trusted in-process host composition seam. The resolver trusts caller-supplied
1231
- * workspace/user context; callers must authorize that context before resolving.
1232
- */
1233
- onWorkspaceAgentDispatcher?: (resolver: WorkspaceAgentDispatcherResolver) => void;
1234
- }
1235
- interface AgentHostLegacyRouteScopePolicy {
1236
- /** App-owned capability issuer for the already-created Host. */
1237
- issueScope(input: {
1238
- readonly claim: VerifiedAgentScopeClaim;
1239
- readonly runtimeScope: ResolvedAgentRuntimeScope;
1240
- }): AuthorizedAgentScope;
1241
- /** True only for the legacy wrapper whose Host admission calls admitEffect. */
1242
- readonly gatewayUsesLegacyAdmission?: boolean;
1243
- }
1244
- type AgentHostLegacyRoutePolicyOptions = Omit<RegisterAgentRoutesOptions, 'agentHost' | 'runtimeModeAdapter'> & {
1245
- readonly runtimeModeAdapter: RuntimeModeAdapter;
1246
- };
1247
-
1248
- /** Normalize legacy options into the nested Host projection seam. */
1249
- declare function createAgentHostLegacyRoutePolicy(options: AgentHostLegacyRoutePolicyOptions, scopePolicy: AgentHostLegacyRouteScopePolicy): AgentHostLegacyRoutePolicy;
1428
+ /**
1429
+ * Canonical final merge seam for runtime-owned and request-scoped bindings.
1430
+ * Duplicates *within* either list stay configuration errors; a host/request
1431
+ * collision on the same id composes as an intersection of both capabilities.
1432
+ */
1433
+ declare function mergeRuntimeFilesystemBindings<T extends RuntimeFilesystemBinding>(runtimeBindings: readonly T[] | undefined, requestBindings: readonly T[] | undefined): readonly RuntimeFilesystemBinding[] | undefined;
1250
1434
 
1435
+ declare const RUNTIME_READONLY_FILESYSTEM_POLICY_INVALID_CODE: "RUNTIME_READONLY_FILESYSTEM_POLICY_INVALID";
1436
+ declare class RuntimeReadonlyFilesystemPolicyError extends Error {
1437
+ readonly code: "RUNTIME_READONLY_FILESYSTEM_POLICY_INVALID";
1438
+ constructor();
1439
+ }
1251
1440
  /**
1252
- * Compatibility wrapper for legacy embedding callers.
1253
- *
1254
- * It normalizes legacy construction inputs, creates or reuses exactly one Host,
1255
- * and delegates the complete route profile through CreatedAgentHost.registerRoutes().
1441
+ * Default protected prefixes applied when a host does not configure its own.
1442
+ * `.agents` holds agent governance/skill definitions: agents may read them but
1443
+ * must never rewrite the rules they run under. Hosts opt out with an explicit
1444
+ * empty array.
1256
1445
  */
1257
- declare const registerAgentRoutes: FastifyPluginAsync<RegisterAgentRoutesOptions>;
1446
+ declare const DEFAULT_READONLY_WORKSPACE_PATHS: readonly string[];
1447
+ interface RuntimeReadonlyFilesystemPolicy {
1448
+ readonly readonlyPaths: readonly string[];
1449
+ readonly revision: string;
1450
+ }
1451
+ declare function normalizeRuntimeReadonlyFilesystemPolicy(paths: readonly string[]): RuntimeReadonlyFilesystemPolicy;
1452
+ /** Resolve policy after the Workspace adapter has normalized/confined the path. */
1453
+ declare function resolveRuntimeReadonlyFilesystemAccess(policy: RuntimeReadonlyFilesystemPolicy, descriptor: {
1454
+ readonly filesystem: string;
1455
+ readonly normalizedPath: string;
1456
+ }): RuntimeFilesystemAccessDecision;
1457
+
1458
+ /** Primary-user Operations adapter shared by HTTP and Pi filesystem tools. */
1459
+ declare function createUserFilesystemBinding(workspace: Workspace, policy: RuntimeReadonlyFilesystemPolicy, resolvePolicyPath: (path: string) => Promise<string>): RuntimeFilesystemBinding;
1258
1460
 
1259
1461
  interface CredentialStoreBackendV1 {
1260
1462
  read(workspaceId: string, providerId: ProviderId, allowedFieldIds: readonly CredentialFieldId[]): Promise<ResolvedCredentialMaterialV1 & {
@@ -1287,4 +1489,4 @@ declare function createInMemoryCredentialBackendV1(entries: readonly InMemoryCre
1287
1489
 
1288
1490
  declare function withResolvedCredential<T>(resolver: WorkspaceCredentialResolverV1, workspace: AuthorizedWorkspaceCredentialScopeV1, ref: ProviderCredentialRefV1, fn: (lease: ResolvedCredentialLeaseV1) => T | Promise<T>): Promise<T>;
1289
1491
 
1290
- export { AgentConfig, AgentDirectoryCompilerError, type AgentDirectoryCompilerErrorCode, type AgentDirectoryCompilerPublicErrorCode, AgentEffectAdmission, AgentFleetCompilationError, AgentFleetCompilationErrorCode, AgentFleetCompiler, type AgentFleetPluginBindingContract, AgentGatewayEffect, AgentHarnessFactory, AgentHostLegacyRoutePolicy, type AgentHostLegacyRoutePolicyOptions, type AgentHostLegacyRouteScopePolicy, AgentMeteringSink, AgentRequestKey, AgentRequestLedger, AgentRequestLedgerRecord, AgentRuntimeHostOperations, AuthoredAgentMaterializationError, type AuthoredAgentMaterializationErrorCode, type AuthoredAgentSourceV1, AuthorizedAgentScope, BuiltinRuntimeModeId, CompiledAgentHostAgentSpec, type CreateAgentAppOptions, CreateAgentHostOptions, type CreateValidatingAgentFleetCompilerOptions, CreatedAgentHost, type CredentialStoreBackendV1, type DeploymentSnapshotProvider, type DeploymentSnapshotRecipe, type DeploymentSnapshotResult, type DeploymentSnapshotStatus, EmbeddedAgentGateway, type FakeAuthorityVerifierGrantV1, type HostSideCredentialResolverOptionsV1, InMemoryAgentRequestLedger, type InMemoryCredentialBackendEntryV1, MANAGED_AGENT_MCP_DELIVERY_RULE, MANAGED_AGENT_MCP_ORIGIN_SURFACE, type ManagedAgentArtifact, type ManagedAgentArtifactCandidate, type ManagedAgentArtifactRef, type ManagedAgentBoundRunnerWorkspace, type ManagedAgentCollectArtifactsInput, type ManagedAgentDelegateInput, type ManagedAgentDelegateProgress, type ManagedAgentDelegateRequestContext, type ManagedAgentDelegateResult, type ManagedAgentDelegateRunInput, type ManagedAgentDelegateRunner, type ManagedAgentDelegateStatus, type ManagedAgentDelegateStatusResult, ManagedAgentMcpDelegateController, type ManagedAgentMcpDelegateOptions, ManagedAgentMcpError, type ManagedAgentMcpHttpHandlerOptions, type ManagedAgentMcpServerOptions, type ManagedAgentSafeError, type ManagedAgentWorkspaceResolutionInput, type MaterializeAgentDirectoryInput, MeteringErrorLogger, ModeContext, PiHarnessOptions, type PrebuiltAgentHostRoutePolicy, type ProvisionRuntimeWorkspaceOptions, ProvisionWorkspaceRuntimeOptions, type ProvisioningArtifactRequest, type RegisterAgentRoutesOptions, RemoteWorkerClient, RemoteWorkerClientError, type RemoteWorkerClientOptions, RemoteWorkerExecRequest, type RemoteWorkerModeAdapterOptions, RemoteWorkerWorkspaceOp, RemoteWorkerWorkspaceResult, type ResolvedAgent, type ResolvedAgentDigestInput, ResolvedAgentRuntimeScope, RuntimeBundle, type RuntimeEnvContribution, type RuntimeEnvContributionContext, RuntimeFilesystemBinding, RuntimeModeAdapter, RuntimeModeId, type RuntimeWorkspaceProvisioningResult, type SandboxRuntimeModeOptions, type ShareEntryMcpResourceOptions, UV_SETUP_COMMANDS, VerifiedAgentScopeClaim, type WorkspaceAgentDispatcherBinding, type WorkspaceAgentDispatcherResolveOptions, type WorkspaceAgentDispatcherResolver, WorkspaceProvisioningAdapter, WorkspaceProvisioningResult, applyCspHeaders, autoDetectMode, buildDeploymentSnapshotRecipe, compileAgentDirectory, constantTimeTokenEqual, createAgent, createAgentApp, createAgentHost, createAgentHostLegacyRoutePolicy, createDirectModeAdapter, createEnvironmentProvisioningFingerprint, createFakeAuthorityVerifierV1, createHostSideCredentialResolverV1, createInMemoryCredentialBackendV1, createLocalModeAdapter, createManagedAgentMcpDelegateController, createManagedAgentMcpHttpHandler, createManagedAgentMcpServer, createProviderRuntimeModeAdapter, createRemoteWorkerModeAdapter, createRemoteWorkerSandbox, createRemoteWorkerWorkspace, createResolvedAgentDigest, createResolvedRuntimeScopeIdentity, createSandboxRuntimeModeAdapter, createValidatingAgentFleetCompiler, createVercelSandboxModeAdapter, decodeBytesFromWorker, encodeBytesForWorker, hasBwrap, materializeAgentDirectory, prepareDeploymentSnapshot, provisionRuntimeWorkspace, provisionWorkspaceRuntime, registerAgentRoutes, registerShareEntryResources, resolveAgentDeployment, resolveBuiltinRuntimeLayoutRoot, resolveMode, resolveWorkspaceRoot, sandboxRuntimeHostOperations, shareResourceUri, withResolvedCredential };
1492
+ export { AgentDirectoryCompilerError, type AgentDirectoryCompilerErrorCode, type AgentDirectoryCompilerPublicErrorCode, AgentEffectAdmission, AgentFleetCompilationError, AgentFleetCompilationErrorCode, AgentFleetCompiler, type AgentFleetPluginBindingContract, AgentHarnessFactory, AgentHostAgentSpec, type AgentHostEnvironmentHttpProjectionOptions, AgentHostEnvironmentScope, AgentInstructionFileRef, AgentMeteringSink, AgentRequestKey, AgentRequestLedger, AgentRequestLedgerPrepareResult, AgentRequestLedgerRecord, AgentRuntimeHostOperations, AuthoredAgentMaterializationError, type AuthoredAgentMaterializationErrorCode, type AuthoredAgentSourceV1, AuthorizedAgentScope, AuthorizedEnvironmentIntent, type AuthorizedSessionRunDetails, BuiltinRuntimeModeId, CompiledAgentHostAgentSpec, ConfiguredAgentHostAgentSpec, CreateAgentHostOptions, type CreateConfiguredAgentHostAgentSpecInput, type CreateStandaloneAgentHostAppOptions, type CreateValidatingAgentFleetCompilerOptions, CreatedAgentHost, type CredentialStoreBackendV1, DEFAULT_PI_RESOURCE_DIGEST_LIMITS, DEFAULT_READONLY_WORKSPACE_PATHS, type DeploymentSnapshotProvider, type DeploymentSnapshotRecipe, type DeploymentSnapshotResult, type DeploymentSnapshotStatus, type DiscoveredAgentPackageDescriptor, EmbeddedAgentGateway, type FakeAuthorityVerifierGrantV1, FleetConfigError, type FleetConfigErrorCode, type FleetLoaderDiagnostic, type FleetLoaderDiagnosticCode, type FleetSeatBinding, type FleetSkillBinding, type HostSideCredentialResolverOptionsV1, InMemoryAgentRequestLedger, type InMemoryCredentialBackendEntryV1, LEGACY_DEFAULT_AGENT_FLEET, type LoadConfiguredAgentFleetOptions, type LoadConfiguredAgentFleetResult, MANAGED_AGENT_MCP_DELIVERY_RULE, MANAGED_AGENT_MCP_ORIGIN_SURFACE, type ManagedAgentArtifact, type ManagedAgentArtifactCandidate, type ManagedAgentArtifactRef, type ManagedAgentBoundRunnerWorkspace, type ManagedAgentCollectArtifactsInput, type ManagedAgentDelegateInput, type ManagedAgentDelegateProgress, type ManagedAgentDelegateRequestContext, type ManagedAgentDelegateResult, type ManagedAgentDelegateRunInput, type ManagedAgentDelegateRunner, type ManagedAgentDelegateStatus, type ManagedAgentDelegateStatusResult, ManagedAgentMcpDelegateController, type ManagedAgentMcpDelegateOptions, ManagedAgentMcpError, type ManagedAgentMcpHttpHandlerOptions, type ManagedAgentMcpServerOptions, type ManagedAgentSafeError, type ManagedAgentWorkspaceResolutionInput, type MaterializeAgentDirectoryInput, MeteringErrorLogger, ModeContext, type ModelTierCandidate, PiHarnessOptions, PiPackageSource, type PiResourceDigestInput, type PiResourceDigestLimits, type PiResourceSet, type ProvisionRuntimeWorkspaceOptions, ProvisionWorkspaceRuntimeOptions, type ProvisioningArtifactRequest, RUNTIME_FILESYSTEM_BINDING_DUPLICATE_CODE, RUNTIME_READONLY_FILESYSTEM_POLICY_INVALID_CODE, RemoteWorkerClient, RemoteWorkerClientError, type RemoteWorkerClientOptions, RemoteWorkerExecRequest, type RemoteWorkerModeAdapterOptions, RemoteWorkerWorkspaceOp, RemoteWorkerWorkspaceResult, type ResolveDefaultAgentFleetOptions, type ResolvedAgent, type ResolvedAgentDigestInput, ResolvedAgentRuntimeScope, RuntimeBundle, type RuntimeEnvContribution, type RuntimeEnvContributionContext, RuntimeFilesystemAccessDecision, RuntimeFilesystemBinding, RuntimeFilesystemBindingConfigurationError, RuntimeModeAdapter, RuntimeModeId, type RuntimeReadonlyFilesystemPolicy, RuntimeReadonlyFilesystemPolicyError, type RuntimeWorkspaceProvisioningResult, type SandboxRuntimeModeOptions, type ShareEntryMcpResourceOptions, type SkillMetadataFrontmatter, SqliteAgentRequestLedger, TrustedAgentCompositionError, type TrustedAgentInstructionAppendix, type TrustedAuthoredAgentPolicy, UV_SETUP_COMMANDS, VerifiedAgentScopeClaim, type WorkspaceAgentDispatcherBinding, type WorkspaceAgentDispatcherResolveOptions, type WorkspaceAgentDispatcherResolver, WorkspaceProvisioningAdapter, WorkspaceProvisioningResult, applyCspHeaders, autoDetectMode, buildDeploymentSnapshotRecipe, compileAgentDirectory, compilePersonaPackageDirectory, constantTimeTokenEqual, createAgentHost, createBlaxelSandboxModeAdapter, createBoundWorkspaceAgentDispatcher, createConfiguredAgentHostAgentSpec, createDirectModeAdapter, createEnvironmentProvisioningFingerprint, createFakeAuthorityVerifierV1, createHostSideCredentialResolverV1, createInMemoryCredentialBackendV1, createLocalModeAdapter, createManagedAgentMcpDelegateController, createManagedAgentMcpHttpHandler, createManagedAgentMcpServer, createPiResourceDigestFence, createPiResourceDigestInput, createPluginDiagnosticsTool, createProviderRuntimeModeAdapter, createRemoteWorkerModeAdapter, createRemoteWorkerSandbox, createRemoteWorkerWorkspace, createResolvedAgentDigest, createResolvedRuntimeScopeIdentity, createResourceSettingsManager, createSandboxRuntimeModeAdapter, createStandaloneAgentHostApp, createUserFilesystemBinding, createValidatingAgentFleetCompiler, createVercelSandboxModeAdapter, decodeBytesFromWorker, deepLinkRoutes, digestPiResourceInputs, encodeBytesForWorker, hasBwrap, loadConfiguredAgentFleet, materializeAgentDirectory, mergeRuntimeFilesystemBindings, normalizeRuntimeReadonlyFilesystemPolicy, parseSkillMetadataFrontmatter, prepareDeploymentSnapshot, projectAuthorizedSessionRunDetails, provisionRuntimeWorkspace, provisionWorkspaceRuntime, registerAgentHostEnvironmentRoutes, registerShareEntryResources, resolveAgentDeployment, resolveBuiltinRuntimeLayoutRoot, resolveDefaultAgentFleet, resolveMode, resolveRuntimeReadonlyFilesystemAccess, resolveWorkspaceRoot, sandboxRuntimeHostOperations, shareResourceUri, withResolvedCredential, withRuntimeEnvContributions };