@zpi-dev/agent-sdk 0.0.0-stage → 0.1.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/NOTICE +1206 -0
  2. package/README.md +54 -2
  3. package/dist/chunk-GPIEWH3K.js +24368 -0
  4. package/dist/chunk-GPIEWH3K.js.map +1 -0
  5. package/dist/chunk-YPFTXFZL.js +29655 -0
  6. package/dist/chunk-YPFTXFZL.js.map +1 -0
  7. package/dist/host.d.ts +1 -0
  8. package/dist/host.js +32 -0
  9. package/dist/host.js.map +1 -0
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.js +23 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/src-GYA4LFM7.js +126 -0
  14. package/dist/src-GYA4LFM7.js.map +1 -0
  15. package/dist/types/agent/src/agent-loop.d.ts +3 -0
  16. package/dist/types/agent/src/agent.d.ts +21 -0
  17. package/dist/types/agent/src/index.d.ts +3 -0
  18. package/dist/types/agent/src/streaming-tool-coordinator.d.ts +10 -0
  19. package/dist/types/agent/src/tool-execution.d.ts +9 -0
  20. package/dist/types/agent/src/types.d.ts +144 -0
  21. package/dist/types/agent-sdk/src/hooks.d.ts +12 -0
  22. package/dist/types/agent-sdk/src/host.d.ts +4 -0
  23. package/dist/types/agent-sdk/src/index.d.ts +4 -0
  24. package/dist/types/agent-sdk/src/messages.d.ts +12 -0
  25. package/dist/types/agent-sdk/src/permissions.d.ts +10 -0
  26. package/dist/types/agent-sdk/src/query-result.d.ts +7 -0
  27. package/dist/types/agent-sdk/src/query.d.ts +6 -0
  28. package/dist/types/agent-sdk/src/resources.d.ts +16 -0
  29. package/dist/types/agent-sdk/src/runtime.d.ts +7 -0
  30. package/dist/types/agent-sdk/src/sessions.d.ts +48 -0
  31. package/dist/types/agent-sdk/src/tasks.d.ts +8 -0
  32. package/dist/types/agent-sdk/src/tools.d.ts +5 -0
  33. package/dist/types/agent-sdk/src/types.d.ts +428 -0
  34. package/dist/types/ai/src/api/anthropic-messages.d.ts +70 -0
  35. package/dist/types/ai/src/api/constrained-sampling.d.ts +5 -0
  36. package/dist/types/ai/src/api/github-copilot-headers.d.ts +7 -0
  37. package/dist/types/ai/src/api/openai-completions.d.ts +10 -0
  38. package/dist/types/ai/src/api/openai-responses.d.ts +5 -0
  39. package/dist/types/ai/src/api/responses-cache.d.ts +6 -0
  40. package/dist/types/ai/src/api/responses-events.d.ts +3 -0
  41. package/dist/types/ai/src/api/responses-session.d.ts +56 -0
  42. package/dist/types/ai/src/api/simple-options.d.ts +14 -0
  43. package/dist/types/ai/src/api/transform-messages.d.ts +3 -0
  44. package/dist/types/ai/src/auth/openai-chatgpt.d.ts +32 -0
  45. package/dist/types/ai/src/index.d.ts +20 -0
  46. package/dist/types/ai/src/providers/discovery.d.ts +14 -0
  47. package/dist/types/ai/src/providers/registry.d.ts +155 -0
  48. package/dist/types/ai/src/stream.d.ts +5 -0
  49. package/dist/types/ai/src/types.d.ts +395 -0
  50. package/dist/types/ai/src/utils/abort.d.ts +2 -0
  51. package/dist/types/ai/src/utils/context-breakdown.d.ts +3 -0
  52. package/dist/types/ai/src/utils/cost.d.ts +2 -0
  53. package/dist/types/ai/src/utils/diagnostics.d.ts +16 -0
  54. package/dist/types/ai/src/utils/error-body.d.ts +24 -0
  55. package/dist/types/ai/src/utils/estimate.d.ts +16 -0
  56. package/dist/types/ai/src/utils/event-stream.d.ts +15 -0
  57. package/dist/types/ai/src/utils/guard-model-stream.d.ts +3 -0
  58. package/dist/types/ai/src/utils/headers.d.ts +1 -0
  59. package/dist/types/ai/src/utils/json-parse.d.ts +7 -0
  60. package/dist/types/ai/src/utils/media-policy.d.ts +68 -0
  61. package/dist/types/ai/src/utils/model-performance.d.ts +23 -0
  62. package/dist/types/ai/src/utils/model-retry.d.ts +3 -0
  63. package/dist/types/ai/src/utils/option-map/compiler.d.ts +2 -0
  64. package/dist/types/ai/src/utils/option-map/evaluator.d.ts +3 -0
  65. package/dist/types/ai/src/utils/option-map/parser.d.ts +40 -0
  66. package/dist/types/ai/src/utils/option-map/tokenizer.d.ts +8 -0
  67. package/dist/types/ai/src/utils/option-map/types.d.ts +15 -0
  68. package/dist/types/ai/src/utils/overflow.d.ts +68 -0
  69. package/dist/types/ai/src/utils/provider-cache.d.ts +11 -0
  70. package/dist/types/ai/src/utils/provider-env.d.ts +2 -0
  71. package/dist/types/ai/src/utils/provider-retry.d.ts +17 -0
  72. package/dist/types/ai/src/utils/reasoning.d.ts +14 -0
  73. package/dist/types/ai/src/utils/redact-error.d.ts +2 -0
  74. package/dist/types/ai/src/utils/retry.d.ts +62 -0
  75. package/dist/types/ai/src/utils/sanitize-unicode.d.ts +21 -0
  76. package/dist/types/ai/src/utils/stream-idle-timeout.d.ts +36 -0
  77. package/dist/types/ai/src/utils/text.d.ts +5 -0
  78. package/dist/types/ai/src/utils/transcript.d.ts +28 -0
  79. package/dist/types/coding-agent/src/core/agent-session.d.ts +175 -0
  80. package/dist/types/coding-agent/src/core/commands.d.ts +19 -0
  81. package/dist/types/coding-agent/src/core/compaction-utils.d.ts +37 -0
  82. package/dist/types/coding-agent/src/core/compaction.d.ts +139 -0
  83. package/dist/types/coding-agent/src/core/dynamic-context.d.ts +3 -0
  84. package/dist/types/coding-agent/src/core/file-rewind.d.ts +24 -0
  85. package/dist/types/coding-agent/src/core/fs.d.ts +1 -0
  86. package/dist/types/coding-agent/src/core/http-idle-timeout.d.ts +2 -0
  87. package/dist/types/coding-agent/src/core/image-limits.d.ts +19 -0
  88. package/dist/types/coding-agent/src/core/images.d.ts +18 -0
  89. package/dist/types/coding-agent/src/core/input.d.ts +3 -0
  90. package/dist/types/coding-agent/src/core/markdown-code.d.ts +7 -0
  91. package/dist/types/coding-agent/src/core/markdown.d.ts +13 -0
  92. package/dist/types/coding-agent/src/core/mentions.d.ts +12 -0
  93. package/dist/types/coding-agent/src/core/microcompact.d.ts +40 -0
  94. package/dist/types/coding-agent/src/core/model-performance.d.ts +57 -0
  95. package/dist/types/coding-agent/src/core/model-runtime.d.ts +51 -0
  96. package/dist/types/coding-agent/src/core/read-file-bounded.d.ts +2 -0
  97. package/dist/types/coding-agent/src/core/record-validation.d.ts +6 -0
  98. package/dist/types/coding-agent/src/core/resources.d.ts +51 -0
  99. package/dist/types/coding-agent/src/core/sdk.d.ts +48 -0
  100. package/dist/types/coding-agent/src/core/session-manager.d.ts +138 -0
  101. package/dist/types/coding-agent/src/core/session-state.d.ts +14 -0
  102. package/dist/types/coding-agent/src/core/settings-manager.d.ts +41 -0
  103. package/dist/types/coding-agent/src/core/streaming-tool-journal.d.ts +17 -0
  104. package/dist/types/coding-agent/src/core/system-prompt.d.ts +32 -0
  105. package/dist/types/coding-agent/src/core/tools/file-change.d.ts +21 -0
  106. package/dist/types/coding-agent/src/core/tools/index.d.ts +20 -0
  107. package/dist/types/coding-agent/src/core/tools/pi/bash.d.ts +185 -0
  108. package/dist/types/coding-agent/src/core/tools/pi/edit-diff.d.ts +84 -0
  109. package/dist/types/coding-agent/src/core/tools/pi/edit.d.ts +69 -0
  110. package/dist/types/coding-agent/src/core/tools/pi/file-mutation-queue.d.ts +5 -0
  111. package/dist/types/coding-agent/src/core/tools/pi/file-read-state.d.ts +12 -0
  112. package/dist/types/coding-agent/src/core/tools/pi/output-accumulator.d.ts +68 -0
  113. package/dist/types/coding-agent/src/core/tools/pi/path-utils.d.ts +7 -0
  114. package/dist/types/coding-agent/src/core/tools/pi/read.d.ts +63 -0
  115. package/dist/types/coding-agent/src/core/tools/pi/text-range-reader.d.ts +22 -0
  116. package/dist/types/coding-agent/src/core/tools/pi/tool-definition-wrapper.d.ts +4 -0
  117. package/dist/types/coding-agent/src/core/tools/pi/truncate.d.ts +60 -0
  118. package/dist/types/coding-agent/src/core/tools/pi/utils/bmp-source.d.ts +2 -0
  119. package/dist/types/coding-agent/src/core/tools/pi/utils/child-process.d.ts +13 -0
  120. package/dist/types/coding-agent/src/core/tools/pi/utils/image-budget.d.ts +16 -0
  121. package/dist/types/coding-agent/src/core/tools/pi/utils/image-process.d.ts +18 -0
  122. package/dist/types/coding-agent/src/core/tools/pi/utils/image-resize-core.d.ts +26 -0
  123. package/dist/types/coding-agent/src/core/tools/pi/utils/image-resize.d.ts +3 -0
  124. package/dist/types/coding-agent/src/core/tools/pi/utils/image-source.d.ts +11 -0
  125. package/dist/types/coding-agent/src/core/tools/pi/utils/mime.d.ts +3 -0
  126. package/dist/types/coding-agent/src/core/tools/pi/utils/paths.d.ts +16 -0
  127. package/dist/types/coding-agent/src/core/tools/pi/utils/read-file.d.ts +2 -0
  128. package/dist/types/coding-agent/src/core/tools/pi/utils/shell.d.ts +18 -0
  129. package/dist/types/coding-agent/src/core/tools/pi/utils/text.d.ts +5 -0
  130. package/dist/types/coding-agent/src/core/tools/pi/write.d.ts +44 -0
  131. package/dist/types/coding-agent/src/core/transcript-store.d.ts +71 -0
  132. package/dist/types/coding-agent/src/core/types.d.ts +60 -0
  133. package/dist/types/coding-agent/src/index.d.ts +42 -0
  134. package/dist/types/coding-agent/src/plugins/assembly.d.ts +36 -0
  135. package/dist/types/coding-agent/src/plugins/hooks.d.ts +82 -0
  136. package/dist/types/coding-agent/src/plugins/resources.d.ts +4 -0
  137. package/dist/types/coding-agent/src/plugins/session-hooks.d.ts +26 -0
  138. package/dist/types/coding-agent/src/plugins/types.d.ts +41 -0
  139. package/dist/types/plugin-compat/src/command-hooks.d.ts +184 -0
  140. package/dist/types/plugin-compat/src/index.d.ts +11 -0
  141. package/package.json +53 -4
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Repairs malformed JSON string literals by:
3
+ * - escaping raw control characters inside strings
4
+ * - doubling backslashes before invalid escape characters
5
+ */
6
+ export declare function repairJson(json: string): string;
7
+ export declare function parseJsonWithRepair<T>(json: string): T;
@@ -0,0 +1,68 @@
1
+ import type { Model, TranscriptContext } from "../types.js";
2
+ export declare const DEFAULT_MODEL_REQUEST_MEDIA_BUDGET_BYTES: number;
3
+ export declare const MEDIA_BUDGET_CURRENT_ATTACHMENT_TOO_LARGE = "MEDIA_BUDGET_CURRENT_ATTACHMENT_TOO_LARGE";
4
+ interface ContentBlock {
5
+ type: string;
6
+ text?: string;
7
+ mimeType?: string;
8
+ mediaType?: string;
9
+ name?: string;
10
+ data?: string;
11
+ dataUrl?: string;
12
+ }
13
+ interface MediaMessage {
14
+ role: string;
15
+ content: string | readonly ContentBlock[];
16
+ /** Synthetic summaries/reminders must not acquire current-user attachment protection. */
17
+ synthetic?: boolean;
18
+ }
19
+ export interface MediaBudgetStats {
20
+ omittedMediaCount: number;
21
+ projectedMediaBytes: number;
22
+ retainedMediaCount: number;
23
+ totalMediaBytes: number;
24
+ evictionFrontier: {
25
+ messageIndex: number;
26
+ blockIndex: number;
27
+ } | null;
28
+ }
29
+ export declare class MediaBudgetError extends Error {
30
+ readonly code = "MEDIA_BUDGET_CURRENT_ATTACHMENT_TOO_LARGE";
31
+ readonly type = "InvalidInput";
32
+ readonly recoverable = true;
33
+ readonly context: {
34
+ maxMediaBytes: number;
35
+ protectedMediaBytes: number;
36
+ totalMediaBytes: number;
37
+ };
38
+ constructor(context: {
39
+ maxMediaBytes: number;
40
+ protectedMediaBytes: number;
41
+ totalMediaBytes: number;
42
+ });
43
+ }
44
+ export declare function mediaBlockToText(block: ContentBlock): string;
45
+ export declare function mediaRequestBytes(block: ContentBlock): number;
46
+ export declare function omittedMediaBlock(block: ContentBlock): {
47
+ type: "text";
48
+ text: string;
49
+ };
50
+ /** Request-only projection: original transcript, artifacts and tool results remain untouched. */
51
+ export declare function projectMessagesForMediaBudget<T extends MediaMessage>(messages: T[], options?: {
52
+ maxMediaBytes?: number;
53
+ latestRealUserMessageIndex?: number;
54
+ preserveLatestUserMedia?: boolean;
55
+ }): {
56
+ messages: T[];
57
+ } & MediaBudgetStats;
58
+ /** Always bind capability projection and aggregate budget at the same provider request boundary. */
59
+ export declare function projectContextForModelMediaPolicy(context: TranscriptContext, model: Pick<Model, "input">, options?: {
60
+ maxMediaBytes?: number;
61
+ onProjection?: (stats: MediaBudgetStats) => void;
62
+ }): TranscriptContext;
63
+ /** Compact retries use their own short placeholders, never the aggregate-budget omission text. */
64
+ export declare function projectCompactMediaForRetry<T extends MediaMessage>(messages: T[]): {
65
+ messages: T[];
66
+ replacedMediaCount: number;
67
+ };
68
+ export {};
@@ -0,0 +1,23 @@
1
+ import type { AssistantMessageEvent, StreamOptions } from "../types.js";
2
+ import { AssistantMessageEventStream } from "./event-stream.js";
3
+ /** Measures at the producer, before consumers, tool execution or backpressure can delay events. */
4
+ export declare class MeasuredAssistantStream extends AssistantMessageEventStream {
5
+ private started?;
6
+ private first?;
7
+ private last?;
8
+ private contentVersion;
9
+ private receivedAt?;
10
+ private usageVersion;
11
+ private sample;
12
+ private options;
13
+ private now;
14
+ constructor(options?: StreamOptions, now?: () => number);
15
+ startRequest(): void;
16
+ /** All deltas decoded from one wire event share one arrival time. */
17
+ received(): void;
18
+ generated(): void;
19
+ /** Call only when a fresh cumulative output count arrives, after content from the same wire event. */
20
+ recordUsage(outputTokens: unknown): void;
21
+ push(event: AssistantMessageEvent): void;
22
+ private publish;
23
+ }
@@ -0,0 +1,3 @@
1
+ import type { ModelFailure } from "../types.js";
2
+ /** Preserve retry facts before provider errors are converted into transcript text. */
3
+ export declare function modelFailure(error: unknown, signal?: AbortSignal): ModelFailure;
@@ -0,0 +1,2 @@
1
+ import { type ModelOptionMapProgram, type ModelOptionName } from "./types.js";
2
+ export declare function compileModelOptionMap(source: string, variableName: ModelOptionName): ModelOptionMapProgram;
@@ -0,0 +1,3 @@
1
+ import type { RestrictedCelExpression } from "./parser.js";
2
+ import { type JsonValue, type RestrictedCelValue } from "./types.js";
3
+ export declare function evaluateRestrictedCel(expression: RestrictedCelExpression, input: RestrictedCelValue): JsonValue;
@@ -0,0 +1,40 @@
1
+ import type { RestrictedCelToken } from "./tokenizer.js";
2
+ import { type ModelOptionName } from "./types.js";
3
+ export type RestrictedCelExpression = {
4
+ readonly type: "literal";
5
+ readonly value: string | number | boolean | null;
6
+ readonly offset: number;
7
+ } | {
8
+ readonly type: "input";
9
+ readonly offset: number;
10
+ } | {
11
+ readonly type: "array";
12
+ readonly elements: readonly RestrictedCelExpression[];
13
+ readonly offset: number;
14
+ } | {
15
+ readonly type: "object";
16
+ readonly entries: readonly {
17
+ readonly key: string;
18
+ readonly value: RestrictedCelExpression;
19
+ readonly offset: number;
20
+ }[];
21
+ readonly offset: number;
22
+ } | {
23
+ readonly type: "unary";
24
+ readonly operator: "!" | "-" | "+";
25
+ readonly operand: RestrictedCelExpression;
26
+ readonly offset: number;
27
+ } | {
28
+ readonly type: "binary";
29
+ readonly operator: string;
30
+ readonly left: RestrictedCelExpression;
31
+ readonly right: RestrictedCelExpression;
32
+ readonly offset: number;
33
+ } | {
34
+ readonly type: "conditional";
35
+ readonly condition: RestrictedCelExpression;
36
+ readonly whenTrue: RestrictedCelExpression;
37
+ readonly whenFalse: RestrictedCelExpression;
38
+ readonly offset: number;
39
+ };
40
+ export declare function parseRestrictedCel(tokens: readonly RestrictedCelToken[], variableName: ModelOptionName): RestrictedCelExpression;
@@ -0,0 +1,8 @@
1
+ export type RestrictedCelTokenKind = "identifier" | "string" | "number" | "operator" | "punctuation" | "eof";
2
+ export interface RestrictedCelToken {
3
+ readonly kind: RestrictedCelTokenKind;
4
+ readonly value: string;
5
+ readonly offset: number;
6
+ readonly end: number;
7
+ }
8
+ export declare function tokenizeRestrictedCel(source: string): readonly RestrictedCelToken[];
@@ -0,0 +1,15 @@
1
+ export type JsonPrimitive = string | number | boolean | null;
2
+ export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];
3
+ export interface JsonObject {
4
+ readonly [key: string]: JsonValue;
5
+ }
6
+ export type RestrictedCelValue = string | number;
7
+ export type ModelOptionName = "reasoningLevel" | "maxOutputTokens";
8
+ export interface ModelOptionMapProgram {
9
+ readonly source: string;
10
+ evaluate(input: RestrictedCelValue): JsonObject;
11
+ }
12
+ export declare class RestrictedCelError extends Error {
13
+ readonly offset: number;
14
+ constructor(message: string, offset: number);
15
+ }
@@ -0,0 +1,68 @@
1
+ import type { AssistantMessage } from "../types.js";
2
+ /**
3
+ * Check if an assistant message represents a context overflow error.
4
+ *
5
+ * This handles three cases:
6
+ * 1. Error-based overflow: Most providers return stopReason "error" with a
7
+ * specific error message pattern.
8
+ * 2. Silent overflow: Some providers accept overflow requests and return
9
+ * successfully. For these, we check if usage.input exceeds the context window.
10
+ * 3. Length-stop overflow: Xiaomi MiMo can return "length" with zero output when
11
+ * the input fills the context window.
12
+ *
13
+ * ## Reliability by Provider
14
+ *
15
+ * **Reliable detection (returns error with detectable message):**
16
+ * - Anthropic: "prompt is too long: X tokens > Y maximum" or "request_too_large"
17
+ * - OpenAI (Completions & Responses): "exceeds the context window", "exceeds the model's maximum context length of X tokens", or "exceeds model's maximum context length (X)"
18
+ * - Google Gemini: "input token count exceeds the maximum"
19
+ * - xAI (Grok): "maximum prompt length is X but request contains Y"
20
+ * - Groq: "reduce the length of the messages"
21
+ * - Cerebras: 400/413 status code (no body)
22
+ * - Mistral: "Prompt contains X tokens ... too large for model with Y maximum context length"
23
+ * - OpenRouter (most backends): "maximum context length is X tokens"
24
+ * - OpenRouter/Poolside: "Input length X exceeds the maximum allowed input length of Y tokens."
25
+ * - Together AI: "The input (X tokens) is longer than the model's context length (Y tokens)."
26
+ * - llama.cpp: "exceeds the available context size"
27
+ * - LM Studio: "greater than the context length"
28
+ * - Kimi For Coding: "exceeded model token limit: X (requested: Y)"
29
+ * - DS4: "Prompt has X tokens, but the configured context size is Y tokens"
30
+ * - DashScope/Qwen: "Range of input length should be [1, X]"
31
+ *
32
+ * **Unreliable detection:**
33
+ * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),
34
+ * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.
35
+ * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason "length" with
36
+ * output=0. Pass contextWindow param to detect via the "filled context + zero output" signal.
37
+ * - Ollama: May truncate input silently for some setups, but may also return explicit
38
+ * overflow errors that match the patterns above. Silent truncation still cannot be
39
+ * detected here because we do not know the expected token count.
40
+ *
41
+ * ## Custom Providers
42
+ *
43
+ * If you've added custom models via settings.json, this function may not detect
44
+ * overflow errors from those providers. To add support:
45
+ *
46
+ * 1. Send a request that exceeds the model's context window
47
+ * 2. Check the errorMessage in the response
48
+ * 3. Create a regex pattern that matches the error
49
+ * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or
50
+ * check the errorMessage yourself before calling this function
51
+ *
52
+ * @param message - The assistant message to check
53
+ * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)
54
+ * @returns true if the message indicates a context overflow
55
+ */
56
+ export declare function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean;
57
+ /**
58
+ * Check whether a length stop ended below the caller or model's intended output limit.
59
+ * Such responses may be caused by context pressure or provider-side truncation, so callers
60
+ * can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original
61
+ * limit before any context-based clamping.
62
+ */
63
+ export declare function isRecoverableLength(message: AssistantMessage, desiredMaxOutput: number): boolean;
64
+ /** Exact ZCode message predicates. Bare HTTP 413 / length limit exceeded matches neither. */
65
+ export declare function isModelContextExceededMessage(value: string | undefined): boolean;
66
+ export declare function isModelMediaTooLargeMessage(value: string | undefined): boolean;
67
+ export declare function isModelContextExceededError(error: unknown): boolean;
68
+ export declare function isModelMediaTooLargeError(error: unknown): boolean;
@@ -0,0 +1,11 @@
1
+ import type { Message } from "../types.js";
2
+ /** System breakpoints are independent; replace only non-system markers on a request copy. */
3
+ export declare function finalizeProviderCacheControl(messages: Message[], options?: {
4
+ skipCacheWrite?: boolean;
5
+ }): Message[];
6
+ /** Count only protocol cache locations, never user/tool input objects with similarly named fields. */
7
+ export declare function assertProviderCacheControlLimit(request: {
8
+ system?: unknown;
9
+ tools?: unknown;
10
+ messages?: unknown;
11
+ }): void;
@@ -0,0 +1,2 @@
1
+ import type { ProviderEnv } from "../types.js";
2
+ export declare function getProviderEnvValue(name: string, env?: ProviderEnv): string | undefined;
@@ -0,0 +1,17 @@
1
+ import type { ModelRetryStatus } from "../types.js";
2
+ interface ProviderRetryOptions {
3
+ maxRetries?: number;
4
+ maxRetryDelayMs?: number;
5
+ signal?: AbortSignal;
6
+ onRetry?: (status: ModelRetryStatus | null) => void;
7
+ }
8
+ /**
9
+ * Reproduce the retry behavior used by the OpenAI and Anthropic SDKs while making
10
+ * their backoff sleep interruptible. Their built-in retry timers ignore the
11
+ * request AbortSignal, so callers must invoke the SDK with `maxRetries: 0` and
12
+ * wrap the request with this helper. Provider-requested delays above
13
+ * `maxRetryDelayMs` fail immediately (60 seconds by default); set it to zero to
14
+ * disable the limit.
15
+ */
16
+ export declare function retryProviderRequest<T>(request: () => Promise<T>, options?: ProviderRetryOptions): Promise<T>;
17
+ export {};
@@ -0,0 +1,14 @@
1
+ import type { JsonObject, Model, ReasoningConfig, ThinkingLevel } from "../types.js";
2
+ export declare const reasoningParameterKeys: readonly ["reasoning_effort", "thinking", "reasoning", "enable_thinking", "thinking_budget", "reasoning_budget", "output_config"];
3
+ type ReasoningModel = Pick<Model, "reasoning" | "compat" | "thinkingLevelMap" | "defaultThinkingLevel" | "reasoningConfig"> & Partial<Pick<Model, "api">>;
4
+ export declare const thinkingLevels: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
5
+ export declare function thinkingChoices(model: ReasoningModel): ("off" | ThinkingLevel)[];
6
+ export declare function defaultThinkingLevel(model: ReasoningModel): "off" | ThinkingLevel;
7
+ /** Pi chooses the next supported strength, then searches downwards. */
8
+ export declare function clampThinkingLevel(model: ReasoningModel, level: "off" | ThinkingLevel): "off" | ThinkingLevel;
9
+ export declare function validateThinkingMap(map: unknown): void;
10
+ export declare function canControlThinking(model: ReasoningModel, level: "off" | ThinkingLevel): boolean;
11
+ export declare function reasoningParameters(model: ReasoningModel, level?: "off" | ThinkingLevel | undefined): JsonObject | undefined;
12
+ export declare function validateReasoningConfig(config: unknown): void;
13
+ export declare function editableReasoningConfig(model: ReasoningModel): ReasoningConfig;
14
+ export {};
@@ -0,0 +1,2 @@
1
+ /** Remove configured credentials before provider errors enter the durable transcript. */
2
+ export declare function redactProviderError(message: string, secrets: readonly (string | null | undefined)[]): string;
@@ -0,0 +1,62 @@
1
+ import type { AssistantMessage, ModelRetryStatus } from "../types.js";
2
+ /**
3
+ * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).
4
+ * `maxAgentDelayMs` caps each computed delay and defaults to 60 seconds.
5
+ * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`, `maxAgentDelayMs`) in coding-agent; kept
6
+ * here so the classifier and the policy-driven retry loop live together and stay reusable
7
+ * by the SDK and other callers.
8
+ */
9
+ export interface RetryPolicy {
10
+ enabled: boolean;
11
+ /** Max retry attempts (0 = no retries). The initial call never counts as a retry. */
12
+ maxRetries: number;
13
+ /** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)`. */
14
+ baseDelayMs: number;
15
+ /** Optional cap for agent-level retry delays in ms. Defaults to 60 seconds. */
16
+ maxAgentDelayMs?: number;
17
+ /** Recovery time allowed after the first failure; <= 0 disables the cap. */
18
+ maxElapsedMs?: number;
19
+ }
20
+ export declare const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60000;
21
+ /** Keep failure-specific retry limits shared by session and summary recovery. */
22
+ export declare function retryAttemptLimit(message: AssistantMessage, configuredLimit: number): number;
23
+ export declare function retryDelayMs(policy: Pick<RetryPolicy, "baseDelayMs" | "maxAgentDelayMs">, attempt: number, retryAfterMs?: number): number;
24
+ /** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */
25
+ export interface RetryCallbacks {
26
+ /** Emitted before the backoff sleep of each retry attempt (1-indexed). */
27
+ onRetryScheduled?: (attempt: number, maxAttempts: number, delayMs: number, errorMessage: string, origin?: ModelRetryStatus["origin"]) => void | Promise<void>;
28
+ /** Emitted after the backoff sleep, immediately before the retried call starts. */
29
+ onRetryAttemptStart?: () => void | Promise<void>;
30
+ /** Optional interruptible backoff. Return true when an explicit user retry resets the recovery budget. */
31
+ waitBeforeRetry?: (delayMs: number, signal?: AbortSignal) => Promise<boolean>;
32
+ /** Emitted once when the loop ends: success if a later call completed normally. */
33
+ onRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;
34
+ }
35
+ /**
36
+ * Run a single assistant-producing call with bounded retry on transient errors.
37
+ *
38
+ * Behavior:
39
+ * - A successful response is returned immediately. Aborts are terminal and never
40
+ * retried, but reported as unsuccessful if they happen after a retry was scheduled.
41
+ * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`
42
+ * too, so callers do not need to care when cancellation happened.
43
+ * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/
44
+ * billing exhaustion) is returned immediately so deterministic errors fail fast.
45
+ * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting
46
+ * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before
47
+ * the retried call starts, and `onRetryFinished` once at the end (whether the loop
48
+ * ends in success, exhausted retries, or an aborted backoff).
49
+ *
50
+ * When `policy` is undefined or disabled, only an explicit manual retry can repeat a request.
51
+ */
52
+ export declare function retryAssistantCall(produce: (deadlineMs?: number) => Promise<AssistantMessage>, policy: RetryPolicy | undefined, signal: AbortSignal | undefined, callbacks?: RetryCallbacks): Promise<AssistantMessage>;
53
+ /**
54
+ * Classifies whether a failed assistant message looks like a transient provider
55
+ * or transport error, so callers can decide if the last assistant turn should be
56
+ * restarted.
57
+ *
58
+ * This does not implement retry policy. Callers should first handle context
59
+ * overflow separately, then apply their own retry budget, backoff, and reporting
60
+ * before restarting the assistant turn.
61
+ */
62
+ export declare function isRetryableAssistantError(message: AssistantMessage): boolean;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Removes unpaired Unicode surrogate characters from a string.
3
+ *
4
+ * Unpaired surrogates (high surrogates 0xD800-0xDBFF without matching low surrogates 0xDC00-0xDFFF,
5
+ * or vice versa) cause JSON serialization errors in many API providers.
6
+ *
7
+ * Valid emoji and other characters outside the Basic Multilingual Plane use properly paired
8
+ * surrogates and will NOT be affected by this function.
9
+ *
10
+ * @param text - The text to sanitize
11
+ * @returns The sanitized text with unpaired surrogates removed
12
+ *
13
+ * @example
14
+ * // Valid emoji (properly paired surrogates) are preserved
15
+ * sanitizeSurrogates("Hello 🙈 World") // => "Hello 🙈 World"
16
+ *
17
+ * // Unpaired high surrogate is removed
18
+ * const unpaired = String.fromCharCode(0xD83D); // high surrogate without low
19
+ * sanitizeSurrogates(`Text ${unpaired} here`) // => "Text here"
20
+ */
21
+ export declare function sanitizeSurrogates(text: string): string;
@@ -0,0 +1,36 @@
1
+ export declare const DEFAULT_MODEL_FIRST_RESPONSE_TIMEOUT_MS = 120000;
2
+ export declare const DEFAULT_MODEL_STREAM_IDLE_TIMEOUT_MS = 300000;
3
+ export declare function resolveModelStreamIdleTimeoutMs(options: {
4
+ baseTimeoutMs?: number;
5
+ retryNumber?: number;
6
+ }): number;
7
+ export declare class ModelRequestRetryError extends Error {
8
+ readonly code = "MODEL_REQUEST_RETRY";
9
+ constructor();
10
+ }
11
+ export declare class ModelRecoveryDeadlineError extends Error {
12
+ readonly code = "MODEL_RECOVERY_DEADLINE";
13
+ constructor();
14
+ }
15
+ export declare class ModelStreamIdleTimeoutError extends Error {
16
+ readonly code = "MODEL_STREAM_IDLE_TIMEOUT";
17
+ readonly idleMs: number;
18
+ readonly timeoutMs: number;
19
+ constructor(options: {
20
+ idleMs: number;
21
+ timeoutMs: number;
22
+ });
23
+ }
24
+ export declare function createLinkedAbortController(parentSignal?: AbortSignal): {
25
+ controller: AbortController;
26
+ signal: AbortSignal;
27
+ cleanup(): void;
28
+ };
29
+ export declare function readNextWithStreamIdleTimeout<T>(iterator: AsyncIterator<T>, options: {
30
+ abortController: AbortController;
31
+ onTimeout?: (error: ModelStreamIdleTimeoutError) => void | Promise<void>;
32
+ timeoutMs: number;
33
+ startedAt?: number;
34
+ }): Promise<IteratorResult<T>>;
35
+ /** A provider can ignore abort and hang in return(); cleanup must not block recovery. */
36
+ export declare function closeStreamIterator(iterator: AsyncIterator<unknown> | undefined): Promise<void>;
@@ -0,0 +1,5 @@
1
+ import type { SystemMessage } from "../types.js";
2
+ /**
3
+ * Shared wire representation of named context changes, regardless of provider role.
4
+ */
5
+ export declare function renderSystemMessageUpdate(message: SystemMessage): string;
@@ -0,0 +1,28 @@
1
+ import type { AssistantMessage, Context, JsonObject, JsonValue, Model, SystemMessage, Tool, TranscriptContext } from "../types.js";
2
+ export declare function normalizeContext(context: Context): TranscriptContext;
3
+ export declare function contentText(content: string | readonly {
4
+ type: string;
5
+ text?: string;
6
+ }[], separator?: string): string;
7
+ export declare function getCurrentSystemPrompt(messages: readonly {
8
+ role: string;
9
+ }[]): string;
10
+ export declare function getCurrentTools(messages: readonly {
11
+ role: string;
12
+ }[]): Tool[];
13
+ export declare function toToolDeclaration(tool: Tool): Tool;
14
+ export declare function emptyAssistant(model: Model): AssistantMessage;
15
+ export declare function isJsonValue(value: unknown, seen?: Set<object>): value is JsonValue;
16
+ export declare function isJsonObject(value: unknown): value is JsonObject;
17
+ export declare function assertSupportedOptions(value: object, allowed: readonly string[], label: string): void;
18
+ export type TranscriptMessages = readonly {
19
+ role: string;
20
+ }[];
21
+ /** Return the leading system message, if the transcript starts with one. */
22
+ export declare function getInitialSystemMessage(messages: TranscriptMessages): SystemMessage | undefined;
23
+ export declare function getDeclaredTools(messages: TranscriptMessages): Tool[];
24
+ /**
25
+ * Whether a tool name was declared twice with different definitions. Transports that
26
+ * reference tools by name (Anthropic `tool_addition`/`tool_removal`) cannot express that.
27
+ */
28
+ export declare function hasToolRedefinitions(messages: TranscriptMessages): boolean;
@@ -0,0 +1,175 @@
1
+ import type { AgentEvent, AgentState, AgentTool, ThinkingLevel } from "../../../agent/src/index.js";
2
+ import type { ImageContent, Model, ModelRetryStatus, ModelWaitStatus, SimpleStreamOptions, UserGuide } from "../../../ai/src/index.js";
3
+ import type { HookExecution, HookRegistration } from "../plugins/hooks.js";
4
+ import type { PluginCommand } from "../plugins/types.js";
5
+ import type { ParsedInput } from "./commands.js";
6
+ import { type ModelPerformance, type ModelPerformanceTotals } from "./model-performance.js";
7
+ import type { ModelRuntime } from "./model-runtime.js";
8
+ import type { LoadedSkill, SkillList } from "./resources.js";
9
+ import type { SessionEntry, SessionManager } from "./session-manager.js";
10
+ import type { ContextUsage } from "./session-state.js";
11
+ import { SettingsManager } from "./settings-manager.js";
12
+ import type { SystemContext } from "./system-prompt.js";
13
+ import type { ResourceDiagnostic, ResourceLoader } from "./types.js";
14
+ export interface InputContext {
15
+ images?: ImageContent[];
16
+ fileReferences?: string[];
17
+ }
18
+ export type AgentSessionEvent = {
19
+ type: "hook_execution";
20
+ execution: HookExecution;
21
+ } | {
22
+ type: "model_performance";
23
+ performance: ModelPerformance;
24
+ totals: ModelPerformanceTotals;
25
+ } | Exclude<AgentEvent, {
26
+ type: "agent_end";
27
+ }> | {
28
+ type: "agent_end";
29
+ messages: AgentState["messages"];
30
+ willRetry: boolean;
31
+ } | {
32
+ type: "agent_settled";
33
+ } | {
34
+ type: "entry_appended";
35
+ entry: SessionEntry;
36
+ } | {
37
+ type: "session_info_changed";
38
+ name: string;
39
+ } | {
40
+ type: "thinking_level_changed";
41
+ thinkingLevel: ThinkingLevel;
42
+ } | {
43
+ type: "model_retry";
44
+ status: ModelRetryStatus | null;
45
+ } | {
46
+ type: "model_wait";
47
+ status: ModelWaitStatus | null;
48
+ } | {
49
+ type: "compaction";
50
+ id: string;
51
+ status: "running" | "completed" | "aborted" | "error" | "noop";
52
+ origin: "manual" | "auto";
53
+ error?: string;
54
+ } | {
55
+ type: "command_result";
56
+ message: string;
57
+ };
58
+ export declare class AgentSession {
59
+ private modelRequestOptions?;
60
+ private onCompaction?;
61
+ private agent;
62
+ private pluginCommands;
63
+ private hooks;
64
+ private manager;
65
+ private steering;
66
+ private pendingMessages;
67
+ private allTools;
68
+ private listeners;
69
+ private running?;
70
+ private active?;
71
+ private disposed;
72
+ private abortRequested;
73
+ private fault?;
74
+ private runtime;
75
+ private responsesSession?;
76
+ private responsesWarmupTimer?;
77
+ private responsesWarmupController?;
78
+ private resources?;
79
+ private compactController?;
80
+ readonly settingsManager: SettingsManager;
81
+ private overflowRecoveryAttempted;
82
+ private retryAttempt;
83
+ private recoveryStartedAt?;
84
+ private retryCurrentRequest?;
85
+ private lastAssistantCompletedAtMs?;
86
+ private microcompactProjection;
87
+ private recoveredCalls;
88
+ private performance;
89
+ get modelPerformance(): ModelPerformance;
90
+ constructor(model: Model, runtime: ModelRuntime, manager: SessionManager, allTools: AgentTool[], activeTools: AgentTool[], systemPrompt: string, thinkingLevel: ThinkingLevel, resources?: {
91
+ loader: ResourceLoader;
92
+ buildContext: () => SystemContext;
93
+ settingsManager?: SettingsManager;
94
+ }, performanceTotals?: ModelPerformanceTotals, extensions?: {
95
+ modelRequestOptions?: () => SimpleStreamOptions;
96
+ onCompaction?: (phase: "before" | "after", context: {
97
+ manual: boolean;
98
+ instructions: string;
99
+ }, signal?: AbortSignal) => Promise<void>;
100
+ beforeModelRequest?: (model: Model, context: import("../../../ai/src/index.js").Context) => void;
101
+ commands?: readonly PluginCommand[];
102
+ hooks?: readonly (HookRegistration & {
103
+ pluginId?: string;
104
+ })[];
105
+ });
106
+ private prepareResponsesSession;
107
+ static create(...args: ConstructorParameters<typeof AgentSession>): Promise<AgentSession>;
108
+ get state(): AgentState;
109
+ get messages(): AgentState["messages"];
110
+ get model(): Model;
111
+ get thinkingLevel(): ThinkingLevel;
112
+ get isStreaming(): boolean;
113
+ get isIdle(): boolean;
114
+ get systemPrompt(): string;
115
+ getContextUsage(): ContextUsage;
116
+ listSkills(): SkillList;
117
+ getResourceDiagnostics(): ResourceDiagnostic[];
118
+ loadSkill(name: string): Promise<LoadedSkill>;
119
+ prepareInput(text: string, context?: InputContext): Promise<ParsedInput>;
120
+ listCommands(): {
121
+ name: string;
122
+ description: string;
123
+ }[];
124
+ submit(text: string): Promise<void>;
125
+ executeInput(input: ParsedInput, context?: InputContext): Promise<void>;
126
+ private syncContext;
127
+ private refreshInstructions;
128
+ private compactionBoundary;
129
+ private estimateTokens;
130
+ private precedesCompaction;
131
+ private tryAutoCompact;
132
+ private checkCompaction;
133
+ private dropFailedAssistant;
134
+ private waitForRetry;
135
+ private waitForRetryDelay;
136
+ private canRetry;
137
+ private recoveryDeadline;
138
+ /** Only the active model request or retry backoff can be retried; tools keep their lifecycle. */
139
+ retryModelRequest(): boolean;
140
+ private requestOptions;
141
+ private alreadyCompacted;
142
+ private summarize;
143
+ private summarizeContext;
144
+ private streamWithRecovery;
145
+ private measuredStream;
146
+ compact(instructions?: string): Promise<void>;
147
+ get sessionId(): string;
148
+ get sessionFile(): string | undefined;
149
+ get sessionName(): string | undefined;
150
+ subscribe(listener: (event: AgentSessionEvent) => void): () => void;
151
+ private notify;
152
+ private notifyLastEntry;
153
+ private idleCheck;
154
+ prompt(text: string, options?: {
155
+ images?: ImageContent[];
156
+ }): Promise<void>;
157
+ /** Queue input for the next completed model/tool boundary without interrupting generation. */
158
+ steer(text: string, options?: {
159
+ queueOnly?: boolean;
160
+ inputId?: string;
161
+ userGuide?: UserGuide;
162
+ images?: ImageContent[];
163
+ fileReferences?: string[];
164
+ }): boolean;
165
+ abort(): Promise<void>;
166
+ waitForIdle(): Promise<void>;
167
+ dispose(): void;
168
+ getToolDefinitions(): AgentTool[];
169
+ validateImages(images?: ImageContent[]): void;
170
+ getActiveToolNames(): string[];
171
+ setActiveToolsByName(names: string[]): void;
172
+ setModel(model: Model): Promise<void>;
173
+ setThinkingLevel(thinkingLevel: ThinkingLevel): void;
174
+ setSessionName(name: string): void;
175
+ }
@@ -0,0 +1,19 @@
1
+ export declare const localCommands: readonly [{
2
+ readonly name: "compact";
3
+ readonly description: "摘要旧对话,保留完整历史";
4
+ }];
5
+ export declare function listCommands(commands?: readonly {
6
+ name: string;
7
+ description: string;
8
+ }[]): {
9
+ name: string;
10
+ description: string;
11
+ }[];
12
+ export type ParsedInput = {
13
+ kind: "prompt";
14
+ text: string;
15
+ } | {
16
+ kind: "compact";
17
+ args: string;
18
+ };
19
+ export declare function parseInput(text: string): ParsedInput;