@hachej/boring-agent 0.1.94 → 0.1.96

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-OFQ7J6SI.js → chunk-LSO2AO6Q.js} +57 -1
  6. package/dist/{chunk-N4AATPH7.js → chunk-NSE2RHU3.js} +8973 -7731
  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 +87 -17
  18. package/dist/front/index.js +1232 -690
  19. package/dist/front/styles.css +1228 -2167
  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 +570 -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,13 +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;
985
+ private canRefreshFromPersistedState;
754
986
  private harnessMayHaveLiveSession;
987
+ private attachmentUrlFor;
755
988
  private readPersistedState;
756
989
  subscribe(ctx: PiSessionRequestContext, sessionId: string, cursor: number, subscriber: PiChatEventSubscriber): Promise<PiChatEventStreamResult>;
757
990
  private subscribeBeforeDispose;
@@ -787,8 +1020,23 @@ declare class HarnessPiChatService implements PiChatSessionService {
787
1020
  private ensureChannel;
788
1021
  /** Coalesce concurrent cold callers so only one adapter subscription wins. */
789
1022
  private createChannelOnce;
1023
+ private generationOf;
1024
+ private assertSessionIncarnation;
790
1025
  private buildChannel;
1026
+ /** Cheap cold-snapshot seq lookup (no buffer hydration) — see {@link hydrateDurableReplayBuffer} for the live-channel path. */
791
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;
792
1040
  /**
793
1041
  * Validate the persisted session identity and instantiate its lazily-created
794
1042
  * Pi adapter under the same full cache key. This is intentionally a narrow
@@ -814,7 +1062,6 @@ interface EnvironmentLease {
814
1062
  }
815
1063
 
816
1064
  interface BuiltAgentComposition {
817
- readonly agent: Agent;
818
1065
  readonly harness: AgentHarness;
819
1066
  readonly sessionStore: SessionStore;
820
1067
  readonly service: HarnessPiChatService;
@@ -830,17 +1077,27 @@ interface AgentSessionRuntimeAuthority {
830
1077
  /** Absent only for a pre-AH0 transcript created before runtime pins existed. */
831
1078
  readonly runtimeScopeIdentity?: string;
832
1079
  }
1080
+ interface AgentSessionActivityUpdate {
1081
+ readonly ref: AgentSessionRef;
1082
+ readonly status: AgentSessionActivity;
1083
+ }
833
1084
  /** Process-lifetime live-turn projection. Reads never create activity rows. */
834
1085
  declare class AgentSessionActivityIndex {
835
1086
  private readonly activity;
1087
+ private readonly subscribers;
836
1088
  get(workspaceScopeId: string, ref: AgentSessionRef): AgentSessionActivity;
837
- 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;
838
1092
  delete(workspaceScopeId: string, ref: AgentSessionRef): void;
839
1093
  observe(workspaceScopeId: string, ref: AgentSessionRef, event: PiChatEvent): void;
840
1094
  }
841
1095
 
