@irogane/kaji 0.2.0-beta.11
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.
- package/LICENSE +105 -0
- package/README.md +598 -0
- package/contracts/README.md +14 -0
- package/contracts/beta-core-v1.json +52 -0
- package/contracts/cli/init-cases-v1.json +27 -0
- package/contracts/errors/error-codes.json +48 -0
- package/contracts/errors/integration-recovery-v1.json +127 -0
- package/contracts/errors/provider-normalization.json +111 -0
- package/contracts/events/conformance-invalid.json +20 -0
- package/contracts/events/conformance.json +511 -0
- package/contracts/events/new-kaji-event-v1.schema.json +1021 -0
- package/contracts/events/stored-kaji-event-v1.schema.json +1025 -0
- package/contracts/feature-tiers-v1.json +488 -0
- package/contracts/integrations/abi-index-v1.json +8 -0
- package/contracts/integrations/conformance-invalid.json +443 -0
- package/contracts/integrations/conformance-valid.json +121 -0
- package/contracts/integrations/copy-provenance-v1.schema.json +61 -0
- package/contracts/integrations/echo-tool-abi-v1.json +37 -0
- package/contracts/integrations/github-api-conformance-v1.json +644 -0
- package/contracts/integrations/github-tool-abi-typescript-v1.json +369 -0
- package/contracts/integrations/github-tool-abi-v1.json +146 -0
- package/contracts/integrations/gmail-api-conformance-v1.json +750 -0
- package/contracts/integrations/gmail-tool-abi-v1.json +62 -0
- package/contracts/integrations/index.schema.json +37 -0
- package/contracts/integrations/manifest.schema.json +119 -0
- package/contracts/parity/expected-normalized.json +4906 -0
- package/contracts/parity/scenarios.json +100 -0
- package/contracts/parity/scenarios.schema.json +214 -0
- package/contracts/providers/cost-conformance.json +112 -0
- package/contracts/release/github-proof-v1.schema.json +138 -0
- package/contracts/release/gmail-proof-v1.schema.json +138 -0
- package/contracts/release/kaji-ts-consumer-handoff-v1.schema.json +1289 -0
- package/contracts/release/publisher-identity-receipt-v1.schema.json +319 -0
- package/contracts/release/typescript-onboarding-evidence-v1.schema.json +740 -0
- package/contracts/tools/conformance-invalid.json +271 -0
- package/contracts/tools/conformance-valid.json +78 -0
- package/contracts/tools/tool-schema-v1.schema.json +18 -0
- package/dist/anthropic.cjs +1231 -0
- package/dist/anthropic.cjs.map +1 -0
- package/dist/anthropic.d.cts +26 -0
- package/dist/anthropic.d.ts +26 -0
- package/dist/anthropic.js +270 -0
- package/dist/anthropic.js.map +1 -0
- package/dist/auth.cjs +1507 -0
- package/dist/auth.cjs.map +1 -0
- package/dist/auth.d.cts +129 -0
- package/dist/auth.d.ts +129 -0
- package/dist/auth.js +1039 -0
- package/dist/auth.js.map +1 -0
- package/dist/base-B9FRMcP8.d.cts +140 -0
- package/dist/base-nHQd1VtS.d.ts +140 -0
- package/dist/chunk-AAM33KAO.js +4367 -0
- package/dist/chunk-AAM33KAO.js.map +1 -0
- package/dist/chunk-KAJ6BM64.js +153 -0
- package/dist/chunk-KAJ6BM64.js.map +1 -0
- package/dist/chunk-KCAXIOZS.js +308 -0
- package/dist/chunk-KCAXIOZS.js.map +1 -0
- package/dist/chunk-LSJ4AVO2.js +243 -0
- package/dist/chunk-LSJ4AVO2.js.map +1 -0
- package/dist/chunk-TM7ZGOJX.js +716 -0
- package/dist/chunk-TM7ZGOJX.js.map +1 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +13 -0
- package/dist/cli/bin.js.map +1 -0
- package/dist/cli/chunk-2RCWPRVY.js +6277 -0
- package/dist/cli/chunk-2RCWPRVY.js.map +1 -0
- package/dist/cli/chunk-SEBX54TR.js +681 -0
- package/dist/cli/chunk-SEBX54TR.js.map +1 -0
- package/dist/cli/index.d.ts +232 -0
- package/dist/cli/index.js +11 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli/init-worker.d.ts +2 -0
- package/dist/cli/init-worker.js +18 -0
- package/dist/cli/init-worker.js.map +1 -0
- package/dist/cli/integration-copy-worker.js +48 -0
- package/dist/cli/integration-copy-worker.js.map +1 -0
- package/dist/cli/package-entry-cjs.cjs +21 -0
- package/dist/cli/package-entry-cjs.cjs.map +1 -0
- package/dist/cli/package-entry-cjs.d.cts +2 -0
- package/dist/cli/package-entry.d.ts +2 -0
- package/dist/cli/package-entry.js +13 -0
- package/dist/cli/package-entry.js.map +1 -0
- package/dist/context-BaFHrQHv.d.cts +21 -0
- package/dist/context-BaFHrQHv.d.ts +21 -0
- package/dist/context-C-YPY-GS.d.cts +1538 -0
- package/dist/context-C-YPY-GS.d.ts +1538 -0
- package/dist/index.cjs +12346 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1560 -0
- package/dist/index.d.ts +1560 -0
- package/dist/index.js +7852 -0
- package/dist/index.js.map +1 -0
- package/dist/integrations/github.cjs +2092 -0
- package/dist/integrations/github.cjs.map +1 -0
- package/dist/integrations/github.d.cts +21 -0
- package/dist/integrations/github.d.ts +21 -0
- package/dist/integrations/github.js +2088 -0
- package/dist/integrations/github.js.map +1 -0
- package/dist/integrations.cjs +3370 -0
- package/dist/integrations.cjs.map +1 -0
- package/dist/integrations.d.cts +202 -0
- package/dist/integrations.d.ts +202 -0
- package/dist/integrations.js +2650 -0
- package/dist/integrations.js.map +1 -0
- package/dist/observability-Cj--OkME.d.cts +96 -0
- package/dist/observability-Cj--OkME.d.ts +96 -0
- package/dist/openai.cjs +1235 -0
- package/dist/openai.cjs.map +1 -0
- package/dist/openai.d.cts +32 -0
- package/dist/openai.d.ts +32 -0
- package/dist/openai.js +272 -0
- package/dist/openai.js.map +1 -0
- package/dist/testing.cjs +554 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +43 -0
- package/dist/testing.d.ts +43 -0
- package/dist/testing.js +118 -0
- package/dist/testing.js.map +1 -0
- package/package.json +188 -0
- package/registry/echo/index.ts +53 -0
- package/registry/echo/manifest.json +53 -0
- package/registry/github/LICENSE +105 -0
- package/registry/github/client.ts +1727 -0
- package/registry/github/index.ts +263 -0
- package/registry/github/manifest.json +227 -0
- package/registry/github/owner-fixtures.json +10 -0
- package/registry/github/tests/github.test.ts +32 -0
- package/registry/gmail/LICENSE +105 -0
- package/registry/gmail/client.ts +548 -0
- package/registry/gmail/index.ts +165 -0
- package/registry/gmail/manifest.json +102 -0
- package/registry/gmail/owner-fixtures.json +10 -0
- package/registry/gmail/tests/gmail.test.ts +32 -0
- package/registry/index.json +21 -0
- package/registry/index.schema.json +37 -0
- package/registry/schema.json +119 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,1560 @@
|
|
|
1
|
+
import { N as NewKajiEvent, S as StoredKajiEvent, K as KajiEvent, M as MetricsSink, C as ContextWindow, a as SessionState, b as ContextBuildResult, T as ToolRisk, c as ToolCall, d as ToolExecutionContext, e as TimerScheduler, f as TraceSink, g as ToolSpec, I as IdFactory, h as Clock, R as RetryOptions, i as ModelProvider, P as ProviderMessage, j as ModelProviderOptions, k as ModelResponse, l as ModelResponseChunk, m as ToolHandler, n as ToolRegistry, o as ToolMeta, J as JSONSchema, p as CancellationTokenLike, q as TurnContext, r as ContextDiagnostics, s as CancellationToken, t as TokenUsage } from './context-C-YPY-GS.js';
|
|
2
|
+
export { A as AgentTurnFailed, u as ApprovalFailureCode, v as ApprovalKey, B as BaseEvent, w as CancellationError, x as ContextIntegrityError, y as ContextWindowOverflowError, D as DEFAULT_CONTEXT_WINDOW, z as DEFAULT_PROVIDER_RESPONSE_LIMITS, E as IdScope, F as JournalStage, G as KajiEventInput, L as ListToolSpecsOptions, H as METRIC_NAMES, O as Message, Q as MetricLabels, U as MetricMeasurement, V as MetricName, W as MissingToolIdentityError, X as NOOP_METRICS, Y as NOOP_TRACE, Z as ProviderFamily, _ as ProviderResponseLimits, $ as ProviderStatus, a0 as SessionCreated, a1 as SessionTokens, a2 as SpanName, a3 as SubscriberStage, a4 as TimerHandle, a5 as ToolArgumentValidationError, a6 as ToolExecutionOutcome, a7 as ToolMetricOutcome, a8 as ToolParameters, a9 as ToolSchemaValidationError, aa as ToolSchemaValidator, ab as ToolValidationCode, ac as ToolValidationError, ad as TraceAttributeName, ae as TraceAttributeValue, af as TraceAttributes, ag as TraceSpan, ah as TurnOutcome, ai as UnclassifiedToolRiskError, aj as UnknownToolError, ak as UuidFactory, al as applyEvent, am as approvalKey, an as deadlineAfter, ao as executeTool, ap as listToolSpecs, aq as providerFamily, ar as recordMetric, as as registerTool, at as replaySession, au as resolveProviderResponseLimits, av as startSpan, aw as throwIfCancellationRequested, ax as toolSpecFromSchema, ay as validateNewEvent, az as validateStoredEvent } from './context-C-YPY-GS.js';
|
|
3
|
+
import * as z from 'zod';
|
|
4
|
+
import 'ajv/dist/2020.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Event type discriminants. String values are the wire format and must match
|
|
8
|
+
* the Python SDK (`kaji.infra.events.types.EventType`) byte for byte.
|
|
9
|
+
*/
|
|
10
|
+
declare const EventType: {
|
|
11
|
+
readonly SESSION_CREATED: "session.created";
|
|
12
|
+
readonly SESSION_CLOSED: "session.closed";
|
|
13
|
+
readonly USER_MESSAGE: "user.message";
|
|
14
|
+
readonly USER_AUDIO_CHUNK: "user.audio.chunk";
|
|
15
|
+
readonly TRANSCRIPT_PARTIAL: "transcript.partial";
|
|
16
|
+
readonly TRANSCRIPT_FINAL: "transcript.final";
|
|
17
|
+
readonly MEMORY_RETRIEVAL_STARTED: "memory.retrieval.started";
|
|
18
|
+
readonly MEMORY_RETRIEVAL_COMPLETED: "memory.retrieval.completed";
|
|
19
|
+
readonly AGENT_REASONING_STARTED: "agent.reasoning.started";
|
|
20
|
+
readonly AGENT_MESSAGE_DELTA: "agent.message.delta";
|
|
21
|
+
readonly AGENT_MESSAGE_COMPLETED: "agent.message.completed";
|
|
22
|
+
readonly AGENT_TURN_EXHAUSTED: "agent.turn.exhausted";
|
|
23
|
+
readonly AGENT_TURN_FAILED: "agent.turn.failed";
|
|
24
|
+
readonly TOOL_CALL_REQUESTED: "tool.call.requested";
|
|
25
|
+
readonly TOOL_CALL_STARTED: "tool.call.started";
|
|
26
|
+
readonly TOOL_CALL_COMPLETED: "tool.call.completed";
|
|
27
|
+
readonly TOOL_CALL_FAILED: "tool.call.failed";
|
|
28
|
+
readonly TOOL_APPROVAL_REQUESTED: "tool.approval.requested";
|
|
29
|
+
readonly TOOL_APPROVAL_APPROVED: "tool.approval.approved";
|
|
30
|
+
readonly TOOL_APPROVAL_REJECTED: "tool.approval.rejected";
|
|
31
|
+
readonly WORKFLOW_STARTED: "workflow.started";
|
|
32
|
+
readonly WORKFLOW_COMPLETED: "workflow.completed";
|
|
33
|
+
readonly WORKFLOW_FAILED: "workflow.failed";
|
|
34
|
+
readonly CANCELLATION_REQUESTED: "cancellation.requested";
|
|
35
|
+
readonly CANCELLATION_COMPLETED: "cancellation.completed";
|
|
36
|
+
};
|
|
37
|
+
type EventType = (typeof EventType)[keyof typeof EventType];
|
|
38
|
+
|
|
39
|
+
type DurableJsonSubject = "tool_result" | "workflow_result" | "event_metadata" | "memory_document" | "pending_tool_call" | "event";
|
|
40
|
+
declare class InvalidDurableValueError extends Error {
|
|
41
|
+
readonly subject: DurableJsonSubject;
|
|
42
|
+
readonly code: "INVALID_DURABLE_VALUE";
|
|
43
|
+
constructor(subject: DurableJsonSubject);
|
|
44
|
+
}
|
|
45
|
+
declare class DurableJsonLimitError extends Error {
|
|
46
|
+
readonly subject: DurableJsonSubject;
|
|
47
|
+
readonly maxBytes: number;
|
|
48
|
+
readonly code: "EVENT_PAYLOAD_TOO_LARGE";
|
|
49
|
+
constructor(subject: DurableJsonSubject, maxBytes: number);
|
|
50
|
+
}
|
|
51
|
+
declare class EventSchemaIncompatibleError extends Error {
|
|
52
|
+
readonly path: string;
|
|
53
|
+
readonly code = "EVENT_SCHEMA_INCOMPATIBLE";
|
|
54
|
+
constructor(path: string);
|
|
55
|
+
}
|
|
56
|
+
declare class EventIdConflictError extends Error {
|
|
57
|
+
readonly eventId: string;
|
|
58
|
+
readonly code = "EVENT_ID_CONFLICT";
|
|
59
|
+
constructor(eventId: string);
|
|
60
|
+
}
|
|
61
|
+
declare class EventStoreCapacityError extends Error {
|
|
62
|
+
readonly sessionId: string;
|
|
63
|
+
readonly code = "EVENT_STORE_CAPACITY_EXCEEDED";
|
|
64
|
+
constructor(sessionId: string, message: string);
|
|
65
|
+
}
|
|
66
|
+
type SessionPurgeComponent = "event_store" | "event_delivery" | "tool_idempotency_ledger";
|
|
67
|
+
declare class SessionPurgeBusyError extends Error {
|
|
68
|
+
readonly sessionId: string;
|
|
69
|
+
readonly code: "SESSION_PURGE_BUSY";
|
|
70
|
+
constructor(sessionId: string);
|
|
71
|
+
}
|
|
72
|
+
declare class SessionPurgeUnsupportedError extends Error {
|
|
73
|
+
readonly sessionId: string;
|
|
74
|
+
readonly component: SessionPurgeComponent;
|
|
75
|
+
readonly code: "SESSION_PURGE_UNSUPPORTED";
|
|
76
|
+
constructor(sessionId: string, component?: SessionPurgeComponent);
|
|
77
|
+
}
|
|
78
|
+
declare class EventBufferOverflowError extends Error {
|
|
79
|
+
readonly lastSequence: number;
|
|
80
|
+
readonly latestSequence: number;
|
|
81
|
+
readonly code = "EVENT_BUFFER_OVERFLOW";
|
|
82
|
+
constructor(lastSequence: number, latestSequence: number);
|
|
83
|
+
}
|
|
84
|
+
type EventDeliveryPhase = "append" | "publish";
|
|
85
|
+
declare class EventDeliveryError extends Error {
|
|
86
|
+
readonly phase: EventDeliveryPhase;
|
|
87
|
+
readonly eventId: string;
|
|
88
|
+
readonly persisted: boolean;
|
|
89
|
+
readonly code: "EVENT_APPEND_FAILED" | "EVENT_PUBLISH_FAILED";
|
|
90
|
+
constructor(phase: EventDeliveryPhase, eventId: string, persisted: boolean, options?: ErrorOptions);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Internal physical-delete capability; intentionally absent from public barrels. */
|
|
94
|
+
declare const coordinatedSessionPurge: unique symbol;
|
|
95
|
+
/** Internal listener-detach capability; intentionally absent from public barrels. */
|
|
96
|
+
declare const authorizedListenerTeardown: unique symbol;
|
|
97
|
+
declare class SessionPurgeAuthorization {
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface AppendResult {
|
|
101
|
+
event: StoredKajiEvent;
|
|
102
|
+
inserted: boolean;
|
|
103
|
+
}
|
|
104
|
+
interface EventStore {
|
|
105
|
+
/** Optional retained-session bound used to align runtime projection caches. */
|
|
106
|
+
readonly maxSessions?: number;
|
|
107
|
+
append(event: NewKajiEvent): Promise<AppendResult>;
|
|
108
|
+
getEvents(sessionId: string, options?: {
|
|
109
|
+
afterSequence?: number;
|
|
110
|
+
limit?: number;
|
|
111
|
+
}): Promise<StoredKajiEvent[]>;
|
|
112
|
+
lastSequence(sessionId: string): Promise<number>;
|
|
113
|
+
}
|
|
114
|
+
interface PurgeableEventStore extends EventStore {
|
|
115
|
+
purgeSession(sessionId: string): Promise<boolean>;
|
|
116
|
+
}
|
|
117
|
+
declare function supportsSessionPurge(store: EventStore): store is PurgeableEventStore;
|
|
118
|
+
type SessionEventListener = (event: StoredKajiEvent) => boolean;
|
|
119
|
+
interface EventStoreSession {
|
|
120
|
+
appendLocked(event: NewKajiEvent): Promise<AppendResult>;
|
|
121
|
+
getEventsLocked(options?: {
|
|
122
|
+
afterSequence?: number;
|
|
123
|
+
limit?: number;
|
|
124
|
+
}): StoredKajiEvent[];
|
|
125
|
+
lastSequenceLocked(): number;
|
|
126
|
+
attachListenerLocked(listener: SessionEventListener): void;
|
|
127
|
+
detachListenerLocked(listener: SessionEventListener): void;
|
|
128
|
+
}
|
|
129
|
+
interface InMemoryEventStoreOptions {
|
|
130
|
+
maxSessions?: number;
|
|
131
|
+
maxEventsPerSession?: number;
|
|
132
|
+
}
|
|
133
|
+
declare class InMemoryEventStore implements PurgeableEventStore {
|
|
134
|
+
private readonly sessions;
|
|
135
|
+
private readonly eventsById;
|
|
136
|
+
private readonly idReservations;
|
|
137
|
+
private readonly listeners;
|
|
138
|
+
private readonly lanes;
|
|
139
|
+
readonly maxSessions: number;
|
|
140
|
+
private readonly maxEventsPerSession;
|
|
141
|
+
constructor(options?: InMemoryEventStoreOptions);
|
|
142
|
+
get sessionTransactionsEnabled(): boolean;
|
|
143
|
+
/** @internal Diagnostics for deterministic leak tests. */
|
|
144
|
+
get activeSessionLaneCount(): number;
|
|
145
|
+
/** @internal Diagnostics for deterministic leak tests. */
|
|
146
|
+
get activeIdReservationCount(): number;
|
|
147
|
+
/** @internal Diagnostics for deterministic leak tests. */
|
|
148
|
+
get activeListenerCount(): number;
|
|
149
|
+
sessionTransaction<T>(sessionId: string, operation: (transaction: EventStoreSession) => Promise<T>): Promise<T>;
|
|
150
|
+
append(input: NewKajiEvent): Promise<AppendResult>;
|
|
151
|
+
private claimId;
|
|
152
|
+
private finishReservation;
|
|
153
|
+
private appendTransaction;
|
|
154
|
+
protected insertReserved(event: NewKajiEvent): Promise<AppendResult>;
|
|
155
|
+
private fanoutSnapshot;
|
|
156
|
+
private attachListenerLocked;
|
|
157
|
+
private detachListenerLocked;
|
|
158
|
+
getEvents(sessionId: string, options?: {
|
|
159
|
+
afterSequence?: number;
|
|
160
|
+
limit?: number;
|
|
161
|
+
}): Promise<StoredKajiEvent[]>;
|
|
162
|
+
private getEventsLocked;
|
|
163
|
+
lastSequence(sessionId: string): Promise<number>;
|
|
164
|
+
purgeSession(sessionId: string): Promise<boolean>;
|
|
165
|
+
[coordinatedSessionPurge](sessionId: string, authorization: SessionPurgeAuthorization): Promise<boolean>;
|
|
166
|
+
[authorizedListenerTeardown](sessionId: string, listeners: readonly object[], authorization: SessionPurgeAuthorization): Promise<void>;
|
|
167
|
+
private lastSequenceLocked;
|
|
168
|
+
private admitSession;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
interface EventBusSubscribeOptions {
|
|
172
|
+
afterSequence?: number;
|
|
173
|
+
}
|
|
174
|
+
interface EventBusProtocol<TEvent extends {
|
|
175
|
+
readonly session_id: string;
|
|
176
|
+
} = KajiEvent> {
|
|
177
|
+
publish(event: TEvent): Promise<void | string>;
|
|
178
|
+
/**
|
|
179
|
+
* Return an iterator that cannot miss events published after `afterSequence`.
|
|
180
|
+
* Implementations must either attach synchronously before returning or retain
|
|
181
|
+
* cursor-addressable history that a lazy iterator reads when iteration starts.
|
|
182
|
+
*/
|
|
183
|
+
subscribe(sessionId: string, options?: EventBusSubscribeOptions): AsyncIterableIterator<TEvent>;
|
|
184
|
+
close(): void | Promise<void>;
|
|
185
|
+
}
|
|
186
|
+
interface EventCommitter {
|
|
187
|
+
readonly store: EventStore;
|
|
188
|
+
commit(event: NewKajiEvent): Promise<StoredKajiEvent>;
|
|
189
|
+
subscribe(sessionId: string, options?: {
|
|
190
|
+
afterSequence?: number;
|
|
191
|
+
}): AsyncIterableIterator<StoredKajiEvent>;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
declare class EventBus<TEvent extends {
|
|
195
|
+
readonly session_id: string;
|
|
196
|
+
} = KajiEvent> implements EventBusProtocol<TEvent> {
|
|
197
|
+
private readonly subscriberCapacity;
|
|
198
|
+
private readonly metrics;
|
|
199
|
+
private readonly subscribers;
|
|
200
|
+
constructor(subscriberCapacity?: number, metrics?: MetricsSink);
|
|
201
|
+
publish(event: TEvent): Promise<void>;
|
|
202
|
+
subscribe(sessionId: string, options?: EventBusSubscribeOptions): AsyncIterableIterator<TEvent>;
|
|
203
|
+
close(): void;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
interface InMemoryEventCommitterOptions {
|
|
207
|
+
subscriberCapacity?: number;
|
|
208
|
+
metricsSink?: MetricsSink;
|
|
209
|
+
}
|
|
210
|
+
interface SplitEventCommitterOptions {
|
|
211
|
+
subscriberCapacity?: number;
|
|
212
|
+
maxPendingEvents?: number;
|
|
213
|
+
metricsSink?: MetricsSink;
|
|
214
|
+
}
|
|
215
|
+
/** Stable single-process append + fanout boundary. */
|
|
216
|
+
declare class InMemoryEventCommitter implements EventCommitter {
|
|
217
|
+
readonly store: EventStore;
|
|
218
|
+
private readonly serial;
|
|
219
|
+
private readonly subscribers;
|
|
220
|
+
private readonly subscriberCapacity;
|
|
221
|
+
private readonly metrics;
|
|
222
|
+
private readonly transactionalStore;
|
|
223
|
+
private readonly subscriptions;
|
|
224
|
+
constructor(store?: EventStore, options?: InMemoryEventCommitterOptions);
|
|
225
|
+
commit(event: NewKajiEvent): Promise<StoredKajiEvent>;
|
|
226
|
+
private commitWith;
|
|
227
|
+
subscribe(sessionId: string, options?: {
|
|
228
|
+
afterSequence?: number;
|
|
229
|
+
}): AsyncIterableIterator<StoredKajiEvent>;
|
|
230
|
+
closeSessionSubscriptions(sessionId: string, authorization: SessionPurgeAuthorization): Promise<void>;
|
|
231
|
+
close(): Promise<void>;
|
|
232
|
+
}
|
|
233
|
+
/** Experimental adapter for stores and buses that cannot share one atomic boundary. */
|
|
234
|
+
declare class SplitEventCommitter implements EventCommitter {
|
|
235
|
+
readonly store: EventStore;
|
|
236
|
+
readonly bus: EventBusProtocol<KajiEvent | StoredKajiEvent>;
|
|
237
|
+
private readonly serial;
|
|
238
|
+
private readonly pending;
|
|
239
|
+
private readonly subscriberCapacity;
|
|
240
|
+
private readonly metrics;
|
|
241
|
+
private readonly transactionalStore;
|
|
242
|
+
private pendingReservations;
|
|
243
|
+
private subscriptionCreations;
|
|
244
|
+
private readonly subscriptions;
|
|
245
|
+
private readonly orphanSubscriptionTeardowns;
|
|
246
|
+
private closed;
|
|
247
|
+
private readonly unregisterPurgeBlocker;
|
|
248
|
+
readonly sessionPurgeComponent: "event_delivery";
|
|
249
|
+
readonly maxPendingEvents: number;
|
|
250
|
+
constructor(store: EventStore, bus: EventBusProtocol<KajiEvent | StoredKajiEvent>, options?: SplitEventCommitterOptions);
|
|
251
|
+
close(): void;
|
|
252
|
+
private retainOrphanSubscription;
|
|
253
|
+
private startOrphanSubscriptionTeardown;
|
|
254
|
+
commit(input: NewKajiEvent): Promise<StoredKajiEvent>;
|
|
255
|
+
private reservePendingSlot;
|
|
256
|
+
private releasePendingSlot;
|
|
257
|
+
private promotePendingSlot;
|
|
258
|
+
private commitUnlocked;
|
|
259
|
+
retryPublish(eventId: string): Promise<StoredKajiEvent>;
|
|
260
|
+
private publishPendingUnlocked;
|
|
261
|
+
private hasPendingForSession;
|
|
262
|
+
retry(eventId: string): Promise<StoredKajiEvent>;
|
|
263
|
+
subscribe(sessionId: string, options?: {
|
|
264
|
+
afterSequence?: number;
|
|
265
|
+
}): AsyncIterableIterator<StoredKajiEvent>;
|
|
266
|
+
pendingEventIds(): string[];
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
interface ContextIndexStats {
|
|
270
|
+
readonly fullColdBuilds: number;
|
|
271
|
+
readonly coldEvents: number;
|
|
272
|
+
readonly incrementalEvents: number;
|
|
273
|
+
readonly suffixCalls: number;
|
|
274
|
+
readonly maxVisitedTurnEntries: number;
|
|
275
|
+
readonly copiedOutputMessages: number;
|
|
276
|
+
readonly persistentCopiedPayloadBytes: number;
|
|
277
|
+
readonly retainedTurns: number;
|
|
278
|
+
readonly turnEntries: number;
|
|
279
|
+
readonly sentinelEntries: number;
|
|
280
|
+
readonly totalEntries: number;
|
|
281
|
+
readonly latestUserAccesses: number;
|
|
282
|
+
readonly scannedToolCalls: number;
|
|
283
|
+
readonly scannedToolArgumentBytes: number;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Incremental projection that owns one session-local sequence cursor. */
|
|
287
|
+
declare class SessionProjector {
|
|
288
|
+
readonly sessionId: string;
|
|
289
|
+
private readonly metrics;
|
|
290
|
+
private readonly projectionState;
|
|
291
|
+
private readonly contextIndex;
|
|
292
|
+
lastSequence: number;
|
|
293
|
+
appliedEvents: number;
|
|
294
|
+
initialized: boolean;
|
|
295
|
+
constructor(sessionId: string, metrics?: MetricsSink, contextWindow?: Readonly<ContextWindow>);
|
|
296
|
+
/** Return a deep snapshot; projection state remains privately owned. */
|
|
297
|
+
get state(): SessionState;
|
|
298
|
+
apply(event: StoredKajiEvent): void;
|
|
299
|
+
private applyValidated;
|
|
300
|
+
sync(store: EventStore, onApplied?: (event: StoredKajiEvent) => void): Promise<number>;
|
|
301
|
+
get contextIndexStats(): Readonly<ContextIndexStats>;
|
|
302
|
+
buildProjectedContext(systemPrompt?: string, window?: ContextWindow): ContextBuildResult;
|
|
303
|
+
latestUserContent(): string | undefined;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
interface SessionRecord {
|
|
307
|
+
sessionId: string;
|
|
308
|
+
userId: string;
|
|
309
|
+
createdAt: number;
|
|
310
|
+
title: string;
|
|
311
|
+
}
|
|
312
|
+
interface SessionStore {
|
|
313
|
+
recordSession(record: SessionRecord): Promise<void>;
|
|
314
|
+
listSessions(userId: string): Promise<SessionRecord[]>;
|
|
315
|
+
}
|
|
316
|
+
declare class InMemorySessionStore implements SessionStore {
|
|
317
|
+
private readonly records;
|
|
318
|
+
recordSession(record: SessionRecord): Promise<void>;
|
|
319
|
+
listSessions(userId: string): Promise<SessionRecord[]>;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
declare class SessionManager {
|
|
323
|
+
private readonly _store;
|
|
324
|
+
private readonly _sessionStore?;
|
|
325
|
+
constructor(store: EventStore, sessionStore?: SessionStore);
|
|
326
|
+
getState(sessionId: string): Promise<SessionState>;
|
|
327
|
+
recordSession(sessionId: string, userId: string, title?: string): Promise<void>;
|
|
328
|
+
listActive(userId: string): Promise<Array<{
|
|
329
|
+
sessionId: string;
|
|
330
|
+
userId: string;
|
|
331
|
+
createdAt: number;
|
|
332
|
+
title: string;
|
|
333
|
+
}>>;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Tool policy enforcement, mirroring `kaji.runtime.tools.policies`.
|
|
338
|
+
* Controls which tools may run and which require explicit approval before
|
|
339
|
+
* execution, keyed on tool name and risk classification.
|
|
340
|
+
*/
|
|
341
|
+
|
|
342
|
+
/** Thrown by `ToolPolicy.enforce` when a tool call is not permitted. */
|
|
343
|
+
declare class ToolPolicyViolation extends Error {
|
|
344
|
+
constructor(toolName: string);
|
|
345
|
+
}
|
|
346
|
+
interface ToolPolicyOptions {
|
|
347
|
+
/** Explicit allowlist. When undefined, all tools not in `denied` are allowed. */
|
|
348
|
+
allowed?: ReadonlySet<string>;
|
|
349
|
+
/** Tools that are always blocked, even if in `allowed`. */
|
|
350
|
+
denied?: ReadonlySet<string>;
|
|
351
|
+
/** Risk levels that require explicit approval before the tool runs. */
|
|
352
|
+
requireApprovalFor?: ReadonlySet<ToolRisk>;
|
|
353
|
+
}
|
|
354
|
+
declare class ToolPolicy {
|
|
355
|
+
private readonly allowed;
|
|
356
|
+
private readonly denied;
|
|
357
|
+
readonly requireApprovalFor: ReadonlySet<ToolRisk>;
|
|
358
|
+
constructor(opts?: ToolPolicyOptions);
|
|
359
|
+
/** Returns true when the tool is not denied and (if an allowlist exists) is in it. */
|
|
360
|
+
isAllowed(toolName: string): boolean;
|
|
361
|
+
isAllowedAny(toolNames: Iterable<string>): boolean;
|
|
362
|
+
/** Throws `ToolPolicyViolation` if the tool is not allowed. */
|
|
363
|
+
enforce(toolName: string): void;
|
|
364
|
+
enforceAny(toolName: string, aliases?: Iterable<string>): void;
|
|
365
|
+
/**
|
|
366
|
+
* Returns true when the tool's effective risk level is at or above the
|
|
367
|
+
* minimum rank in `requireApprovalFor`. So `requireApprovalFor: {"destructive"}`
|
|
368
|
+
* also catches `"admin"`. Enabled tools must carry a known risk; missing
|
|
369
|
+
* and unknown classifications fail instead of defaulting to `read`.
|
|
370
|
+
*/
|
|
371
|
+
requiresApproval(_toolName: string, risk: ToolRisk | undefined): boolean;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Typed approval decisions and the canonical runtime request context. */
|
|
375
|
+
|
|
376
|
+
type ApprovalRejectionCode = "rejected" | "timeout" | "turn_timeout" | "cancelled" | "unavailable";
|
|
377
|
+
type ApprovalDeadlineSource = "approval" | "turn";
|
|
378
|
+
type ApprovalDecision = Readonly<{
|
|
379
|
+
granted: true;
|
|
380
|
+
code: "approved";
|
|
381
|
+
recorded?: boolean;
|
|
382
|
+
}> | Readonly<{
|
|
383
|
+
granted: false;
|
|
384
|
+
code: ApprovalRejectionCode;
|
|
385
|
+
reason: string;
|
|
386
|
+
recorded?: boolean;
|
|
387
|
+
}>;
|
|
388
|
+
/**
|
|
389
|
+
* Runtime-owned approval boundary. `committer` is used only to subscribe;
|
|
390
|
+
* `emit` is the canonical runtime write path so projection and turn collection
|
|
391
|
+
* stay coherent.
|
|
392
|
+
*/
|
|
393
|
+
interface ApprovalRequestContext {
|
|
394
|
+
readonly execution: ToolExecutionContext;
|
|
395
|
+
readonly toolName: string;
|
|
396
|
+
readonly risk: ToolRisk;
|
|
397
|
+
readonly arguments: Readonly<Record<string, unknown>>;
|
|
398
|
+
readonly committer: EventCommitter;
|
|
399
|
+
readonly emit: (event: KajiEvent) => Promise<StoredKajiEvent>;
|
|
400
|
+
readonly deadlineMonotonicMs: number;
|
|
401
|
+
readonly deadlineSource: ApprovalDeadlineSource;
|
|
402
|
+
/** Runtime clock paired with `deadlineMonotonicMs`; custom contexts may omit it. */
|
|
403
|
+
readonly nowMonotonic?: () => number;
|
|
404
|
+
readonly timerScheduler: TimerScheduler;
|
|
405
|
+
}
|
|
406
|
+
interface TypedApprovalHandler {
|
|
407
|
+
request(call: ToolCall, context: ApprovalRequestContext): Promise<ApprovalDecision>;
|
|
408
|
+
}
|
|
409
|
+
/** Dedicated marker for the one handler that owns approval-request emission. */
|
|
410
|
+
interface EventBackedApprovalHandler extends TypedApprovalHandler {
|
|
411
|
+
readonly approvalRequestOwner: "handler";
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** Closed, redaction-safe recovery metadata shared by errors and renderers. */
|
|
415
|
+
type IntegrationRecoveryReason = "github_token_missing" | "gmail_grant_missing" | "keychain_missing" | "keychain_locked" | "keychain_corrupt" | "keychain_unsupported" | "gmail_scope_drift" | "policy_rejected" | "api_rejected" | "transient_read_failed" | "rate_limited" | "redirect_rejected" | "response_limit_exceeded" | "github_mutation_unknown" | "gmail_mutation_unknown";
|
|
416
|
+
interface IntegrationRecoveryFields {
|
|
417
|
+
readonly reason_code: IntegrationRecoveryReason;
|
|
418
|
+
readonly recovery_code: string;
|
|
419
|
+
readonly doc_url: string;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
type ToolFailureOutcome = "not_started" | "failed" | "unknown";
|
|
423
|
+
interface ToolFailureFields {
|
|
424
|
+
readonly error_code: string;
|
|
425
|
+
readonly retryable: boolean;
|
|
426
|
+
readonly outcome: ToolFailureOutcome;
|
|
427
|
+
readonly reason_code?: IntegrationRecoveryReason;
|
|
428
|
+
readonly recovery_code?: string;
|
|
429
|
+
readonly doc_url?: string;
|
|
430
|
+
}
|
|
431
|
+
/** Stable public tool failure without retaining the originating exception. */
|
|
432
|
+
declare class ToolExecutionError extends Error implements ToolFailureFields {
|
|
433
|
+
readonly error_code: string;
|
|
434
|
+
readonly retryable: boolean;
|
|
435
|
+
readonly outcome: ToolFailureOutcome;
|
|
436
|
+
static [Symbol.hasInstance](value: unknown): boolean;
|
|
437
|
+
constructor(message: string, error_code: string, retryable: boolean, outcome: ToolFailureOutcome, recovery?: IntegrationRecoveryFields);
|
|
438
|
+
readonly reason_code?: IntegrationRecoveryReason;
|
|
439
|
+
readonly recovery_code?: string;
|
|
440
|
+
readonly doc_url?: string;
|
|
441
|
+
}
|
|
442
|
+
declare class IdempotencyCapacityError extends ToolExecutionError {
|
|
443
|
+
constructor();
|
|
444
|
+
}
|
|
445
|
+
declare class IdempotencyConflictError extends ToolExecutionError {
|
|
446
|
+
constructor();
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
type ToolLedgerOutcome = {
|
|
450
|
+
readonly status: "completed";
|
|
451
|
+
readonly result: unknown;
|
|
452
|
+
} | {
|
|
453
|
+
readonly status: "failed";
|
|
454
|
+
readonly error: ToolExecutionError;
|
|
455
|
+
};
|
|
456
|
+
interface ToolIdempotencyClaim {
|
|
457
|
+
readonly sessionId: string;
|
|
458
|
+
readonly toolCallId: string;
|
|
459
|
+
readonly fingerprint: string;
|
|
460
|
+
}
|
|
461
|
+
type ToolClaimResult = {
|
|
462
|
+
readonly status: "owner";
|
|
463
|
+
readonly claim: ToolIdempotencyClaim;
|
|
464
|
+
} | {
|
|
465
|
+
readonly status: "running";
|
|
466
|
+
readonly outcome: Promise<ToolLedgerOutcome>;
|
|
467
|
+
} | {
|
|
468
|
+
readonly status: "completed";
|
|
469
|
+
readonly result: unknown;
|
|
470
|
+
} | {
|
|
471
|
+
readonly status: "unknown";
|
|
472
|
+
readonly error: ToolExecutionError;
|
|
473
|
+
};
|
|
474
|
+
/** Replaceable persistence boundary for exact tool-call idempotency. */
|
|
475
|
+
interface ToolIdempotencyLedger {
|
|
476
|
+
claim(sessionId: string, toolCallId: string, fingerprint: string): Promise<ToolClaimResult>;
|
|
477
|
+
complete(claim: ToolIdempotencyClaim, result: unknown): Promise<void>;
|
|
478
|
+
retryableFailure(claim: ToolIdempotencyClaim, error: ToolExecutionError): Promise<void>;
|
|
479
|
+
unknownOutcome(claim: ToolIdempotencyClaim, error: ToolExecutionError): Promise<void>;
|
|
480
|
+
releaseCompleted(sessionId: string): Promise<number>;
|
|
481
|
+
/** Remove completed and unknown entries, but never an in-flight claim. */
|
|
482
|
+
releaseSettled?(sessionId: string): Promise<number>;
|
|
483
|
+
}
|
|
484
|
+
interface InMemoryToolIdempotencyLedgerOptions {
|
|
485
|
+
capacity?: number;
|
|
486
|
+
completedTtlMs?: number;
|
|
487
|
+
now?: () => number;
|
|
488
|
+
}
|
|
489
|
+
/** Process-local bounded ledger. Running and unknown entries are never evicted. */
|
|
490
|
+
declare class InMemoryToolIdempotencyLedger implements ToolIdempotencyLedger {
|
|
491
|
+
private readonly entries;
|
|
492
|
+
private readonly capacity;
|
|
493
|
+
private readonly completedTtlMs;
|
|
494
|
+
private readonly now;
|
|
495
|
+
constructor(options?: InMemoryToolIdempotencyLedgerOptions);
|
|
496
|
+
claim(sessionId: string, toolCallId: string, fingerprint: string): Promise<ToolClaimResult>;
|
|
497
|
+
complete(claim: ToolIdempotencyClaim, result: unknown): Promise<void>;
|
|
498
|
+
retryableFailure(claim: ToolIdempotencyClaim, error: ToolExecutionError): Promise<void>;
|
|
499
|
+
unknownOutcome(claim: ToolIdempotencyClaim, error: ToolExecutionError): Promise<void>;
|
|
500
|
+
releaseCompleted(sessionId: string): Promise<number>;
|
|
501
|
+
releaseSettled(sessionId: string): Promise<number>;
|
|
502
|
+
private runningEntry;
|
|
503
|
+
private evictCompletedForCapacity;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
interface ToolExecutionLimits {
|
|
507
|
+
readonly maxParallel: number;
|
|
508
|
+
readonly timeoutMs: number | null;
|
|
509
|
+
readonly approvalTimeoutMs: number;
|
|
510
|
+
}
|
|
511
|
+
declare const DEFAULT_TOOL_EXECUTION_LIMITS: Readonly<ToolExecutionLimits>;
|
|
512
|
+
type ToolExecutionControllerOutcome = {
|
|
513
|
+
readonly status: "completed";
|
|
514
|
+
readonly result: unknown;
|
|
515
|
+
} | {
|
|
516
|
+
readonly status: "failed";
|
|
517
|
+
readonly error: ToolExecutionError;
|
|
518
|
+
/** True only for a deadline observed by this invocation, never a ledger replay. */
|
|
519
|
+
readonly turnTimeout?: true;
|
|
520
|
+
};
|
|
521
|
+
interface ToolExecutionRequest {
|
|
522
|
+
readonly name: string;
|
|
523
|
+
readonly args: Readonly<Record<string, unknown>>;
|
|
524
|
+
readonly context: ToolExecutionContext;
|
|
525
|
+
readonly timeoutMs?: number;
|
|
526
|
+
readonly exclusive: boolean;
|
|
527
|
+
/**
|
|
528
|
+
* Persist the start acknowledgement and settle when the append is no longer active.
|
|
529
|
+
* Implementations must observe `signal`; otherwise the claim and permit remain owned,
|
|
530
|
+
* `drain()` reports the call, and the process must be restarted if it never settles.
|
|
531
|
+
*/
|
|
532
|
+
readonly onStarted: (signal: AbortSignal) => Promise<void>;
|
|
533
|
+
readonly execute: (context: ToolExecutionContext) => Promise<unknown>;
|
|
534
|
+
}
|
|
535
|
+
interface ToolExecutionControllerOptions {
|
|
536
|
+
limits?: Partial<ToolExecutionLimits>;
|
|
537
|
+
ledger?: ToolIdempotencyLedger;
|
|
538
|
+
now?: () => number;
|
|
539
|
+
monotonicNow?: () => number;
|
|
540
|
+
timerScheduler?: TimerScheduler;
|
|
541
|
+
metricsSink?: MetricsSink;
|
|
542
|
+
traceSink?: TraceSink;
|
|
543
|
+
}
|
|
544
|
+
/** Runtime-lifetime bounded tool execution and idempotency controller. */
|
|
545
|
+
declare class ToolExecutionController {
|
|
546
|
+
readonly limits: Readonly<ToolExecutionLimits>;
|
|
547
|
+
readonly ledger: ToolIdempotencyLedger;
|
|
548
|
+
private readonly permits;
|
|
549
|
+
private readonly monotonicNow;
|
|
550
|
+
private readonly timerScheduler;
|
|
551
|
+
private readonly metrics;
|
|
552
|
+
private readonly trace;
|
|
553
|
+
private readonly active;
|
|
554
|
+
private readonly pendingStarts;
|
|
555
|
+
private readonly claimCleanups;
|
|
556
|
+
private readonly pendingApprovals;
|
|
557
|
+
constructor(options?: ToolExecutionControllerOptions);
|
|
558
|
+
execute(request: ToolExecutionRequest): Promise<ToolExecutionControllerOutcome>;
|
|
559
|
+
private executeBounded;
|
|
560
|
+
/** Wait for real start/handler settlement; report calls still owned at the deadline. */
|
|
561
|
+
drain(timeoutMs: number): Promise<readonly string[]>;
|
|
562
|
+
/** @internal Whether start recording or handler code still owns this session. */
|
|
563
|
+
hasActiveSession(sessionId: string): boolean;
|
|
564
|
+
/** @internal Retain approval ownership after a timeout/cancellation race. */
|
|
565
|
+
trackApproval<T>(sessionId: string, callId: string, operation: Promise<T>): Promise<T>;
|
|
566
|
+
private trackPendingStart;
|
|
567
|
+
private finishPendingStart;
|
|
568
|
+
private abortOutcome;
|
|
569
|
+
private waitForRunningOutcome;
|
|
570
|
+
private scheduleLateClaimCleanup;
|
|
571
|
+
private linkedSignal;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** Bounded, ordered planning and execution of provider tool calls. */
|
|
575
|
+
|
|
576
|
+
/** A single tool call instruction from the LLM. */
|
|
577
|
+
interface ToolCallInstruction {
|
|
578
|
+
id?: string;
|
|
579
|
+
name: string;
|
|
580
|
+
arguments: Record<string, unknown>;
|
|
581
|
+
}
|
|
582
|
+
/** Result of a single tool call execution. */
|
|
583
|
+
type ToolCallResult = {
|
|
584
|
+
id: string;
|
|
585
|
+
name: string;
|
|
586
|
+
result: unknown;
|
|
587
|
+
} | {
|
|
588
|
+
id: string;
|
|
589
|
+
name: string;
|
|
590
|
+
error: string;
|
|
591
|
+
error_code?: string;
|
|
592
|
+
error_path?: string;
|
|
593
|
+
retryable?: boolean;
|
|
594
|
+
outcome?: "not_started" | "failed" | "unknown";
|
|
595
|
+
reason_code?: IntegrationRecoveryReason;
|
|
596
|
+
recovery_code?: string;
|
|
597
|
+
doc_url?: string;
|
|
598
|
+
};
|
|
599
|
+
type ToolExecutor = (name: string, args: Readonly<Record<string, unknown>>, context: ToolExecutionContext) => Promise<unknown>;
|
|
600
|
+
/** Start acknowledgements receive `signal`; custom emitters must settle when it aborts. */
|
|
601
|
+
type EmitFn = (event: KajiEvent, signal?: AbortSignal) => Promise<StoredKajiEvent | void>;
|
|
602
|
+
interface ToolPlannerOptions {
|
|
603
|
+
executor: ToolExecutor;
|
|
604
|
+
policy?: ToolPolicy;
|
|
605
|
+
approvalHandler?: TypedApprovalHandler;
|
|
606
|
+
specs?: ReadonlyMap<string, ToolSpec>;
|
|
607
|
+
idFactory?: IdFactory;
|
|
608
|
+
clock?: Clock;
|
|
609
|
+
executionController?: ToolExecutionController;
|
|
610
|
+
executionLimits?: Partial<ToolExecutionLimits>;
|
|
611
|
+
idempotencyLedger?: ToolIdempotencyLedger;
|
|
612
|
+
/** Canonical runtime committer used by event-backed approval waiters. */
|
|
613
|
+
approvalCommitter?: EventCommitter;
|
|
614
|
+
/** Monotonic clock source used to derive the absolute approval deadline. */
|
|
615
|
+
now?: () => number;
|
|
616
|
+
metricsSink?: MetricsSink;
|
|
617
|
+
traceSink?: TraceSink;
|
|
618
|
+
timerScheduler?: TimerScheduler;
|
|
619
|
+
}
|
|
620
|
+
declare class ToolPlanner {
|
|
621
|
+
private readonly executor;
|
|
622
|
+
private readonly policy;
|
|
623
|
+
private readonly approvalHandler;
|
|
624
|
+
readonly approvalCommitter: EventCommitter | undefined;
|
|
625
|
+
private readonly specs;
|
|
626
|
+
private readonly schemaValidator;
|
|
627
|
+
private readonly idFactory;
|
|
628
|
+
private readonly clock;
|
|
629
|
+
private readonly now;
|
|
630
|
+
private readonly timerScheduler;
|
|
631
|
+
readonly executionController: ToolExecutionController;
|
|
632
|
+
/** Canonical emitter for standalone planner usage. */
|
|
633
|
+
static committerEmitter(committer: EventCommitter): EmitFn;
|
|
634
|
+
constructor(opts: ToolPlannerOptions);
|
|
635
|
+
/**
|
|
636
|
+
* Execute one provider batch with bounded parallelism and provider-order
|
|
637
|
+
* request/result/terminal semantics. Explicitly parallel-safe runs overlap;
|
|
638
|
+
* every unmarked tool is an exclusive barrier.
|
|
639
|
+
*/
|
|
640
|
+
executeBatch(sessionId: string, toolCalls: ToolCallInstruction[], emit: EmitFn, turnId?: string, turnContext?: {
|
|
641
|
+
readonly principalId?: string;
|
|
642
|
+
readonly requestId?: string;
|
|
643
|
+
readonly traceId?: string;
|
|
644
|
+
readonly deadlineMonotonicMs?: number;
|
|
645
|
+
readonly db?: unknown;
|
|
646
|
+
readonly metadata?: Readonly<Record<string, unknown>>;
|
|
647
|
+
}, signal?: AbortSignal): Promise<ToolCallResult[]>;
|
|
648
|
+
private executeParallelGroup;
|
|
649
|
+
private normalizeCalls;
|
|
650
|
+
private requestedEvent;
|
|
651
|
+
private preflight;
|
|
652
|
+
private authoritativeApprovalDecision;
|
|
653
|
+
private raceApprovalDecision;
|
|
654
|
+
private executePrepared;
|
|
655
|
+
private terminalEvent;
|
|
656
|
+
private event;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
interface CliApprovalInput {
|
|
660
|
+
readonly readableEnded?: boolean;
|
|
661
|
+
readonly destroyed?: boolean;
|
|
662
|
+
on(event: string | symbol, listener: (...args: unknown[]) => void): this;
|
|
663
|
+
once(event: string | symbol, listener: (...args: unknown[]) => void): this;
|
|
664
|
+
removeListener(event: string | symbol, listener: (...args: unknown[]) => void): this;
|
|
665
|
+
pause(): this;
|
|
666
|
+
resume(): this;
|
|
667
|
+
}
|
|
668
|
+
interface CliApprovalOutput {
|
|
669
|
+
write(chunk: string): boolean;
|
|
670
|
+
}
|
|
671
|
+
interface CliApprovalOptions {
|
|
672
|
+
/** Defaults to process.stdin. Override in tests with a readable input. */
|
|
673
|
+
input?: CliApprovalInput;
|
|
674
|
+
/** Defaults to process.stdout. Override in tests with a writable output. */
|
|
675
|
+
output?: CliApprovalOutput;
|
|
676
|
+
/**
|
|
677
|
+
* Optional label printed in the prompt header to disambiguate concurrent
|
|
678
|
+
* agents (e.g. `"agent-a"`, `"session-c1"`). Defaults to empty.
|
|
679
|
+
*/
|
|
680
|
+
label?: string;
|
|
681
|
+
}
|
|
682
|
+
declare function cliApprovalHandler(opts?: CliApprovalOptions): TypedApprovalHandler;
|
|
683
|
+
|
|
684
|
+
interface OpenAIProviderOptions {
|
|
685
|
+
apiKey: string;
|
|
686
|
+
model?: string;
|
|
687
|
+
baseURL?: string;
|
|
688
|
+
temperature?: number;
|
|
689
|
+
maxTokens?: number;
|
|
690
|
+
/** Per-request timeout in milliseconds. Must be a positive finite integer. */
|
|
691
|
+
requestTimeoutMs?: number;
|
|
692
|
+
/** Extra HTTP headers to send with every request. Used by OpenAI-compatible
|
|
693
|
+
* gateways (OpenRouter, Together, Groq) to attach attribution or routing
|
|
694
|
+
* metadata. Ignored when the value is empty. */
|
|
695
|
+
defaultHeaders?: Record<string, string>;
|
|
696
|
+
/** Rate-limit retry configuration. */
|
|
697
|
+
retry?: RetryOptions;
|
|
698
|
+
}
|
|
699
|
+
declare class OpenAIProvider implements ModelProvider {
|
|
700
|
+
readonly providerFamily: "openai";
|
|
701
|
+
private readonly opts;
|
|
702
|
+
private client;
|
|
703
|
+
constructor(opts: OpenAIProviderOptions);
|
|
704
|
+
/** Expose the model name for downstream cost calculation. */
|
|
705
|
+
get model(): string;
|
|
706
|
+
protected createClient(): Promise<object>;
|
|
707
|
+
private getClient;
|
|
708
|
+
generate(messages: ProviderMessage[], tools: ToolSpec[], options?: ModelProviderOptions): Promise<ModelResponse>;
|
|
709
|
+
generateStream(messages: ProviderMessage[], tools: ToolSpec[], options?: ModelProviderOptions): AsyncGenerator<ModelResponseChunk>;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
interface AnthropicProviderOptions {
|
|
713
|
+
apiKey: string;
|
|
714
|
+
model?: string;
|
|
715
|
+
temperature?: number;
|
|
716
|
+
maxTokens?: number;
|
|
717
|
+
/** Per-request timeout in milliseconds. Must be a positive finite integer. */
|
|
718
|
+
requestTimeoutMs?: number;
|
|
719
|
+
/** Rate-limit retry configuration. */
|
|
720
|
+
retry?: RetryOptions;
|
|
721
|
+
}
|
|
722
|
+
declare class AnthropicProvider implements ModelProvider {
|
|
723
|
+
readonly providerFamily: "anthropic";
|
|
724
|
+
private readonly opts;
|
|
725
|
+
private client;
|
|
726
|
+
constructor(opts: AnthropicProviderOptions);
|
|
727
|
+
get model(): string;
|
|
728
|
+
protected createClient(): Promise<object>;
|
|
729
|
+
private getClient;
|
|
730
|
+
generate(messages: ProviderMessage[], tools: ToolSpec[], options?: ModelProviderOptions): Promise<ModelResponse>;
|
|
731
|
+
generateStream(messages: ProviderMessage[], tools: ToolSpec[], options?: ModelProviderOptions): AsyncGenerator<ModelResponseChunk>;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
interface ProviderErrorOptions {
|
|
735
|
+
service?: string;
|
|
736
|
+
action?: string;
|
|
737
|
+
statusCode?: number;
|
|
738
|
+
}
|
|
739
|
+
declare class ProviderError extends Error {
|
|
740
|
+
readonly service: string;
|
|
741
|
+
readonly action: string;
|
|
742
|
+
readonly statusCode?: number;
|
|
743
|
+
static [Symbol.hasInstance](value: unknown): boolean;
|
|
744
|
+
constructor(message: string, options?: ProviderErrorOptions);
|
|
745
|
+
}
|
|
746
|
+
declare class ProviderConfigError extends ProviderError {
|
|
747
|
+
static [Symbol.hasInstance](value: unknown): boolean;
|
|
748
|
+
constructor(message: string, options?: Omit<ProviderErrorOptions, "action">);
|
|
749
|
+
}
|
|
750
|
+
declare class ProviderAPIError extends ProviderError {
|
|
751
|
+
static [Symbol.hasInstance](value: unknown): boolean;
|
|
752
|
+
constructor(message: string, options?: ProviderErrorOptions);
|
|
753
|
+
}
|
|
754
|
+
declare class ProviderConnectionError extends ProviderError {
|
|
755
|
+
static [Symbol.hasInstance](value: unknown): boolean;
|
|
756
|
+
constructor(message: string, options?: ProviderErrorOptions);
|
|
757
|
+
}
|
|
758
|
+
declare class ProviderRateLimitedError extends ProviderError {
|
|
759
|
+
readonly retryAfterMs: number;
|
|
760
|
+
readonly attempts: number;
|
|
761
|
+
static [Symbol.hasInstance](value: unknown): boolean;
|
|
762
|
+
constructor(message: string, options: Omit<ProviderErrorOptions, "action"> & {
|
|
763
|
+
retryAfterMs: number;
|
|
764
|
+
attempts: number;
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
type ProviderOutputDimension = "text" | "tool_arguments" | "total_response" | "tool_calls";
|
|
768
|
+
declare class ProviderOutputLimitError extends Error {
|
|
769
|
+
readonly dimension: ProviderOutputDimension;
|
|
770
|
+
readonly limit: number;
|
|
771
|
+
readonly code: "PROVIDER_OUTPUT_LIMIT";
|
|
772
|
+
readonly phase: "provider_stream";
|
|
773
|
+
readonly retryable: false;
|
|
774
|
+
readonly outcome: "unknown";
|
|
775
|
+
static [Symbol.hasInstance](value: unknown): boolean;
|
|
776
|
+
constructor(dimension: ProviderOutputDimension, limit: number);
|
|
777
|
+
}
|
|
778
|
+
interface NormalizedProviderError {
|
|
779
|
+
type: "api" | "auth" | "config" | "network" | "rate_limit";
|
|
780
|
+
code: "PROVIDER_API_ERROR" | "PROVIDER_AUTH_ERROR" | "PROVIDER_CONFIG_ERROR" | "PROVIDER_NETWORK_ERROR" | "PROVIDER_RATE_LIMITED";
|
|
781
|
+
service: string;
|
|
782
|
+
action: string;
|
|
783
|
+
status: number | null;
|
|
784
|
+
retryable: boolean;
|
|
785
|
+
}
|
|
786
|
+
declare function normalizeProviderError(error: ProviderError): NormalizedProviderError;
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* Per-model $/1M token cost table. Updated quarterly.
|
|
790
|
+
* All rates are USD per 1,000,000 tokens.
|
|
791
|
+
*/
|
|
792
|
+
interface ModelCostEntry {
|
|
793
|
+
/** Cost in USD per 1M input tokens. */
|
|
794
|
+
inputPer1M: number;
|
|
795
|
+
/** Cost in USD per 1M output tokens. */
|
|
796
|
+
outputPer1M: number;
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Look up cost for an exact supported model or a provider snapshot suffix.
|
|
800
|
+
* Returns `undefined` rather than guessing for unknown or routed models.
|
|
801
|
+
*/
|
|
802
|
+
declare function lookupCost(model: string): ModelCostEntry | undefined;
|
|
803
|
+
/**
|
|
804
|
+
* Calculate cost in USD for a given token count and model.
|
|
805
|
+
* Returns 0 if the model is not in the cost table.
|
|
806
|
+
*/
|
|
807
|
+
declare function calculateCostUsd(model: string, inputTokens: number, outputTokens: number): number;
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* Provider registry: a process-level map from name to `ModelProvider`.
|
|
811
|
+
* Mirrors `kaji.runtime.providers.registry`.
|
|
812
|
+
*/
|
|
813
|
+
|
|
814
|
+
/** Register a provider under a name. Throws on duplicate. */
|
|
815
|
+
declare function registerProvider(name: string, provider: ModelProvider): void;
|
|
816
|
+
/** Retrieve a registered provider. Throws if not found. */
|
|
817
|
+
declare function getProvider(name: string): ModelProvider;
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* Function-style provider factories.
|
|
821
|
+
*
|
|
822
|
+
* Convenience wrappers so callers can write `openai("gpt-5.4-mini")` instead of
|
|
823
|
+
* `new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY!, model: "gpt-5.4-mini" })`.
|
|
824
|
+
* Reads the conventional environment variable when no apiKey is given.
|
|
825
|
+
*
|
|
826
|
+
* import { openai, anthropic, generateText } from "@irogane/kaji";
|
|
827
|
+
* const { text } = await generateText({
|
|
828
|
+
* provider: openai("gpt-5.4-mini"),
|
|
829
|
+
* messages: [{ role: "user", content: "Hello" }],
|
|
830
|
+
* });
|
|
831
|
+
*/
|
|
832
|
+
|
|
833
|
+
type ModelOrOptions<TOpts> = string | (Omit<TOpts, "apiKey"> & {
|
|
834
|
+
apiKey?: string;
|
|
835
|
+
});
|
|
836
|
+
/** Create an OpenAI provider. Reads `OPENAI_API_KEY` from the environment when no `apiKey` is passed. */
|
|
837
|
+
declare function openai(arg?: ModelOrOptions<OpenAIProviderOptions>): OpenAIProvider;
|
|
838
|
+
/** Create an Anthropic provider. Reads `ANTHROPIC_API_KEY` from the environment when no `apiKey` is passed. */
|
|
839
|
+
declare function anthropic(arg?: ModelOrOptions<AnthropicProviderOptions>): AnthropicProvider;
|
|
840
|
+
/** Optional OpenRouter-specific options for routing and attribution. */
|
|
841
|
+
interface OpenRouterFactoryOptions extends Omit<OpenAIProviderOptions, "apiKey" | "baseURL"> {
|
|
842
|
+
apiKey?: string;
|
|
843
|
+
/** Sent as `HTTP-Referer`. OpenRouter shows the app on its leaderboard. */
|
|
844
|
+
httpReferer?: string;
|
|
845
|
+
/** Sent as `X-OpenRouter-Title`. Human-readable app name on the OpenRouter dashboard. */
|
|
846
|
+
appTitle?: string;
|
|
847
|
+
}
|
|
848
|
+
declare function openrouter(arg?: string | OpenRouterFactoryOptions): OpenAIProvider;
|
|
849
|
+
declare function kimi(arg?: string | OpenRouterFactoryOptions): OpenAIProvider;
|
|
850
|
+
/** Optional Gemini factory options. Mirrors the OpenAI/anthropic shape. */
|
|
851
|
+
interface GeminiFactoryOptions extends Omit<OpenAIProviderOptions, "apiKey" | "baseURL"> {
|
|
852
|
+
apiKey?: string;
|
|
853
|
+
}
|
|
854
|
+
declare function gemini(arg?: string | GeminiFactoryOptions): OpenAIProvider;
|
|
855
|
+
|
|
856
|
+
/** Interface for reading secrets at runtime. v1 default: env-only. */
|
|
857
|
+
interface SecretSource {
|
|
858
|
+
get(key: string): Promise<string | undefined>;
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Reads secrets from process.env. Default for all v1 integrations.
|
|
862
|
+
* v1.1 will add VaultSecretSource, DopplerSecretSource, AWSSecretsSource.
|
|
863
|
+
*/
|
|
864
|
+
declare class EnvSecretSource implements SecretSource {
|
|
865
|
+
get(key: string): Promise<string | undefined>;
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/**
|
|
869
|
+
* Integration abstract base class: namespace-scoped tool bundle.
|
|
870
|
+
* Mirrors `kaji.runtime.integrations.base.Integration`.
|
|
871
|
+
*/
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* Mark a handler function as a tool with the given metadata.
|
|
875
|
+
*
|
|
876
|
+
* Usage on an Integration subclass:
|
|
877
|
+
*
|
|
878
|
+
* readonly retrieveCharge = tool(
|
|
879
|
+
* { description: "Retrieve a charge", parameters: {...}, risk: "read" },
|
|
880
|
+
* async (ctx, args) => { ... },
|
|
881
|
+
* );
|
|
882
|
+
*
|
|
883
|
+
* `Integration.tools()` will auto-discover all own properties that are
|
|
884
|
+
* handlers marked this way.
|
|
885
|
+
*/
|
|
886
|
+
declare function tool(meta: ToolMeta, handler: ToolHandler): ToolHandler;
|
|
887
|
+
declare abstract class Integration {
|
|
888
|
+
/** The namespace prefix applied to all tools in this integration. */
|
|
889
|
+
abstract readonly namespace: string;
|
|
890
|
+
/** Return all [spec, handler] pairs for this integration.
|
|
891
|
+
*
|
|
892
|
+
* The default implementation scans own instance properties for handlers
|
|
893
|
+
* marked with `tool(meta, fn)`. Override to return tuples manually.
|
|
894
|
+
*/
|
|
895
|
+
tools(): [ToolSpec, ToolHandler][];
|
|
896
|
+
/** Register all tools into the given registry, namespace-prefixed. */
|
|
897
|
+
register(registry: ToolRegistry): void;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/**
|
|
901
|
+
* Function-level `functionTool` for one-off tools without an `Integration` subclass.
|
|
902
|
+
* Mirrors `kaji.runtime.integrations.functional`.
|
|
903
|
+
*
|
|
904
|
+
* The class-based `Integration` path remains the right shape for namespaced,
|
|
905
|
+
* multi-tool bundles. This module adds a lightweight alternative for the common
|
|
906
|
+
* case of "I have one async function; expose it as a tool."
|
|
907
|
+
*
|
|
908
|
+
* const getWeather = functionTool(
|
|
909
|
+
* { description: "Return weather.", parameters: z.object({ city: z.string() }) },
|
|
910
|
+
* async ({ city }) => ({ city, tempF: 68 }),
|
|
911
|
+
* );
|
|
912
|
+
*
|
|
913
|
+
* const runtime = new AgentBuilder().provider(p).tool(getWeather).build();
|
|
914
|
+
*/
|
|
915
|
+
|
|
916
|
+
type ArgsOf<P> = P extends z.ZodType ? z.input<P> : Record<string, unknown>;
|
|
917
|
+
/** Signature accepted by `functionTool`. Zod validates the provider arguments,
|
|
918
|
+
* but its defaults, coercions, and transformations are deliberately discarded.
|
|
919
|
+
* The second context parameter may be ignored and matches registry handlers. */
|
|
920
|
+
type FunctionToolHandler<P> = (args: ArgsOf<P>, context: ToolExecutionContext) => Promise<unknown>;
|
|
921
|
+
/** Tool packaged with its spec + adapter handler, registrable like an Integration. */
|
|
922
|
+
declare class BoundTool {
|
|
923
|
+
readonly spec: ToolSpec;
|
|
924
|
+
readonly handler: ToolHandler;
|
|
925
|
+
readonly namespace: string;
|
|
926
|
+
constructor(spec: ToolSpec, handler: ToolHandler, namespace?: string);
|
|
927
|
+
register(registry: ToolRegistry): void;
|
|
928
|
+
}
|
|
929
|
+
interface FunctionToolMeta<P> extends Omit<ToolMeta, "parameters"> {
|
|
930
|
+
/** Tool name. Defaults to the handler's `.name` if available. */
|
|
931
|
+
name?: string;
|
|
932
|
+
/** Zod schema or JSON Schema describing the arguments. */
|
|
933
|
+
parameters: P;
|
|
934
|
+
/** Namespace prefix (defaults to "fn"). */
|
|
935
|
+
namespace?: string;
|
|
936
|
+
}
|
|
937
|
+
/**
|
|
938
|
+
* Build a single tool from a meta + handler pair. The handler receives the
|
|
939
|
+
* a byte-equivalent isolated clone after validation succeeds.
|
|
940
|
+
*/
|
|
941
|
+
declare function functionTool<P extends z.ZodType | Record<string, unknown>>(meta: FunctionToolMeta<P>, handler: FunctionToolHandler<P>): BoundTool;
|
|
942
|
+
|
|
943
|
+
type IntegrationValidationCode = "INTEGRATION_SCHEMA_INVALID";
|
|
944
|
+
type IntegrationStability = "experimental" | "beta";
|
|
945
|
+
type IntegrationRuntime = "python" | "typescript";
|
|
946
|
+
type IntegrationToolRisk = ToolRisk;
|
|
947
|
+
interface NormalizedIntegrationValidationError {
|
|
948
|
+
code: IntegrationValidationCode;
|
|
949
|
+
path: string;
|
|
950
|
+
}
|
|
951
|
+
declare abstract class IntegrationValidationError extends Error {
|
|
952
|
+
readonly code: IntegrationValidationCode;
|
|
953
|
+
readonly path: string;
|
|
954
|
+
protected constructor(code: IntegrationValidationCode, path: string, message: string);
|
|
955
|
+
normalized(): NormalizedIntegrationValidationError;
|
|
956
|
+
}
|
|
957
|
+
declare class ManifestValidationError extends IntegrationValidationError {
|
|
958
|
+
constructor(path: string, message: string);
|
|
959
|
+
}
|
|
960
|
+
declare class IndexValidationError extends IntegrationValidationError {
|
|
961
|
+
constructor(path: string, message: string);
|
|
962
|
+
}
|
|
963
|
+
declare class IntegrationExperimentalError extends Error {
|
|
964
|
+
readonly integrationName: string;
|
|
965
|
+
readonly code: "INTEGRATION_EXPERIMENTAL";
|
|
966
|
+
readonly path: string;
|
|
967
|
+
constructor(integrationName: string);
|
|
968
|
+
normalized(): {
|
|
969
|
+
code: "INTEGRATION_EXPERIMENTAL";
|
|
970
|
+
path: string;
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
declare class IntegrationNotFoundError extends Error {
|
|
974
|
+
readonly integrationName: string;
|
|
975
|
+
constructor(integrationName: string);
|
|
976
|
+
}
|
|
977
|
+
interface RegistryIndexEntry {
|
|
978
|
+
manifest: string;
|
|
979
|
+
stability: IntegrationStability;
|
|
980
|
+
runtimes: IntegrationRuntime[];
|
|
981
|
+
}
|
|
982
|
+
interface RegistryIndexDocument {
|
|
983
|
+
$schema: "./index.schema.json";
|
|
984
|
+
version: string;
|
|
985
|
+
integrations: Record<string, RegistryIndexEntry>;
|
|
986
|
+
}
|
|
987
|
+
type IntegrationAuth = Readonly<{
|
|
988
|
+
kind: "none";
|
|
989
|
+
}> | Readonly<{
|
|
990
|
+
kind: "env";
|
|
991
|
+
env: string;
|
|
992
|
+
optional?: boolean;
|
|
993
|
+
docs?: string;
|
|
994
|
+
}> | Readonly<{
|
|
995
|
+
kind: "oauth";
|
|
996
|
+
provider: "google";
|
|
997
|
+
clientIdEnv: string;
|
|
998
|
+
clientSecretEnv?: string;
|
|
999
|
+
scopes: readonly string[];
|
|
1000
|
+
docs?: string;
|
|
1001
|
+
}>;
|
|
1002
|
+
interface IntegrationManifestTool {
|
|
1003
|
+
readonly name: string;
|
|
1004
|
+
readonly description: string;
|
|
1005
|
+
readonly parameters: JSONSchema;
|
|
1006
|
+
readonly risk: IntegrationToolRisk;
|
|
1007
|
+
readonly parallel_safe: boolean;
|
|
1008
|
+
readonly timeout_ms?: number;
|
|
1009
|
+
}
|
|
1010
|
+
interface IntegrationManifestDocument {
|
|
1011
|
+
name: string;
|
|
1012
|
+
version: string;
|
|
1013
|
+
namespace: string;
|
|
1014
|
+
description: string;
|
|
1015
|
+
auth: IntegrationAuth;
|
|
1016
|
+
files: string[];
|
|
1017
|
+
tools: IntegrationManifestTool[];
|
|
1018
|
+
extras?: string[];
|
|
1019
|
+
peerDeps?: Record<string, string>;
|
|
1020
|
+
}
|
|
1021
|
+
interface LoadedIntegrationManifest extends IntegrationManifestDocument {
|
|
1022
|
+
stability: IntegrationStability;
|
|
1023
|
+
runtimes: IntegrationRuntime[];
|
|
1024
|
+
/** Absolute path to manifest.json. */
|
|
1025
|
+
path: string;
|
|
1026
|
+
/** Absolute directory containing manifest.json. */
|
|
1027
|
+
root: string;
|
|
1028
|
+
}
|
|
1029
|
+
interface RegistryLoaderOptions {
|
|
1030
|
+
/** Directory containing schema.json and index.schema.json. Defaults to registryRoot. */
|
|
1031
|
+
schemaRoot?: string;
|
|
1032
|
+
/** Reuse an already validated index when loading several manifests. */
|
|
1033
|
+
index?: RegistryIndexDocument;
|
|
1034
|
+
}
|
|
1035
|
+
declare function validateManifestDocument(document: unknown, options: {
|
|
1036
|
+
schemaRoot: string;
|
|
1037
|
+
}): Promise<IntegrationManifestDocument>;
|
|
1038
|
+
declare function validateIndexDocument(document: unknown, options: {
|
|
1039
|
+
schemaRoot: string;
|
|
1040
|
+
}): Promise<RegistryIndexDocument>;
|
|
1041
|
+
declare function loadRegistryIndex(registryRoot: string, options?: RegistryLoaderOptions): Promise<RegistryIndexDocument>;
|
|
1042
|
+
declare function loadManifest(registryRoot: string, name: string, options?: RegistryLoaderOptions): Promise<LoadedIntegrationManifest>;
|
|
1043
|
+
declare function formatIntegrationError(error: unknown): string;
|
|
1044
|
+
|
|
1045
|
+
interface SafeFetchPolicy {
|
|
1046
|
+
readonly allowedHosts: readonly string[];
|
|
1047
|
+
readonly allowPublicInternet?: boolean;
|
|
1048
|
+
readonly allowHttp?: boolean;
|
|
1049
|
+
readonly timeoutMs?: number;
|
|
1050
|
+
readonly maxResponseBytes?: number;
|
|
1051
|
+
readonly maxRedirects?: number;
|
|
1052
|
+
/** Additional credential-bearing request headers to remove on cross-origin redirects. */
|
|
1053
|
+
readonly sensitiveHeaders?: readonly string[];
|
|
1054
|
+
}
|
|
1055
|
+
interface BoundNetworkTransport {
|
|
1056
|
+
request(target: {
|
|
1057
|
+
readonly url: URL;
|
|
1058
|
+
readonly validatedAddresses: readonly string[];
|
|
1059
|
+
}, init: RequestInit & {
|
|
1060
|
+
readonly signal: AbortSignal;
|
|
1061
|
+
}): Promise<Response>;
|
|
1062
|
+
}
|
|
1063
|
+
interface BoundedResponse {
|
|
1064
|
+
readonly status: number;
|
|
1065
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
1066
|
+
readonly bytes: Uint8Array;
|
|
1067
|
+
}
|
|
1068
|
+
/** Injectable only so registry tests and application egress adapters never need public DNS. */
|
|
1069
|
+
type AddressResolver = (hostname: string) => Promise<readonly string[]>;
|
|
1070
|
+
/**
|
|
1071
|
+
* Execute one bounded request through an address-pinning application transport.
|
|
1072
|
+
* The optional resolver argument is intentionally not re-exported from the beta root.
|
|
1073
|
+
*/
|
|
1074
|
+
declare function safeRequest(input: URL, init: RequestInit, context: ToolExecutionContext, policy: SafeFetchPolicy, transport: BoundNetworkTransport, resolver?: AddressResolver): Promise<BoundedResponse>;
|
|
1075
|
+
|
|
1076
|
+
/** Whole-turn execution limits and stable timeout errors. */
|
|
1077
|
+
type TurnPhase = "queue" | "provider_open" | "provider_stream" | "approval" | "tool";
|
|
1078
|
+
type TurnOutcome = "not_started" | "failed" | "unknown";
|
|
1079
|
+
interface TurnExecutionLimits {
|
|
1080
|
+
readonly turnTimeoutMs: number;
|
|
1081
|
+
readonly providerCancellationGraceMs: number;
|
|
1082
|
+
readonly providerTextMaxBytes: number;
|
|
1083
|
+
readonly providerToolArgumentsMaxBytes: number;
|
|
1084
|
+
readonly providerResponseMaxBytes: number;
|
|
1085
|
+
readonly providerToolCallsMax: number;
|
|
1086
|
+
}
|
|
1087
|
+
declare const DEFAULT_TURN_EXECUTION_LIMITS: Readonly<TurnExecutionLimits>;
|
|
1088
|
+
declare class TurnTimeoutError extends Error {
|
|
1089
|
+
readonly phase: TurnPhase;
|
|
1090
|
+
readonly retryable: boolean;
|
|
1091
|
+
readonly outcome: TurnOutcome;
|
|
1092
|
+
readonly code: "TURN_TIMEOUT";
|
|
1093
|
+
constructor(phase: TurnPhase, retryable: boolean, outcome: TurnOutcome);
|
|
1094
|
+
}
|
|
1095
|
+
declare class ProviderCancellationContractViolation extends Error {
|
|
1096
|
+
readonly phase: Extract<TurnPhase, "provider_open" | "provider_stream">;
|
|
1097
|
+
readonly code: "PROVIDER_CANCELLATION_CONTRACT_VIOLATION";
|
|
1098
|
+
readonly retryable = false;
|
|
1099
|
+
readonly outcome: "unknown";
|
|
1100
|
+
constructor(phase?: Extract<TurnPhase, "provider_open" | "provider_stream">);
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/** Cancellation token whose state changes can be observed while queued. */
|
|
1104
|
+
interface ObservableCancellationToken extends CancellationTokenLike {
|
|
1105
|
+
readonly signal: AbortSignal;
|
|
1106
|
+
}
|
|
1107
|
+
/** Process-local serialization boundary for turns that share a session. */
|
|
1108
|
+
interface SessionTurnCoordinator {
|
|
1109
|
+
acquire(sessionId: string, token?: ObservableCancellationToken, options?: TurnLeaseOptions): Promise<SessionTurnLease>;
|
|
1110
|
+
quarantine(sessionId: string): void | Promise<void>;
|
|
1111
|
+
clearQuarantine(sessionId: string): void | Promise<void>;
|
|
1112
|
+
runExclusive<T>(sessionId: string, token: ObservableCancellationToken | undefined, operation: () => Promise<T>): Promise<T>;
|
|
1113
|
+
}
|
|
1114
|
+
interface TurnLeaseOptions {
|
|
1115
|
+
readonly deadlineMonotonicMs?: number;
|
|
1116
|
+
readonly clock?: Clock;
|
|
1117
|
+
readonly scheduler?: TimerScheduler;
|
|
1118
|
+
}
|
|
1119
|
+
/** Exclusive ownership that may be transferred to runtime quarantine. */
|
|
1120
|
+
interface SessionTurnLease {
|
|
1121
|
+
transfer(): SessionTurnLease;
|
|
1122
|
+
release(): void | Promise<void>;
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* FIFO keyed coordinator for one process. Different session IDs never share a
|
|
1126
|
+
* queue; callers that need cross-process serialization must inject another
|
|
1127
|
+
* implementation.
|
|
1128
|
+
*/
|
|
1129
|
+
declare class InMemorySessionTurnCoordinator implements SessionTurnCoordinator {
|
|
1130
|
+
private readonly entries;
|
|
1131
|
+
/** Number of session queues currently held or waiting. */
|
|
1132
|
+
get entryCount(): number;
|
|
1133
|
+
/** Total actively linked waiters across session queues. */
|
|
1134
|
+
get waitingCount(): number;
|
|
1135
|
+
runExclusive<T>(sessionId: string, token: ObservableCancellationToken | undefined, operation: () => Promise<T>): Promise<T>;
|
|
1136
|
+
acquire(sessionId: string, token?: ObservableCancellationToken, options?: TurnLeaseOptions): Promise<SessionTurnLease>;
|
|
1137
|
+
quarantine(sessionId: string): void;
|
|
1138
|
+
clearQuarantine(sessionId: string): void;
|
|
1139
|
+
private lease;
|
|
1140
|
+
private enqueue;
|
|
1141
|
+
private unlink;
|
|
1142
|
+
private release;
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
interface StreamDiagnostics {
|
|
1146
|
+
readonly inputFragments: number;
|
|
1147
|
+
readonly durableDeltaEvents: number;
|
|
1148
|
+
readonly deltaJoinOperations: number;
|
|
1149
|
+
readonly responseJoinOperations: number;
|
|
1150
|
+
readonly textBytes: number;
|
|
1151
|
+
readonly totalResponseBytes: number;
|
|
1152
|
+
readonly toolCalls: number;
|
|
1153
|
+
readonly rawFragments: number;
|
|
1154
|
+
readonly toolArgumentJoinOperations: number;
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/**
|
|
1158
|
+
* Agent runtime: the ReAct tool-using loop, mirroring
|
|
1159
|
+
* `kaji.runtime.agents.runtime.AgentRuntime`.
|
|
1160
|
+
*
|
|
1161
|
+
* runTurn: replay state -> build messages -> stream from provider -> emit
|
|
1162
|
+
* events -> execute a bounded tool batch -> loop until the
|
|
1163
|
+
* provider returns no tool calls -> emit AgentMessageCompleted.
|
|
1164
|
+
*/
|
|
1165
|
+
|
|
1166
|
+
/** Tuning parameters for the ReAct loop, mirroring Python `AgentStrategy`. */
|
|
1167
|
+
interface AgentStrategy {
|
|
1168
|
+
/** Maximum tool-call iterations before the loop terminates. Default: 5. */
|
|
1169
|
+
maxToolIterations?: number;
|
|
1170
|
+
/**
|
|
1171
|
+
* When `false`, the loop breaks after the first provider response even if
|
|
1172
|
+
* it requested tool calls (the calls are never executed). Default: `true`.
|
|
1173
|
+
*/
|
|
1174
|
+
allowToolCalls?: boolean;
|
|
1175
|
+
}
|
|
1176
|
+
interface AgentRuntimeOptions {
|
|
1177
|
+
provider: ModelProvider;
|
|
1178
|
+
store: EventStore;
|
|
1179
|
+
/** Canonical append + subscription boundary. */
|
|
1180
|
+
committer: EventCommitter;
|
|
1181
|
+
systemPrompt?: string;
|
|
1182
|
+
strategy?: AgentStrategy;
|
|
1183
|
+
/**
|
|
1184
|
+
* Tool specs to surface to the provider each turn. When provided, only
|
|
1185
|
+
* these tools are offered (scoped registry). When omitted, falls back to
|
|
1186
|
+
* `listToolSpecs()` from the global registry.
|
|
1187
|
+
*/
|
|
1188
|
+
tools?: ToolSpec[];
|
|
1189
|
+
/**
|
|
1190
|
+
* Optional tool policy. When provided, tool calls whose risk level is in
|
|
1191
|
+
* `policy.requireApprovalFor` require an `approvalHandler` before execution.
|
|
1192
|
+
*/
|
|
1193
|
+
policy?: ToolPolicy;
|
|
1194
|
+
/**
|
|
1195
|
+
* Optional approval handler for tools that require explicit approval.
|
|
1196
|
+
* Wired into the default `ToolPlanner` when `planner` is not provided.
|
|
1197
|
+
*/
|
|
1198
|
+
approvalHandler?: TypedApprovalHandler;
|
|
1199
|
+
/**
|
|
1200
|
+
* Tool execution planner. When omitted, a default planner is constructed from
|
|
1201
|
+
* `toolExecutor`, `policy`, `approvalHandler`, and `tools`.
|
|
1202
|
+
*/
|
|
1203
|
+
planner?: ToolPlanner;
|
|
1204
|
+
/**
|
|
1205
|
+
* Scoped tool executor. Used by the default planner when `planner` is omitted.
|
|
1206
|
+
* Falls back to the global `executeTool` registry.
|
|
1207
|
+
*/
|
|
1208
|
+
toolExecutor?: ToolExecutor;
|
|
1209
|
+
/** Runtime-lifetime tool execution bounds used by every dynamic planner. */
|
|
1210
|
+
toolExecutionLimits?: Partial<ToolExecutionLimits>;
|
|
1211
|
+
/** Replace the process-local tool idempotency ledger. */
|
|
1212
|
+
toolIdempotencyLedger?: ToolIdempotencyLedger;
|
|
1213
|
+
/** Whole-turn deadline and provider response bounds. */
|
|
1214
|
+
turnExecutionLimits?: Partial<TurnExecutionLimits>;
|
|
1215
|
+
/** Explicit defaults for a single-tenant application. */
|
|
1216
|
+
defaultContext?: TurnContext;
|
|
1217
|
+
/**
|
|
1218
|
+
* Defaults to one process-local coordinator per store object. Inject a
|
|
1219
|
+
* distributed implementation when runtimes span processes.
|
|
1220
|
+
*/
|
|
1221
|
+
turnCoordinator?: SessionTurnCoordinator;
|
|
1222
|
+
/** Complete-turn provider-history bounds. Defaults to 32 turns / 100,000 characters. */
|
|
1223
|
+
contextWindow?: ContextWindow;
|
|
1224
|
+
/** Dependency-free recording sink; defaults to a no-op. */
|
|
1225
|
+
metricsSink?: MetricsSink;
|
|
1226
|
+
/** Privileged trace sink; defaults to a no-op. */
|
|
1227
|
+
traceSink?: TraceSink;
|
|
1228
|
+
/** Scoped identifier source used for every runtime and event identifier. */
|
|
1229
|
+
idFactory?: IdFactory;
|
|
1230
|
+
/** Wall and monotonic clock used by runtime events and timing. */
|
|
1231
|
+
clock?: Clock;
|
|
1232
|
+
/** Disposable one-shot timers used for deterministic deadline races. */
|
|
1233
|
+
timerScheduler?: TimerScheduler;
|
|
1234
|
+
}
|
|
1235
|
+
/** Immutable snapshot of the resolved limits used by one runtime instance. */
|
|
1236
|
+
interface EffectiveRuntimeLimits {
|
|
1237
|
+
readonly maxToolIterations: number;
|
|
1238
|
+
readonly contextWindowTurns: number | null;
|
|
1239
|
+
readonly contextWindowCharacters: number | null;
|
|
1240
|
+
readonly toolMaxParallel: number;
|
|
1241
|
+
readonly toolTimeoutMs: number | null;
|
|
1242
|
+
readonly approvalTimeoutMs: number;
|
|
1243
|
+
readonly turnTimeoutMs: number;
|
|
1244
|
+
readonly providerCancellationGraceMs: number;
|
|
1245
|
+
readonly providerTextMaxBytes: number;
|
|
1246
|
+
readonly providerToolArgumentsMaxBytes: number;
|
|
1247
|
+
readonly providerResponseMaxBytes: number;
|
|
1248
|
+
readonly providerToolCallsMax: number;
|
|
1249
|
+
}
|
|
1250
|
+
interface RunTurnOptions {
|
|
1251
|
+
cancellationToken?: CancellationToken;
|
|
1252
|
+
context?: TurnContext;
|
|
1253
|
+
}
|
|
1254
|
+
interface TurnOptions {
|
|
1255
|
+
/** Existing session to reuse; a fresh UUID is generated when omitted. */
|
|
1256
|
+
sessionId?: string;
|
|
1257
|
+
cancellationToken?: CancellationToken;
|
|
1258
|
+
context?: TurnContext;
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* Result of one `AgentRuntime.turn` call.
|
|
1262
|
+
*
|
|
1263
|
+
* - `text` is built from `AGENT_MESSAGE_COMPLETED` content joined across
|
|
1264
|
+
* iterations, not delta accumulation. It may be empty when the provider keeps
|
|
1265
|
+
* returning tool calls; inspect `events` for `AGENT_TURN_EXHAUSTED`.
|
|
1266
|
+
* - `toolCallEvents` are `KajiEvent`s of type `TOOL_CALL_REQUESTED`, not
|
|
1267
|
+
* provider-neutral `ToolCall` payloads. The name reflects the type.
|
|
1268
|
+
* - `events` contains persisted events after this call's starting cursor.
|
|
1269
|
+
* - `accounting` covers completed provider iterations, including iterations
|
|
1270
|
+
* with no durable assistant completion event.
|
|
1271
|
+
*/
|
|
1272
|
+
interface TurnResult {
|
|
1273
|
+
text: string;
|
|
1274
|
+
sessionId: string;
|
|
1275
|
+
turnId: string;
|
|
1276
|
+
toolCallEvents: StoredKajiEvent[];
|
|
1277
|
+
events: StoredKajiEvent[];
|
|
1278
|
+
accounting: TurnAccounting;
|
|
1279
|
+
}
|
|
1280
|
+
/** Immutable provider usage and cost totals for one successful turn. */
|
|
1281
|
+
interface TurnAccounting {
|
|
1282
|
+
readonly providerIterations: number;
|
|
1283
|
+
readonly usage: Readonly<TokenUsage> | null;
|
|
1284
|
+
readonly usageComplete: boolean;
|
|
1285
|
+
readonly costUsd: number | null;
|
|
1286
|
+
readonly costComplete: boolean;
|
|
1287
|
+
}
|
|
1288
|
+
declare class AgentRuntime {
|
|
1289
|
+
private readonly provider;
|
|
1290
|
+
private readonly store;
|
|
1291
|
+
private readonly committer;
|
|
1292
|
+
private readonly systemPrompt?;
|
|
1293
|
+
private readonly maxToolIterations;
|
|
1294
|
+
private readonly allowToolCalls;
|
|
1295
|
+
private readonly fixedTools;
|
|
1296
|
+
private readonly toolExecutor;
|
|
1297
|
+
private readonly policy;
|
|
1298
|
+
private readonly approvalHandler;
|
|
1299
|
+
private readonly defaultContext;
|
|
1300
|
+
private readonly turnCoordinator;
|
|
1301
|
+
private readonly contextWindow;
|
|
1302
|
+
private readonly projectionCacheCapacity;
|
|
1303
|
+
private readonly projectors;
|
|
1304
|
+
private readonly projectionTails;
|
|
1305
|
+
private readonly activeProjectionSessions;
|
|
1306
|
+
private readonly turnEventCollectors;
|
|
1307
|
+
private readonly contextDiagnosticsBySession;
|
|
1308
|
+
private readonly streamDiagnosticsBySession;
|
|
1309
|
+
private readonly toolExecutionController;
|
|
1310
|
+
private readonly metrics;
|
|
1311
|
+
private readonly trace;
|
|
1312
|
+
private readonly idFactory;
|
|
1313
|
+
private readonly clock;
|
|
1314
|
+
private readonly turnLimits;
|
|
1315
|
+
private readonly providerResponseLimits;
|
|
1316
|
+
private readonly timerScheduler;
|
|
1317
|
+
private readonly providerQuarantine;
|
|
1318
|
+
private readonly storeRuntimeOwner;
|
|
1319
|
+
private closed;
|
|
1320
|
+
/**
|
|
1321
|
+
* Resolved planner: explicit if caller provided one, cached when the tool
|
|
1322
|
+
* set is fixed at construction, `null` when the runtime must rebuild a
|
|
1323
|
+
* planner per turn from the dynamic global registry.
|
|
1324
|
+
*/
|
|
1325
|
+
private readonly planner;
|
|
1326
|
+
constructor(options: AgentRuntimeOptions);
|
|
1327
|
+
private buildPlanner;
|
|
1328
|
+
private resolvePlanner;
|
|
1329
|
+
/** Drain actual tool handler settlement without claiming cancellation stopped work. */
|
|
1330
|
+
drainTools(timeoutMs: number): Promise<readonly string[]>;
|
|
1331
|
+
drainProviders(timeoutMs: number): Promise<readonly string[]>;
|
|
1332
|
+
/**
|
|
1333
|
+
* Deterministically remove one settled session from the store and every
|
|
1334
|
+
* runtime-owned cache. Applications should shut down in this order:
|
|
1335
|
+
*
|
|
1336
|
+
* ```ts
|
|
1337
|
+
* await runtime.drainTools(graceMs);
|
|
1338
|
+
* await runtime.drainProviders(graceMs);
|
|
1339
|
+
* await runtime.purgeSession(sessionId);
|
|
1340
|
+
* runtime.close();
|
|
1341
|
+
* ```
|
|
1342
|
+
*/
|
|
1343
|
+
purgeSession(sessionId: string): Promise<boolean>;
|
|
1344
|
+
private finishIrreversiblePurge;
|
|
1345
|
+
private sessionPurgeUnsupportedComponent;
|
|
1346
|
+
private closeSessionSubscriptions;
|
|
1347
|
+
close(): void;
|
|
1348
|
+
private hasBusySessionState;
|
|
1349
|
+
private clearSessionCaches;
|
|
1350
|
+
private releaseSettledSession;
|
|
1351
|
+
private ensureOpen;
|
|
1352
|
+
/** Return an immutable snapshot of the limits this runtime will use. */
|
|
1353
|
+
effectiveLimits(): Readonly<EffectiveRuntimeLimits>;
|
|
1354
|
+
private resolveTurnContext;
|
|
1355
|
+
private event;
|
|
1356
|
+
/** Canonical application write path for event drafts. */
|
|
1357
|
+
appendEvent(event: NewKajiEvent): Promise<StoredKajiEvent>;
|
|
1358
|
+
private projectorFor;
|
|
1359
|
+
private withProjectionSession;
|
|
1360
|
+
private trimProjectionCache;
|
|
1361
|
+
get projectionCacheSize(): number;
|
|
1362
|
+
private withProjectionLock;
|
|
1363
|
+
private syncProjection;
|
|
1364
|
+
/** Diagnostics from the latest provider context built for a session. */
|
|
1365
|
+
contextDiagnostics(sessionId: string): ContextDiagnostics | undefined;
|
|
1366
|
+
/** Immutable counters from the latest provider call for a session. */
|
|
1367
|
+
streamDiagnostics(sessionId: string): StreamDiagnostics | undefined;
|
|
1368
|
+
/** Read index counters without creating a session projector. */
|
|
1369
|
+
contextIndexStats(sessionId: string): Readonly<ContextIndexStats> | undefined;
|
|
1370
|
+
private runCoordinated;
|
|
1371
|
+
/**
|
|
1372
|
+
* Run one full agent turn and return a structured result.
|
|
1373
|
+
*
|
|
1374
|
+
* Wraps the ceremony of bootstrapping a session, sending the prompt,
|
|
1375
|
+
* running the ReAct loop, and slicing the new events out of the store.
|
|
1376
|
+
* Errors from the underlying loop propagate unchanged.
|
|
1377
|
+
*/
|
|
1378
|
+
turn(prompt: string, options?: TurnOptions): Promise<TurnResult>;
|
|
1379
|
+
/**
|
|
1380
|
+
* Append a user message and immediately run the agent turn.
|
|
1381
|
+
*
|
|
1382
|
+
* This is the idiomatic one-shot call:
|
|
1383
|
+
* await runtime.send("s1", "What time is it?");
|
|
1384
|
+
*
|
|
1385
|
+
* For more control (batch-append, replay, pre-seeding), call `appendEvent()`
|
|
1386
|
+
* and then `runTurn()` separately.
|
|
1387
|
+
*/
|
|
1388
|
+
send(sessionId: string, content: string, options?: RunTurnOptions): Promise<void>;
|
|
1389
|
+
private sendUnlocked;
|
|
1390
|
+
/**
|
|
1391
|
+
* Return a cursor page of persisted events for `sessionId` in append order.
|
|
1392
|
+
*/
|
|
1393
|
+
history(sessionId: string, options?: {
|
|
1394
|
+
afterSequence?: number;
|
|
1395
|
+
limit?: number;
|
|
1396
|
+
}): Promise<StoredKajiEvent[]>;
|
|
1397
|
+
runTurn(sessionId: string, options?: RunTurnOptions): Promise<void>;
|
|
1398
|
+
private runTurnUnlocked;
|
|
1399
|
+
private recordTurnFailure;
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/**
|
|
1403
|
+
* AgentBuilder: fluent builder for AgentRuntime.
|
|
1404
|
+
* Mirrors `kaji.runtime.agents.builder.AgentBuilder`.
|
|
1405
|
+
*/
|
|
1406
|
+
|
|
1407
|
+
/** Anything with a register(registry: ToolRegistry) method. */
|
|
1408
|
+
interface Integrable {
|
|
1409
|
+
register(registry: ToolRegistry): void;
|
|
1410
|
+
}
|
|
1411
|
+
interface AgentBuilderBuildOptions {
|
|
1412
|
+
/** Canonical append + subscription boundary. */
|
|
1413
|
+
committer?: EventCommitter;
|
|
1414
|
+
/** Defaults to the injected committer's store, otherwise a fresh in-memory store. */
|
|
1415
|
+
store?: EventStore;
|
|
1416
|
+
/** Defaults to the process-local coordinator shared by this store object. */
|
|
1417
|
+
turnCoordinator?: SessionTurnCoordinator;
|
|
1418
|
+
}
|
|
1419
|
+
declare class AgentBuilder {
|
|
1420
|
+
private _provider;
|
|
1421
|
+
private readonly _integrations;
|
|
1422
|
+
private _policy;
|
|
1423
|
+
private _approvalHandler;
|
|
1424
|
+
private _systemPrompt;
|
|
1425
|
+
private _strategy;
|
|
1426
|
+
private _contextWindow;
|
|
1427
|
+
private _defaultContext;
|
|
1428
|
+
private _toolExecutionLimits;
|
|
1429
|
+
private _turnExecutionLimits;
|
|
1430
|
+
private _toolIdempotencyLedger;
|
|
1431
|
+
private _metricsSink;
|
|
1432
|
+
private _traceSink;
|
|
1433
|
+
private _idFactory;
|
|
1434
|
+
private _clock;
|
|
1435
|
+
private _timerScheduler;
|
|
1436
|
+
provider(p: ModelProvider): this;
|
|
1437
|
+
integration(i: Integrable): this;
|
|
1438
|
+
/** Add a function-level tool created by `functionTool({...}, handler)`. */
|
|
1439
|
+
tool(bound: Integrable): this;
|
|
1440
|
+
policy(p: ToolPolicy): this;
|
|
1441
|
+
approvalHandler(handler: TypedApprovalHandler): this;
|
|
1442
|
+
systemPrompt(prompt: string): this;
|
|
1443
|
+
strategy(s: AgentStrategy): this;
|
|
1444
|
+
contextWindow(window: ContextWindow): this;
|
|
1445
|
+
/** Configure explicit defaults for a single-tenant application. */
|
|
1446
|
+
defaultContext(context: TurnContext): this;
|
|
1447
|
+
toolExecutionLimits(limits: Partial<ToolExecutionLimits>): this;
|
|
1448
|
+
turnExecutionLimits(limits: Partial<TurnExecutionLimits>): this;
|
|
1449
|
+
toolIdempotencyLedger(ledger: ToolIdempotencyLedger): this;
|
|
1450
|
+
metricsSink(sink: MetricsSink): this;
|
|
1451
|
+
traceSink(sink: TraceSink): this;
|
|
1452
|
+
idFactory(factory: IdFactory): this;
|
|
1453
|
+
clock(clock: Clock): this;
|
|
1454
|
+
timerScheduler(scheduler: TimerScheduler): this;
|
|
1455
|
+
build(opts?: AgentBuilderBuildOptions): AgentRuntime;
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
/**
|
|
1459
|
+
* One-shot helpers: call a provider without spinning up the full
|
|
1460
|
+
* event-sourced runtime. Use when you just want one model response.
|
|
1461
|
+
*
|
|
1462
|
+
* const { text } = await generateText({
|
|
1463
|
+
* provider: openai("gpt-5.4-mini"),
|
|
1464
|
+
* messages: [{ role: "user", content: "Hello" }],
|
|
1465
|
+
* });
|
|
1466
|
+
*
|
|
1467
|
+
* For tool-using ReAct loops, durable replay, batched tools, or policy
|
|
1468
|
+
* gating, build an `AgentRuntime`/`AgentBuilder` instead.
|
|
1469
|
+
*/
|
|
1470
|
+
|
|
1471
|
+
interface GenerateTextOptions extends ModelProviderOptions {
|
|
1472
|
+
provider: ModelProvider;
|
|
1473
|
+
messages: ProviderMessage[];
|
|
1474
|
+
/** Optional tool specs to surface to the model. */
|
|
1475
|
+
tools?: ToolSpec[];
|
|
1476
|
+
}
|
|
1477
|
+
/**
|
|
1478
|
+
* Single-call wrapper around `provider.generate`. Returns the full text and
|
|
1479
|
+
* any tool calls the model produced. Does not execute tool calls; the caller
|
|
1480
|
+
* decides what to do with them.
|
|
1481
|
+
*/
|
|
1482
|
+
declare function generateText(options: GenerateTextOptions): Promise<ModelResponse>;
|
|
1483
|
+
interface StreamTextResult {
|
|
1484
|
+
/**
|
|
1485
|
+
* Async-iterable of text deltas as they arrive from the provider.
|
|
1486
|
+
*
|
|
1487
|
+
* Each of `textStream`, `text`, and `toolCalls` is independently
|
|
1488
|
+
* consumable; awaiting any one of them does not require iterating
|
|
1489
|
+
* any of the others. All three reject if the source stream errors.
|
|
1490
|
+
*/
|
|
1491
|
+
textStream: AsyncIterable<string>;
|
|
1492
|
+
/** Resolves to the concatenated text once the source stream finishes. */
|
|
1493
|
+
text: Promise<string>;
|
|
1494
|
+
/** Resolves to the tool calls the model emitted, if any. */
|
|
1495
|
+
toolCalls: Promise<ModelResponse["toolCalls"]>;
|
|
1496
|
+
}
|
|
1497
|
+
/**
|
|
1498
|
+
* Stream a single provider call. All three result handles
|
|
1499
|
+
* (`textStream`, `text`, `toolCalls`) are independent: the source stream
|
|
1500
|
+
* is drained eagerly in the background so awaiting any one of them is
|
|
1501
|
+
* sufficient. All three reject if the source errors.
|
|
1502
|
+
*
|
|
1503
|
+
* const { textStream, text } = streamText({ provider: openai("gpt-5.4-mini"), messages });
|
|
1504
|
+
* for await (const chunk of textStream) process.stdout.write(chunk);
|
|
1505
|
+
* console.log("\nfinal:", await text);
|
|
1506
|
+
*
|
|
1507
|
+
* For a non-streaming one-shot, use `generateText`.
|
|
1508
|
+
*/
|
|
1509
|
+
declare function streamText(options: GenerateTextOptions): StreamTextResult;
|
|
1510
|
+
|
|
1511
|
+
interface EventApprovalHandlerOptions {
|
|
1512
|
+
/** Monotonic clock source for approval deadlines. */
|
|
1513
|
+
now?: () => number;
|
|
1514
|
+
idFactory?: IdFactory;
|
|
1515
|
+
clock?: Clock;
|
|
1516
|
+
}
|
|
1517
|
+
declare class EventApprovalHandler implements EventBackedApprovalHandler {
|
|
1518
|
+
readonly approvalRequestOwner: "handler";
|
|
1519
|
+
private readonly now;
|
|
1520
|
+
private readonly idFactory;
|
|
1521
|
+
private readonly clock;
|
|
1522
|
+
constructor(options?: EventApprovalHandlerOptions);
|
|
1523
|
+
request(call: ToolCall, context: ApprovalRequestContext): Promise<ApprovalDecision>;
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
/**
|
|
1527
|
+
* Policy-driven approval handler that resolves decisions synchronously
|
|
1528
|
+
* without any I/O. Useful for testing, sandboxed environments, or as a
|
|
1529
|
+
* safe default that denies everything not explicitly listed.
|
|
1530
|
+
*/
|
|
1531
|
+
|
|
1532
|
+
interface AutoApprovalPolicy {
|
|
1533
|
+
/** Tool names to always allow, regardless of `allowAll`. */
|
|
1534
|
+
allow: string[];
|
|
1535
|
+
/** Tool names to always deny (checked before `allow`). */
|
|
1536
|
+
deny: string[];
|
|
1537
|
+
/** When `true`, allow any tool that is not in `deny`. Defaults to `false`. */
|
|
1538
|
+
allowAll?: boolean;
|
|
1539
|
+
}
|
|
1540
|
+
declare class AutoApprovalHandler implements TypedApprovalHandler {
|
|
1541
|
+
private readonly policy;
|
|
1542
|
+
constructor(policy: AutoApprovalPolicy);
|
|
1543
|
+
request(call: ToolCall, _context: ApprovalRequestContext): Promise<ApprovalDecision>;
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
/**
|
|
1547
|
+
* Kaji: build agents in TypeScript.
|
|
1548
|
+
*
|
|
1549
|
+
* Infra-free core, mirroring the Python `kaji` SDK's public surface:
|
|
1550
|
+
* event-sourced building blocks (events, bus, store, replay) and a tool
|
|
1551
|
+
* registry. Import what you need and compose it; nothing here requires a
|
|
1552
|
+
* database, server, or any environment configured.
|
|
1553
|
+
*
|
|
1554
|
+
* Implementation helpers (test resets, internal symbols, low-level Zod/JSON
|
|
1555
|
+
* Schema converters, the planner's `EmitFn`/`buildMessages`) deliberately are
|
|
1556
|
+
* not re-exported here; reach into the submodule path when you need them.
|
|
1557
|
+
*/
|
|
1558
|
+
declare const VERSION = "0.2.0-beta.11";
|
|
1559
|
+
|
|
1560
|
+
export { AgentBuilder, type AgentBuilderBuildOptions, AgentRuntime, type AgentRuntimeOptions, type AgentStrategy, AnthropicProvider, type AnthropicProviderOptions, type ApprovalDeadlineSource, type ApprovalDecision, type ApprovalRejectionCode, type ApprovalRequestContext, AutoApprovalHandler, type AutoApprovalPolicy, type BoundNetworkTransport, BoundTool, type BoundedResponse, CancellationToken, CancellationTokenLike, type CliApprovalInput, type CliApprovalOptions, type CliApprovalOutput, Clock, ContextDiagnostics, ContextWindow, DEFAULT_TOOL_EXECUTION_LIMITS, DEFAULT_TURN_EXECUTION_LIMITS, DurableJsonLimitError, type EffectiveRuntimeLimits, EnvSecretSource, EventApprovalHandler, type EventApprovalHandlerOptions, type EventBackedApprovalHandler, EventBufferOverflowError, EventBus, type EventBusProtocol, type EventCommitter, EventDeliveryError, EventIdConflictError, EventSchemaIncompatibleError, type EventStore, EventStoreCapacityError, EventType, type FunctionToolHandler, type FunctionToolMeta, type GeminiFactoryOptions, type GenerateTextOptions, IdFactory, IdempotencyCapacityError, IdempotencyConflictError, InMemoryEventCommitter, type InMemoryEventCommitterOptions, InMemoryEventStore, InMemorySessionStore, InMemorySessionTurnCoordinator, InMemoryToolIdempotencyLedger, type InMemoryToolIdempotencyLedgerOptions, IndexValidationError, type Integrable, Integration, type IntegrationAuth, IntegrationExperimentalError, type IntegrationManifestDocument, type IntegrationManifestTool, IntegrationNotFoundError, type IntegrationRuntime, type IntegrationStability, type IntegrationToolRisk, type IntegrationValidationCode, IntegrationValidationError, InvalidDurableValueError, JSONSchema, KajiEvent, type LoadedIntegrationManifest, ManifestValidationError, MetricsSink, type ModelCostEntry, ModelProvider, ModelProviderOptions, ModelResponse, ModelResponseChunk, NewKajiEvent, type NormalizedIntegrationValidationError, type NormalizedProviderError, type ObservableCancellationToken, OpenAIProvider, type OpenAIProviderOptions, type OpenRouterFactoryOptions, ProviderAPIError, ProviderCancellationContractViolation, ProviderConfigError, ProviderConnectionError, ProviderError, ProviderMessage, type ProviderOutputDimension, ProviderOutputLimitError, ProviderRateLimitedError, type PurgeableEventStore, type RegistryIndexDocument, type RegistryIndexEntry, type RegistryLoaderOptions, RetryOptions, type RunTurnOptions, type SafeFetchPolicy, type SecretSource, SessionManager, SessionProjector, SessionPurgeBusyError, SessionPurgeUnsupportedError, type SessionRecord, SessionState, type SessionStore, type SessionTurnCoordinator, type SessionTurnLease, SplitEventCommitter, type SplitEventCommitterOptions, StoredKajiEvent, type StreamTextResult, TimerScheduler, TokenUsage, ToolCall, type ToolCallInstruction, type ToolCallResult, type ToolClaimResult, ToolExecutionContext, ToolExecutionController, type ToolExecutionControllerOptions, type ToolExecutionControllerOutcome, ToolExecutionError, type ToolExecutionLimits, type ToolExecutionRequest, type ToolExecutor, type ToolFailureFields, type ToolFailureOutcome, ToolHandler, type ToolIdempotencyClaim, type ToolIdempotencyLedger, type ToolLedgerOutcome, ToolPlanner, type ToolPlannerOptions, ToolPolicy, type ToolPolicyOptions, ToolPolicyViolation, ToolRegistry, ToolRisk, ToolSpec, TraceSink, type TurnAccounting, TurnContext, type TurnOutcome as TurnDeadlineOutcome, type TurnExecutionLimits, type TurnLeaseOptions, type TurnOptions, type TurnPhase, type TurnResult, TurnTimeoutError, type TypedApprovalHandler, VERSION, anthropic, calculateCostUsd, cliApprovalHandler, formatIntegrationError, functionTool, gemini, generateText, getProvider, kimi, loadManifest, loadRegistryIndex, lookupCost, normalizeProviderError, openai, openrouter, registerProvider, safeRequest, streamText, supportsSessionPurge, tool, validateIndexDocument, validateManifestDocument };
|