@clinebot/shared 0.0.8 → 0.0.10

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/src/index.ts ADDED
@@ -0,0 +1,131 @@
1
+ export type { OAuthProviderId } from "./auth/constants";
2
+ export {
3
+ AUTH_ERROR_PATTERNS,
4
+ isLikelyAuthError,
5
+ isOAuthProviderId,
6
+ OAUTH_PROVIDER_IDS,
7
+ } from "./auth/constants";
8
+ export type {
9
+ ConnectorHookEvent,
10
+ ConnectorHookEventName,
11
+ } from "./connectors/events";
12
+ export {
13
+ ConnectorHookEventNameSchema,
14
+ ConnectorHookEventSchema,
15
+ } from "./connectors/events";
16
+ export {
17
+ MODELS_DEV_PROVIDER_KEY_ENTRIES,
18
+ MODELS_DEV_PROVIDER_KEY_MAP,
19
+ resolveProviderModelCatalogKeys,
20
+ } from "./llms/model-id";
21
+ export type {
22
+ Tool,
23
+ ToolApprovalRequest,
24
+ ToolApprovalResult,
25
+ ToolCallRecord,
26
+ ToolContext,
27
+ ToolPolicy,
28
+ } from "./llms/tools";
29
+ export { ToolCallRecordSchema, ToolContextSchema } from "./llms/tools";
30
+ export type { BasicLogger } from "./logging/logger";
31
+ export { parseJsonStream, safeJsonStringify } from "./parse/json";
32
+ export { formatHumanReadableDate } from "./parse/time";
33
+ export { validateWithZod, zodToJsonSchema } from "./parse/zod";
34
+ export {
35
+ formatFileContentBlock,
36
+ formatUserInputBlock,
37
+ normalizeUserInput,
38
+ xmlTagsRemoval,
39
+ } from "./prompt/format";
40
+ export type {
41
+ RpcAddProviderActionRequest,
42
+ RpcAgentMode,
43
+ RpcChatAttachmentFile,
44
+ RpcChatAttachments,
45
+ RpcChatMessage,
46
+ RpcChatRunTurnRequest,
47
+ RpcChatRuntimeConfigBase,
48
+ RpcChatRuntimeLoggerConfig,
49
+ RpcChatStartSessionArtifacts,
50
+ RpcChatStartSessionRequest,
51
+ RpcChatStartSessionResponse,
52
+ RpcChatToolCallResult,
53
+ RpcChatTurnResult,
54
+ RpcClineAccountActionRequest,
55
+ RpcClineAccountBalance,
56
+ RpcClineAccountOrganization,
57
+ RpcClineAccountOrganizationBalance,
58
+ RpcClineAccountOrganizationUsageTransaction,
59
+ RpcClineAccountPaymentTransaction,
60
+ RpcClineAccountUsageTransaction,
61
+ RpcClineAccountUser,
62
+ RpcGetProviderModelsActionRequest,
63
+ RpcListProvidersActionRequest,
64
+ RpcOAuthProviderId,
65
+ RpcProviderActionRequest,
66
+ RpcProviderCapability,
67
+ RpcProviderCatalogResponse,
68
+ RpcProviderListItem,
69
+ RpcProviderModel,
70
+ RpcProviderModelsResponse,
71
+ RpcProviderOAuthLoginResponse,
72
+ RpcProviderSettingsActionRequest,
73
+ RpcSaveProviderSettingsActionRequest,
74
+ RpcSessionStorageOptions,
75
+ } from "./rpc/runtime";
76
+ export type {
77
+ TeamProgressCounts,
78
+ TeamProgressLifecycleEvent,
79
+ TeamProgressMemberRole,
80
+ TeamProgressMemberStatus,
81
+ TeamProgressOutcomeFragmentStatus,
82
+ TeamProgressOutcomeStatus,
83
+ TeamProgressProjectionEvent,
84
+ TeamProgressRunStatus,
85
+ TeamProgressSummary,
86
+ TeamProgressTaskStatus,
87
+ } from "./rpc/team-progress";
88
+ export {
89
+ RPC_TEAM_LIFECYCLE_EVENT_TYPE,
90
+ RPC_TEAM_PROGRESS_EVENT_TYPE,
91
+ } from "./rpc/team-progress";
92
+ export type {
93
+ ITelemetryService,
94
+ OpenTelemetryClientConfig,
95
+ TelemetryArray,
96
+ TelemetryMetadata,
97
+ TelemetryObject,
98
+ TelemetryPrimitive,
99
+ TelemetryProperties,
100
+ TelemetryValue,
101
+ } from "./services/telemetry";
102
+ export type { ClineTelemetryServiceConfig } from "./services/telemetry-config";
103
+ export {
104
+ createClineTelemetryServiceConfig,
105
+ createClineTelemetryServiceMetadata,
106
+ } from "./services/telemetry-config";
107
+ export type {
108
+ HookSessionContext,
109
+ HookSessionContextLookup,
110
+ HookSessionContextProvider,
111
+ } from "./session/hook-context";
112
+ export {
113
+ resolveHookLogPath,
114
+ resolveHookSessionContext,
115
+ resolveRootSessionId,
116
+ } from "./session/hook-context";
117
+ export type {
118
+ SessionLineage,
119
+ SessionRuntimeRecordShape,
120
+ SharedSessionStatus,
121
+ } from "./session/records";
122
+ export { SESSION_STATUS_VALUES } from "./session/records";
123
+ export type {
124
+ AgentMode,
125
+ SessionExecutionConfig,
126
+ SessionPromptConfig,
127
+ SessionWorkspaceConfig,
128
+ } from "./session/runtime-config";
129
+ export type { RuntimeEnv } from "./session/runtime-env";
130
+ export type { VcrRecording } from "./vcr";
131
+ export { initVcr } from "./vcr";
@@ -0,0 +1,154 @@
1
+ export const MODELS_DEV_PROVIDER_KEY_ENTRIES: ReadonlyArray<{
2
+ modelsDevKey: string;
3
+ generatedProviderId?: string;
4
+ runtimeProviderId?: string;
5
+ }> = [
6
+ {
7
+ modelsDevKey: "openai",
8
+ generatedProviderId: "openai",
9
+ runtimeProviderId: "openai-native",
10
+ },
11
+ {
12
+ modelsDevKey: "openai",
13
+ generatedProviderId: "openai",
14
+ runtimeProviderId: "openai-codex",
15
+ },
16
+ {
17
+ modelsDevKey: "anthropic",
18
+ generatedProviderId: "anthropic",
19
+ },
20
+ {
21
+ modelsDevKey: "anthropic",
22
+ generatedProviderId: "anthropic",
23
+ runtimeProviderId: "claude-code",
24
+ },
25
+ {
26
+ modelsDevKey: "google",
27
+ generatedProviderId: "gemini",
28
+ },
29
+ {
30
+ modelsDevKey: "deepseek",
31
+ generatedProviderId: "deepseek",
32
+ },
33
+ { modelsDevKey: "xai", generatedProviderId: "xai" },
34
+ {
35
+ modelsDevKey: "togetherai",
36
+ runtimeProviderId: "together",
37
+ generatedProviderId: "together",
38
+ },
39
+ {
40
+ modelsDevKey: "sap-ai-core",
41
+ runtimeProviderId: "sapaicore",
42
+ generatedProviderId: "sapaicore",
43
+ },
44
+ {
45
+ modelsDevKey: "fireworks-ai",
46
+ runtimeProviderId: "fireworks",
47
+ generatedProviderId: "fireworks",
48
+ },
49
+ {
50
+ modelsDevKey: "groq",
51
+ runtimeProviderId: "groq",
52
+ generatedProviderId: "groq",
53
+ },
54
+ {
55
+ modelsDevKey: "cerebras",
56
+ runtimeProviderId: "cerebras",
57
+ generatedProviderId: "cerebras",
58
+ },
59
+ {
60
+ modelsDevKey: "sambanova",
61
+ runtimeProviderId: "sambanova",
62
+ generatedProviderId: "sambanova",
63
+ },
64
+ {
65
+ modelsDevKey: "nebius",
66
+ runtimeProviderId: "nebius",
67
+ generatedProviderId: "nebius",
68
+ },
69
+ {
70
+ modelsDevKey: "huggingface",
71
+ runtimeProviderId: "huggingface",
72
+ generatedProviderId: "huggingface",
73
+ },
74
+ {
75
+ modelsDevKey: "openrouter",
76
+ runtimeProviderId: "cline",
77
+ generatedProviderId: "openrouter",
78
+ },
79
+ { modelsDevKey: "ollama", runtimeProviderId: "ollama-cloud" },
80
+ { modelsDevKey: "ollama-cloud", generatedProviderId: "ollama" },
81
+ {
82
+ modelsDevKey: "vercel",
83
+ runtimeProviderId: "dify",
84
+ generatedProviderId: "vercel-ai-gateway",
85
+ },
86
+ {
87
+ modelsDevKey: "vercel",
88
+ generatedProviderId: "vercel-ai-gateway",
89
+ },
90
+ {
91
+ modelsDevKey: "aihubmix",
92
+ runtimeProviderId: "aihubmix",
93
+ generatedProviderId: "aihubmix",
94
+ },
95
+ { modelsDevKey: "hicap", runtimeProviderId: "hicap" },
96
+ { modelsDevKey: "nous-research", runtimeProviderId: "nousResearch" },
97
+ { modelsDevKey: "huawei-cloud-maas", runtimeProviderId: "huawei-cloud-maas" },
98
+ {
99
+ modelsDevKey: "baseten",
100
+ runtimeProviderId: "baseten",
101
+ generatedProviderId: "baseten",
102
+ },
103
+ {
104
+ modelsDevKey: "google-vertex-anthropic",
105
+ generatedProviderId: "vertex",
106
+ },
107
+ { modelsDevKey: "lmstudio", generatedProviderId: "lmstudio" },
108
+ { modelsDevKey: "zai", generatedProviderId: "zai" },
109
+ { modelsDevKey: "requesty", generatedProviderId: "requesty" },
110
+ { modelsDevKey: "amazon-bedrock", generatedProviderId: "bedrock" },
111
+ { modelsDevKey: "moonshotai", generatedProviderId: "moonshot" },
112
+ { modelsDevKey: "minimax", generatedProviderId: "minimax" },
113
+ ];
114
+
115
+ function buildProviderKeyMap(
116
+ key: "modelsDevKey" | "generatedProviderId",
117
+ ): Record<string, string> {
118
+ return Object.fromEntries(
119
+ MODELS_DEV_PROVIDER_KEY_ENTRIES.flatMap((entry) => {
120
+ const providerId =
121
+ key === "modelsDevKey" ? entry.modelsDevKey : entry.generatedProviderId;
122
+ return providerId ? [[entry.modelsDevKey, providerId]] : [];
123
+ }),
124
+ );
125
+ }
126
+
127
+ export const MODELS_DEV_PROVIDER_KEY_MAP = buildProviderKeyMap(
128
+ "generatedProviderId",
129
+ );
130
+
131
+ function dedupe(values: readonly string[]): string[] {
132
+ return [...new Set(values)];
133
+ }
134
+
135
+ export function resolveProviderModelCatalogKeys(providerId: string): string[] {
136
+ const mapped = MODELS_DEV_PROVIDER_KEY_ENTRIES.flatMap((entry) => {
137
+ if (!entry.generatedProviderId) {
138
+ return [];
139
+ }
140
+ if (
141
+ entry.generatedProviderId === providerId ||
142
+ entry.runtimeProviderId === providerId
143
+ ) {
144
+ return [entry.generatedProviderId];
145
+ }
146
+ return [];
147
+ });
148
+
149
+ if (providerId === "nousResearch") {
150
+ return dedupe([...mapped, "nousresearch", providerId]);
151
+ }
152
+
153
+ return dedupe([...mapped, providerId]);
154
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Types and Zod Schemas for the Agent Package
3
+ *
4
+ * This module defines all TypeScript types and Zod validation schemas
5
+ * for agent configuration, tools, events, and results.
6
+ */
7
+
8
+ import { z } from "zod";
9
+
10
+ // =============================================================================
11
+ // Tool Context
12
+ // =============================================================================
13
+
14
+ /**
15
+ * Context passed to tool execution functions
16
+ */
17
+ export interface ToolContext {
18
+ /** Unique identifier for the agent instance */
19
+ agentId: string;
20
+ /** Unique identifier for the current conversation */
21
+ conversationId: string;
22
+ /** Current iteration number in the agentic loop */
23
+ iteration: number;
24
+ /** Abort signal for cancellation */
25
+ abortSignal?: AbortSignal;
26
+ /** Optional metadata for the tool execution */
27
+ metadata?: Record<string, unknown>;
28
+ }
29
+
30
+ export interface ToolPolicy {
31
+ /**
32
+ * Whether the tool can be executed at all.
33
+ * @default true
34
+ */
35
+ enabled?: boolean;
36
+ /**
37
+ * Whether this tool can run without asking the client for approval.
38
+ * @default true
39
+ */
40
+ autoApprove?: boolean;
41
+ }
42
+
43
+ export const ToolContextSchema = z.object({
44
+ agentId: z.string(),
45
+ conversationId: z.string(),
46
+ iteration: z.number(),
47
+ abortSignal: z.custom<AbortSignal>().optional(),
48
+ metadata: z.record(z.string(), z.unknown()).optional(),
49
+ });
50
+
51
+ // =============================================================================
52
+ // Tool Definition
53
+ // =============================================================================
54
+
55
+ /**
56
+ * A tool that the agent can use
57
+ *
58
+ * @template TInput - The type of the input to the tool
59
+ * @template TOutput - The type of the output from the tool
60
+ */
61
+ export interface Tool<TInput = unknown, TOutput = unknown> {
62
+ /** Unique name for the tool */
63
+ name: string;
64
+ /** Human-readable description of what the tool does */
65
+ description: string;
66
+ /** JSON Schema defining the tool's input parameters */
67
+ inputSchema: Record<string, unknown>;
68
+ /** The function that executes the tool */
69
+ execute: (input: TInput, context: ToolContext) => Promise<TOutput>;
70
+ /**
71
+ * Optional timeout in milliseconds for tool execution
72
+ * @default 30000 (30 seconds)
73
+ */
74
+ timeoutMs?: number;
75
+ /**
76
+ * Whether the tool can be retried on failure
77
+ * @default true
78
+ */
79
+ retryable?: boolean;
80
+ /**
81
+ * Maximum number of retries for this tool
82
+ * @default 2
83
+ */
84
+ maxRetries?: number;
85
+ }
86
+
87
+ // =============================================================================
88
+ // Tool Call Record
89
+ // =============================================================================
90
+
91
+ /**
92
+ * Record of a tool call execution
93
+ */
94
+ export interface ToolCallRecord {
95
+ /** Unique identifier for this tool call */
96
+ id: string;
97
+ /** Name of the tool that was called */
98
+ name: string;
99
+ /** Input passed to the tool */
100
+ input: unknown;
101
+ /** Output returned from the tool (if successful) */
102
+ output: unknown;
103
+ /** Error message (if the tool failed) */
104
+ error?: string;
105
+ /** Time taken to execute the tool in milliseconds */
106
+ durationMs: number;
107
+ /** Timestamp when the tool call started */
108
+ startedAt: Date;
109
+ /** Timestamp when the tool call ended */
110
+ endedAt: Date;
111
+ }
112
+
113
+ export interface ToolApprovalRequest {
114
+ agentId: string;
115
+ conversationId: string;
116
+ iteration: number;
117
+ toolCallId: string;
118
+ toolName: string;
119
+ input: unknown;
120
+ policy: ToolPolicy;
121
+ }
122
+
123
+ export interface ToolApprovalResult {
124
+ approved: boolean;
125
+ reason?: string;
126
+ }
127
+
128
+ export const ToolCallRecordSchema = z.object({
129
+ id: z.string(),
130
+ name: z.string(),
131
+ input: z.unknown(),
132
+ output: z.unknown(),
133
+ error: z.string().optional(),
134
+ durationMs: z.number(),
135
+ startedAt: z.date(),
136
+ endedAt: z.date(),
137
+ });
@@ -0,0 +1,9 @@
1
+ export interface BasicLogger {
2
+ debug?: (message: string, metadata?: Record<string, unknown>) => void;
3
+ info?: (message: string, metadata?: Record<string, unknown>) => void;
4
+ warn?: (message: string, metadata?: Record<string, unknown>) => void;
5
+ error?: (
6
+ message: string,
7
+ metadata?: Record<string, unknown> & { error?: unknown },
8
+ ) => void;
9
+ }
@@ -0,0 +1,43 @@
1
+ import { jsonrepair } from "jsonrepair";
2
+
3
+ function tryParseJson(text: string): unknown {
4
+ return JSON.parse(text);
5
+ }
6
+
7
+ export function parseJsonStream(input: unknown): unknown {
8
+ if (typeof input !== "string") return input;
9
+
10
+ const text = input.trimStart();
11
+ if (!(text.startsWith("{") || text.startsWith("["))) return input;
12
+
13
+ try {
14
+ return tryParseJson(text);
15
+ } catch {
16
+ try {
17
+ return tryParseJson(jsonrepair(text));
18
+ } catch {
19
+ return input;
20
+ }
21
+ }
22
+ }
23
+
24
+ export function safeJsonStringify(input: unknown): string {
25
+ const seen = new WeakSet<object>();
26
+
27
+ try {
28
+ const result = JSON.stringify(input, (_key, value) => {
29
+ if (typeof value === "bigint") return value.toString();
30
+
31
+ if (value && typeof value === "object") {
32
+ if (seen.has(value as object)) return "[Circular]";
33
+ seen.add(value as object);
34
+ }
35
+
36
+ return value;
37
+ });
38
+
39
+ return result ?? "null";
40
+ } catch {
41
+ return String(input);
42
+ }
43
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Parses a date string and returns a human-readable format.
3
+ * If the input is invalid, it returns the original string or a placeholder.
4
+ *
5
+ * @param dateStr - The date string to parse.
6
+ * @returns A human-readable date string or the original input if invalid.
7
+ */
8
+ export function formatHumanReadableDate(dateStr?: string): string {
9
+ if (!dateStr) return "(unknown-date)";
10
+ const date = new Date(dateStr);
11
+ if (Number.isNaN(date.getTime())) return dateStr;
12
+ return date.toLocaleString("en-US", {
13
+ year: "numeric",
14
+ month: "numeric",
15
+ day: "numeric",
16
+ hour: "numeric",
17
+ minute: "numeric",
18
+ second: "numeric",
19
+ hour12: true,
20
+ });
21
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Zod Utilities
3
+ *
4
+ * Helper functions for working with Zod schemas.
5
+ */
6
+
7
+ import { z } from "zod";
8
+
9
+ /**
10
+ * Validate input using a Zod schema
11
+ * Throws a formatted error if validation fails
12
+ */
13
+ export function validateWithZod<T>(schema: z.ZodType<T>, input: unknown): T {
14
+ const result = schema.safeParse(input);
15
+ if (!result.success) {
16
+ throw new Error(z.prettifyError(result.error));
17
+ }
18
+ return result.data;
19
+ }
20
+
21
+ export function zodToJsonSchema(schema: z.ZodTypeAny): Record<string, unknown> {
22
+ return z.toJSONSchema(schema);
23
+ }
@@ -0,0 +1,22 @@
1
+ export function formatFileContentBlock(path: string, content: string): string {
2
+ return `<file_content path="${path}">\n${content}\n</file_content>`;
3
+ }
4
+
5
+ export function formatUserInputBlock(
6
+ input: string,
7
+ mode: "act" | "plan" = "act",
8
+ ): string {
9
+ return `<user_input mode="${mode}">${input}</user_input>`;
10
+ }
11
+
12
+ export function normalizeUserInput(input?: string): string {
13
+ if (!input?.trim()) return "";
14
+ return xmlTagsRemoval(input, "user_input");
15
+ }
16
+
17
+ export function xmlTagsRemoval(input?: string, tag?: string): string {
18
+ if (!input?.trim()) return "";
19
+ if (!tag) return input;
20
+ const regex = new RegExp(`<${tag}.*?>(.*?)</${tag}>`, "g");
21
+ return input.replace(regex, "$1");
22
+ }