842
1096
  interface RuntimeBinding {
843
1097
  readonly key: string;
1098
+ readonly agentTypeId: string;
1099
+ readonly workspaceScopeId: string;
1100
+ readonly generation: number;
844
1101
  readonly scope: ResolvedAgentRuntimeScope;
845
1102
  readonly environmentLease: EnvironmentLease;
846
1103
  readonly composition: BuiltAgentComposition;
@@ -852,21 +1109,45 @@ interface AgentHostRuntime {
852
1109
  readonly ledger: AgentRequestLedger;
853
1110
  readonly effectAdmission: AgentEffectAdmission;
854
1111
  readonly activity: AgentSessionActivityIndex;
1112
+ readonly shutdownGraceMs: number;
855
1113
  listSessionSummaries(agentTypeId: string, scope: AuthorizedAgentScope, claim: VerifiedAgentScopeClaim): Promise<readonly SessionSummary[]>;
856
1114
  isDraining(): boolean;
857
1115
  assertOpen(): void;
858
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>;
859
1120
  resolveSessionRuntime(agentTypeId: string, scope: AuthorizedAgentScope, claim: VerifiedAgentScopeClaim, sessionId: string): Promise<AgentSessionRuntimeAuthority | undefined>;
860
- 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;
861
1125
  startDrain(): void;
862
1126
  drainRuntime(): Promise<void>;
863
1127
  registerSubscription(close: () => void | Promise<void>): () => void;
864
- trackEffect<T>(effect: Promise<T>, key: AgentRequestKey): Promise<T>;
865
- 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>;
866
1130
  closeRuntime(): Promise<void>;
867
1131
  }
868
1132
  declare function createAgentHost(options: CreateAgentHostOptions): Promise<CreatedAgentHost>;
869
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
+
870
1151
  declare const AgentFleetCompilationErrorCode: {
871
1152
  readonly AGENT_FLEET_PLUGIN_UNKNOWN: "AGENT_FLEET_PLUGIN_UNKNOWN";
872
1153
  readonly AGENT_FLEET_CONFIG_BINDING_UNKNOWN: "AGENT_FLEET_CONFIG_BINDING_UNKNOWN";
@@ -897,20 +1178,44 @@ interface CreateValidatingAgentFleetCompilerOptions {
897
1178
  */
898
1179
  declare function createValidatingAgentFleetCompiler(options: CreateValidatingAgentFleetCompilerOptions): AgentFleetCompiler;
899
1180
 
900
- type RetryableSessionGuard = () => Promise<AgentGatewayErrorDTO | undefined>;
901
1181
  declare class EmbeddedAgentGateway implements AgentGateway {
902
1182
  private readonly runtime;
903
1183
  private readonly cursorSecret;
904
1184
  private readonly connections;
905
- private readonly effects;
906
1185
  private readonly pins;
1186
+ private readonly unpinnedSessionFallbackPins;
907
1187
  private readonly writerTails;
908
1188
  private sessionRuntimeResolutionObserver?;
909
1189
  private closed;
910
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
+ }>;
911
1216
  /** Server-only test observer for distinguishing runtime pin resolution paths. */
912
1217
  setSessionRuntimeResolutionObserverForTesting(observer: (input: {
913
- readonly source: 'pre-ah0-compatibility-fallback' | 'persisted-runtime-pin';
1218
+ readonly source: 'unpinned-session-fallback' | 'persisted-runtime-pin';
914
1219
  readonly runtimeScopeIdentity: string;
915
1220
  }) => void): void;
916
1221
  /** Test-only activity seam used by the shared implementation conformance. */
@@ -924,6 +1229,7 @@ declare class EmbeddedAgentGateway implements AgentGateway {
924
1229
  version: string;
925
1230
  digest: string;
926
1231
  } | undefined;
1232
+ pluginIds?: string[] | undefined;
927
1233
  agentTypeId: string;
928
1234
  label: string;
929
1235
  }[]>;
@@ -941,20 +1247,12 @@ declare class EmbeddedAgentGateway implements AgentGateway {
941
1247
  private bindingForSession;
942
1248
  private loadSummary;
943
1249
  private sessionEffect;
944
- /** Internal legacy-alias seam; never exposed through the public Gateway contract. */
945
- runLegacyCompatibilityEffect(input: {
946
- readonly scope: AuthorizedAgentScope;
947
- readonly operation: AgentGatewayEffect;
948
- readonly target: AgentRequestTarget;
949
- readonly requestId: string;
950
- readonly payload: JsonValue;
951
- readonly action: () => Promise<unknown>;
952
- readonly retryableGuard?: RetryableSessionGuard;
953
- }): Promise<unknown>;
954
1250
  private effect;
1251
+ private applyClassification;
955
1252
  private replayReceipt;
956
1253
  private failure;
957
1254
  private promptAdmission;
1255
+ private queueClearAdmission;
958
1256
  private withWriter;
959
1257
  private encodeCursor;
960
1258
  private decodeCursor;
@@ -962,8 +1260,9 @@ declare class EmbeddedAgentGateway implements AgentGateway {
962
1260
 
963
1261
  /** Process-lifetime Level-B ledger with the exact published state machine. */
964
1262
  declare class InMemoryAgentRequestLedger implements AgentRequestLedger {
1263
+ readonly durability: "in-memory";
965
1264
  private readonly records;
966
- prepare(key: AgentRequestKey, digest: string): Promise<AgentRequestLedgerRecord>;
1265
+ prepare(key: AgentRequestKey, digest: string): Promise<AgentRequestLedgerPrepareResult>;
967
1266
  acceptAdmission(key: AgentRequestKey, admissionReceipt: string): Promise<void>;
968
1267
  beginEffect(key: AgentRequestKey): Promise<void>;
969
1268
  reject(key: AgentRequestKey, failure: AgentRequestFailure): Promise<void>;
@@ -980,10 +1279,12 @@ interface RuntimeScopeIdentityInput {
980
1279
  }[];
981
1280
  readonly validatedConfig: JsonValue;
982
1281
  readonly grants: readonly string[];
983
- readonly placementIdentity: string;
1282
+ /** Stable semantic placement class; never an absolute root or lease key. */
1283
+ readonly placementClassIdentity: string;
984
1284
  readonly isolationMode: string;
985
1285
  readonly toolContractDigests: readonly string[];
986
- readonly provisioningGeneration: string;
1286
+ /** Stable semantic provisioning contract. */
1287
+ readonly provisioningIdentity: string;
987
1288
  readonly bindingInputs?: JsonValue;
988
1289
  }
989
1290
  interface EnvironmentProvisioningIdentityInput {
@@ -1013,247 +1314,146 @@ declare function applyCspHeaders(response: HeaderLike, opts?: {
1013
1314
  dev?: boolean;
1014
1315
  }): void;
1015
1316
 
1016
- interface AgentModelSelection {
1017
- provider: string;
1018
- 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;
1019
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
+ readonly limits?: Partial<PiResourceDigestLimits>;
1360
+ }
1361
+ interface PiResourceSet {
1362
+ readonly promptParts?: readonly (string | undefined)[];
1363
+ readonly additionalSkillPaths?: readonly string[];
1364
+ readonly packages?: readonly PiPackageSource[];
1365
+ readonly extensionPaths?: readonly string[];
1366
+ }
1367
+ /** Canonical normalization shared by Workspace and CLI resource resolvers. */
1368
+ declare function createPiResourceDigestInput(input: {
1369
+ readonly piCwd: string;
1370
+ readonly piAgentDir?: string;
1371
+ readonly piUserHome?: string;
1372
+ readonly noSkills?: boolean;
1373
+ readonly resourceSets: readonly PiResourceSet[];
1374
+ readonly authorizedRoots: readonly string[];
1375
+ readonly limits?: Partial<PiResourceDigestLimits>;
1376
+ }): PiResourceDigestInput;
1377
+ /** Bounded asynchronous content identity for the exact Pi resources considered by a reload candidate. */
1378
+ declare function digestPiResourceInputs(input: PiResourceDigestInput): Promise<string>;
1379
+ /** Immutable digest plus the reload fences that defend that exact snapshot. */
1380
+ declare function createPiResourceDigestFence(resolveInput: () => PiResourceDigestInput | Promise<PiResourceDigestInput>): Promise<{
1381
+ readonly resourceInputDigest: string;
1382
+ readonly revalidateResourceInputs: () => Promise<void>;
1383
+ }>;
1020
1384
 
1021
1385
  /**
1022
- * GET /api/v1/agent/models
1386
+ * `plugin_diagnostics` built-in agent tool.
1023
1387
  *
1024
- * Returns the list of models pi-coding-agent has auth for (i.e. where
1025
- * the corresponding provider API key is present in the environment or
1026
- * `~/.pi/agent/auth.json`). Consumers — including the shadcn example
1027
- * ChatPanel — fetch this endpoint to populate the model-selector dropdown
1028
- * instead of hardcoding a short alias list.
1388
+ * Surfaces current plugin/skill loading errors to the agent so it can iterate
1389
+ * on them without the failures being silently swallowed. It merges three
1390
+ * sources:
1029
1391
  *
1030
- * Shape:
1031
- * {
1032
- * models: [
1033
- * { provider: "anthropic", id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6", available: true },
1034
- * ...
1035
- * ]
1036
- * }
1392
+ * - `lastReloadDiagnostics`: diagnostics captured by the most recent
1393
+ * /api/v1/agents/:agentTypeId/reload (hook + harness resource diagnostics).
1394
+ * - `resourceDiagnostics`: live Pi skill/extension load diagnostics for the
1395
+ * current session, read straight from the harness.
1396
+ * - `pluginErrors`: host-provided plugin load/preflight errors for the
1397
+ * workspace (wired by the embedding host).
1037
1398
  *
1038
- * Safe to call unauthenticated — we only report {provider, id, label,
1039
- * available}, never any key material.
1399
+ * The tool is informational: it returns the diagnostics as data and never
1400
+ * reports `isError`, even when diagnostics exist.
1040
1401
  */
1041
1402
 
1042
- interface ModelSummary {
1043
- provider: string;
1044
- id: string;
1045
- label: string;
1046
- available: boolean;
1047
- }
1048
- interface ModelFilterContext {
1049
- request: FastifyRequest;
1050
- workspaceId?: string;
1403
+ interface PluginDiagnostic {
1404
+ source: string;
1405
+ message: string;
1406
+ pluginId?: string;
1051
1407
  }
1052
- type ModelFilterResult = {
1053
- models: readonly ModelSummary[];
1054
- defaultModel?: AgentModelSelection;
1055
- };
1056
- interface ModelsRoutesOptions {
1057
- filterModels?: (ctx: ModelFilterContext, models: readonly ModelSummary[], defaultModel: AgentModelSelection | undefined) => ModelFilterResult | Promise<ModelFilterResult>;
1408
+ interface PluginDiagnosticsToolDeps {
1409
+ /** Diagnostics stashed by the last /reload. Read via a thunk because the
1410
+ * runtime binding is assigned after the tool catalog is built. */
1411
+ getLastReloadDiagnostics: () => ReadonlyArray<PluginDiagnostic>;
1412
+ /** Live harness, used to read per-session resource diagnostics. */
1413
+ getHarness: () => AgentHarness | undefined;
1414
+ /** Optional host callback returning workspace plugin load/preflight errors. */
1415
+ getPluginErrors?: () => Promise<ReadonlyArray<PluginDiagnostic>>;
1058
1416
  }
1417
+ declare function createPluginDiagnosticsTool(deps: PluginDiagnosticsToolDeps): AgentTool;
1059
1418
 
1060
- type PiSessionRequestContextResolver = (request: FastifyRequest, defaultContext: PiSessionRequestContext) => PiSessionRequestContext | Promise<PiSessionRequestContext>;
1061
-
1062
- interface PrebuiltAgentHostRoutePolicy {
1063
- /** The sole Host instance constructed by the embedding composition root. */
1064
- readonly created: CreatedAgentHost;
1065
- /** Default Agent used by the legacy unaddressed route family. */
1066
- readonly defaultAgentTypeId: string;
1067
- /**
1068
- * App-owned capability issuer. The app may replace workspaceScopeId with its
1069
- * canonical workspace/storage partition while retaining the normalized
1070
- * runtime scope as private issuer context.
1071
- */
1072
- issueScope(input: {
1073
- readonly claim: VerifiedAgentScopeClaim;
1074
- readonly runtimeScope: ResolvedAgentRuntimeScope;
1075
- }): AuthorizedAgentScope;
1419
+ declare const RUNTIME_FILESYSTEM_BINDING_DUPLICATE_CODE: "RUNTIME_FILESYSTEM_BINDING_DUPLICATE";
1420
+ declare class RuntimeFilesystemBindingConfigurationError extends Error {
1421
+ readonly code: "RUNTIME_FILESYSTEM_BINDING_DUPLICATE";
1422
+ readonly filesystem: string;
1423
+ constructor(filesystem: string);
1076
1424
  }
1077
- interface RegisterAgentRoutesOptions {
1078
- /**
1079
- * Reuse a Host created by the embedding composition root. Omission preserves
1080
- * the historical wrapper behavior and constructs one legacy default Host.
1081
- */
1082
- agentHost?: PrebuiltAgentHostRoutePolicy;
1083
- workspaceRoot?: string;
1084
- sessionId?: string;
1085
- templatePath?: string;
1086
- getTemplatePath?: (ctx: {
1087
- workspaceId: string;
1088
- workspaceRoot: string;
1089
- request?: FastifyRequest;
1090
- }) => string | undefined | Promise<string | undefined>;
1091
- mode?: RuntimeModeId;
1092
- /** Supply a custom runtime adapter to plug in non-built-in sandbox/workspace modes. */
1093
- runtimeModeAdapter?: RuntimeModeAdapter;
1094
- /** Provider/runtime values supplied by the embedding host. */
1095
- runtimeHost?: AgentRuntimeHostOperations;
1096
- version?: string;
1097
- extraTools?: AgentTool[];
1098
- /** When true, omit the six filesystem tools (read/write/edit/find/grep/ls). */
1099
- disableDefaultFileTools?: boolean;
1100
- getExtraTools?: (ctx: {
1101
- workspaceId: string;
1102
- workspaceRoot: string;
1103
- runtimeMode: RuntimeModeId;
1104
- workspaceFsCapability?: Workspace['fsCapability'];
1105
- authSubject?: string;
1106
- }) => AgentTool[] | Promise<AgentTool[]>;
1107
- systemPromptAppend?: string;
1108
- /** Optional dynamic system-prompt source forwarded to the harness. */
1109
- systemPromptDynamic?: () => string | undefined | Promise<string | undefined>;
1110
- getSystemPromptDynamic?: (ctx: {
1111
- workspaceId: string;
1112
- workspaceRoot: string;
1113
- }) => string | undefined | Promise<string | undefined>;
1114
- /** Immutable host contribution captured once in the runtime binding scope. */
1115
- getRuntimeScopeContribution?: (ctx: {
1116
- workspaceId: string;
1117
- workspaceRoot: string;
1118
- request?: FastifyRequest;
1119
- }) => Readonly<{
1120
- identity: string;
1121
- loadSystemPromptAppend?: () => Promise<string | undefined>;
1122
- }> | Promise<Readonly<{
1123
- identity: string;
1124
- loadSystemPromptAppend?: () => Promise<string | undefined>;
1125
- }>>;
1126
- /** Override the default pi-backed harness with a custom agent runtime. */
1127
- harnessFactory?: AgentHarnessFactory;
1128
- /** Optional pi adapter/runtime knobs used by the default harness. */
1129
- pi?: PiHarnessOptions;
1130
- getPi?: (ctx: {
1131
- workspaceId: string;
1132
- workspaceRoot: string;
1133
- request?: FastifyRequest;
1134
- }) => PiHarnessOptions | undefined | Promise<PiHarnessOptions | undefined>;
1135
- sessionNamespace?: string;
1136
- /** Optional explicit root for file-backed Pi chat transcript storage. */
1137
- sessionRoot?: string;
1138
- /** Trusted host seam for resolving Pi HTTP session scope. */
1139
- resolvePiSessionRequestContext?: PiSessionRequestContextResolver;
1140
- /** Optional best-effort telemetry sink supplied by an embedding host. */
1141
- telemetry?: TelemetrySink;
1142
- /** Optional host admission called immediately before each agent effect. */
1143
- admitEffect?: AgentEffectAdmission$1;
1144
- /** Generic request-aware model filtering seam. Hosts may filter per user/workspace. */
1145
- filterModels?: ModelsRoutesOptions['filterModels'];
1146
- /** Generic per-request/per-run filesystem binding seam. Hosts may return user/session-filtered bindings. */
1147
- getFilesystemBindings?: (ctx: {
1148
- request?: FastifyRequest;
1149
- workspaceId: string;
1150
- workspaceRoot: string;
1151
- sessionId?: string;
1152
- userId?: string;
1153
- userEmail?: string;
1154
- userEmailVerified?: boolean;
1155
- requestId?: string;
1156
- }) => RuntimeFilesystemBinding[] | undefined | Promise<RuntimeFilesystemBinding[] | undefined>;
1157
- /**
1158
- * Optional billing sink for native Pi usage. Reserve happens before
1159
- * accepted prompt/follow-up execution (fail closed), usage is recorded from
1160
- * native assistant message_end events, and runs settle/release from native
1161
- * terminal lifecycle. See AgentMeteringSink.
1162
- */
1163
- metering?: AgentMeteringSink;
1164
- /**
1165
- * Enable user/global Pi extension auto-discovery from .pi/ and ~/.pi.
1166
- * App/internal plugins should be passed through extraTools/pi instead.
1167
- * Defaults to true for standalone agent compatibility.
1168
- */
1169
- externalPlugins?: boolean;
1170
- getSessionNamespace?: (ctx: {
1171
- workspaceId: string;
1172
- workspaceRoot: string;
1173
- request?: FastifyRequest;
1174
- /** Verified actor id for trusted requestless dispatcher resolution. */
1175
- userId?: string;
1176
- }) => string | undefined | Promise<string | undefined>;
1177
- registerHealthRoute?: boolean;
1178
- /**
1179
- * Optional Lane W share-entry store (AR1-002/AR1-003, same-workspace
1180
- * shareable links, `docs/issues/391/runtime-refactor/work/
1181
- * AR1-shareable-artifacts/AR1-001-SPEC.md` §3). When supplied, mounts the
1182
- * membership-gated `GET /a/:id` deep-link route. Omit to leave Lane W
1183
- * entirely unmounted (no widening for hosts that don't use it yet).
1184
- */
1185
- shareEntryStore?: ShareEntryStore;
1186
- getWorkspaceId?: (request: FastifyRequest) => string | Promise<string>;
1187
- getWorkspaceRoot?: (workspaceId: string, request: FastifyRequest) => string | Promise<string>;
1188
- getTrustedWorkspaceRoot?: (ctx: WorkspaceAgentDispatcherContext) => string | Promise<string>;
1189
- /** Generic runtime env contributors. Agent stays workspace-neutral; hosts decide env names/values. */
1190
- runtimeEnvContributions?: RuntimeEnvContribution[];
1191
- /**
1192
- * Optional runtime reconciliation hook. Callers own plugin discovery and may
1193
- * call provisionWorkspaceRuntime() with the normalized structural inputs.
1194
- * registerAgentRoutes only consumes the returned env/PATH/skill paths.
1195
- */
1196
- provisionRuntime?: (ctx: {
1197
- workspaceId: string;
1198
- workspaceRoot: string;
1199
- runtimeMode: RuntimeModeId;
1200
- runtimeLayout: BoringAgentRuntimePaths;
1201
- provisioningAdapter?: WorkspaceProvisioningAdapter;
1202
- /** Already-created paired Workspace/Sandbox runtime for this binding. */
1203
- runtimeBundle: RuntimeBundle;
1204
- request?: FastifyRequest;
1205
- /** Aborted when this binding retires; retirement still drains the task before provider disposal. */
1206
- signal: AbortSignal;
1207
- }) => WorkspaceProvisioningResult | undefined | Promise<WorkspaceProvisioningResult | undefined>;
1208
- provisionWorkspace?: boolean;
1209
- /** Optional hook called before /api/v1/agent/reload reloads the harness. */
1210
- beforeReload?: (ctx: {
1211
- workspaceId: string;
1212
- workspaceRoot: string;
1213
- request: FastifyRequest;
1214
- }) => void | ReloadHookResult | undefined | Promise<void | ReloadHookResult | undefined>;
1215
- /**
1216
- * Optional host callback returning current plugin/skill load diagnostics
1217
- * for a workspace. Surfaced by the `plugin_diagnostics` agent tool so the
1218
- * model can iterate on plugin/skill load errors after a /reload.
1219
- */
1220
- getPluginDiagnostics?: (args: {
1221
- workspaceId: string;
1222
- workspaceRoot: string;
1223
- }) => Promise<Array<{
1224
- source: string;
1225
- message: string;
1226
- pluginId?: string;
1227
- }>>;
1228
- /**
1229
- * Trusted in-process host composition seam. The resolver trusts caller-supplied
1230
- * workspace/user context; callers must authorize that context before resolving.
1231
- */
1232
- onWorkspaceAgentDispatcher?: (resolver: WorkspaceAgentDispatcherResolver) => void;
1233
- }
1234
- interface AgentHostLegacyRouteScopePolicy {
1235
- /** App-owned capability issuer for the already-created Host. */
1236
- issueScope(input: {
1237
- readonly claim: VerifiedAgentScopeClaim;
1238
- readonly runtimeScope: ResolvedAgentRuntimeScope;
1239
- }): AuthorizedAgentScope;
1240
- /** True only for the legacy wrapper whose Host admission calls admitEffect. */
1241
- readonly gatewayUsesLegacyAdmission?: boolean;
1242
- }
1243
- type AgentHostLegacyRoutePolicyOptions = Omit<RegisterAgentRoutesOptions, 'agentHost' | 'runtimeModeAdapter'> & {
1244
- readonly runtimeModeAdapter: RuntimeModeAdapter;
1245
- };
1246
-
1247
- /** Normalize legacy options into the nested Host projection seam. */
1248
- declare function createAgentHostLegacyRoutePolicy(options: AgentHostLegacyRoutePolicyOptions, scopePolicy: AgentHostLegacyRouteScopePolicy): AgentHostLegacyRoutePolicy;
1425
+ /**
1426
+ * Canonical final merge seam for runtime-owned and request-scoped bindings.
1427
+ * Duplicates *within* either list stay configuration errors; a host/request
1428
+ * collision on the same id composes as an intersection of both capabilities.
1429
+ */
1430
+ declare function mergeRuntimeFilesystemBindings<T extends RuntimeFilesystemBinding>(runtimeBindings: readonly T[] | undefined, requestBindings: readonly T[] | undefined): readonly RuntimeFilesystemBinding[] | undefined;
1249
1431
 
1432
+ declare const RUNTIME_READONLY_FILESYSTEM_POLICY_INVALID_CODE: "RUNTIME_READONLY_FILESYSTEM_POLICY_INVALID";
1433
+ declare class RuntimeReadonlyFilesystemPolicyError extends Error {
1434
+ readonly code: "RUNTIME_READONLY_FILESYSTEM_POLICY_INVALID";
1435
+ constructor();
1436
+ }
1250
1437
  /**
1251
- * Compatibility wrapper for legacy embedding callers.
1252
- *
1253
- * It normalizes legacy construction inputs, creates or reuses exactly one Host,
1254
- * and delegates the complete route profile through CreatedAgentHost.registerRoutes().
1438
+ * Default protected prefixes applied when a host does not configure its own.
1439
+ * `.agents` holds agent governance/skill definitions: agents may read them but
1440
+ * must never rewrite the rules they run under. Hosts opt out with an explicit
1441
+ * empty array.
1255
1442
  */
1256
- declare const registerAgentRoutes: FastifyPluginAsync<RegisterAgentRoutesOptions>;
1443
+ declare const DEFAULT_READONLY_WORKSPACE_PATHS: readonly string[];
1444
+ interface RuntimeReadonlyFilesystemPolicy {
1445
+ readonly readonlyPaths: readonly string[];
1446
+ readonly revision: string;
1447
+ }
1448
+ declare function normalizeRuntimeReadonlyFilesystemPolicy(paths: readonly string[]): RuntimeReadonlyFilesystemPolicy;
1449
+ /** Resolve policy after the Workspace adapter has normalized/confined the path. */
1450
+ declare function resolveRuntimeReadonlyFilesystemAccess(policy: RuntimeReadonlyFilesystemPolicy, descriptor: {
1451
+ readonly filesystem: string;
1452
+ readonly normalizedPath: string;
1453
+ }): RuntimeFilesystemAccessDecision;
1454
+
1455
+ /** Primary-user Operations adapter shared by HTTP and Pi filesystem tools. */
1456
+ declare function createUserFilesystemBinding(workspace: Workspace, policy: RuntimeReadonlyFilesystemPolicy, resolvePolicyPath: (path: string) => Promise<string>): RuntimeFilesystemBinding;
1257
1457
 
1258
1458
  interface CredentialStoreBackendV1 {
1259
1459
  read(workspaceId: string, providerId: ProviderId, allowedFieldIds: readonly CredentialFieldId[]): Promise<ResolvedCredentialMaterialV1 & {
@@ -1286,4 +1486,4 @@ declare function createInMemoryCredentialBackendV1(entries: readonly InMemoryCre
1286
1486
 
1287
1487
  declare function withResolvedCredential<T>(resolver: WorkspaceCredentialResolverV1, workspace: AuthorizedWorkspaceCredentialScopeV1, ref: ProviderCredentialRefV1, fn: (lease: ResolvedCredentialLeaseV1) => T | Promise<T>): Promise<T>;
1288
1488
 
1289
- 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 };
1489
+ 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 };