@sorbetai/plugins 0.0.0-stage → 0.1.0-alpha.17

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.
@@ -0,0 +1,27 @@
1
+ import { C as RunYieldHook, E as YieldDecision, I as ObjectMethodSchemas, Mt as PluginSessionRecord, Nt as PluginSessionRecordAppend, O as PluginContextPreparationScope, Pt as PluginSessionRecordsPort, Q as PluginCompactionObservation, R as ObjectRef, S as CommittedAnswer, T as YieldContext, _t as ToolHookContext, bt as ToolHookFeedback, cn as SessionBehaviorCommandSchema, dn as SessionBehaviorMetadata, et as PluginCompactionObserverContribution, fn as SessionBehaviorMetadataSchema, ft as PluginStateReadResult, gt as PreparedToolHooksSchema, hn as SessionBehaviorViewSchema, ht as PreparedToolHooks, l as PluginToolRegistration, ln as SessionBehaviorContribution, mn as SessionBehaviorView, mt as PluginToolResultSnapshot, ot as PluginInput, pn as SessionBehaviorScope, pt as PluginToolResultObservation, sn as SessionBehaviorCommand, st as PluginInputSchema, un as SessionBehaviorDispatch, vt as ToolHookContinuation, w as UsageTotals, xt as ToolHookFeedbackSchema } from "./context-VD8Q9ax-.js";
2
+ import { a as ModelToolSource, c as ModelView, d as ObjectCapabilityGrant, f as ObjectCapabilityOptions, i as ModelToolRequest, l as ModelViewSchema, n as ModelToolLease, o as PluginModelProvider, p as ObjectCapabilitySource, r as ModelToolMetadata, s as ModelToolBinding, t as CommandToolDeclaration, u as ObjectCapabilityBinding } from "./source-Dlv8HG5K.js";
3
+ import { n as ObjectInvocationUnknownSchema, t as ObjectInvocationUnknownError } from "./object-invocation-DMnRagqW.js";
4
+ import * as s from "@earendil-works/pi-schema";
5
+ import * as Effect from "effect/Effect";
6
+ import "ensure-error";
7
+ import * as Scope from "effect/Scope";
8
+
9
+ //#region src/model/object-method.d.ts
10
+ /** Captures a method generation. Model arguments always use { input: nativeInput }.
11
+ * Committed contributions and request leases independently extend the binding's scoped borrow. */
12
+ declare function bindObjectMethod<Key extends s.Schema, Methods extends ObjectMethodSchemas, Name extends keyof Methods & string>(ref: ObjectRef<Key, Methods>, method: Name, metadata: Pick<PluginToolRegistration, 'key' | 'name' | 'description'>): Effect.Effect<PluginToolRegistration, Error, Scope.Scope>;
13
+ //#endregion
14
+ //#region src/model/tool-sources.d.ts
15
+ /**
16
+ * Adds borrowed Tool-only providers while preserving the primary provider's other callback domains.
17
+ * Hosts may opt into additional Session behaviors, yield hooks and Tool hooks.
18
+ * Tool hook chains prepare in source order and feed back in reverse source order;
19
+ * each source retains its captured internal ordering.
20
+ * Other callback domains remain owned by the primary source.
21
+ * This owner releases failed partial captures as well as leases left open at shutdown.
22
+ */
23
+ declare function combineToolSources(primary: ModelToolSource | undefined, additions: readonly ModelToolSource[], options?: {
24
+ readonly sessionContributions?: boolean;
25
+ }): ModelToolSource & AsyncDisposable;
26
+ //#endregion
27
+ export { type CommandToolDeclaration, type CommittedAnswer, type ModelToolBinding, type ModelToolLease, type ModelToolMetadata, type ModelToolRequest, type ModelToolSource, type ModelView, ModelViewSchema, type ObjectCapabilityBinding, type ObjectCapabilityGrant, type ObjectCapabilityOptions, type ObjectCapabilitySource, ObjectInvocationUnknownError, ObjectInvocationUnknownSchema, type PluginCompactionObservation, type PluginCompactionObserverContribution, type PluginContextPreparationScope, type PluginInput, PluginInputSchema, type PluginModelProvider, type PluginSessionRecord, type PluginSessionRecordAppend, type PluginSessionRecordsPort, type PluginStateReadResult, type PluginToolResultObservation, type PluginToolResultSnapshot, type PreparedToolHooks, PreparedToolHooksSchema, type RunYieldHook, type SessionBehaviorCommand, SessionBehaviorCommandSchema, type SessionBehaviorContribution, type SessionBehaviorDispatch, type SessionBehaviorMetadata, SessionBehaviorMetadataSchema, type SessionBehaviorScope, type SessionBehaviorView, SessionBehaviorViewSchema, type ToolHookContext, type ToolHookContinuation, type ToolHookFeedback, ToolHookFeedbackSchema, type UsageTotals, type YieldContext, type YieldDecision, bindObjectMethod, combineToolSources };
package/dist/model.js ADDED
@@ -0,0 +1,274 @@
1
+ import { F as SessionBehaviorCommandSchema, I as SessionBehaviorMetadataSchema, L as SessionBehaviorViewSchema, N as PluginInputSchema, l as ToolHookFeedbackSchema, s as PreparedToolHooksSchema } from "./object-borrow-C81Gj5tq.js";
2
+ import "./run-yield-B1AE7-PN.js";
3
+ import { n as freezeModelEvidence, t as ModelViewSchema } from "./view-Cn9jz2Wx.js";
4
+ import { t as bindObjectMethod } from "./object-method-Bs7hYSjS.js";
5
+ import { n as ObjectInvocationUnknownSchema, t as ObjectInvocationUnknownError } from "./object-invocation-DC6PCiFY.js";
6
+ import { isPromise } from "es-toolkit";
7
+
8
+ //#region src/model/tool-sources.ts
9
+ /**
10
+ * Adds borrowed Tool-only providers while preserving the primary provider's other callback domains.
11
+ * Hosts may opt into additional Session behaviors, yield hooks and Tool hooks.
12
+ * Tool hook chains prepare in source order and feed back in reverse source order;
13
+ * each source retains its captured internal ordering.
14
+ * Other callback domains remain owned by the primary source.
15
+ * This owner releases failed partial captures as well as leases left open at shutdown.
16
+ */
17
+ function combineToolSources(primary, additions, options = {}) {
18
+ let closed = false;
19
+ const leases = /* @__PURE__ */ new Set();
20
+ const subscriptions = /* @__PURE__ */ new Set();
21
+ const releases = /* @__PURE__ */ new Set();
22
+ const released = /* @__PURE__ */ new WeakMap();
23
+ const release = (lease) => {
24
+ const prior = released.get(lease);
25
+ if (prior) return prior;
26
+ leases.delete(lease);
27
+ const result = Promise.resolve(lease[Symbol.asyncDispose]());
28
+ releases.add(result);
29
+ released.set(lease, result);
30
+ result.then(() => {
31
+ releases.delete(result);
32
+ }, () => void 0);
33
+ return result;
34
+ };
35
+ return {
36
+ get commandTools() {
37
+ return [...primary === void 0 ? [] : [primary], ...additions].flatMap((source, index) => (source.commandTools ?? []).map((tool) => ({
38
+ ...tool,
39
+ bindingId: `${index}:${tool.bindingId}`
40
+ })));
41
+ },
42
+ subscribeCommands(listener) {
43
+ if (closed) throw new Error("Combined Tool sources are closed");
44
+ const unsubscribes = [...primary === void 0 ? [] : [primary], ...additions].map((source) => source.subscribeCommands?.(() => {
45
+ try {
46
+ const result = listener();
47
+ if (isPromise(result)) result.catch(() => {});
48
+ } catch {}
49
+ }));
50
+ const unsubscribe = () => {
51
+ subscriptions.delete(unsubscribe);
52
+ for (const dispose of unsubscribes) dispose?.();
53
+ };
54
+ subscriptions.add(unsubscribe);
55
+ return unsubscribe;
56
+ },
57
+ get tools() {
58
+ return [...primary?.tools ?? [], ...additions.flatMap((source) => source.tools ?? [])];
59
+ },
60
+ get sessionBehaviors() {
61
+ return [...primary?.sessionBehaviors ?? [], ...options.sessionContributions ? additions.flatMap((source) => source.sessionBehaviors ?? []) : []];
62
+ },
63
+ get compaction() {
64
+ const sources = [...primary === void 0 ? [] : [primary], ...additions];
65
+ const policies = sources.flatMap((source) => source.compaction?.policy === void 0 ? [] : [source.compaction.policy]);
66
+ const compilers = sources.flatMap((source) => source.compaction?.compiler === void 0 ? [] : [source.compaction.compiler]);
67
+ const observers = sources.flatMap((source) => source.compaction?.observers ?? []);
68
+ if (policies.length > 1) throw new Error("Multiple compaction policies are installed");
69
+ if (compilers.length > 1) throw new Error("Multiple compaction compilers are installed");
70
+ const policy = policies[0];
71
+ const compiler = compilers[0];
72
+ if (policy === void 0 && compiler === void 0 && observers.length === 0) return void 0;
73
+ return {
74
+ ...policy === void 0 ? {} : { policy },
75
+ ...compiler === void 0 ? {} : { compiler },
76
+ ...observers.length === 0 ? {} : { observers }
77
+ };
78
+ },
79
+ acquire(input) {
80
+ if (closed) throw new Error("Combined Tool sources are closed");
81
+ const captured = [];
82
+ try {
83
+ const base = primary?.acquire(input);
84
+ if (base) {
85
+ captured.push(base);
86
+ leases.add(base);
87
+ }
88
+ const extra = additions.map((source) => {
89
+ if (!options.sessionContributions && source.sessionBehaviors?.length) throw new TypeError("Additional Tool sources cannot contribute Session behaviors");
90
+ const lease = source.acquire(input);
91
+ captured.push(lease);
92
+ leases.add(lease);
93
+ const view$1 = lease.view;
94
+ if ([
95
+ ...options.sessionContributions ? [] : [view$1.hooks],
96
+ ...options.sessionContributions ? [] : [view$1.namedStates, view$1.prefixes],
97
+ view$1.inputTransforms,
98
+ view$1.preparationHooks,
99
+ ...options.sessionContributions ? [] : [view$1.sessionBehaviors, view$1.runYield],
100
+ view$1.historySelectors
101
+ ].some((entries) => (entries?.length ?? 0) > 0)) throw new TypeError("Additional Tool sources must contain only Tools");
102
+ return lease;
103
+ });
104
+ const bindings = /* @__PURE__ */ new Map();
105
+ const names = /* @__PURE__ */ new Set();
106
+ const contributions = /* @__PURE__ */ new Set();
107
+ const tools = captured.flatMap((lease, sourceIndex) => lease.view.tools.filter((tool) => input.operationId !== void 0 || tool.discovery?.exposure !== "hidden").map((tool) => {
108
+ if (names.has(tool.name)) throw new TypeError(`Duplicate Plugin Tool name: ${tool.name}`);
109
+ if (contributions.has(tool.contributionId)) throw new TypeError(`Duplicate Plugin contribution: ${tool.contributionId}`);
110
+ names.add(tool.name);
111
+ contributions.add(tool.contributionId);
112
+ const bindingId = `${sourceIndex}:${tool.bindingId}`;
113
+ bindings.set(bindingId, {
114
+ lease,
115
+ original: tool.bindingId
116
+ });
117
+ return {
118
+ ...tool,
119
+ bindingId
120
+ };
121
+ }));
122
+ let disposal;
123
+ const assertExecution = () => {
124
+ if (disposal) throw new Error("Combined Tool lease is released");
125
+ for (const lease of captured) lease.assertExecution();
126
+ };
127
+ const bindingFor = (bindingId) => {
128
+ assertExecution();
129
+ const binding = bindings.get(bindingId);
130
+ if (!binding) throw new Error(`Tool binding ${bindingId} does not belong to this lease`);
131
+ return binding;
132
+ };
133
+ const signals = captured.map((lease) => lease.signal);
134
+ const deadlines = [input.deadline, ...captured.map((lease) => lease.deadline)].filter((deadline) => deadline !== void 0);
135
+ const view = structuredClone({
136
+ ...base?.view,
137
+ schemaVersion: 1,
138
+ tools
139
+ });
140
+ if (options.sessionContributions) {
141
+ view.prefixes = captured.flatMap((lease) => lease.view.prefixes ?? []);
142
+ view.namedStates = captured.flatMap((lease) => lease.view.namedStates ?? []);
143
+ const contextIds = [...view.prefixes, ...view.namedStates].map((entry) => entry.contributionId);
144
+ for (const id of contextIds) {
145
+ if (contributions.has(id)) throw new TypeError(`Duplicate Plugin contribution: ${id}`);
146
+ contributions.add(id);
147
+ }
148
+ const stateNames = view.namedStates.map((entry) => entry.stateName);
149
+ if (new Set(stateNames).size !== stateNames.length) throw new TypeError("Duplicate Plugin named state");
150
+ view.hooks = captured.flatMap((lease) => lease.view.hooks ?? []);
151
+ const hookIds = view.hooks.map((hook) => hook.contributionId);
152
+ if (new Set(hookIds).size !== hookIds.length) throw new Error("Duplicate Tool Hook contribution");
153
+ view.sessionBehaviors = captured.flatMap((lease) => lease.view.sessionBehaviors ?? []);
154
+ view.runYield = captured.flatMap((lease) => lease.view.runYield ?? []).sort((a, b) => a.contributionId.localeCompare(b.contributionId));
155
+ const behaviorNames = view.sessionBehaviors.map((entry) => entry.name);
156
+ if (new Set(behaviorNames).size !== behaviorNames.length) throw new Error("Duplicate Session behavior");
157
+ const ids = view.runYield.map((entry) => entry.contributionId);
158
+ if (new Set(ids).size !== ids.length) throw new Error("Duplicate Run yield hook");
159
+ }
160
+ const behaviorOwner = (name) => captured.find((lease) => lease.view.sessionBehaviors?.some((entry) => entry.name === name));
161
+ const primaryHookOwners = base === void 0 ? [] : [base];
162
+ const hookOwners = options.sessionContributions ? captured : primaryHookOwners;
163
+ const prepareHooks = async (value, context) => {
164
+ assertExecution();
165
+ const prepared = {
166
+ input: value,
167
+ steps: [],
168
+ outcome: { kind: "execute" }
169
+ };
170
+ for (const owner of hookOwners) {
171
+ if (!owner.view.hooks?.length) continue;
172
+ if (!owner.prepareToolHooks) throw new Error("Tool Hook preparation is unavailable");
173
+ const next = await owner.prepareToolHooks(prepared.input, context);
174
+ prepared.input = next.input;
175
+ prepared.steps.push(...next.steps);
176
+ prepared.outcome = next.outcome;
177
+ if (next.outcome.kind !== "execute") break;
178
+ }
179
+ return prepared;
180
+ };
181
+ const finishHooks = async (prepared, result, context) => {
182
+ assertExecution();
183
+ let feedback = result;
184
+ for (const owner of [...hookOwners].reverse()) {
185
+ const ids = new Set(owner.view.hooks?.map((hook) => hook.contributionId));
186
+ const steps = prepared.steps.filter((step) => ids.has(step.contributionId));
187
+ if (!steps.length) continue;
188
+ if (!owner.finishToolHooks) throw new Error("Tool Hook feedback is unavailable");
189
+ feedback = await owner.finishToolHooks({
190
+ ...prepared,
191
+ steps
192
+ }, feedback, context);
193
+ }
194
+ return feedback;
195
+ };
196
+ freezeModelEvidence(view);
197
+ return {
198
+ leaseId: JSON.stringify(captured.map((lease) => lease.leaseId)),
199
+ view,
200
+ deadline: deadlines.length ? Math.min(...deadlines) : void 0,
201
+ signal: signals.length ? AbortSignal.any(signals) : input.signal,
202
+ assertExecution,
203
+ toolRecovery(bindingId) {
204
+ const binding = bindingFor(bindingId);
205
+ return binding.lease.toolRecovery?.(binding.original) ?? "unsafe";
206
+ },
207
+ prepareToolArguments(bindingId, value) {
208
+ const binding = bindingFor(bindingId);
209
+ return binding.lease.prepareToolArguments?.(binding.original, value) ?? value;
210
+ },
211
+ selectHistory: base?.selectHistory?.bind(base),
212
+ prepareContext: base?.prepareContext?.bind(base),
213
+ reduceBehavior: (name, ...args) => {
214
+ assertExecution();
215
+ const owner = behaviorOwner(name);
216
+ if (owner?.reduceBehavior === void 0) throw new Error("Behavior is unavailable");
217
+ return owner.reduceBehavior(name, ...args);
218
+ },
219
+ behaviorSignal: (name) => {
220
+ const owner = behaviorOwner(name);
221
+ if (owner?.behaviorSignal === void 0) throw new Error("Behavior is unavailable");
222
+ return owner.behaviorSignal(name);
223
+ },
224
+ yieldRun: async (id, ...args) => {
225
+ assertExecution();
226
+ const owner = captured.find((lease) => lease.view.runYield?.some((entry) => entry.contributionId === id));
227
+ if (owner?.yieldRun === void 0) throw new Error("Yield hook is unavailable");
228
+ return owner.yieldRun(id, ...args);
229
+ },
230
+ transformInput: base?.transformInput?.bind(base),
231
+ readNamedState: (id, ...args) => {
232
+ assertExecution();
233
+ const owner = captured.find((lease) => lease.view.namedStates?.some((entry) => entry.contributionId === id));
234
+ if (owner?.readNamedState === void 0) throw new Error("Named State is unavailable");
235
+ return owner.readNamedState(id, ...args);
236
+ },
237
+ prepareToolHooks: prepareHooks,
238
+ finishToolHooks: finishHooks,
239
+ async runToolHooks(value, context, continuation) {
240
+ const prepared = await prepareHooks(value, context);
241
+ const outcome = prepared.outcome;
242
+ if (outcome.kind === "block") return continuation.block(outcome.reason, outcome.contributionId);
243
+ const result = outcome.kind === "respond" ? await continuation.respond(prepared.input, outcome.result, outcome.contributionId) : await continuation.execute(prepared.input);
244
+ return continuation.canProcessFeedback?.() === false ? result : finishHooks(prepared, result, context);
245
+ },
246
+ invoke(bindingId, value, ...invocationOptions) {
247
+ const binding = bindingFor(bindingId);
248
+ return binding.lease.invoke(binding.original, value, ...invocationOptions);
249
+ },
250
+ [Symbol.asyncDispose]() {
251
+ disposal ??= (async () => {
252
+ const failures = (await Promise.allSettled([...base ? [base] : [], ...extra].map(release))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
253
+ if (failures.length) throw new AggregateError(failures, "Failed to release combined Tool borrow");
254
+ })();
255
+ return disposal;
256
+ }
257
+ };
258
+ } catch (error) {
259
+ for (const lease of captured) release(lease).catch(() => void 0);
260
+ throw error;
261
+ }
262
+ },
263
+ async [Symbol.asyncDispose]() {
264
+ closed = true;
265
+ for (const unsubscribe of subscriptions) unsubscribe();
266
+ for (const lease of leases) release(lease).catch(() => void 0);
267
+ const failures = (await Promise.allSettled(releases)).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
268
+ if (failures.length) throw new AggregateError(failures, "Failed to close combined Tool sources");
269
+ }
270
+ };
271
+ }
272
+
273
+ //#endregion
274
+ export { ModelViewSchema, ObjectInvocationUnknownError, ObjectInvocationUnknownSchema, PluginInputSchema, PreparedToolHooksSchema, SessionBehaviorCommandSchema, SessionBehaviorMetadataSchema, SessionBehaviorViewSchema, ToolHookFeedbackSchema, bindObjectMethod, combineToolSources };
package/dist/node.d.ts ADDED
@@ -0,0 +1,273 @@
1
+ import { b as ToolPluginComponent, d as ModelToolContribution, i as PluginDefinition, m as PluginLifetime, t as PluginApply } from "./context-VD8Q9ax-.js";
2
+ import { C as PluginPackageDocument, T as StoredPluginPackage, a as PluginCommitData, l as PluginAuthorityJournalBatch, o as PluginStore, r as PluginExecutionReference, s as PluginAuthorityCheckpoint, t as PluginCompositionAuthority, y as PluginPackageInspector } from "./authority-DGNilDTs.js";
3
+ import "./object-invocation-DMnRagqW.js";
4
+ import { a as ObjectFacetTransport, t as ObjectFacet } from "./facet-DnC_pqrd.js";
5
+ import * as Context from "effect/Context";
6
+ import { Duplex } from "node:stream";
7
+
8
+ //#region src/node/sqlite-store.d.ts
9
+ /** One exclusive connection; an uncertain commit requires closing and reopening the owner and store. */
10
+ declare class SqlitePluginStore implements PluginStore {
11
+ #private;
12
+ readonly authorityId: string;
13
+ private constructor();
14
+ static open(directory: string, authorityId: string): Promise<SqlitePluginStore>;
15
+ read(): Promise<readonly PluginAuthorityJournalBatch[]>;
16
+ readCheckpoint(): Promise<PluginAuthorityCheckpoint | undefined>;
17
+ readPackage(packageId: string): Promise<StoredPluginPackage | undefined>;
18
+ append(batch: PluginAuthorityJournalBatch, data?: PluginCommitData): Promise<'committed' | 'not-committed' | 'unknown' | 'conflict'>;
19
+ reconcile(batch: PluginAuthorityJournalBatch): Promise<'committed' | 'absent' | 'unknown'>;
20
+ compact(checkpoint: PluginAuthorityCheckpoint): Promise<'committed' | 'not-committed' | 'unknown' | 'conflict'>;
21
+ close(): void;
22
+ }
23
+ //#endregion
24
+ //#region src/node/plugin-directory.d.ts
25
+ /** Host-supplied adapter for non-Sorbet package layouts such as a Pi extension directory. */
26
+ interface NodePluginSource {
27
+ readonly name: string;
28
+ /** Returns a complete package document, or undefined when the directory is not its layout. */
29
+ read(directory: string): Promise<PluginPackageDocument | undefined>;
30
+ }
31
+ interface NodePluginDirectoryDiagnostic {
32
+ readonly entryId: string;
33
+ readonly path: string;
34
+ readonly message: string;
35
+ readonly retainedPrevious: boolean;
36
+ }
37
+ /** Host-trusted package containers; filesystem changes submit Desired, never manage Mount resources. */
38
+ declare class NodePluginDirectory {
39
+ #private;
40
+ private constructor();
41
+ static open(options: {
42
+ readonly directory: string;
43
+ readonly authority: PluginCompositionAuthority;
44
+ readonly watch?: boolean;
45
+ readonly onError?: (error: Error) => void;
46
+ /** Reject custom ABIs before Authority registration when the Host uses only the native profile. */
47
+ readonly nativeOnly?: boolean;
48
+ /** Preflight custom source profiles independently, before any Authority write. */
49
+ readonly packageProfiles?: readonly PluginPackageInspector[];
50
+ /** Host-supplied adapters for non-Sorbet package layouts. */
51
+ readonly sources?: readonly NodePluginSource[];
52
+ /** UTF-8 resource suffixes captured alongside custom-profile sources; dependencies are excluded. */
53
+ readonly resourceExtensions?: readonly string[];
54
+ /** Select decoded packages to include in the Host composition. */
55
+ readonly include?: (entryId: string, document: PluginPackageDocument) => boolean;
56
+ }): Promise<NodePluginDirectory>;
57
+ /** Only current Host source generations are eligible for new Client intent. */
58
+ allows(packageId: string): boolean;
59
+ /** Current source failures; an invalid edit retains only that source's last accepted generation. */
60
+ diagnostics(): readonly NodePluginDirectoryDiagnostic[];
61
+ /** Cancellation joins any in-flight Authority append; uncertain writes are never retried. */
62
+ refresh(signal?: AbortSignal): Promise<void>;
63
+ close(): Promise<void>;
64
+ }
65
+ //#endregion
66
+ //#region src/node/object-facet.d.ts
67
+ interface ObjectFacetTransportOptions {
68
+ /** Optional execution policy. Expiry cancels only this request and joins its terminal reply. */
69
+ readonly requestTimeoutMs?: number;
70
+ /** Stop observing cancellation after this duration. The pending request and its permit remain
71
+ * owned until its real reply or connection termination; expiry never closes the connection. */
72
+ readonly cancellationTimeoutMs?: number;
73
+ /** Concurrent data requests; excess callers wait interruptibly. Control requests bypass it. */
74
+ readonly concurrency?: number;
75
+ }
76
+ /** The Host owns connection authentication and placement. Closing the wire aborts requests
77
+ * and releases only this connection's holds; already dispatched effects are never replayed. */
78
+ declare function serveObjectFacet(socket: Duplex, facet: ObjectFacet, options?: {
79
+ readonly concurrency?: number;
80
+ }): Promise<void>;
81
+ /** Owns a preconnected authenticated Duplex. It never reconnects or retries a request. */
82
+ declare function objectFacetTransport(socket: Duplex, options?: ObjectFacetTransportOptions): ObjectFacetTransport;
83
+ //#endregion
84
+ //#region src/node/process/error.d.ts
85
+ type PluginProcessErrorCode = 'cancelled' | 'timeout' | 'crashed' | 'protocol' | 'quota' | 'closed' | 'spawn' | 'unsupported';
86
+ /** The first process termination cause applies to every invocation sharing that worker. */
87
+ declare class PluginProcessError extends Error {
88
+ readonly code: PluginProcessErrorCode;
89
+ constructor(code: PluginProcessErrorCode, message: string, options?: ErrorOptions);
90
+ }
91
+ //#endregion
92
+ //#region src/node/process/observation.d.ts
93
+ interface PluginWorkerIdentity {
94
+ readonly loaderId?: string;
95
+ readonly workerId: string;
96
+ readonly activationId: string;
97
+ readonly entryId: string;
98
+ /** Host-visible owned PID; a sandbox's inner PID can differ. */
99
+ readonly pid: number | undefined;
100
+ }
101
+ interface PluginWorkerInventory extends PluginWorkerIdentity {
102
+ readonly state: 'starting' | 'active' | 'retiring';
103
+ readonly pendingCalls: number;
104
+ readonly outputQueueBytes: number;
105
+ readonly startedAt: number;
106
+ }
107
+ interface PluginWorkerExit extends PluginWorkerIdentity {
108
+ readonly reason: PluginProcessErrorCode;
109
+ readonly exitCode: number | null;
110
+ readonly signal: NodeJS.Signals | null;
111
+ readonly durationMs: number;
112
+ readonly startedAtUnixMs?: number;
113
+ readonly endedAtUnixMs?: number;
114
+ }
115
+ interface PluginInvocationObservation extends PluginWorkerIdentity {
116
+ readonly sessionId?: string;
117
+ readonly runId?: string;
118
+ readonly toolCallId?: string;
119
+ readonly callType: 'init' | 'activate' | 'close' | 'tool' | 'state' | 'transform';
120
+ readonly outcome: 'succeeded' | 'failed' | PluginProcessErrorCode;
121
+ /** Monotonic elapsed time, including IPC and joined Host callbacks. */
122
+ readonly durationMs: number;
123
+ /** Wall-clock anchors for display; durationMs remains the monotonic measurement. */
124
+ readonly startedAtUnixMs?: number;
125
+ readonly endedAtUnixMs?: number;
126
+ }
127
+ type PluginDiagnosticDropReason = 'rate' | 'size' | 'buffer' | 'redaction' | 'invalid_utf8' | 'expired' | 'closed';
128
+ interface PluginWorkerDiagnostic extends PluginWorkerIdentity {
129
+ readonly recordedAt: number;
130
+ readonly source: 'plugin.author.stderr';
131
+ readonly bytes: number;
132
+ readonly truncated: boolean;
133
+ /** Absent unless the Host explicitly enables local capture and sanitizes the line. */
134
+ readonly text?: string;
135
+ }
136
+ interface PluginDiagnosticDrop extends PluginWorkerIdentity {
137
+ readonly reason: PluginDiagnosticDropReason;
138
+ readonly bytes: number;
139
+ readonly lines: number;
140
+ }
141
+ /** Passive, synchronous enqueue-only callbacks. Network I/O and content export belong to the Host.
142
+ * Callback throws/rejections are counted and cannot change process execution or capacity. */
143
+ interface PluginProcessObservationPort {
144
+ readonly ipcFrame?: (data: PluginWorkerIdentity & {
145
+ readonly direction: 'inbound' | 'outbound';
146
+ readonly bytes: number;
147
+ }) => void;
148
+ readonly ipcQueueChanged?: (data: PluginWorkerIdentity & {
149
+ readonly bytes: number;
150
+ }) => void;
151
+ readonly protocolFailed?: (data: PluginWorkerIdentity & {
152
+ readonly reason: 'framing' | 'schema' | 'transport' | 'output_limit' | 'callback';
153
+ }) => void;
154
+ readonly capacityChanged?: (data: {
155
+ readonly loaderId: string;
156
+ readonly capacity: number;
157
+ readonly starting: number;
158
+ readonly owned: number;
159
+ readonly retiring: number;
160
+ readonly pendingCalls: number;
161
+ readonly pendingCallbacks: number;
162
+ readonly outputQueueBytes: number;
163
+ readonly closed: boolean;
164
+ }) => void;
165
+ readonly workerStarted?: (data: PluginWorkerIdentity) => void;
166
+ readonly workerExited?: (data: PluginWorkerExit) => void;
167
+ readonly invocationSettled?: (data: PluginInvocationObservation) => void;
168
+ readonly diagnostic?: (data: PluginWorkerDiagnostic) => void;
169
+ readonly diagnosticDropped?: (data: PluginDiagnosticDrop) => void;
170
+ }
171
+ interface PluginDiagnosticCaptureOptions {
172
+ /** Explicit local-only content opt-in. Return undefined to discard sensitive lines.
173
+ * A sanitizer is a policy boundary, not a guarantee that arbitrary secrets are recognized. */
174
+ readonly sanitize?: (line: string) => string | undefined;
175
+ readonly maxLineBytes?: number;
176
+ readonly maxWorkerBytesPerSecond?: number;
177
+ readonly maxHostBytesPerSecond?: number;
178
+ readonly maxWorkerBufferBytes?: number;
179
+ readonly maxHostBufferBytes?: number;
180
+ readonly retentionMs?: number;
181
+ }
182
+ interface PluginProcessSnapshot {
183
+ readonly loaderId: string;
184
+ readonly capacity: number;
185
+ readonly starting: number;
186
+ readonly pendingCallbacks: number;
187
+ readonly workers: readonly PluginWorkerInventory[];
188
+ readonly observerFailures: number;
189
+ readonly diagnosticBufferBytes: number;
190
+ readonly diagnosticDrops: Readonly<Record<PluginDiagnosticDropReason, number>>;
191
+ readonly diagnostics: readonly PluginWorkerDiagnostic[];
192
+ }
193
+ //#endregion
194
+ //#region src/node/process/diagnostics.d.ts
195
+ /** The Loader owns one capture budget shared by all of its workers. */
196
+ declare class PluginDiagnosticCapture {
197
+ #private;
198
+ constructor(options?: PluginDiagnosticCaptureOptions, diagnostic?: (record: PluginWorkerDiagnostic) => void, dropped?: (record: PluginDiagnosticDrop) => void);
199
+ snapshot(): {
200
+ readonly bytes: number;
201
+ readonly drops: Record<PluginDiagnosticDropReason, number>;
202
+ readonly records: PluginWorkerDiagnostic[];
203
+ readonly observerFailures: number;
204
+ };
205
+ drain(identity: PluginWorkerIdentity): {
206
+ write(chunk: Buffer): void;
207
+ end(): void;
208
+ error(): void;
209
+ };
210
+ /** Host-owned capture outlives borrowers; close after every attached Loader has closed. */
211
+ close(): void;
212
+ }
213
+ //#endregion
214
+ //#region src/node/process/loader.d.ts
215
+ interface NodePluginProcessLoaderOptions {
216
+ /** Bundled worker entry. Defaults to the worker distributed beside this module. */
217
+ readonly workerPath?: string;
218
+ /** Optional Host deadline for initialization, activation and graceful cleanup before
219
+ * physical SIGKILL. Without one these operations remain owned until they settle.
220
+ * Executing requests use their Host lease's deadline and cancellation signal. */
221
+ readonly lifecycleTimeoutMs?: number;
222
+ /** Optional Host process window, including pending, active and retiring processes.
223
+ * Admission waits until an owned process exits. No process count is imposed by default. */
224
+ readonly maxProcesses?: number;
225
+ /** Optional V8 old-space budget in MiB for each isolated process. */
226
+ readonly maxOldSpaceSizeMb?: number;
227
+ readonly observation?: PluginProcessObservationPort;
228
+ /** Metadata-only by default, with bounded local retention. */
229
+ readonly diagnostics?: PluginDiagnosticCaptureOptions;
230
+ /** Borrowed Host budget shared by every Session Loader. Its owner closes it after the loaders. */
231
+ readonly diagnosticsBudget?: PluginDiagnosticCapture;
232
+ }
233
+ /** One sandboxed OS process per Activation: module globals and caches are never shared across Entries. */
234
+ declare class NodePluginProcessLoader {
235
+ #private;
236
+ constructor(authority: PluginCompositionAuthority, options?: NodePluginProcessLoaderOptions);
237
+ /** Read-only process ownership and bounded local diagnostics; no OS memory attribution is inferred. */
238
+ snapshot(): PluginProcessSnapshot;
239
+ componentAt(reference: PluginExecutionReference): ToolPluginComponent;
240
+ /** Close borrowing Platforms first. Exiting workers releases their complete ESM cache. */
241
+ close(): Promise<void>;
242
+ }
243
+ //#endregion
244
+ //#region src/node/native-loader.d.ts
245
+ /** Conversion only; the loader owns current input capture and managed authorization checks. */
246
+ interface NodePluginPackageProfile extends PluginPackageInspector {
247
+ /** Returns a normalized author definition; loading and apply share an instance Scope. */
248
+ load(record: StoredPluginPackage, lifetime: PluginLifetime, document: PluginPackageDocument): Promise<PluginApply<never> | PluginDefinition<never, readonly Context.Key<unknown, unknown>[]>>;
249
+ }
250
+ /** Explicit Host rebinding for one Package/Entry; not available to author callbacks as a capability. */
251
+ interface NodePluginHostToolBinding {
252
+ readonly packageId: string;
253
+ readonly entryId: string;
254
+ readonly bindingId: string;
255
+ readonly tool: ModelToolContribution;
256
+ }
257
+ /**
258
+ * Trusted in-process ESM, not a sandbox. Node owns module evaluation and its
259
+ * process-lifetime cache; close deregisters resolution, not that cache or active
260
+ * code. Close borrowing Platforms first. Each loader has its own module cache
261
+ * namespace, with one module instance per Package/path inside that loader.
262
+ */
263
+ declare class NodePluginPackageLoader {
264
+ #private;
265
+ constructor(authority: PluginCompositionAuthority, hostTools?: readonly NodePluginHostToolBinding[], profiles?: readonly NodePluginPackageProfile[], effectModuleUrl?: string);
266
+ /** Captures current desired provenance now; reconstruction and evaluation run under Activation readiness. */
267
+ component(entryId: string): ToolPluginComponent;
268
+ /** Captures current Desired inputs without evaluating code; stale references reject on load. */
269
+ componentAt(reference: PluginExecutionReference): ToolPluginComponent;
270
+ close(): void;
271
+ }
272
+ //#endregion
273
+ export { NodePluginDirectory, type NodePluginHostToolBinding, NodePluginPackageLoader, type NodePluginPackageProfile, NodePluginProcessLoader, type NodePluginProcessLoaderOptions, type NodePluginSource, type ObjectFacetTransportOptions, PluginDiagnosticCapture, type PluginDiagnosticCaptureOptions, type PluginDiagnosticDrop, type PluginDiagnosticDropReason, type PluginInvocationObservation, PluginProcessError, type PluginProcessErrorCode, type PluginProcessObservationPort, type PluginProcessSnapshot, type PluginWorkerDiagnostic, type PluginWorkerExit, type PluginWorkerIdentity, type PluginWorkerInventory, SqlitePluginStore, objectFacetTransport, serveObjectFacet };