@cline/core 0.0.58 → 0.0.59
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/dist/ClineCore.d.ts +15 -2
- package/dist/cline-core/runtime-services.d.ts +2 -2
- package/dist/extensions/context/compaction.d.ts +7 -0
- package/dist/extensions/tools/team/delegated-agent.d.ts +1 -1
- package/dist/hub/daemon/entry.js +186 -182
- package/dist/hub/daemon/telemetry.d.ts +19 -0
- package/dist/hub/index.js +183 -179
- package/dist/hub/runtime-host/hub-runtime-host.d.ts +7 -1
- package/dist/hub/server/handlers/context.d.ts +5 -2
- package/dist/hub/server/handlers/session-handlers.d.ts +5 -0
- package/dist/hub/server/hub-session-records.d.ts +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +182 -178
- package/dist/runtime/config/connection-update.d.ts +13 -0
- package/dist/runtime/host/local-runtime-host.d.ts +11 -1
- package/dist/runtime/host/runtime-host.d.ts +11 -0
- package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +2 -11
- package/dist/services/providers/local-provider-service.d.ts +8 -0
- package/dist/services/session-artifacts.d.ts +1 -0
- package/dist/services/telemetry/index.js +1 -1
- package/dist/session/models/session-compaction.d.ts +22 -0
- package/dist/session/models/session-manifest.d.ts +1 -0
- package/dist/session/models/session-row.d.ts +1 -0
- package/dist/session/services/persistence-service.d.ts +5 -0
- package/dist/session/stores/atomic-file.d.ts +1 -0
- package/dist/session/stores/session-manifest-store.d.ts +18 -0
- package/dist/types/config.d.ts +4 -0
- package/dist/types/session.d.ts +3 -0
- package/package.json +4 -4
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { CoreSessionConfig } from "../../types/config";
|
|
2
|
+
export interface ConnectionUpdate {
|
|
3
|
+
providerId?: string;
|
|
4
|
+
modelId?: string;
|
|
5
|
+
apiKey?: string;
|
|
6
|
+
baseUrl?: string;
|
|
7
|
+
headers?: Record<string, string>;
|
|
8
|
+
providerConfig?: CoreSessionConfig["providerConfig"];
|
|
9
|
+
reasoningEffort?: CoreSessionConfig["reasoningEffort"] | null;
|
|
10
|
+
thinking?: CoreSessionConfig["thinking"] | null;
|
|
11
|
+
thinkingBudgetTokens?: CoreSessionConfig["thinkingBudgetTokens"] | null;
|
|
12
|
+
}
|
|
13
|
+
export declare function normalizeConnectionUpdate(updates: ConnectionUpdate): ConnectionUpdate;
|
|
@@ -2,6 +2,7 @@ import type * as LlmsProviders from "@cline/llms";
|
|
|
2
2
|
import { type AgentConfig, type AgentResult, type ITelemetryService } from "@cline/shared";
|
|
3
3
|
import type { HookEventPayload } from "../../hooks";
|
|
4
4
|
import { ProviderSettingsManager } from "../../services/storage/provider-settings-manager";
|
|
5
|
+
import { type SessionCompactionState } from "../../session/models/session-compaction";
|
|
5
6
|
import type { CoreSessionConfig } from "../../types/config";
|
|
6
7
|
import type { CoreSessionEvent } from "../../types/events";
|
|
7
8
|
import type { SessionRecord } from "../../types/sessions";
|
|
@@ -10,7 +11,7 @@ import { RuntimeOAuthTokenManager } from "../orchestration/runtime-oauth-token-m
|
|
|
10
11
|
import type { RuntimeBuilder } from "../orchestration/session-runtime";
|
|
11
12
|
import { SessionRuntime } from "../orchestration/session-runtime-orchestrator";
|
|
12
13
|
import { type SessionBackend } from "./local/session-record";
|
|
13
|
-
import type { PendingPromptsServiceApi, RestoreSessionInput, RestoreSessionResult, RuntimeHost, RuntimeHostSubscribeOptions, SendSessionInput, SessionUsageSummary, StartSessionInput, StartSessionResult } from "./runtime-host";
|
|
14
|
+
import type { PendingPromptsServiceApi, RestoreSessionInput, RestoreSessionResult, RuntimeHost, RuntimeHostSubscribeOptions, SendSessionInput, SessionConnectionUpdate, SessionUsageSummary, StartSessionInput, StartSessionResult } from "./runtime-host";
|
|
14
15
|
export interface LocalRuntimeHostOptions {
|
|
15
16
|
distinctId?: string;
|
|
16
17
|
sessionService: SessionBackend;
|
|
@@ -68,10 +69,19 @@ export declare class LocalRuntimeHost implements RuntimeHost {
|
|
|
68
69
|
}): Promise<{
|
|
69
70
|
updated: boolean;
|
|
70
71
|
}>;
|
|
72
|
+
updateSessionCompactionState(sessionId: string, state: SessionCompactionState): Promise<{
|
|
73
|
+
updated: boolean;
|
|
74
|
+
}>;
|
|
75
|
+
readSessionCompactionState(sessionId: string): Promise<SessionCompactionState | undefined>;
|
|
76
|
+
private isCompactionStateForSession;
|
|
77
|
+
private canPersistCompactionState;
|
|
78
|
+
private persistActiveSessionCompactionState;
|
|
79
|
+
private enqueueCompactionStateWrite;
|
|
71
80
|
readSessionMessages(sessionId: string): Promise<LlmsProviders.Message[]>;
|
|
72
81
|
dispatchHookEvent(payload: HookEventPayload): Promise<void>;
|
|
73
82
|
subscribe(listener: (event: CoreSessionEvent) => void, options?: RuntimeHostSubscribeOptions): () => void;
|
|
74
83
|
updateSessionModel(sessionId: string, modelId: string): Promise<void>;
|
|
84
|
+
updateSessionConnection(sessionId: string, rawUpdates: SessionConnectionUpdate): Promise<void>;
|
|
75
85
|
handlePluginEvent(rootSessionId: string, event: {
|
|
76
86
|
name: string;
|
|
77
87
|
payload?: unknown;
|
|
@@ -3,12 +3,14 @@ import type { AgentMode, AgentResult, RuntimeConfigExtensionKind } from "@cline/
|
|
|
3
3
|
import type { HookEventPayload } from "../../hooks";
|
|
4
4
|
import type { CheckpointEntry } from "../../hooks/checkpoint-hooks";
|
|
5
5
|
import type { ProviderSettings } from "../../services/llms/provider-settings";
|
|
6
|
+
import type { SessionCompactionState } from "../../session/models/session-compaction";
|
|
6
7
|
import type { SessionManifest } from "../../session/models/session-manifest";
|
|
7
8
|
import type { SessionSource } from "../../types/common";
|
|
8
9
|
import type { CoreSessionConfig } from "../../types/config";
|
|
9
10
|
import type { CoreSessionEvent, SessionPendingPrompt } from "../../types/events";
|
|
10
11
|
import type { SessionRecord } from "../../types/sessions";
|
|
11
12
|
import type { RuntimeCapabilities } from "../capabilities";
|
|
13
|
+
import type { ConnectionUpdate } from "../config/connection-update";
|
|
12
14
|
export declare const SESSION_NOT_FOUND_ERROR_CODE = "session_not_found";
|
|
13
15
|
export declare class SessionNotFoundError extends Error {
|
|
14
16
|
readonly sessionId?: string | undefined;
|
|
@@ -48,6 +50,7 @@ export interface StartSessionInput {
|
|
|
48
50
|
interactive?: boolean;
|
|
49
51
|
sessionMetadata?: Record<string, unknown>;
|
|
50
52
|
initialMessages?: LlmsProviders.Message[];
|
|
53
|
+
initialCompactionState?: SessionCompactionState;
|
|
51
54
|
userImages?: string[];
|
|
52
55
|
userFiles?: string[];
|
|
53
56
|
/**
|
|
@@ -122,9 +125,13 @@ export interface PendingPromptsRuntimeService {
|
|
|
122
125
|
export interface SessionUsageRuntimeService {
|
|
123
126
|
getAccumulatedUsage(sessionId: string): Promise<SessionUsageSummary | undefined>;
|
|
124
127
|
}
|
|
128
|
+
export type SessionConnectionUpdate = ConnectionUpdate;
|
|
125
129
|
export interface SessionModelRuntimeService {
|
|
126
130
|
updateSessionModel(sessionId: string, modelId: string): Promise<void>;
|
|
127
131
|
}
|
|
132
|
+
export interface SessionConnectionRuntimeService {
|
|
133
|
+
updateSessionConnection(sessionId: string, updates: SessionConnectionUpdate): Promise<void>;
|
|
134
|
+
}
|
|
128
135
|
export interface RuntimeHostSubscribeOptions {
|
|
129
136
|
sessionId?: string;
|
|
130
137
|
}
|
|
@@ -168,6 +175,10 @@ export interface RuntimeHost {
|
|
|
168
175
|
}): Promise<{
|
|
169
176
|
updated: boolean;
|
|
170
177
|
}>;
|
|
178
|
+
updateSessionCompactionState(sessionId: string, state: SessionCompactionState): Promise<{
|
|
179
|
+
updated: boolean;
|
|
180
|
+
}>;
|
|
181
|
+
readSessionCompactionState(sessionId: string): Promise<SessionCompactionState | undefined>;
|
|
171
182
|
readSessionMessages(sessionId: string): Promise<LlmsProviders.Message[]>;
|
|
172
183
|
dispatchHookEvent(payload: HookEventPayload): Promise<void>;
|
|
173
184
|
subscribe(listener: (event: CoreSessionEvent) => void, options?: RuntimeHostSubscribeOptions): () => void;
|
|
@@ -22,6 +22,7 @@ import type { AgentRuntime } from "@cline/agents";
|
|
|
22
22
|
import { createAgentRuntime } from "@cline/agents";
|
|
23
23
|
import { type AgentConfig, type AgentEvent, type AgentExtensionRegistry, type AgentResult, type AgentTool, type BasicLogger, type ITelemetryService, type Message, type MessageWithMetadata } from "@cline/shared";
|
|
24
24
|
import { MessageBuilder } from "../../session/services/message-builder";
|
|
25
|
+
import { type ConnectionUpdate } from "../config/connection-update";
|
|
25
26
|
/**
|
|
26
27
|
* Listener invoked for every legacy `AgentEvent` produced by the
|
|
27
28
|
* session runtime. Use `subscribeEvents(listener)` — it returns an
|
|
@@ -39,17 +40,7 @@ export interface SessionRuntimeOrchestratorDeps {
|
|
|
39
40
|
readonly createAgentRuntimeImpl?: (config: Parameters<typeof createAgentRuntime>[0]) => AgentRuntime;
|
|
40
41
|
}
|
|
41
42
|
/** Connection overrides applied via `updateConnection`. */
|
|
42
|
-
export
|
|
43
|
-
providerId?: string;
|
|
44
|
-
modelId?: string;
|
|
45
|
-
apiKey?: string;
|
|
46
|
-
baseUrl?: string;
|
|
47
|
-
headers?: Record<string, string>;
|
|
48
|
-
providerConfig?: unknown;
|
|
49
|
-
reasoningEffort?: AgentConfig["reasoningEffort"];
|
|
50
|
-
thinking?: boolean;
|
|
51
|
-
thinkingBudgetTokens?: number;
|
|
52
|
-
}
|
|
43
|
+
export type ConnectionOverrides = ConnectionUpdate;
|
|
53
44
|
/**
|
|
54
45
|
* Per-session orchestrator. Construct once per agent session; call
|
|
55
46
|
* `run` / `continue` repeatedly. The class matches the subset of
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { AddProviderActionRequest, ITelemetryService, ProviderCapability, ProviderListItem, ProviderModel, SaveProviderSettingsActionRequest } from "@cline/shared";
|
|
2
2
|
import { type ProviderOAuthCredentials } from "../../auth/provider-auth-registry";
|
|
3
3
|
import type { ProviderClient, ProviderConfig, ProviderProtocol, ProviderSettings } from "../../services/llms/provider-settings";
|
|
4
|
+
import type { ProviderTokenSource } from "../../types/provider-settings";
|
|
4
5
|
import type { ProviderSettingsManager } from "../storage/provider-settings-manager";
|
|
5
6
|
export { ensureCustomProvidersLoaded } from "./local-provider-registry";
|
|
6
7
|
export interface ListLocalProvidersOptions {
|
|
@@ -40,6 +41,13 @@ export declare function deleteLocalProvider(manager: ProviderSettingsManager, re
|
|
|
40
41
|
settingsPath: string;
|
|
41
42
|
modelsPath: string;
|
|
42
43
|
}>;
|
|
44
|
+
export declare function markLocalProviderEnabled(manager: ProviderSettingsManager, providerId: string, options?: {
|
|
45
|
+
tokenSource?: ProviderTokenSource;
|
|
46
|
+
}): {
|
|
47
|
+
providerId: string;
|
|
48
|
+
enabled: true;
|
|
49
|
+
settingsPath: string;
|
|
50
|
+
};
|
|
43
51
|
export declare function listLocalProviders(manager: ProviderSettingsManager, options?: ListLocalProvidersOptions): Promise<{
|
|
44
52
|
providers: ProviderListItem[];
|
|
45
53
|
settingsPath: string;
|
|
@@ -9,6 +9,7 @@ export declare class SessionArtifacts {
|
|
|
9
9
|
sessionArtifactsDir(sessionId: string): string;
|
|
10
10
|
ensureSessionArtifactsDir(sessionId: string): string;
|
|
11
11
|
sessionMessagesPath(sessionId: string): string;
|
|
12
|
+
sessionCompactionPath(sessionId: string): string;
|
|
12
13
|
sessionManifestPath(sessionId: string, ensureDir?: boolean): string;
|
|
13
14
|
removeSessionDirIfEmpty(sessionId: string): void;
|
|
14
15
|
removeSessionDir(sessionId: string): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as j,mkdirSync as L,readFileSync as R,writeFileSync as U}from"node:fs";import{resolve as W}from"node:path";import{resolveSessionDataDir as F}from"@cline/shared/storage";import{nanoid as H}from"nanoid";import*as I from"node-machine-id";var J="machine-id";function u(e){let t=e?.trim();if(t)return t;let a=$();if(a)return a;return x()}function V(){let e=I;return e.machineIdSync??e.default?.machineIdSync}function $(){try{let e=V();if(!e)return;return e().trim()||void 0}catch{return}}function x(){let e=F(),t=W(e,J);try{if(j(t)){let i=R(t,"utf8").trim();if(i.length>0)return i}}catch{}let a=`cl-${H()}`;try{L(e,{recursive:!0}),U(t,a,"utf8")}catch{}return a}class b{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(e){this.name=e.name??"OpenTelemetryAdapter",this.metadata={...e.metadata},this.meterProvider=e.meterProvider,this.loggerProvider=e.loggerProvider,this.meter=e.meterProvider?.getMeter("cline")??null,this.logger=e.loggerProvider?.getLogger("cline")??null,this.enabled=e.enabled??!0,this.distinctId=e.distinctId,this.commonProperties=e.commonProperties?{...e.commonProperties}:{}}emit(e,t){if(!this.isEnabled())return;this.emitLog(e,t,!1)}emitRequired(e,t){this.emitLog(e,t,!0)}recordCounter(e,t,a,i,l=!1){if(!this.meter||!l&&!this.isEnabled())return;let r=this.counters.get(e);if(!r)r=this.meter.createCounter(e,i?{description:i}:void 0),this.counters.set(e,r);r.add(t,this.flattenProperties(this.buildAttributes(a)))}recordHistogram(e,t,a,i,l=!1){if(!this.meter||!l&&!this.isEnabled())return;let r=this.histograms.get(e);if(!r)r=this.meter.createHistogram(e,i?{description:i}:void 0),this.histograms.set(e,r);r.record(t,this.flattenProperties(this.buildAttributes(a)))}recordGauge(e,t,a,i,l=!1){if(!this.meter||!l&&!this.isEnabled())return;let r=this.buildAttributes(a),d=JSON.stringify(r),g=this.gaugeValues.get(e);if(t===null){if(g){if(g.delete(d),g.size===0)this.gaugeValues.delete(e),this.gauges.delete(e)}return}let n=g;if(!n)n=new Map,this.gaugeValues.set(e,n);if(!this.gauges.has(e)){let s=this.meter.createObservableGauge(e,i?{description:i}:void 0);s.addCallback((c)=>{for(let A of this.snapshotGaugeSeries(e))c.observe(A.value,this.flattenProperties(A.attributes))}),this.gauges.set(e,s)}n.set(d,{value:t,attributes:r})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(e){this.distinctId=e}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(e,t,a){if(!this.logger)return;let i=this.flattenProperties(this.buildAttributes(t,a));this.logger.emit({severityText:"INFO",body:e,attributes:i})}buildAttributes(e,t=!1){return{...this.commonProperties,...this.metadata,...e,...this.distinctId?{distinct_id:this.distinctId}:{},...t?{_required:!0}:{}}}snapshotGaugeSeries(e){let t=this.gaugeValues.get(e);if(!t)return[];return Array.from(t.values(),(a)=>({value:a.value,attributes:a.attributes?{...a.attributes}:void 0}))}flattenProperties(e,t="",a=new WeakSet,i=0){if(!e)return{};let l={},r=100,d=10;for(let[g,n]of Object.entries(e)){if(g==="__proto__"||g==="constructor"||g==="prototype")continue;let s=t?`${t}.${g}`:g;if(n===null||n===void 0){l[s]=String(n);continue}if(Array.isArray(n)){let c=n.length>r?n.slice(0,r):n;try{l[s]=JSON.stringify(c)}catch{l[s]="[UnserializableArray]"}if(n.length>r)l[`${s}_truncated`]=!0,l[`${s}_original_length`]=n.length;continue}if(typeof n==="object"){if(n instanceof Date){l[s]=n.toISOString();continue}if(n instanceof Error){l[s]=n.message;continue}if(a.has(n)){l[s]="[Circular]";continue}if(i>=d){l[s]="[MaxDepthExceeded]";continue}a.add(n),Object.assign(l,this.flattenProperties(n,s,a,i+1));continue}if(B(n)){l[s]=n;continue}try{l[s]=JSON.stringify(n)}catch{l[s]=String(n)}}return l}}function B(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}import{metrics as Y,trace as D}from"@opentelemetry/api";import{logs as q}from"@opentelemetry/api-logs";import{OTLPLogExporter as p}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as ee}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as te}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as ae}from"@opentelemetry/resources";import{BatchLogRecordProcessor as le,ConsoleLogRecordExporter as ie,LoggerProvider as re}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as ne,MeterProvider as se,PeriodicExportingMetricReader as C}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as de,ConsoleSpanExporter as ge,SimpleSpanProcessor as fe}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as ue}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as be,ATTR_SERVICE_VERSION as oe}from"@opentelemetry/semantic-conventions";import{mkdirSync as Re,readFileSync as N,statSync as K,writeFileSync as Ue}from"node:fs";import{resolveGlobalSettingsPath as Q}from"@cline/shared/storage";import{z as f}from"zod";import{AGENT_UNEXPECTED_REASONING_TOKENS_EVENT as Ce,captureAgentUnexpectedReasoningTokens as we,SDK_ERROR_TELEMETRY_EVENT as ze}from"@cline/shared";var O=f.preprocess((e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string").map((t)=>t.trim()).filter(Boolean):void 0,f.array(f.string()).optional()).transform((e)=>{if(!e)return;let t=[...new Set(e)].sort((a,i)=>a.localeCompare(i));return t.length>0?t:void 0}),Z=f.enum(["basic","agentic"]).catch("basic"),v=f.object({telemetryOptOut:f.boolean().default(!1).catch(!1),autoUpdateEnabled:f.boolean().default(!0).catch(!0),compactionStrategy:Z.optional(),disabledTools:O.optional(),disabledPlugins:O.optional()}).strip().transform((e)=>{let t={autoUpdateEnabled:e.autoUpdateEnabled,telemetryOptOut:e.telemetryOptOut};if(e.compactionStrategy)t.compactionStrategy=e.compactionStrategy;if(e.disabledTools?.length)t.disabledTools=e.disabledTools;if(e.disabledPlugins?.length)t.disabledPlugins=e.disabledPlugins;return t});function o(){return v.parse({})}var h;function _(e){if(e.disabledTools)Object.freeze(e.disabledTools);if(e.disabledPlugins)Object.freeze(e.disabledPlugins);return Object.freeze(e)}function k(e){let t;try{t=N(e,"utf8")}catch{return o()}try{let a=v.safeParse(JSON.parse(t));return a.success?a.data:o()}catch{return o()}}function E(){let e=Q(),t=K(e,{throwIfNoEntry:!1}),a=t?.mtimeMs??0,i=t?.size??0,l=h;if(l&&l.path===e&&l.mtimeMs===a&&l.size===i)return l;let r=_(t?k(e):o());return h={path:e,mtimeMs:a,size:i,value:r},h}function X(){return E().value}function G(){return X().telemetryOptOut}class P{name;logger;enabled;constructor(e={}){this.name=e.name??"TelemetryLoggerSink",this.logger=e.logger,this.enabled=e.enabled??!0}emit(e,t){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:e,properties:t})}emitRequired(e,t){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:e,properties:t})}recordCounter(e,t,a,i,l){if(!l&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:e,value:t,attributes:a,description:i,required:l===!0})}recordHistogram(e,t,a,i,l){if(!l&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:e,value:t,attributes:a,description:i,required:l===!0})}recordGauge(e,t,a,i,l){if(!l&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:e,value:t,attributes:a,description:i,required:l===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class m{adapters;metadata;distinctId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new P({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.commonProperties={...e.commonProperties??{}}}addAdapter(e){this.adapters.push(e)}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return this.adapters.some((e)=>e.isEnabled())}capture(e){let t=this.buildAttributes(e.properties);for(let a of this.adapters)a.emit(e.event,t)}captureRequired(e,t){let a=this.buildAttributes(t);for(let i of this.adapters)i.emitRequired(e,a)}recordCounter(e,t,a,i,l=!1){let r=this.buildAttributes(a);for(let d of this.adapters)d.recordCounter(e,t,r,i,l)}recordHistogram(e,t,a,i,l=!1){let r=this.buildAttributes(a);for(let d of this.adapters)d.recordHistogram(e,t,r,i,l)}recordGauge(e,t,a,i,l=!1){let r=this.buildAttributes(a);for(let d of this.adapters)d.recordGauge(e,t,r,i,l)}async flush(){await Promise.all(this.adapters.map((e)=>e.flush()))}async dispose(){await Promise.all(this.adapters.map((e)=>e.dispose()))}buildAttributes(e){return{...this.commonProperties,...e,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class w{distinctId;metadata;commonProperties;constructor(e={}){this.distinctId=e.distinctId,this.metadata={...e.metadata??{}},this.commonProperties={...e.commonProperties??{}}}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return!1}capture(e){this.resolveProperties(e.properties)}captureRequired(e,t){this.resolveProperties(t)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(e){return{...this.commonProperties,...e,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class T{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=ae({[be]:e.serviceName??"cline",...e.serviceVersion?{[oe]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)Y.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)q.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return D.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new b({...e,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(e){let t=this.createAdapter({name:e.name,enabled:this.options.enabled,metadata:e.metadata});return new m({...e,adapters:[t],distinctId:u(e.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(e){let t=y(this.options.metricsExporter);if(t.length===0)return null;let a=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),i=Math.min(30000,Math.floor(a*0.8)),l=t.map((r)=>Pe(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:a,timeout:i})).filter((r)=>r!==null);if(l.length===0)return null;return new se({resource:e,readers:l})}createTracerProvider(e){let t=y(this.options.tracesExporter);if(t.length===0)return null;let a=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,i=this.options.otlpTracesHeaders??this.options.otlpHeaders,l=[];for(let r of t){let d=he(r,{endpoint:a,headers:i,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(d)l.push(d)}if(l.length===0)return null;return new ue({resource:e,spanProcessors:l})}createLoggerProvider(e){let t=y(this.options.logsExporter);if(t.length===0)return null;let a=t.map((i)=>{let l=ce(i,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!l)return null;return new le(l,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((i)=>i!==null);if(a.length===0)return null;return new re({resource:e,processors:a})}}function z(e){let t=new T(e),a=t.createTelemetryService(e);return a.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:e.enabled??!0,logsExporter:Array.isArray(e.logsExporter)?e.logsExporter.join(","):e.logsExporter,metricsExporter:Array.isArray(e.metricsExporter)?e.metricsExporter.join(","):e.metricsExporter,tracesExporter:Array.isArray(e.tracesExporter)?e.tracesExporter.join(","):e.tracesExporter,otlpProtocol:e.otlpProtocol,hasOtlpEndpoint:Boolean(e.otlpEndpoint),serviceName:e.serviceName,serviceVersion:e.serviceVersion}),{provider:t,telemetry:a}}function M(e){if(G())return{telemetry:new w(e)};if(e.enabled!==!0)return{telemetry:new m({...e,distinctId:u(e.distinctId)})};return z(e)}function me(e){let{telemetry:t,provider:a}=M(e);return{telemetry:t,provider:a,flush:async()=>{let r=a;if(r&&typeof r.forceFlush==="function")try{await r.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([t.dispose(),a?.dispose()])}}}function y(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((a)=>a.trim()).filter((a)=>a==="console"||a==="otlp")}function ce(e,t){if(e==="console")return new ie;if(!t.endpoint)return null;let a=S(t.endpoint,"/v1/logs");return new p({url:a,headers:t.headers})}function he(e,t){if(e==="console")return new fe(new ge);if(!t.endpoint)return null;let a=S(t.endpoint,"/v1/traces");return new de(new te({url:a,headers:t.headers}))}function Pe(e,t){if(e==="console")return new C({exporter:new ne,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let a=S(t.endpoint,"/v1/metrics");return new C({exporter:new ee({url:a,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function S(e,t){let a=new URL(e),i=a.pathname.endsWith("/")?a.pathname.slice(0,-1):a.pathname;return a.pathname=i.endsWith(t)?i:`${i}${t}`,a.toString()}export{u as resolveCoreDistinctId,z as createOpenTelemetryTelemetryService,M as createConfiguredTelemetryService,me as createConfiguredTelemetryHandle,T as OpenTelemetryProvider,b as OpenTelemetryAdapter};
|
|
1
|
+
import{existsSync as j,mkdirSync as L,readFileSync as R,writeFileSync as U}from"node:fs";import{resolve as W}from"node:path";import{resolveSessionDataDir as F}from"@cline/shared/storage";import{nanoid as H}from"nanoid";import*as J from"node-machine-id";var V="machine-id";function u(e){let t=e?.trim();if(t)return t;let a=x();if(a)return a;return I()}function $(){let e=J;return e.machineIdSync??e.default?.machineIdSync}function x(){try{let e=$();if(!e)return;return e().trim()||void 0}catch{return}}function I(){let e=F(),t=W(e,V);try{if(j(t)){let i=R(t,"utf8").trim();if(i.length>0)return i}}catch{}let a=`cl-${H()}`;try{L(e,{recursive:!0}),U(t,a,"utf8")}catch{}return a}class b{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(e){this.name=e.name??"OpenTelemetryAdapter",this.metadata={...e.metadata},this.meterProvider=e.meterProvider,this.loggerProvider=e.loggerProvider,this.meter=e.meterProvider?.getMeter("cline")??null,this.logger=e.loggerProvider?.getLogger("cline")??null,this.enabled=e.enabled??!0,this.distinctId=e.distinctId,this.commonProperties=e.commonProperties?{...e.commonProperties}:{}}emit(e,t){if(!this.isEnabled())return;this.emitLog(e,t,!1)}emitRequired(e,t){this.emitLog(e,t,!0)}recordCounter(e,t,a,i,l=!1){if(!this.meter||!l&&!this.isEnabled())return;let r=this.counters.get(e);if(!r)r=this.meter.createCounter(e,i?{description:i}:void 0),this.counters.set(e,r);r.add(t,this.flattenProperties(this.buildAttributes(a)))}recordHistogram(e,t,a,i,l=!1){if(!this.meter||!l&&!this.isEnabled())return;let r=this.histograms.get(e);if(!r)r=this.meter.createHistogram(e,i?{description:i}:void 0),this.histograms.set(e,r);r.record(t,this.flattenProperties(this.buildAttributes(a)))}recordGauge(e,t,a,i,l=!1){if(!this.meter||!l&&!this.isEnabled())return;let r=this.buildAttributes(a),d=JSON.stringify(r),g=this.gaugeValues.get(e);if(t===null){if(g){if(g.delete(d),g.size===0)this.gaugeValues.delete(e),this.gauges.delete(e)}return}let n=g;if(!n)n=new Map,this.gaugeValues.set(e,n);if(!this.gauges.has(e)){let s=this.meter.createObservableGauge(e,i?{description:i}:void 0);s.addCallback((c)=>{for(let A of this.snapshotGaugeSeries(e))c.observe(A.value,this.flattenProperties(A.attributes))}),this.gauges.set(e,s)}n.set(d,{value:t,attributes:r})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(e){this.distinctId=e}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(e,t,a){if(!this.logger)return;let i=this.flattenProperties(this.buildAttributes(t,a));this.logger.emit({severityText:"INFO",body:e,attributes:i})}buildAttributes(e,t=!1){return{...this.commonProperties,...this.metadata,...e,...this.distinctId?{distinct_id:this.distinctId}:{},...t?{_required:!0}:{}}}snapshotGaugeSeries(e){let t=this.gaugeValues.get(e);if(!t)return[];return Array.from(t.values(),(a)=>({value:a.value,attributes:a.attributes?{...a.attributes}:void 0}))}flattenProperties(e,t="",a=new WeakSet,i=0){if(!e)return{};let l={},r=100,d=10;for(let[g,n]of Object.entries(e)){if(g==="__proto__"||g==="constructor"||g==="prototype")continue;let s=t?`${t}.${g}`:g;if(n===null||n===void 0){l[s]=String(n);continue}if(Array.isArray(n)){let c=n.length>r?n.slice(0,r):n;try{l[s]=JSON.stringify(c)}catch{l[s]="[UnserializableArray]"}if(n.length>r)l[`${s}_truncated`]=!0,l[`${s}_original_length`]=n.length;continue}if(typeof n==="object"){if(n instanceof Date){l[s]=n.toISOString();continue}if(n instanceof Error){l[s]=n.message;continue}if(a.has(n)){l[s]="[Circular]";continue}if(i>=d){l[s]="[MaxDepthExceeded]";continue}a.add(n),Object.assign(l,this.flattenProperties(n,s,a,i+1));continue}if(B(n)){l[s]=n;continue}try{l[s]=JSON.stringify(n)}catch{l[s]=String(n)}}return l}}function B(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}import{metrics as Y,trace as D}from"@opentelemetry/api";import{logs as q}from"@opentelemetry/api-logs";import{OTLPLogExporter as p}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as ee}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as te}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as ae}from"@opentelemetry/resources";import{BatchLogRecordProcessor as le,ConsoleLogRecordExporter as ie,LoggerProvider as re}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as ne,MeterProvider as se,PeriodicExportingMetricReader as C}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as de,ConsoleSpanExporter as ge,SimpleSpanProcessor as fe}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as ue}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as be,ATTR_SERVICE_VERSION as me}from"@opentelemetry/semantic-conventions";import{mkdirSync as Re,readFileSync as N,statSync as K,writeFileSync as Ue}from"node:fs";import{resolveGlobalSettingsPath as Q}from"@cline/shared/storage";import{z as f}from"zod";import{AGENT_UNEXPECTED_REASONING_TOKENS_EVENT as Ce,captureAgentUnexpectedReasoningTokens as we,SDK_ERROR_TELEMETRY_EVENT as ze}from"@cline/shared";var O=f.preprocess((e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string").map((t)=>t.trim()).filter(Boolean):void 0,f.array(f.string()).optional()).transform((e)=>{if(!e)return;let t=[...new Set(e)].sort((a,i)=>a.localeCompare(i));return t.length>0?t:void 0}),Z=f.enum(["basic","agentic"]).catch("basic"),v=f.object({telemetryOptOut:f.boolean().default(!1).catch(!1),autoUpdateEnabled:f.boolean().default(!0).catch(!0),compactionStrategy:Z.optional(),disabledTools:O.optional(),disabledPlugins:O.optional()}).strip().transform((e)=>{let t={autoUpdateEnabled:e.autoUpdateEnabled,telemetryOptOut:e.telemetryOptOut};if(e.compactionStrategy)t.compactionStrategy=e.compactionStrategy;if(e.disabledTools?.length)t.disabledTools=e.disabledTools;if(e.disabledPlugins?.length)t.disabledPlugins=e.disabledPlugins;return t});function m(){return v.parse({})}var h;function _(e){if(e.disabledTools)Object.freeze(e.disabledTools);if(e.disabledPlugins)Object.freeze(e.disabledPlugins);return Object.freeze(e)}function k(e){let t;try{t=N(e,"utf8")}catch{return m()}try{let a=v.safeParse(JSON.parse(t));return a.success?a.data:m()}catch{return m()}}function E(){let e=Q(),t=K(e,{throwIfNoEntry:!1}),a=t?.mtimeMs??0,i=t?.size??0,l=h;if(l&&l.path===e&&l.mtimeMs===a&&l.size===i)return l;let r=_(t?k(e):m());return h={path:e,mtimeMs:a,size:i,value:r},h}function X(){return E().value}function G(){return X().telemetryOptOut}class P{name;logger;enabled;constructor(e={}){this.name=e.name??"TelemetryLoggerSink",this.logger=e.logger,this.enabled=e.enabled??!0}emit(e,t){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:e,properties:t})}emitRequired(e,t){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:e,properties:t})}recordCounter(e,t,a,i,l){if(!l&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:e,value:t,attributes:a,description:i,required:l===!0})}recordHistogram(e,t,a,i,l){if(!l&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:e,value:t,attributes:a,description:i,required:l===!0})}recordGauge(e,t,a,i,l){if(!l&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:e,value:t,attributes:a,description:i,required:l===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class o{adapters;metadata;distinctId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new P({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.commonProperties={...e.commonProperties??{}}}addAdapter(e){this.adapters.push(e)}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return this.adapters.some((e)=>e.isEnabled())}capture(e){let t=this.buildAttributes(e.properties);for(let a of this.adapters)a.emit(e.event,t)}captureRequired(e,t){let a=this.buildAttributes(t);for(let i of this.adapters)i.emitRequired(e,a)}recordCounter(e,t,a,i,l=!1){let r=this.buildAttributes(a);for(let d of this.adapters)d.recordCounter(e,t,r,i,l)}recordHistogram(e,t,a,i,l=!1){let r=this.buildAttributes(a);for(let d of this.adapters)d.recordHistogram(e,t,r,i,l)}recordGauge(e,t,a,i,l=!1){let r=this.buildAttributes(a);for(let d of this.adapters)d.recordGauge(e,t,r,i,l)}async flush(){await Promise.all(this.adapters.map((e)=>e.flush()))}async dispose(){await Promise.all(this.adapters.map((e)=>e.dispose()))}buildAttributes(e){return{...this.commonProperties,...e,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class w{distinctId;metadata;commonProperties;constructor(e={}){this.distinctId=e.distinctId,this.metadata={...e.metadata??{}},this.commonProperties={...e.commonProperties??{}}}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return!1}capture(e){this.resolveProperties(e.properties)}captureRequired(e,t){this.resolveProperties(t)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(e){return{...this.commonProperties,...e,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class T{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=ae({[be]:e.serviceName??"cline",...e.serviceVersion?{[me]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)Y.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)q.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return D.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new b({...e,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(e){let t=this.createAdapter({name:e.name,enabled:this.options.enabled,metadata:e.metadata});return new o({...e,adapters:[t],distinctId:u(e.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(e){let t=y(this.options.metricsExporter);if(t.length===0)return null;let a=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),i=Math.min(30000,Math.floor(a*0.8)),l=t.map((r)=>Pe(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:a,timeout:i})).filter((r)=>r!==null);if(l.length===0)return null;return new se({resource:e,readers:l})}createTracerProvider(e){let t=y(this.options.tracesExporter);if(t.length===0)return null;let a=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,i=this.options.otlpTracesHeaders??this.options.otlpHeaders,l=[];for(let r of t){let d=he(r,{endpoint:a,headers:i,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(d)l.push(d)}if(l.length===0)return null;return new ue({resource:e,spanProcessors:l})}createLoggerProvider(e){let t=y(this.options.logsExporter);if(t.length===0)return null;let a=t.map((i)=>{let l=ce(i,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!l)return null;return new le(l,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((i)=>i!==null);if(a.length===0)return null;return new re({resource:e,processors:a})}}function z(e){let t=new T(e),a=t.createTelemetryService(e);return a.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:e.enabled??!0,logsExporter:Array.isArray(e.logsExporter)?e.logsExporter.join(","):e.logsExporter,metricsExporter:Array.isArray(e.metricsExporter)?e.metricsExporter.join(","):e.metricsExporter,tracesExporter:Array.isArray(e.tracesExporter)?e.tracesExporter.join(","):e.tracesExporter,otlpProtocol:e.otlpProtocol,hasOtlpEndpoint:Boolean(e.otlpEndpoint),serviceName:e.serviceName,serviceVersion:e.serviceVersion}),{provider:t,telemetry:a}}function M(e){if(G())return{telemetry:new w(e)};if(e.enabled!==!0)return{telemetry:new o({...e,distinctId:u(e.distinctId)})};return z(e)}function oe(e){let{telemetry:t,provider:a}=M(e);return{telemetry:t,provider:a,flush:async()=>{let r=a;if(r&&typeof r.forceFlush==="function")try{await r.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([t.dispose(),a?.dispose()])}}}function y(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((a)=>a.trim()).filter((a)=>a==="console"||a==="otlp")}function ce(e,t){if(e==="console")return new ie;if(!t.endpoint)return null;let a=S(t.endpoint,"/v1/logs");return new p({url:a,headers:t.headers})}function he(e,t){if(e==="console")return new fe(new ge);if(!t.endpoint)return null;let a=S(t.endpoint,"/v1/traces");return new de(new te({url:a,headers:t.headers}))}function Pe(e,t){if(e==="console")return new C({exporter:new ne,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let a=S(t.endpoint,"/v1/metrics");return new C({exporter:new ee({url:a,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function S(e,t){let a=new URL(e),i=a.pathname.endsWith("/")?a.pathname.slice(0,-1):a.pathname;return a.pathname=i.endsWith(t)?i:`${i}${t}`,a.toString()}export{u as resolveCoreDistinctId,z as createOpenTelemetryTelemetryService,M as createConfiguredTelemetryService,oe as createConfiguredTelemetryHandle,T as OpenTelemetryProvider,b as OpenTelemetryAdapter};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type MessageWithMetadata } from "@cline/shared";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
export declare const SessionCompactionStateSchema: z.ZodObject<{
|
|
4
|
+
version: z.ZodLiteral<1>;
|
|
5
|
+
updated_at: z.ZodString;
|
|
6
|
+
conversation_id: z.ZodOptional<z.ZodString>;
|
|
7
|
+
source_message_count: z.ZodNumber;
|
|
8
|
+
source_prefix_hash: z.ZodOptional<z.ZodString>;
|
|
9
|
+
source_last_message_key: z.ZodOptional<z.ZodString>;
|
|
10
|
+
messages: z.ZodArray<z.ZodCustom<MessageWithMetadata, MessageWithMetadata>>;
|
|
11
|
+
system_prompt: z.ZodOptional<z.ZodString>;
|
|
12
|
+
}, z.core.$strip>;
|
|
13
|
+
export type SessionCompactionState = z.infer<typeof SessionCompactionStateSchema>;
|
|
14
|
+
export declare function createSessionCompactionState(input: {
|
|
15
|
+
sourceMessages: readonly MessageWithMetadata[];
|
|
16
|
+
compactedMessages: readonly MessageWithMetadata[];
|
|
17
|
+
conversationId?: string;
|
|
18
|
+
systemPrompt?: string;
|
|
19
|
+
updatedAt?: string;
|
|
20
|
+
}): SessionCompactionState;
|
|
21
|
+
export declare function projectSessionCompactionState(state: SessionCompactionState, sourceMessages: readonly MessageWithMetadata[]): MessageWithMetadata[] | undefined;
|
|
22
|
+
export declare function parseSessionCompactionState(value: unknown): SessionCompactionState | undefined;
|
|
@@ -27,5 +27,6 @@ export declare const SessionManifestSchema: z.ZodObject<{
|
|
|
27
27
|
prompt: z.ZodOptional<z.ZodString>;
|
|
28
28
|
metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
29
29
|
messages_path: z.ZodOptional<z.ZodString>;
|
|
30
|
+
compaction_path: z.ZodOptional<z.ZodString>;
|
|
30
31
|
}, z.core.$strip>;
|
|
31
32
|
export type SessionManifest = z.infer<typeof SessionManifestSchema>;
|
|
@@ -4,6 +4,7 @@ import type { SubAgentEndContext, SubAgentStartContext } from "../../extensions/
|
|
|
4
4
|
import type { HookEventPayload } from "../../hooks";
|
|
5
5
|
import { type SessionStatus, type TerminalSessionStatus } from "../../types/common";
|
|
6
6
|
import type { PersistedSessionUpdateInput, SessionMessagesArtifactUploader, SessionPersistenceAdapter } from "../../types/session";
|
|
7
|
+
import type { SessionCompactionState } from "../models/session-compaction";
|
|
7
8
|
import type { SessionRow } from "../models/session-row";
|
|
8
9
|
export type { PersistedSessionUpdateInput, SessionPersistenceAdapter };
|
|
9
10
|
export declare class UnifiedSessionPersistenceService {
|
|
@@ -39,6 +40,9 @@ export declare class UnifiedSessionPersistenceService {
|
|
|
39
40
|
upsertSubagentSessionFromHook(event: HookEventPayload): Promise<string | undefined>;
|
|
40
41
|
appendSubagentHookAudit(_subSessionId: string, event: HookEventPayload): Promise<void>;
|
|
41
42
|
persistSessionMessages(sessionId: string, messages: LlmsProviders.Message[], systemPrompt?: string): Promise<void>;
|
|
43
|
+
readSessionCompactionState(sessionId: string): Promise<SessionCompactionState | undefined>;
|
|
44
|
+
persistSessionCompactionState(sessionId: string, state: SessionCompactionState): Promise<void>;
|
|
45
|
+
deleteSessionCompactionState(sessionId: string): Promise<void>;
|
|
42
46
|
applySubagentStatus(subSessionId: string, event: HookEventPayload): Promise<void>;
|
|
43
47
|
applySubagentStatusBySessionId(subSessionId: string, status: SessionStatus): Promise<void>;
|
|
44
48
|
applyStatusToRunningChildSessions(parentSessionId: string, status: TerminalSessionStatus): Promise<void>;
|
|
@@ -56,4 +60,5 @@ export declare class UnifiedSessionPersistenceService {
|
|
|
56
60
|
deleteSession(sessionId: string): Promise<{
|
|
57
61
|
deleted: boolean;
|
|
58
62
|
}>;
|
|
63
|
+
private deleteSessionCompactionStateIfExists;
|
|
59
64
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function writeFileAtomic(path: string, contents: string): Promise<void>;
|
|
@@ -2,6 +2,7 @@ import type * as LlmsProviders from "@cline/llms";
|
|
|
2
2
|
import type { BasicLogger } from "@cline/shared";
|
|
3
3
|
import { SessionArtifacts } from "../../services/session-artifacts";
|
|
4
4
|
import type { SessionMessagesArtifactUploader, SessionPersistenceAdapter } from "../../types/session";
|
|
5
|
+
import { type SessionCompactionState } from "../models/session-compaction";
|
|
5
6
|
import { type SessionManifest } from "../models/session-manifest";
|
|
6
7
|
export declare class SessionManifestStore {
|
|
7
8
|
private readonly adapter;
|
|
@@ -13,11 +14,28 @@ export declare class SessionManifestStore {
|
|
|
13
14
|
initializeMessagesFile(sessionId: string, path: string, startedAt: string): void;
|
|
14
15
|
writeSessionManifest(manifestPath: string, manifest: SessionManifest): void;
|
|
15
16
|
readSessionManifest(sessionId: string): SessionManifest | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* Asynchronously read only the manifest `metadata.title`.
|
|
19
|
+
*
|
|
20
|
+
* The session-listing hot path needs nothing from the manifest except the
|
|
21
|
+
* title, but the manifest JSON can be large (it embeds metadata and prompt
|
|
22
|
+
* text). This reads the file off the event-loop thread and pulls the title
|
|
23
|
+
* out of the parsed JSON directly, skipping the full `SessionManifestSchema`
|
|
24
|
+
* (Zod) validation that `readSessionManifest` performs. On any error (missing
|
|
25
|
+
* file, malformed JSON, non-string title) it resolves to `undefined` so
|
|
26
|
+
* callers fall back to the row metadata/prompt title.
|
|
27
|
+
*/
|
|
28
|
+
readSessionManifestTitle(sessionId: string): Promise<string | undefined>;
|
|
16
29
|
readManifestFile(sessionId: string): {
|
|
17
30
|
path: string;
|
|
18
31
|
manifest?: SessionManifest;
|
|
19
32
|
};
|
|
20
33
|
resolveArtifactPath(sessionId: string, kind: "messagesPath", fallback: (id: string) => string): Promise<string>;
|
|
21
34
|
persistSessionMessages(sessionId: string, messages: LlmsProviders.Message[], systemPrompt?: string): Promise<void>;
|
|
35
|
+
private resolveCompactionPath;
|
|
36
|
+
private updateCompactionPath;
|
|
37
|
+
readSessionCompactionState(sessionId: string): Promise<SessionCompactionState | undefined>;
|
|
38
|
+
persistSessionCompactionState(sessionId: string, state: SessionCompactionState): Promise<void>;
|
|
39
|
+
deleteSessionCompactionState(sessionId: string): Promise<void>;
|
|
22
40
|
appendStaleSessionHookLog(detectedAt: string, sessionId: string, pid: number, reason: string, source: string): void;
|
|
23
41
|
}
|
package/dist/types/config.d.ts
CHANGED
|
@@ -20,6 +20,10 @@ export interface CoreModelConfig {
|
|
|
20
20
|
* Explicit reasoning effort override for capable models.
|
|
21
21
|
*/
|
|
22
22
|
reasoningEffort?: ProviderConfig["reasoningEffort"];
|
|
23
|
+
/**
|
|
24
|
+
* Explicit thinking/reasoning token budget for capable models.
|
|
25
|
+
*/
|
|
26
|
+
thinkingBudgetTokens?: number;
|
|
23
27
|
/**
|
|
24
28
|
* Maximum output tokens per API call.
|
|
25
29
|
*/
|
package/dist/types/session.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { AgentFinishReason } from "@cline/shared";
|
|
|
3
3
|
import type { SessionAccumulatedUsage } from "../runtime/host/runtime-host";
|
|
4
4
|
import type { BuiltRuntime } from "../runtime/orchestration/session-runtime";
|
|
5
5
|
import type { SessionRuntime } from "../runtime/orchestration/session-runtime-orchestrator";
|
|
6
|
+
import type { SessionCompactionState } from "../session/models/session-compaction";
|
|
6
7
|
import type { SessionRow } from "../session/models/session-row";
|
|
7
8
|
import type { RootSessionArtifacts } from "../session/services/session-service";
|
|
8
9
|
import type { SessionSource, SessionStatus } from "./common";
|
|
@@ -25,6 +26,8 @@ export type ActiveSession = {
|
|
|
25
26
|
aborting: boolean;
|
|
26
27
|
interactive: boolean;
|
|
27
28
|
persistedMessages?: LlmsProviders.MessageWithMetadata[];
|
|
29
|
+
compactionState?: SessionCompactionState;
|
|
30
|
+
compactionStateWriteQueue?: Promise<void>;
|
|
28
31
|
activeTeamRunIds: Set<string>;
|
|
29
32
|
pendingTeamRunUpdates: TeamRunUpdate[];
|
|
30
33
|
teamRunWaiters: Array<() => void>;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cline/core",
|
|
3
3
|
"description": "Cline Core SDK for Node Runtime",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.59",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "https://github.com/cline/cline",
|
|
@@ -48,9 +48,9 @@
|
|
|
48
48
|
"test:watch": "vitest --config vitest.config.ts"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@cline/agents": "0.0.
|
|
52
|
-
"@cline/shared": "0.0.
|
|
53
|
-
"@cline/llms": "0.0.
|
|
51
|
+
"@cline/agents": "0.0.59",
|
|
52
|
+
"@cline/shared": "0.0.59",
|
|
53
|
+
"@cline/llms": "0.0.59",
|
|
54
54
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
55
55
|
"@opentelemetry/api": "^1.9.0",
|
|
56
56
|
"@opentelemetry/api-logs": "^0.214.0",
|