@cline/core 0.0.85 → 0.0.86-nightly.1790389788
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/cloud/api.d.ts +118 -0
- package/dist/cloud/controller.d.ts +171 -0
- package/dist/cloud/index.d.ts +9 -0
- package/dist/cloud/index.js +21 -0
- package/dist/cloud/models.d.ts +9 -0
- package/dist/cloud/repositories.d.ts +21 -0
- package/dist/cloud/snapshots.d.ts +22 -0
- package/dist/cloud/state.d.ts +13 -0
- package/dist/cloud/types.d.ts +84 -0
- package/dist/cron/service/schedule-tool.d.ts +3 -3
- package/dist/hub/client/index.d.ts +8 -0
- package/dist/hub/daemon/bind-diagnostics.d.ts +16 -0
- package/dist/hub/daemon/entry.js +196 -195
- package/dist/hub/daemon/index.d.ts +8 -0
- package/dist/hub/discovery/index.d.ts +1 -0
- package/dist/hub/index.js +193 -193
- package/dist/index.d.ts +6 -2
- package/dist/index.js +232 -225
- package/dist/remote/remote-helper-entry.js +4 -4
- package/dist/remote/remote-helper.js +4 -4
- package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +3 -0
- package/dist/services/cloud-handoff/git-preflight.d.ts +24 -0
- package/dist/services/cloud-handoff/index.d.ts +4 -0
- package/dist/services/cloud-handoff/metadata.d.ts +7 -0
- package/dist/services/cloud-handoff/transcript.d.ts +5 -0
- package/dist/services/cloud-handoff/types.d.ts +35 -0
- package/dist/services/global-settings.d.ts +3 -3
- package/dist/services/llms/provider-settings.d.ts +18 -18
- package/dist/services/plugin-commands.d.ts +28 -0
- package/dist/services/providers/local-provider-registry.d.ts +3 -0
- package/dist/services/providers/local-provider-service.d.ts +6 -3
- package/dist/services/telemetry/core-events.d.ts +9 -0
- package/dist/services/telemetry/index.js +1 -1
- package/dist/services/workspace/workspace-manifest.d.ts +34 -0
- package/dist/session/fork-metadata.d.ts +7 -0
- package/dist/session/models/session-manifest.d.ts +1 -1
- package/dist/session/services/persistence-service.d.ts +1 -0
- package/dist/tasks/agenda-task-tool.d.ts +2 -2
- package/dist/tasks/task-tool.d.ts +5 -5
- package/dist/types/chat-schema.d.ts +9 -9
- package/package.json +8 -4
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { type AgentMode, type MessageWithMetadata } from "@cline/shared";
|
|
2
|
+
import type { CloudBranchListOptions, CloudBranchListResult, CloudRepositoryListResult } from "./repositories";
|
|
3
|
+
type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
4
|
+
export type CloudSessionRecord = {
|
|
5
|
+
id: string;
|
|
6
|
+
status: string;
|
|
7
|
+
title?: string;
|
|
8
|
+
sandboxUrl: string;
|
|
9
|
+
repoContext: {
|
|
10
|
+
repoUrl?: string;
|
|
11
|
+
branch?: string;
|
|
12
|
+
};
|
|
13
|
+
metadata: {
|
|
14
|
+
modelId?: string;
|
|
15
|
+
taskId?: string;
|
|
16
|
+
statusReason?: string;
|
|
17
|
+
provisioningPhase?: CloudProvisioningPhase;
|
|
18
|
+
createRequestTitle?: string;
|
|
19
|
+
cwd?: string;
|
|
20
|
+
};
|
|
21
|
+
expiredAt?: string | null;
|
|
22
|
+
lastActivityAt?: string;
|
|
23
|
+
createdAt: string;
|
|
24
|
+
updatedAt: string;
|
|
25
|
+
};
|
|
26
|
+
export type CloudProvisioningPhase = "provisioning" | "cloning_repo" | "agent_starting" | "ready" | "failed";
|
|
27
|
+
export declare function deriveCloudSessionTitle(prompt: string): string;
|
|
28
|
+
export type CreateCloudSessionInput = {
|
|
29
|
+
/** Stable client-planned id for single-flighting one chat's start request. */
|
|
30
|
+
requestId?: string;
|
|
31
|
+
modelId: string;
|
|
32
|
+
repoUrl: string;
|
|
33
|
+
initialPrompt?: string;
|
|
34
|
+
branch?: string;
|
|
35
|
+
autoApproveTools?: boolean;
|
|
36
|
+
thinking?: boolean;
|
|
37
|
+
reasoningEffort?: "low" | "medium" | "high" | "xhigh";
|
|
38
|
+
mode?: AgentMode;
|
|
39
|
+
workspaceRelativePath?: string;
|
|
40
|
+
/** Null explicitly selects Personal; controllers resolve an omitted scope. */
|
|
41
|
+
organizationId?: string | null;
|
|
42
|
+
/** Host persistence hooks; never serialized into the provisioning request. */
|
|
43
|
+
handoff?: {
|
|
44
|
+
sourceSessionId: string;
|
|
45
|
+
resolveMessages: () => Promise<MessageWithMetadata[]>;
|
|
46
|
+
/** Persist dispatch intent after successful recovery lookup, before POST. */
|
|
47
|
+
onCreating: () => void | Promise<void>;
|
|
48
|
+
onOuterSessionCreated: (sessionId: string, context?: {
|
|
49
|
+
created: boolean;
|
|
50
|
+
}) => Promise<void>;
|
|
51
|
+
onOuterSessionRemoved?: (sessionId: string) => Promise<void>;
|
|
52
|
+
onSeeding?: () => void | Promise<void>;
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
export type { CloudBranchListOptions, CloudBranchListResult, CloudRepositoryListResult, CloudRepositoryOption, } from "./repositories";
|
|
56
|
+
export type CloudSessionApiOptions = {
|
|
57
|
+
apiBaseUrl: string;
|
|
58
|
+
appBaseUrl: string;
|
|
59
|
+
getAuthToken: () => Promise<string | undefined>;
|
|
60
|
+
fetch?: FetchLike;
|
|
61
|
+
createTimeoutMs?: number;
|
|
62
|
+
};
|
|
63
|
+
export type CloudErrorCode = "authentication_required" | "github_not_connected" | "session_not_found" | "session_expired" | "session_failed" | "request_failed";
|
|
64
|
+
export declare class CloudSessionError extends Error {
|
|
65
|
+
readonly code: CloudErrorCode;
|
|
66
|
+
readonly detail: string;
|
|
67
|
+
readonly connectUrl?: string | undefined;
|
|
68
|
+
/** HTTP status of the failed request, when one was received. */
|
|
69
|
+
readonly status?: number | undefined;
|
|
70
|
+
constructor(code: CloudErrorCode, detail: string, connectUrl?: string | undefined,
|
|
71
|
+
/** HTTP status of the failed request, when one was received. */
|
|
72
|
+
status?: number | undefined);
|
|
73
|
+
}
|
|
74
|
+
/** The fresh handoff POST definitely did not create a workspace. Marker/list
|
|
75
|
+
* failures and ambiguous transport outcomes deliberately never use this type. */
|
|
76
|
+
export declare class CloudHandoffCreationRejectedError extends Error {
|
|
77
|
+
constructor(cause: unknown);
|
|
78
|
+
}
|
|
79
|
+
export declare function parseCloudProvisioningPhase(value: unknown): CloudProvisioningPhase | undefined;
|
|
80
|
+
export declare class CloudSessionApi {
|
|
81
|
+
private readonly options;
|
|
82
|
+
private readonly apiBaseUrl;
|
|
83
|
+
private readonly appBaseUrl;
|
|
84
|
+
private readonly fetchImpl;
|
|
85
|
+
private readonly createTimeoutMs;
|
|
86
|
+
private readonly unconfirmedHandoffCreates;
|
|
87
|
+
private readonly completedHandoffCreates;
|
|
88
|
+
constructor(options: CloudSessionApiOptions);
|
|
89
|
+
private request;
|
|
90
|
+
list(organizationId?: string): Promise<CloudSessionRecord[]>;
|
|
91
|
+
private listWithToken;
|
|
92
|
+
listRepositories(organizationId?: string): Promise<CloudRepositoryListResult>;
|
|
93
|
+
listBranches(repositoryId: number, organizationId?: string, options?: CloudBranchListOptions): Promise<CloudBranchListResult>;
|
|
94
|
+
status(sessionId: string, options?: {
|
|
95
|
+
authToken?: string;
|
|
96
|
+
signal?: AbortSignal;
|
|
97
|
+
}): Promise<{
|
|
98
|
+
sessionId?: string;
|
|
99
|
+
status?: string;
|
|
100
|
+
phase?: CloudProvisioningPhase;
|
|
101
|
+
statusReason?: string;
|
|
102
|
+
}>;
|
|
103
|
+
create(input: CreateCloudSessionInput): Promise<{
|
|
104
|
+
sessionId: string;
|
|
105
|
+
status: string;
|
|
106
|
+
sandboxUrl: string;
|
|
107
|
+
cleanupAuthToken: string;
|
|
108
|
+
}>;
|
|
109
|
+
private persistHandoffOuterSession;
|
|
110
|
+
waitUntilReady(sessionId: string, signal: AbortSignal, onStatus?: (status: {
|
|
111
|
+
phase?: CloudProvisioningPhase;
|
|
112
|
+
}) => void): Promise<void>;
|
|
113
|
+
delete(sessionId: string, authToken?: string): Promise<void>;
|
|
114
|
+
private deleteWithAuth;
|
|
115
|
+
updateTitle(sessionId: string, title: string): Promise<CloudSessionRecord>;
|
|
116
|
+
/** Raw archived snapshot; null distinguishes a missing archive from []. */
|
|
117
|
+
history(sessionId: string): Promise<unknown[] | null>;
|
|
118
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import type { BasicLogger, MessageWithMetadata, ToolApprovalResult } from "@cline/shared";
|
|
2
|
+
import { NodeHubClient } from "../hub/client/index";
|
|
3
|
+
import { type CloudSessionApi, CloudSessionError, type CloudSessionRecord, type CreateCloudSessionInput } from "./api";
|
|
4
|
+
import { type CloudModel } from "./models";
|
|
5
|
+
import type { CloudBranchListOptions, CloudBranchListResult, CloudRepositoryListResult } from "./repositories";
|
|
6
|
+
import type { CloudCreationOptions, CloudHandoffSeed, CloudSessionAttachment, CloudSessionEvent, CloudSessionSnapshot, CloudSessionState, JsonRecord } from "./types";
|
|
7
|
+
/** The seed command was not dispatched; the host may clear its seed marker. */
|
|
8
|
+
export declare class CloudHandoffSeedRejectedError extends Error {
|
|
9
|
+
constructor(cause: unknown);
|
|
10
|
+
}
|
|
11
|
+
/** A queued prompt may have been accepted even when recovery also fails. */
|
|
12
|
+
export declare class CloudQueueUnconfirmedError extends CloudSessionError {
|
|
13
|
+
constructor();
|
|
14
|
+
}
|
|
15
|
+
export declare class CloudHandoffSeedUnsupportedError extends Error {
|
|
16
|
+
constructor();
|
|
17
|
+
}
|
|
18
|
+
type CloudHubClient = Pick<NodeHubClient, "command" | "connect" | "dispose" | "getClientId" | "subscribe">;
|
|
19
|
+
export type CloudSessionControllerOptions = {
|
|
20
|
+
logger?: BasicLogger;
|
|
21
|
+
clientIdentity?: {
|
|
22
|
+
prefix: string;
|
|
23
|
+
type: string;
|
|
24
|
+
displayName: string;
|
|
25
|
+
source: string;
|
|
26
|
+
};
|
|
27
|
+
/** Desktop preserves its historical cleanup; CLI keeps late successful creations recoverable. */
|
|
28
|
+
lateCreateDisposition?: "preserve" | "delete";
|
|
29
|
+
/** Host-owned first-task policy survives controller replacement; established tasks never qualify. */
|
|
30
|
+
pendingInitialTasks?: Map<string, CloudCreationOptions>;
|
|
31
|
+
api: Pick<CloudSessionApi, "create" | "delete" | "list" | "status" | "waitUntilReady" | "history" | "updateTitle" | "listRepositories" | "listBranches">;
|
|
32
|
+
getAuthToken: () => Promise<string | undefined>;
|
|
33
|
+
apiBaseUrl: string;
|
|
34
|
+
getActiveOrganizationId?: (options?: {
|
|
35
|
+
fresh?: boolean;
|
|
36
|
+
}) => Promise<string | undefined>;
|
|
37
|
+
createHubClient?: (options: ConstructorParameters<typeof NodeHubClient>[0]) => CloudHubClient;
|
|
38
|
+
};
|
|
39
|
+
export declare function isCloudOuterSessionId(sessionId: string): boolean;
|
|
40
|
+
export declare function cloudSessionToDiscoveryRecord(record: CloudSessionRecord): JsonRecord;
|
|
41
|
+
export declare class CloudSessionController {
|
|
42
|
+
private readonly options;
|
|
43
|
+
private readonly sessionGenerations;
|
|
44
|
+
private readonly sessions;
|
|
45
|
+
private readonly approvals;
|
|
46
|
+
private readonly listeners;
|
|
47
|
+
private readonly detachedSessions;
|
|
48
|
+
private readonly restoredOptions;
|
|
49
|
+
private readonly authoritativeMessages;
|
|
50
|
+
private readonly streamingMessages;
|
|
51
|
+
private disposed;
|
|
52
|
+
private readonly connections;
|
|
53
|
+
private readonly connectionPromises;
|
|
54
|
+
private readonly knownSessions;
|
|
55
|
+
private readonly unlistedSessions;
|
|
56
|
+
private readonly pendingInitialTasks;
|
|
57
|
+
private lastListedSessions;
|
|
58
|
+
private discoveryRefresh?;
|
|
59
|
+
private readonly unconfirmedInnerCreates;
|
|
60
|
+
private readonly createRequests;
|
|
61
|
+
private readonly provisioningControllers;
|
|
62
|
+
private readonly sendAbortTokens;
|
|
63
|
+
private readonly titleWrites;
|
|
64
|
+
private readonly deletingSessions;
|
|
65
|
+
private readonly createHubClient;
|
|
66
|
+
constructor(options: CloudSessionControllerOptions);
|
|
67
|
+
/** Restores only pre-creation settings; never mutates a running Hub session's policy. */
|
|
68
|
+
restoreCreationOptions(sessionId: string, options: CloudCreationOptions): void;
|
|
69
|
+
protected seedSessionState(sessionId: string, state: CloudSessionState): void;
|
|
70
|
+
private stateFromRecord;
|
|
71
|
+
getSnapshot(sessionId: string): CloudSessionSnapshot | undefined;
|
|
72
|
+
subscribe(listener: (event: CloudSessionEvent) => void, sessionId?: string): () => void;
|
|
73
|
+
private publish;
|
|
74
|
+
private publishSnapshot;
|
|
75
|
+
private readonly snapshotTimers;
|
|
76
|
+
private cancelScheduledSnapshot;
|
|
77
|
+
private scheduleSnapshot;
|
|
78
|
+
private notify;
|
|
79
|
+
private applyLiveEvent;
|
|
80
|
+
respondApproval(sessionId: string, approvalId: string, result: ToolApprovalResult): Promise<void>;
|
|
81
|
+
/** Detaches this viewer and invalidates waiting sends without stopping or deleting remote work. */
|
|
82
|
+
detach(sessionId: string): Promise<void>;
|
|
83
|
+
isCloudSession(sessionId: string): boolean;
|
|
84
|
+
/** Returns a session this process already created or discovered without
|
|
85
|
+
* making account/environment availability a prerequisite for opening it. */
|
|
86
|
+
getCachedDiscoveryRecord(sessionId: string): JsonRecord | undefined;
|
|
87
|
+
/** Revalidates a cached row by id when the active-scope list does not include it. */
|
|
88
|
+
getCrossScopeDiscoveryRecord(sessionId: string): Promise<JsonRecord | undefined>;
|
|
89
|
+
list(): Promise<CloudSessionRecord[]>;
|
|
90
|
+
handoffTargetExists(sessionId: string): Promise<boolean>;
|
|
91
|
+
private preserveConnectedRuntimeModel;
|
|
92
|
+
private resolveActiveOrganizationId;
|
|
93
|
+
listRepositories(): Promise<CloudRepositoryListResult>;
|
|
94
|
+
listModels(): Promise<CloudModel[]>;
|
|
95
|
+
/** Validates account auth and GitHub access before provisioning a handoff. */
|
|
96
|
+
prepareHandoffRepository(repoUrl: string): Promise<{
|
|
97
|
+
organizationId?: string;
|
|
98
|
+
}>;
|
|
99
|
+
listBranches(repositoryId: number, options?: CloudBranchListOptions): Promise<CloudBranchListResult>;
|
|
100
|
+
listForDiscovery(options?: {
|
|
101
|
+
timeoutMs?: number;
|
|
102
|
+
}): Promise<JsonRecord[]>;
|
|
103
|
+
create(input: CreateCloudSessionInput): Promise<CloudSessionAttachment>;
|
|
104
|
+
private trackProvisioningController;
|
|
105
|
+
private abortProvisioningControllers;
|
|
106
|
+
/** Waits for an adopted pending handoff target before opening its Hub proxy. */
|
|
107
|
+
waitUntilReady(outerSessionId: string): Promise<void>;
|
|
108
|
+
/** Seeds an already-provisioned outer session when retrying a pending handoff. */
|
|
109
|
+
seedHandoff(outerSessionId: string, seed: CloudHandoffSeed): Promise<{
|
|
110
|
+
innerSessionId: string;
|
|
111
|
+
}>;
|
|
112
|
+
verifyHandoffTranscript(outerSessionId: string, expected: readonly MessageWithMetadata[], options?: {
|
|
113
|
+
allowAppendedMessages?: boolean;
|
|
114
|
+
}): Promise<void>;
|
|
115
|
+
private createOnce;
|
|
116
|
+
private deleteProvisionedSessionAfterDispose;
|
|
117
|
+
attach(outerSessionId: string, creationOptions?: CloudCreationOptions): Promise<CloudSessionAttachment>;
|
|
118
|
+
send(outerSessionId: string, prompt: string, requestedDelivery?: "queue" | "steer", modelId?: string, userImages?: string[]): Promise<{
|
|
119
|
+
sessionId: string;
|
|
120
|
+
ok: true;
|
|
121
|
+
queued?: boolean;
|
|
122
|
+
recoveredAfterDisconnect?: boolean;
|
|
123
|
+
status?: string;
|
|
124
|
+
result?: unknown;
|
|
125
|
+
}>;
|
|
126
|
+
private updateModel;
|
|
127
|
+
private applyModel;
|
|
128
|
+
private rehydrateAfterTransportDrop;
|
|
129
|
+
private performTransportRehydration;
|
|
130
|
+
abort(outerSessionId: string): Promise<{
|
|
131
|
+
sessionId: string;
|
|
132
|
+
ok: true;
|
|
133
|
+
}>;
|
|
134
|
+
pendingPrompts(outerSessionId: string): Promise<JsonRecord>;
|
|
135
|
+
updatePendingPrompt(outerSessionId: string, promptId: string, changes: {
|
|
136
|
+
prompt?: string;
|
|
137
|
+
delivery?: "queue" | "steer";
|
|
138
|
+
}): Promise<JsonRecord>;
|
|
139
|
+
removePendingPrompt(outerSessionId: string, promptId: string): Promise<JsonRecord>;
|
|
140
|
+
private queueCommand;
|
|
141
|
+
private applyQueueSnapshot;
|
|
142
|
+
readMessages(outerSessionId: string): Promise<unknown[]>;
|
|
143
|
+
updateTitle(outerSessionId: string, title: string): Promise<void>;
|
|
144
|
+
delete(outerSessionId: string): Promise<void>;
|
|
145
|
+
dispose(): Promise<void>;
|
|
146
|
+
private attachExpired;
|
|
147
|
+
private loadArchivedMessages;
|
|
148
|
+
private refreshKnownSession;
|
|
149
|
+
private ensureKnownSession;
|
|
150
|
+
private assertSessionActive;
|
|
151
|
+
private ensureConnection;
|
|
152
|
+
private resolveInnerSession;
|
|
153
|
+
private assertHandoffConnectionReusable;
|
|
154
|
+
private createInnerSession;
|
|
155
|
+
private adoptExistingHandoffSession;
|
|
156
|
+
private createInnerSessionOnce;
|
|
157
|
+
private handleEvent;
|
|
158
|
+
private forwardEvent;
|
|
159
|
+
private handleApprovalRequested;
|
|
160
|
+
private storePendingApproval;
|
|
161
|
+
private removeApproval;
|
|
162
|
+
private clearPendingApprovals;
|
|
163
|
+
private sendApprovalSnapshot;
|
|
164
|
+
private ensureAttached;
|
|
165
|
+
private subscribeToInnerSession;
|
|
166
|
+
private applySessionModel;
|
|
167
|
+
private disposeConnection;
|
|
168
|
+
/** Stop reconnecting only when the session is gone, not when lookup fails. */
|
|
169
|
+
private disposeConnectionIfSessionGone;
|
|
170
|
+
}
|
|
171
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Experimental cloud execution client. No local runtime or tool execution is initialized. */
|
|
2
|
+
export * from "../services/cloud-handoff";
|
|
3
|
+
export * from "./api";
|
|
4
|
+
export * from "./controller";
|
|
5
|
+
export * from "./models";
|
|
6
|
+
export * from "./repositories";
|
|
7
|
+
export * from "./snapshots";
|
|
8
|
+
export { normalizeSessionTitle, resolveSessionListTitle, stringifyMessageContent, } from "./state";
|
|
9
|
+
export * from "./types";
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import{execFile as J2}from"node:child_process";import{basename as C6,resolve as Z2}from"node:path";import{promisify as X2}from"node:util";import{processWorkspaceInfo as E6}from"@cline/shared";import d0 from"simple-git";var Q2=X2(J2);function V2($,J){return Q2("git",$,{cwd:J.cwd,encoding:"utf8",windowsHide:!0,signal:J.signal,timeout:15000,maxBuffer:10485760,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND||"ssh -o BatchMode=yes"}})}function d($){if(!$||typeof $!=="object"||!("stderr"in $))return"";return typeof $.stderr==="string"?$.stderr.trim():""}function i($){if(!$||typeof $!=="object"||!("code"in $))return;return typeof $.code==="number"?$.code:void 0}function i0($){let J=t0($.cwd),Z=$.git??V2,X=async(V)=>(await Z(V,{cwd:J,signal:$.signal})).stdout,Q=async(V)=>(await X(V)).trim();return{async isInsideWorkTree(){try{return await Q(["rev-parse","--is-inside-work-tree"])==="true"}catch(V){if(i(V)===128&&/not a git repository|Kein Git-Repository/i.test(d(V)))return!1;throw V}},remotes:()=>d0({baseDir:J}).getRemotes(!0),displayBranch:async()=>(await d0({baseDir:J}).branch()).current.trim(),symbolicBranch:()=>Q(["symbolic-ref","--quiet","--short","HEAD"]),headSha:()=>Q(["rev-parse","HEAD"]),workspacePrefix:async()=>(await X(["rev-parse","--show-prefix"])).replace(/[\r\n]+$/,""),worktreeStatus:()=>Q(["status","--porcelain=v1","--untracked-files=all","--ignore-submodules=none"]),branchRemote:(V)=>Q(["config","--get",`branch.${V}.remote`]),branchMergeRef:(V)=>Q(["config","--get",`branch.${V}.merge`]),remoteUrl:(V)=>Q(["remote","get-url",V]),remoteRefs:(V,j)=>Q(["ls-remote","--exit-code",V,j])}}function t0($){return Z2($)}class P extends Error{code;constructor($,J,Z){super(J,Z);this.code=$;this.name="CloudHandoffGitPreflightError"}}function r0($){let J=0,Z=$.length;while(J<Z&&$[J]==="/")J+=1;while(Z>J&&$[Z-1]==="/")Z-=1;let X=$.slice(J,Z);return X.toLowerCase().endsWith(".git")?X.slice(0,-4):X}function s0($){let J=$.trim();if(!J)return null;let Z=J.match(/^(?:[^@/\s]+@)?github\.com:([^\s]+)$/i);if(Z?.[1]){let X=r0(Z[1]);return X.split("/").length===2?`https://github.com/${X}`:null}try{let X=new URL(J);if(X.hostname.toLowerCase()!=="github.com")return null;if(!new Set(["https:","http:","ssh:","git:"]).has(X.protocol))return null;let Q=r0(X.pathname);return Q.split("/").length===2?`https://github.com/${Q}`:null}catch{return null}}async function y($,J,Z){try{return await $()}catch(X){let Q=d(X);throw new P(J,Q?`${Z} (${Q})`:Z,{cause:X})}}function Y2($,J){let Z=`refs/heads/${J}`;for(let X of $.split(`
|
|
2
|
+
`)){let[Q,V]=X.trim().split(/\s+/,2);if(V===Z&&/^[0-9a-f]{40,64}$/i.test(Q??""))return Q??null}return null}function j2($){let J=$.replace(/[\r\n]+$/,"").replace(/\/+$/,"");if(!J)return;let Z=J.split("/");if(J.startsWith("/")||Z.some((X)=>!X||X==="."||X===".."))throw new P("git_command_failed","Could not resolve the workspace path relative to the Git repository.");return J}async function f6($){let J=i0($);if(!await y(J.isInsideWorkTree,"not_git_repository","Cloud handoff requires a Git repository."))throw new P("not_git_repository","Cloud handoff requires a Git working tree.");let X=j2(await y(J.workspacePrefix,"git_command_failed","Could not resolve the workspace path relative to the Git repository.")),Q=await y(J.worktreeStatus,"git_command_failed","Could not inspect the Git worktree.");if(Q){let G=Q.split(`
|
|
3
|
+
`).filter(Boolean),q=G.slice(0,5).join(`
|
|
4
|
+
`),O=G.length>5?`
|
|
5
|
+
...and ${G.length-5} more`:"";throw new P("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
|
|
6
|
+
|
|
7
|
+
${q}${O}`)}let V;try{V=await J.symbolicBranch()}catch(G){let q=i(G)===1,O=d(G),B=q?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new P(q?"detached_head":"git_command_failed",O?`${B} (${O})`:B,{cause:G})}if(!V)throw new P("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[j,Y,W]=await Promise.all([y(()=>J.branchRemote(V),"missing_upstream",`Branch ${V} has no upstream. Push it with -u before handing off.`),y(()=>J.branchMergeRef(V),"missing_upstream",`Branch ${V} has no upstream. Push it with -u before handing off.`),y(J.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!j||j==="."||!Y.startsWith("refs/heads/"))throw new P("missing_upstream",`Branch ${V} has no remote branch upstream. Push it with -u before handing off.`);let F=Y.slice(11),K=j;if(!s0(j))try{K=await J.remoteUrl(j)}catch{throw new P("missing_upstream","Could not resolve the upstream remote.")}let N=s0(K);if(!N)throw new P("unsupported_remote","Cloud handoff currently requires a github.com upstream remote.");let z;try{z=await J.remoteRefs(j,Y)}catch(G){let q=i(G)===2,O=q?`The upstream branch ${F} was not found. Push it before handing off.`:"Could not verify the remote branch. Check your network and GitHub authentication, then try again.";throw new P(q?"remote_branch_missing":"git_command_failed",O)}let L=Y2(z,F);if(!L)throw new P("remote_branch_missing",`The upstream branch ${F} was not found. Push it before handing off.`);if(L.toLowerCase()!==W.toLowerCase())throw new P("unpushed_commits",`Local HEAD does not match the upstream branch ${F}. Push the current commit before handing off.`);return{repoUrl:N,branch:F,headSha:W,...X?{workspaceRelativePath:X}:{}}}function F0($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function T($){if(typeof $!=="string")return;return $.trim()||void 0}function W2($){return typeof $==="string"&&$.length>0?$:void 0}function N2($){let J=T($.repoUrl),Z=T($.branch),X=T($.headSha),Q=T($.modelId);if(!J||!Z||!X||!Q)throw Error("Cloud handoff fingerprint fields cannot be empty.");let V=T($.organizationId),j=W2($.workspaceRelativePath),Y=$.mode;return{repoUrl:J,branch:Z,headSha:X,modelId:Q,...V?{organizationId:V}:{},...j?{workspaceRelativePath:j}:{},...Y?{mode:Y}:{}}}function k6($,J){return $!==void 0&&J!==void 0&&$.repoUrl===J.repoUrl&&$.branch===J.branch&&$.headSha.toLowerCase()===J.headSha.toLowerCase()&&$.modelId===J.modelId&&$.organizationId===J.organizationId&&$.workspaceRelativePath===J.workspaceRelativePath&&$.mode===J.mode}function F2($){let J=F0($);if(!J||typeof J.repoUrl!=="string"||typeof J.branch!=="string"||typeof J.headSha!=="string"||typeof J.modelId!=="string")return;try{return N2({repoUrl:J.repoUrl,branch:J.branch,headSha:J.headSha,modelId:J.modelId,...typeof J.organizationId==="string"?{organizationId:J.organizationId}:{},...typeof J.workspaceRelativePath==="string"?{workspaceRelativePath:J.workspaceRelativePath}:{},...J.mode==="plan"||J.mode==="yolo"||J.mode==="zen"?{mode:J.mode}:{}})}catch{return}}function y6($){let J=F0(F0($)?.handoff);if(!J)return;let Z=T(J.toCloudSessionId),X=T(J.handedOffAt),Q=J.status;if(!Z||!X||Q!=="pending"&&Q!=="complete")return;let V=T(J.innerSessionId),j=T(J.dashboardUrl),Y=F2(J.fingerprint);return{toCloudSessionId:Z,handedOffAt:X,status:Q,...V?{innerSessionId:V}:{},...j?{dashboardUrl:j}:{},...Y?{fingerprint:Y}:{}}}function g6($,J){return{...$??{},handoff:J}}function h6($){let{handoff:J,cloudHandoffIntent:Z,cloudHandoffSeedDispatched:X,...Q}=$??{};return Q}function v6($,J){let Z=J.trim();if(!Z)throw Error("Cloud session id cannot be empty.");let X=new URL("/agents",$);return X.searchParams.set("sessionId",Z),X.toString()}function n0($){return $.map((J)=>{let Z=J&&typeof J==="object"?J:{};return{role:Z.role,content:Z.content}})}function K0($,J){return $.length===J.length&&JSON.stringify(n0($))===JSON.stringify(n0(J))}class L0 extends Error{constructor($,J){super(`Cloud transcript verification failed (local ${$} messages, cloud ${J}).`);this.name="CloudHandoffTranscriptMismatchError"}}import{randomUUID as K2}from"node:crypto";import{decodeJwtPayload as L2}from"@cline/shared";var G2=610000,z2=3000,G0=15000,_2="CLOUD_SESSION_ERROR:",$1="__cline_create_request__:";function J1($){return($.trim().split(`
|
|
8
|
+
`)[0]??"").trim().slice(0,72)}class _ extends Error{code;detail;connectUrl;status;constructor($,J,Z,X){super(`${_2}${JSON.stringify({code:$,message:J,connectUrl:Z})}`);this.code=$;this.detail=J;this.connectUrl=Z;this.status=X;this.name="CloudSessionError"}}class Z1 extends Error{constructor($){super($ instanceof Error?$.message:"Cloud handoff creation was rejected.",{cause:$});this.name="CloudHandoffCreationRejectedError"}}function q0($){let J=$.length;while(J>0&&$[J-1]==="/")J--;return $.slice(0,J)}function q2($){return`${$1}${$}`.slice(0,255)}function o0($){return $?.startsWith($1)===!0}function O0($){switch($){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return $;default:return}}function z0($){let J=L2($.replace(/^workos:/,""));return typeof J?.sub==="string"&&J.sub.trim()?J.sub.trim():void 0}function e0($){return new Promise((J,Z)=>{if($.aborted){Z($.reason);return}let X=()=>{clearTimeout(Q),Z($.reason)},Q=setTimeout(()=>{$.removeEventListener("abort",X),J()},z2);$.addEventListener("abort",X,{once:!0})})}function O2($,J){if($&&typeof $==="object"){let Z=$.error;if(typeof Z==="string"&&Z.trim())return Z.trim()}return J}function _0($,J,Z,X){let Q=O2(J,`Cloud session request failed (${$})`);if($===401)return new _("authentication_required",Q);if($===404)return new _("session_not_found",Q);if($===410)return new _("session_expired",Q);if($===412)return new _("github_not_connected",Q,X??`${q0(Z)}/dashboard/integrations`);if($===403&&Q.trim().toLowerCase()==="forbidden")return new _("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,$);return new _("request_failed",Q,void 0,$)}class A2{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor($){this.options=$;this.apiBaseUrl=q0($.apiBaseUrl),this.appBaseUrl=q0($.appBaseUrl),this.fetchImpl=$.fetch??fetch,this.createTimeoutMs=$.createTimeoutMs??G2}async request($,J={},Z,X,Q){let V=!1,j;while(!0){let Y;try{Y=typeof X==="string"?X:await this.options.getAuthToken()}catch(K){if(j)throw _0(401,void 0,this.appBaseUrl,Z);throw K}if(!Y?.trim())throw new _("authentication_required","Sign in to Cline before starting a cloud session.");if(Y.trim()===j)throw new _("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof X==="object"){if(X.subject?z0(Y.trim())!==X.subject:Y.trim()!==X.token)throw new _("authentication_required","The signed-in account changed during cloud session creation.");X.token=Y.trim()}Q?.();let W=await this.fetchImpl(`${this.apiBaseUrl}${$}`,{...J,signal:J.signal??AbortSignal.timeout(G0),headers:{Accept:"application/json",Authorization:`Bearer ${Y.trim()}`,...J.body?{"Content-Type":"application/json"}:{},...J.headers}}),F=W.status===204?void 0:await W.json().catch(()=>{return});if(!W.ok){if(W.status===401&&typeof X==="object"&&!V&&X.subject){V=!0,j=Y.trim();continue}throw _0(W.status,F,this.appBaseUrl,Z)}return F?.data}}async list($){return await this.listWithToken($)}async listWithToken($,J,Z=!1){let X=$?.trim()?`?organizationId=${encodeURIComponent($.trim())}`:"";return(await this.request(`/api/v1/session${X}`,{},void 0,J)??[]).flatMap((V)=>{if(!V||typeof V!=="object"||typeof V.id!=="string")return[];return[{...V,title:!Z&&o0(V.title)?void 0:V.title,repoContext:V.repoContext&&typeof V.repoContext==="object"?V.repoContext:{},metadata:{...V.metadata&&typeof V.metadata==="object"?V.metadata:{},...!Z&&o0(V.title)?{createRequestTitle:V.title}:{}}}]})}async listRepositories($){let J=$?.trim(),Z=J?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,X=J?`/api/v1/organizations/${encodeURIComponent(J)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let Q=await this.request(X)??[];return{connected:!0,connectUrl:Z,repositories:Q.flatMap((V)=>{let j=Number(V.id),Y=String(V.html_url??V.clone_url??"").trim();if(!Number.isSafeInteger(j)||j<=0||!Y)return[];let W=String(V.name??"").trim();return[{id:j,name:W,fullName:String(V.full_name??(W||Y)).trim(),url:Y,defaultBranch:String(V.default_branch??"").trim()}]})}}catch(Q){if(Q instanceof _&&Q.code==="session_not_found")return{connected:!1,connectUrl:Z,repositories:[]};throw Q}}async listBranches($,J,Z={}){if(!Number.isSafeInteger($)||$<=0)throw new _("request_failed","Select a GitHub repository before loading branches.");let X=J?.trim(),Q=X?`/api/v1/organizations/${encodeURIComponent(X)}/integrations/github/repositories/${$}/branches`:`/api/v1/integrations/github/repositories/${$}/branches`,V=new URLSearchParams,j=Z.query?.trim(),Y=Z.cursor?.trim();if(j)V.set("query",j);if(Y)V.set("cursor",Y);let W=V.size>0?`${Q}?${V}`:Q;try{let F=await this.request(W),K=Array.isArray(F)?F:Array.isArray(F?.items)?F.items:[],N=j?.toLowerCase();return{available:!0,branches:K.flatMap((z)=>{let L=String(z.name??"").trim();return L&&(!Array.isArray(F)||!N||L.toLowerCase().includes(N))?[L]:[]}),nextToken:Array.isArray(F)?"":String(F?.nextToken??"").trim()}}catch(F){if(F instanceof _&&F.code==="session_not_found")return{available:!1,branches:[]};throw F}}async status($,J={}){return await this.request(`/api/v1/session/${encodeURIComponent($)}/status`,{signal:J.signal},void 0,J.authToken)}async create($){if($.handoff&&typeof $.handoff.onCreating!=="function")throw new _("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let J=(await this.options.getAuthToken())?.trim();if(!J)throw new _("authentication_required","Sign in to Cline before starting a cloud session.");let Z={token:J,subject:z0(J)},X=q2($.requestId?.trim()||K2()),Q=$.handoff?`${Z.subject??J}/${$.organizationId??""}/${$.requestId?.trim()??""}`:void 0;if($.handoff&&!$.requestId?.trim())throw new _("request_failed","A stable request id is required for cloud handoff creation.");let V=async()=>(await this.listWithToken($.organizationId??void 0,Z,!0)).filter((N)=>N.title===X&&N.repoContext.repoUrl===$.repoUrl&&N.metadata.modelId===$.modelId&&(!$.branch?.trim()||N.repoContext.branch===$.branch.trim())),j=async(N)=>{if(N.status==="failed"||N.expiredAt&&Date.parse(N.expiredAt)<=Date.now()){let L=new _(N.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(N.id,Z)}catch(G){if(!(G instanceof _&&(G.code==="session_not_found"||G.code==="session_expired")))throw AggregateError([L,G],"The unusable recovered cloud handoff workspace could not be removed.")}if(Q)this.unconfirmedHandoffCreates.delete(Q),this.completedHandoffCreates.delete(Q);throw await $.handoff?.onOuterSessionRemoved?.(N.id),L}await $.handoff?.onOuterSessionCreated(N.id,{created:!1});let z={sessionId:N.id,status:N.status,sandboxUrl:N.sandboxUrl,cleanupAuthToken:Z.token};if(Q)this.unconfirmedHandoffCreates.delete(Q),this.completedHandoffCreates.set(Q,z);return z};if(Q){let N=await V();if(N.length>1)throw new _("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(N[0])return await j(N[0]);let z=this.completedHandoffCreates.get(Q);if(z){try{await this.request(`/api/v1/session/${encodeURIComponent(z.sessionId)}/status`,{},void 0,Z)}catch(L){if(L instanceof _&&(L.code==="session_not_found"||L.code==="session_expired"))await $.handoff?.onOuterSessionRemoved?.(z.sessionId),this.completedHandoffCreates.delete(Q),this.unconfirmedHandoffCreates.delete(Q);throw L}return await $.handoff?.onOuterSessionCreated(z.sessionId,{created:!1}),{...z,cleanupAuthToken:Z.token}}if(this.unconfirmedHandoffCreates.has(Q))throw new _("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(Q)}try{await $.handoff?.onCreating()}catch(N){if(Q)this.unconfirmedHandoffCreates.delete(Q);throw N}let Y=new AbortController,W=setTimeout(()=>Y.abort(),this.createTimeoutMs),F,K=!1;try{let N=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:$.modelId,repoUrl:$.repoUrl,title:X,...$.branch?.trim()?{branch:$.branch.trim()}:{},...$.organizationId?.trim()?{organizationId:$.organizationId.trim()}:{}}),signal:Y.signal},$.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,Z,()=>{K=!0}),z=N?.sessionId?.trim();if(!z)throw new _("request_failed","The cloud session service returned no session id.");F=z,await this.persistHandoffOuterSession($,z,Z,Q);let L={sessionId:z,status:N.status?.trim()||"provisioning",sandboxUrl:N.sandboxUrl?.trim()??"",cleanupAuthToken:Z.token};if(Q)this.unconfirmedHandoffCreates.delete(Q),this.completedHandoffCreates.set(Q,L);return L}catch(N){if(F)throw N;let z=!K||N instanceof _&&(N.status!==void 0&&N.status>=400&&N.status<500&&N.status!==408&&N.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(N.code));if(Q&&z)throw this.unconfirmedHandoffCreates.delete(Q),new Z1(N);if(Y.signal.aborted||!(N instanceof _)||N instanceof _&&N.code==="request_failed"&&(N.status===void 0||N.status>=500||N.status===408||N.status===409)){let G=[];try{G=await V()}catch(O){if($.handoff)throw AggregateError([N,O],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(G.length>1)throw new _("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let q=G[0];if(q){if($.handoff)return await j(q);return{sessionId:q.id,status:q.status,sandboxUrl:q.sandboxUrl,cleanupAuthToken:Z.token}}}else if(Q)this.unconfirmedHandoffCreates.delete(Q);throw N}finally{clearTimeout(W)}}async persistHandoffOuterSession($,J,Z,X){if(!$.handoff)return;try{await $.handoff.onOuterSessionCreated(J,{created:!0})}catch(Q){try{await this.deleteWithAuth(J,Z.token)}catch(V){if(!(V instanceof _&&(V.code==="session_not_found"||V.code==="session_expired")))throw AggregateError([Q,V],`Cloud session ${J} was created but its recovery record could not be saved or its sandbox removed.`)}if(X)this.unconfirmedHandoffCreates.delete(X);throw await $.handoff.onOuterSessionRemoved?.(J),Q}}async waitUntilReady($,J,Z){J=AbortSignal.any([J,AbortSignal.timeout(this.createTimeoutMs)]);let X=await this.options.getAuthToken(),Q=X?{token:X,subject:z0(X)}:void 0;while(!J.aborted){let V;try{V=await this.request(`/api/v1/session/${encodeURIComponent($)}/status`,{signal:AbortSignal.any([J,AbortSignal.timeout(G0)])},void 0,Q)}catch(Y){if(J.aborted)throw Y;if(Y instanceof _&&Y.code!=="request_failed")throw Y;await e0(J);continue}let j=V?.status?.trim().toLowerCase();if(Z?.({phase:O0(V?.phase)}),j==="ready"||j==="active")return;if(j==="failed")throw new _("session_failed",V?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(j!=="provisioning")throw new _("request_failed","The cloud session service returned an unexpected provisioning status.");await e0(J)}throw J.reason}async delete($,J){await this.deleteWithAuth($,J)}async deleteWithAuth($,J){let Z;try{await this.request(`/api/v1/session/${encodeURIComponent($)}`,{method:"DELETE"},void 0,J)}catch(X){if(!(X instanceof _)||X.code!=="session_not_found"&&X.code!=="session_expired")throw X;Z=X}for(let[X,Q]of this.completedHandoffCreates)if(Q.sessionId===$)this.completedHandoffCreates.delete(X),this.unconfirmedHandoffCreates.delete(X);if(Z)throw Z}async updateTitle($,J){return await this.request(`/api/v1/session/${encodeURIComponent($)}`,{method:"PATCH",body:JSON.stringify({title:J})})}async history($){let J=await this.options.getAuthToken();if(!J?.trim())throw new _("authentication_required","Sign in to Cline to load this session's history.");let Z=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent($)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${J.trim()}`},signal:AbortSignal.timeout(G0)});if(Z.status===404)return null;let X=await Z.json().catch(()=>{return});if(!Z.ok)throw _0(Z.status,X,this.appBaseUrl);if(!X||typeof X!=="object"||!("version"in X)||X.version!==1||!("messages"in X)||!Array.isArray(X.messages))throw new _("request_failed","Invalid archived session history");return X.messages}}import{randomUUID as G6}from"node:crypto";import{posix as W0}from"node:path";import{createSessionId as h8,ensureLoopbackProxyBypass as h1,isHubProtocolCompatible as v8,resolveClineBuildEnv as S8,resolveHubCommandTimeoutMs as m8}from"@cline/shared";import I8 from"ws";var X1="session_not_found";class t extends Error{sessionId;code="session_not_found";constructor($,J){super(J??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function Q1($){return $ instanceof t||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}import{spawn as J8}from"node:child_process";import{closeSync as Z8,mkdirSync as X8,openSync as Q8,readFileSync as V8,unlinkSync as Y8}from"node:fs";import{basename as j8,dirname as W8,join as N8}from"node:path";import{fileURLToPath as F8}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as K8,isBunEmbeddedModulePath as L8,isHubDaemonProcess as G8,resolveClineBuildEnv as x1,withResolvedClineBuildEnv as z8}from"@cline/shared";import{createHash as D2,randomBytes as U2}from"node:crypto";import{mkdir as B0,open as V1,readFile as F1,rename as M2,rm as D0,writeFile as R2}from"node:fs/promises";import{dirname as K1,join as U0}from"node:path";import{ensureLoopbackProxyBypass as C2,isHubProtocolCompatible as P2}from"@cline/shared";import{resolveClineDataDir as S,resolveClineDir as J4}from"@cline/shared/storage";var r={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.86-nightly.1790389788",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var H2="CLINE_HUB_DISCOVERY_PATH",E2="CLINE_HUB_BUILD_ID",x2="CLINE_HUB_BUILD_EPOCH_MS",T2=30000,w2=15000,Y1=100;function f2($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function b2($){return D2("sha256").update($).digest("hex").slice(0,12)}function k2($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function j1($){return new Promise((J)=>setTimeout(J,$))}function y2($){return`${$}.lock`}async function g2($){try{let J=JSON.parse(await F1(U0($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function A0($){await D0($,{recursive:!0,force:!0}).catch(()=>{return})}function g(){let $=process.env[E2]?.trim();if($)return $;return"sdk-v1-a08f57052e1df2bce33407947b2593f32f8445a2fd11046e12aeacc802793bf7".trim()||`source-${String(r.version)}`}function h2(){let $=Number(process.env[x2]);if(Number.isFinite($)&&$>0)return $;return Number.isFinite(1790389817343)?1790389817343:void 0}function s($,J=g()){let Z=P2($);if(!Z.compatible)return Z;let X=$.buildId?.trim();if(!X)return{compatible:!1,reason:"missing_build"};if(X!==J)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function W1($){return typeof $==="number"&&Number.isFinite($)&&$>0?$:void 0}function N1($){let J=$?.trim().split(/[-+]/,1)[0];if(!J)return;let Z=J.split(".").map((X)=>Number(X));if(Z.length===0||Z.some((X)=>!Number.isInteger(X)||X<0))return;return Z}function v2($,J){for(let Z=0;Z<Math.max($.length,J.length);Z++){let X=$[Z]??0,Q=J[Z]??0;if(X!==Q)return X<Q?-1:1}return 0}function L1($,J){let Z=$.buildId?.trim(),X=J.buildId?.trim();if(Z&&X&&Z===X)return 0;let Q=W1($.buildEpochMs),V=W1(J.buildEpochMs);if(Q!==void 0&&V!==void 0&&Q!==V)return Q<V?-1:1;let j=N1($.coreVersion),Y=N1(J.coreVersion);if(j&&Y){let W=v2(j,Y);if(W!==0)return W}if(Z&&X&&Z!==X)return Z<X?-1:1;return 0}function G1(){return{buildId:g(),buildEpochMs:h2(),coreVersion:String(r.version)}}function n($,J){let Z=J?.self??G1(),X=s($,Z.buildId??"");if(X.compatible)return!0;if(X.reason!=="build_mismatch"&&X.reason!=="missing_build")return!1;return L1(Z,$)<=0}function z1($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${b2($)}`,Z=process.env[H2]?.trim()||U0(S(),"locks","hub","owners",`${f2(J)}.json`);return{ownerId:J,discoveryPath:Z}}async function b($){try{let J=JSON.parse(await F1($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,protocolVersion:J.protocolVersion,minClientProtocolVersion:typeof J.minClientProtocolVersion==="string"?J.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof J.maxClientProtocolVersion==="string"?J.maxClientProtocolVersion:void 0,capabilities:Array.isArray(J.capabilities)?J.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,buildEpochMs:typeof J.buildEpochMs==="number"?J.buildEpochMs:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function _1($,J){await O1($,async()=>{let Z=K1($);await B0(Z,{recursive:!0});let X=`${$}.${process.pid}.${U2(6).toString("hex")}.tmp`,Q;try{Q=await V1(X,"wx",384),await Q.writeFile(`${JSON.stringify(J,null,2)}
|
|
9
|
+
`,{encoding:"utf8"}),await Q.sync(),await Q.close(),Q=void 0,await M2(X,$);let V;try{V=await V1(Z,"r"),await V.sync()}catch{}finally{await V?.close().catch(()=>{return})}}catch(V){throw await Q?.close().catch(()=>{return}),await D0(X,{force:!0}).catch(()=>{return}),V}})}async function h($){await O1($,async()=>{await D0($,{force:!0}).catch(()=>{return})})}async function q1($,J,Z){let X=y2($);await B0(K1(X),{recursive:!0});let Q=Date.now()+w2;while(!0){try{await B0(X,{recursive:!1})}catch(V){if((V instanceof Error&&"code"in V?String(V.code):"")!=="EEXIST")throw V;let Y=await g2(X);if(!Y){if(Date.now()>=Q){await A0(X);continue}await j1(Y1);continue}let W=Date.now()-Date.parse(Y.acquiredAt);if(!k2(Y.pid)||W>T2){await A0(X);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub ${J} lock ${X}`);await j1(Y1);continue}try{return await R2(U0(X,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
10
|
+
`,"utf8"),await Z()}finally{await A0(X)}}}function O1($,J){return q1(`${$}.mutation`,"discovery mutation",J)}function A1($,J){return q1($,"startup",J)}async function o($,J){C2();try{let Z=await fetch(J?.authToken?S2($):D1($),{headers:J?.authToken?{authorization:`Bearer ${J.authToken}`}:void 0,signal:J?.signal});if(!Z.ok)return;let X=await Z.json();if(typeof X.protocolVersion!=="string"||typeof X.host!=="string"||typeof X.port!=="number"||typeof X.url!=="string")return;return{protocolVersion:X.protocolVersion,minClientProtocolVersion:typeof X.minClientProtocolVersion==="string"?X.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof X.maxClientProtocolVersion==="string"?X.maxClientProtocolVersion:void 0,capabilities:Array.isArray(X.capabilities)?X.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof X.coreVersion==="string"?X.coreVersion:void 0,buildId:typeof X.buildId==="string"?X.buildId:void 0,buildEpochMs:typeof X.buildEpochMs==="number"?X.buildEpochMs:void 0,host:X.host,port:X.port,url:X.url,hubId:typeof X.hubId==="string"?X.hubId:void 0,authToken:typeof X.authToken==="string"?X.authToken:void 0,pid:typeof X.pid==="number"?X.pid:void 0,startedAt:typeof X.startedAt==="string"?X.startedAt:void 0,updatedAt:typeof X.updatedAt==="string"?X.updatedAt:void 0}}catch{return}}function B1($,J,Z="/hub"){return new URL(`ws://${$}:${J}${Z}`).toString()}function D1($){let J=new URL($);return J.protocol=J.protocol==="wss:"?"https:":"http:",J.pathname="/health",J.search="",J.toString()}function S2($){let J=new URL(D1($));return J.pathname="/status",J.toString()}import{CLINE_HUB_DEV_PORT as m2,CLINE_HUB_PORT as I2,resolveClineBuildEnv as p2}from"@cline/shared";var l2="CLINE_HUB_HOST",u2="CLINE_HUB_PORT",c2="CLINE_HUB_PATHNAME",a2="127.0.0.1",d2=I2,i2="/hub";function U1($){return p2($)==="development"?m2:d2}function t2($={}){return($.env??process.env)[l2]?.trim()||a2}function r2($={}){let Z=($.env??process.env)[u2]?.trim();if(!Z)return U1($);let X=Number.parseInt(Z,10);if(!Number.isInteger(X)||X<1||X>65535)return U1($);return X}function s2($={}){return($.env??process.env)[c2]?.trim()||i2}function M1($={},J={}){return{host:$.host??t2(J),port:$.port??r2(J),pathname:$.pathname??s2(J)}}import{join as n2}from"node:path";var o2="shared:cline",e2="CLINE_HUB_DISCOVERY_PATH",$8="hub-production";function m($=o2){return z1(`${$}@${g()}`)}function e(){return{ownerId:$8,discoveryPath:process.env[e2]?.trim()||n2(S(),"locks","hub","production.json")}}var R1=15000,_8=200,C1=3000,q8=100,O8=[100,250,500,1000,2000],A8="--cline-hub-daemon",B8=3,D8=60000,P1=new Map;function U8($,J=Date.now()){let Z=P1.get($);if(!Z||J-Z.windowStartedAt>D8)return P1.set($,{count:1,windowStartedAt:J}),!0;return Z.count+=1,Z.count<=B8}function M8($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function R8(){try{let $=N8(S(),"logs","hub-daemon.log");return X8(W8($),{recursive:!0}),{fd:Q8($,"a"),logPath:$}}catch{return}}function C8(){return x1()==="production"?e():m()}function I($){return n($)}function P8($){try{let J=JSON.parse(V8(`${$}.superseded`,"utf8"));return{url:typeof J.url==="string"?J.url:void 0,authToken:typeof J.authToken==="string"?J.authToken:void 0,pid:typeof J.pid==="number"?J.pid:void 0}}catch{return}}function M0($){try{Y8(`${$}.superseded`)}catch{}}function H1($,J,Z){if(!J||J.url!==Z)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function p($,J){try{return await o($,{authToken:J})}catch{return}}async function E1($,J){let Z=Date.now()+J;while(Date.now()<Z){if(!(await p($))?.url)return!0;await new Promise((Q)=>setTimeout(Q,q8))}return!1}async function C0($,J){if(!U8($.url))return!1;await l($.url,$.authToken,"retired by newer install").catch(()=>!1),await w1($.url,$.authToken).catch(()=>!1);let Z=await E1($.url,C1);if(!Z&&$.pid&&H8($.pid)){try{process.kill($.pid,"SIGTERM")}catch{}Z=await E1($.url,C1)}if(Z)await h(J).catch(()=>{return});return Z}function H8($){try{return process.kill($,0),!0}catch(J){return J?.code==="EPERM"}}async function E8($){try{return(await P0($.url,$.authToken)).activeSessionCount>0}catch{return!1}}async function R0($,J){if(I($))return"reusable";let Z=await l($.url,$.authToken,"retired by newer install").catch(()=>!1);if(await E8($)){if(Z)await l($.url,$.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let X=await C0($,J);if(!X&&Z)await l($.url,$.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return X?"retired":"failed"}async function x8($){if(x1()!=="production")return;let J=m();if(J.discoveryPath===$.discoveryPath)return;let Z=await b(J.discoveryPath);if(Z?.url)await C0(Z,J.discoveryPath);else await h(J.discoveryPath).catch(()=>{return})}function T8(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return F8(new URL(`./entry.${$}`,import.meta.url))}function w8($,J){if(L8($))return[A8];return[...J&&$.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],$]}function f8($,J){let Z=T8(),X=process.execPath?.trim();if(!X)throw Error("unable to resolve runtime executable for hub daemon");let Q=j8(X).toLowerCase().includes("bun"),V=w8(Z,Q);return{launcher:X,args:[...V,"--cwd",$,...M8(J),...J.manageConnectors===!1?["--no-connectors"]:[]],cwd:$,env:{...z8(process.env),CLINE_NO_INTERACTIVE:"1",[K8]:"1"}}}function b8($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function k8($,J={}){if(G8())return;let Z=f8($,J),X=R8();try{J8(Z.launcher,Z.args,{detached:!0,stdio:X?["ignore",X.fd,X.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(X)Z8(X.fd)}}async function y8($,J={}){for(let Z=0;;Z++)try{k8($,J);return}catch(X){let Q=O8[Z];if(!b8(X)||Q===void 0)throw X;await new Promise((V)=>setTimeout(V,Q))}}async function g8($,J,Z={}){let X=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=M1(Z),V=B1(Q.host,Q.port,Q.pathname),j=(G)=>{if(!X)$0(G.url,G.authToken);return G};await x8($).catch(()=>{return});let Y=await b($.discoveryPath),W=Y?.url?void 0:P8($.discoveryPath),F=!1;if(Y?.url){let G=Y.authToken;if(!G)F=!0,await C0(Y,$.discoveryPath);else{let q=await p(Y.url,G);if(q?.url&&I(q)&&await w(q.url,{authToken:G}))return M0($.discoveryPath),j({url:q.url,authToken:G});if(q?.url){if(await R0({...q,authToken:G},$.discoveryPath)==="deferred_busy"&&await w(q.url,{authToken:G}))return j({url:q.url,authToken:G})}else await h($.discoveryPath).catch(()=>{return})}}let K=await p(V);if(K?.url){let G=H1(K,Y??W,V);if(I(K)){let O=[K.authToken,Y?.authToken,W?.authToken].filter((D)=>typeof D==="string"&&D.trim().length>0);for(let D of O){if(!await w(K.url,{authToken:D}))continue;let H={hubId:K.hubId??`repaired-${K.port}`,protocolVersion:K.protocolVersion,minClientProtocolVersion:K.minClientProtocolVersion,maxClientProtocolVersion:K.maxClientProtocolVersion,capabilities:K.capabilities,coreVersion:K.coreVersion,buildId:K.buildId,authToken:D,host:K.host,port:K.port,url:K.url,pid:K.pid??Y?.pid??W?.pid,startedAt:K.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await _1($.discoveryPath,H)}catch{}return M0($.discoveryPath),j({url:K.url,authToken:D})}throw Error(`A compatible Cline Hub is already running at ${V}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${F?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let q=await R0(G,$.discoveryPath);if(q==="deferred_busy"){for(let O of[G.authToken,Y?.authToken].filter((B)=>typeof B==="string"&&B.trim().length>0))if(await w(K.url,{authToken:O}))return j({url:K.url,authToken:O});if(Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An older Cline Hub is running at ${V} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(q==="failed"&&Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An incompatible Cline Hub is already running at ${V} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let z=Z.allowPortFallback===!0&&Q.port!==0?{...Q,port:0}:Q;await y8(J,{...z,manageConnectors:Z.manageConnectors});let L=Date.now()+R1;while(Date.now()<L){let G=await b($.discoveryPath);if(G?.url&&G.authToken){let O=await p(G.url,G.authToken);if(O?.url&&I(O)&&await w(O.url,{authToken:G.authToken}))return M0($.discoveryPath),j({url:O.url,authToken:G.authToken})}let q=await p(V);if(q?.url&&!I(q)){let O=H1(q,G??W,V),B=await R0(O,$.discoveryPath);if(B==="deferred_busy"&&G?.authToken&&await w(q.url,{authToken:G.authToken}))return j({url:q.url,authToken:G.authToken});if(B==="failed"&&Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An incompatible Cline Hub is still running at ${V} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((O)=>setTimeout(O,_8))}throw Error(`Timed out after ${R1}ms waiting for detached hub startup.`)}async function T1($,J={}){let Z=C8();return await A1(Z.discoveryPath,async()=>g8(Z,$,J))}function p8(){return S8()==="production"?e():m()}function l8(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function v1($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return v1($.data);return String($)}function u8($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function f1($){let J=$,Z=u8(J.reason);return new R("hub_connection_closed",J.code||Z?`Hub connection closed (code=${J.code??0}${Z?`, reason=${Z}`:""})`:E0,{closeCode:J.code,closeReason:Z||void 0})}function b1($,J){if($ instanceof R)return $;if($ instanceof Error)return new R("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new R("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new R("hub_connect_failed",Z);let X=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new R("hub_connect_failed",X?`Failed to connect to hub at ${J.toString()} (${X} event before socket open).`:`Failed to connect to hub at ${J.toString()}.`)}var H0="*",J0=8000,c8="cline-hub-auth.",S1=new Map,m1=new Set,a8=3000;var E0="Hub connection closed",d8=250,i8=5000,k1=0.5;class R extends Error{code;details;constructor($,J,Z){super(J);this.code=$;this.details=Z;this.name="HubTransportError"}}function t8($){return $ instanceof R}class x0 extends Error{command;code;constructor($,J,Z){super(Z);this.command=$;this.code=J;this.name="HubCommandError"}}function w0($,J={}){let Z=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),Z)return Z;if(J.skipRegistry)return;let X=f0($.toString());return X?S1.get(X):void 0}function r8($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function f0($){if(!r8($))return;let J=new URL(I1($));return J.search="",J.hash="",J.toString()}function y1($){let J=f0($);return!!J&&m1.has(J)}function $0($,J){let Z=f0($);if(Z){if(m1.add(Z),J?.trim())S1.set(Z,J)}return $}class u{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new R("hub_connection_closed",E0);sawSocketClose=!1;registered=!1;capabilities;constructor($){this.options=$;if($.authToken?.trim()&&$.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url,this.capabilities=[...$.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities($){if(this.capabilities=$.map((J)=>({...J})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),J=this.options.authToken?.trim()||w0($,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if($.hash="",J&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,X=this.openSocket($,J,Z),Q;this.connectPromise=X.then(async(j)=>{if(Q=j,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{j.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let Y of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Y));this.reconnectAttempt=0});let V=this.connectPromise;try{await V}catch(j){if(this.connectPromise===V)this.connectPromise=void 0;if(Q&&this.socket===Q){this.lastCloseError=b1(j,$),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{Q.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw j}}async openSocket($,J,Z){let X=this.options.resolveConnectionHeaders,Q;if(X){let W;try{Q=await Promise.race([Promise.resolve().then(()=>X()),new Promise((F,K)=>{W=setTimeout(()=>{K(new R("hub_connect_timeout",`Timed out resolving hub connection headers after ${J0}ms`))},J0)})])}catch(F){let K=F instanceof R?F:new R("hub_connect_failed",F instanceof Error?F.message:String(F));if(Z===this.connectGeneration)this.lastCloseError=K;throw K}finally{clearTimeout(W)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(Q&&Object.keys(Q).some((W)=>W.toLowerCase()==="sec-websocket-protocol")){let W=new R("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=W;throw W}let V=Q?new I8($.toString(),{headers:{...Q}}):new(l8())($.toString(),J?[`${c8}${J}`]:void 0);this.socket=V;let j=!1,Y=new Promise((W,F)=>{let K=!1,N=setTimeout(()=>{if(K)return;K=!0,j=!0;let z=new R("hub_connect_timeout",`Timed out connecting to hub after ${J0}ms`);if(this.socket===V)this.lastCloseError=z,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{V.close()}catch{}F(z)},J0);V.addEventListener("open",()=>{if(K)return;K=!0,clearTimeout(N),W()}),V.addEventListener("error",(z)=>{if(K)return;K=!0,clearTimeout(N);let L=b1(z,$);if(this.socket===V)this.lastCloseError=L,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;F(L)}),V.addEventListener("close",(z)=>{if(K)return;K=!0,clearTimeout(N);let L=j?this.lastCloseError:f1(z);if(this.socket===V){if(!j)this.lastCloseError=L,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}F(L)})});return V.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(v1(W)))}),V.addEventListener("close",(W)=>{if(this.socket!==V)return;if(!j)this.lastCloseError=f1(W),this.sawSocketClose=!0;this.registered=!1;for(let F of this.pendingReplies.values())F.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await Y,V}subscribe($,J){let Z=J?.sessionId?.trim()||void 0,X={listener:$,sessionId:Z};return this.listeners.add(X),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(X))return;this.adjustSubscriptionCount(Z,-1)}}async command($,J,Z,X){let Q=0,V=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Z,X)}catch(j){if(!V||Q>=1||!await this.recoverLocalHubTransport(j))throw j;Q+=1}}async commandOnce($,J,Z,X,Q=!0){if(Q)await this.connect();X?.beforeDispatch?.();let V=h8("hubreq_");X?.onDispatch?.(V);let j=m8($,X?.timeoutMs),Y=new Promise((F,K)=>{let N=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(V))return;K(new x0($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${V}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(V,{resolve:(z)=>{if(N)clearTimeout(N);F(z)},reject:(z)=>{if(N)clearTimeout(N);K(z)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:V,clientId:this.clientId,sessionId:Z,timeoutMs:j,payload:J}})}catch(F){throw this.pendingReplies.delete(V),F}let W=await Y;if(!W.ok){if(W.error?.code===X1){let F=Z??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new t(F,W.error.message)}throw new x0($,W.error?.code,W.error?.message??`Hub command ${$} failed`)}return W}async recoverLocalHubTransport($){if(!y1(this.currentUrl)||!t8($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let J=await g1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!J)return!1;return this.currentUrl=J,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(d8*2**this.reconnectAttempt,i8),J=Math.round($*(1-k1)+Math.random()*$*k1);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},J)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!y1(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await g1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,$)this.lastCloseError=new R("hub_connection_closed",E0);for(let J of this.pendingReplies.values())J.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!$)return;this.sawSocketClose=!1,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new R("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,J){let Z=$==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(J)):void 0;this.sendFrame({kind:$,clientId:this.clientId,...J?{sessionId:J}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount($,J){let Z=this.subscriptionKeyForSessionId($),X=(this.subscriptionCounts.get(Z)??0)+J;if(X<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(J<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,X),J>0&&X===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??H0}subscriptionSessionIdFromKey($){return $===H0?void 0:$}handleFrame($){switch($.kind){case"reply":{let J=$.envelope.requestId;if(!J)return;let Z=this.pendingReplies.get(J);if(!Z)return;this.pendingReplies.delete(J),Z.resolve($.envelope);return}case"event":{let J=$.envelope.sequence;if(typeof J==="number"){let Z=$.envelope.sessionId?.trim();for(let X of[H0,Z]){if(!X||!this.subscriptionCounts.has(X))continue;let Q=this.lastEventSequenceByKey.get(X)??0;if(J>Q)this.lastEventSequenceByKey.set(X,J)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==$.envelope.sessionId?.trim())continue;Z.listener($.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function I1($){let J=new URL($);if(J.protocol==="http:")J.protocol="ws:";else if(J.protocol==="https:")J.protocol="wss:";return J.toString()}async function w($,J){let Z=new u({url:$,authToken:J?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function T0($,J){let Z=I1($),X=await o(Z,{authToken:J?.authToken});if(!X)return{status:"unreachable",url:Z};if(J?.requireCurrentBuild){let Q=g(),V=s(X,Q);if(!V.compatible&&!n(X))return{status:V.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!v8(X).compatible)return{status:"protocol_mismatch",url:Z};if(J?.verifyConnection===!0&&!await w(Z,{workspaceRoot:J.workspaceRoot,cwd:J.cwd,authToken:J.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}function s8($){let J=$&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[],Z=0,X=new Set;for(let Q of J){if(!Q||typeof Q!=="object")continue;let V=Q.participants;if(!Array.isArray(V)||V.length===0)continue;Z+=1;for(let j of V){let Y=j&&typeof j==="object"?j.clientId:void 0;if(typeof Y==="string"&&Y.trim())X.add(Y)}}return{activeSessionCount:Z,participantClientCount:X.size}}async function P0($,J,Z){let X=new u({url:$,authToken:J,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let Q=await X.command("session.list",{limit:500},void 0,{timeoutMs:a8});return s8(Q.payload)}finally{await X.dispose().catch(()=>{return})}}async function n8($,J,Z){try{return(await P0($,J,Z)).activeSessionCount===0}catch{return!1}}async function o8($,J){let Z=`${$.discoveryPath}.superseded`,X=await b(Z);if(!X?.url||!X.authToken)return;let Q=await T0(X.url,{authToken:X.authToken});if(Q.status!=="compatible")return;if(await n8(Q.url,X.authToken,J))return;return $0(Q.url,X.authToken)}async function e8($={}){if($.endpoint?.trim()){let Q=await T0($.endpoint);return Q.status==="compatible"?Q.url:void 0}let J=p8(),Z=await b(J.discoveryPath);if(!Z?.url)return await o8(J,$);let X=await T0(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if(X.status==="compatible")return $0(X.url,Z.authToken);if(X.status==="protocol_mismatch")await h(J.discoveryPath).catch(()=>{return});return}async function g1($={}){let J=await e8($);if(J&&await w(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return J;if($.endpoint?.trim())return;try{return(await T1($.workspaceRoot??process.cwd())).url}catch(Z){$.onStartupError?.(Z);return}}async function l($,J,Z,X){h1();let Q=new URL($),V=J?.trim()||w0(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";if(Q.pathname="/drain",Q.hash="",Z)Q.searchParams.set("reason",Z);if(X?.off)Q.searchParams.set("off","1");return(await fetch(Q,{method:"POST",headers:V?{authorization:`Bearer ${V}`}:void 0})).ok}async function w1($,J){h1();let Z=new URL($),X=J?.trim()||w0(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:X?{authorization:`Bearer ${X}`}:void 0})).ok}function $6($,J){if(!$||typeof $!=="object")return;let Z=$,X=typeof Z.id==="string"?Z.id.trim():"";if(!X)return;let Q=typeof Z.display_name==="string"?Z.display_name.trim():typeof Z.displayName==="string"?Z.displayName.trim():"",V=typeof Z.name==="string"?Z.name.trim():"";return{id:X,name:Q||V||X,catalogId:J}}function b0($,J){return Array.isArray($)?$.flatMap((Z)=>{let X=$6(Z,J);return X?[X]:[]}):[]}async function p1($,J={}){let Z=$.trim(),X=Z.length;while(X>0&&Z[X-1]==="/")X--;let Q=Z.slice(0,X),V=async(q)=>{let O=await(J.fetchImpl??fetch)(`${Q}${q}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!O.ok)throw Error(`HTTP ${O.status}`);return await O.json()},j,Y;try{[j,Y]=await Promise.all([V("/api/v1/ai/cline/models"),V("/api/v1/ai/cline/recommended-models")])}catch(q){throw Error("Could not load the cloud model catalog.",{cause:q})}let W=j&&typeof j==="object"?j:void 0,F=b0(Array.isArray(j)?j:W?.data,"cline"),K=Y&&typeof Y==="object"?Y:void 0,N=K?.data&&typeof K.data==="object"?K.data:K,z=b0(N?.clinePass,"cline-pass"),L=b0(N?.clineCloud,"cline-cloud"),G=new Set;return[...J.isOrganizationSession?[]:z,...L,...F].filter((q)=>{if(G.has(q.id))return!1;return G.add(q.id),!0})}import{formatDisplayUserInput as l1}from"@cline/shared";var J6=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function Z6($){switch($){case"user":case"assistant":case"tool":case"system":case"status":case"error":return $;default:return"assistant"}}function X6($){return $.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}function Q6($){let J=$?.userRunSpan;return typeof J==="number"&&Number.isInteger(J)&&J>=0?J:void 0}function V6($){if(typeof $.content==="string")return{hasAttachment:!1,text:$.content};if(!Array.isArray($.content))return{hasAttachment:!1,text:"unknown"};let J=!1,Z=!1,X=[];for(let Q of $.content){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let V=Q;if(V.type==="text"&&typeof V.text==="string")X.push(V.text);else if(V.type==="tool_result"||V.type==="tool-result")Z=!0;else if(V.type==="file"||V.type==="image")J=!0}return{hasAttachment:J&&!Z,text:X.join(`
|
|
11
|
+
`)}}function Y6($){let J=l1($);return J.startsWith("[TASK RESUMPTION]")||J==="The user approved switching to act mode. Continue with the approved plan now."}function j6($){if(Z6($.role)!=="user")return 0;let J=X6($),Z=typeof J?.kind==="string"?J.kind:void 0,X=Q6(J);if(Z==="compaction"||Z==="compaction_summary")return X??1;if(X!==void 0)return X;if(Z&&J6.has(Z))return 0;let Q=V6($);if(!Q.hasAttachment&&!l1(Q.text))return 0;if(!Q.hasAttachment&&Y6(Q.text))return 0;return 1}function u1($){return j6($)>0}function Q0($){return Array.isArray($?.sessions)?$.sessions.filter((J)=>Boolean(J)&&typeof J==="object"&&!Array.isArray(J)):[]}function k0($){let J=$.updatedAt;return typeof J==="number"?J:Date.parse(String(J??""))||0}function y0($){let J=$?.metadata&&typeof $.metadata==="object"?$.metadata:void 0;return String(J?.model??$?.model??"").trim()}function V0($){let J=$.metadata&&typeof $.metadata==="object"?$.metadata:void 0;return!String(J?.parentSessionId??$.parentSessionId??"").trim()}function i1($,J="text"){if(!$||typeof $!=="object"||Array.isArray($))return"";let Z=$.content;if(typeof Z==="string")return J==="text"?Z.trim():"";if(!Array.isArray(Z))return"";return Z.map((X)=>X&&typeof X==="object"&&!Array.isArray(X)?J==="thinking"&&X.type==="redacted_thinking"?"[redacted]":String(X[J]??""):"").join("").trim()}function Z0($){let J=$.trim(),Z=J.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(Z?Z[1]:J).trim()}function c($,J,Z){let X=Z0(Z);return $.filter((Q)=>Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)&&String(Q.role??"").toLowerCase()==="user"&&(X!==""||u1(Q))&&Z0(i1(Q))===X).length+J.filter((Q)=>Z0(Q.prompt)===X).length}function g0($){return $.flatMap((J)=>{if(J.event!=="session.pending_prompt_submitted")return[];let Z=J.payload?.prompt&&typeof J.payload.prompt==="object"&&!Array.isArray(J.payload.prompt)?J.payload.prompt:void 0,X=String(Z?.id??"").trim();if(!X)return[];return[{id:X,prompt:String(Z?.prompt??""),steer:Z?.delivery==="steer",attachmentCount:typeof Z?.attachmentCount==="number"?Z.attachmentCount:0,userImages:Array.isArray(Z?.userImages)?Z.userImages.filter((Q)=>typeof Q==="string"):void 0}]})}var W6=new Set(["run.completed","run.aborted","run.failed"]),N6=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function c1($,J){return $.filter((Z)=>Boolean(Z)&&typeof Z==="object"&&!Array.isArray(Z)&&String(Z.role??"").toLowerCase()==="assistant").map((Z)=>i1(Z,J)).filter(Boolean)}function a1($,J,Z="text"){let X=new Map;for(let Q of c1(J,Z))X.set(Q,(X.get(Q)??0)+1);return c1($,Z).filter((Q)=>{let V=X.get(Q)??0;if(V===0)return!0;if(V===1)X.delete(Q);else X.set(Q,V-1);return!1})}function X0($,J,Z=new Set){if(!$||typeof $!=="object")return Z;if(Array.isArray($)){for(let V of $)X0(V,J,Z);return Z}let X=$,Q=J==="tool_use"?X.id:X.tool_use_id;if(X.type===J&&typeof Q==="string")Z.add(Q);for(let V of Object.values(X))X0(V,J,Z);return Z}function d1($,J="assistant"){let Z="",X="";for(let Q of $)if(Q.event===`${J}.delta`)X+=J==="reasoning"&&Q.payload?.redacted&&!Q.payload?.text?"[redacted]":typeof Q.payload?.text==="string"?Q.payload.text:"";else if(Q.event===`${J}.finished`){let V=Q.payload?.[J==="assistant"?"text":"reasoning"],j=typeof V==="string"&&V?V:X;if(j)Z=j;X=""}return(Z||X).trim()}function t1($,J,Z={}){let X=Z.queueSnapshotApplied!==!1,Q=a1(J,Z.baselineMessages??[]),V=a1(J,Z.baselineMessages??[],"thinking"),j=X0(J,"tool_use"),Y=X0(J,"tool_result"),W=new Set($.slice(0,Z.messagesSnapshotEventCutoff??$.length)),F=new Set,K=new Map;for(let O of $.slice(0,Z.messagesSnapshotEventCutoff??$.length)){let B=g0([O])[0];if(!B)continue;let D=Z0(B.prompt),H=K.get(D)??Math.max(0,c(J,[],D)-c(Z.baselineMessages??[],[],D));if(K.set(D,Math.max(0,H-1)),H>0)F.add(O)}let z=[...X?$.slice(Z.queueSnapshotEventCutoff??$.length):$].reverse().find((O)=>O.event==="session.pending_prompts"),L=[],G=[],q=(O)=>{if(G.length===0)return;let B=G.filter((E)=>W.has(E)),D=(E)=>{if(!O)return-1;let M=[...B].reverse().findIndex(($2)=>$2.event===`${E}.finished`),v=M<0?-1:B.length-1-M;return v>=0||G.at(-1)?.event==="run.aborted"?v:B.length-1},H=D("assistant"),f=D("reasoning"),A=d1(B.slice(0,H+1)),C=A?Q.findIndex((E)=>E.endsWith(A)):-1,k=C>=0;if(k)Q.splice(C,1);let a=d1(B.slice(0,f+1),"reasoning"),N0=a?V.findIndex((E)=>E.endsWith(a)):-1;if(N0>=0)V.splice(N0,1);for(let[E,M]of G.entries()){if(F.has(M)){L.push({...M,payload:{...M.payload,transcriptReflected:!0}});continue}if(W.has(M)&&N6.has(M.event)&&(M.event.startsWith("reasoning.")?N0>=0&&E<=f:k&&E<=H))continue;if(M.event==="session.pending_prompts"&&M!==z)continue;if(W.has(M)&&M.event.startsWith("tool.")){let v=String(M.payload?.toolCallId??"").trim();if(Y.has(v)||M.event==="tool.started"&&j.has(v))continue}L.push(M)}G=[]};for(let O of $)if(G.push(O),W6.has(O.event))q(!0);return q(!1),L}import{formatDisplayUserInput as F6}from"@cline/shared";function Y0($){let J=structuredClone($),Z=(X)=>{if(!X||typeof X!=="object"||Object.isFrozen(X))return;for(let Q of Object.values(X))Z(Q);Object.freeze(X)};return Z(J),J}function j0($){let J=$?.trim();return J?F6(J).slice(0,120):void 0}function h0($){if(typeof $==="string")return $;if(Array.isArray($)){let J=[];for(let Z of $){if(typeof Z==="string"){if(Z.trim())J.push(Z);continue}if(!Z||typeof Z!=="object")continue;let X=Z,Q=typeof X.type==="string"?X.type:"",V=Q==="text"?String(X.text??""):Q==="thinking"?String(X.thinking??""):Q==="tool_use"?`[tool] ${String(X.name??"tool_call")}`:Q==="tool_result"?`[tool_result]
|
|
12
|
+
${h0(X.content)}`:Q==="image"?"[image]":Q==="redacted_thinking"?"[redacted_thinking]":typeof X.text==="string"?X.text:"";if(V.trim())J.push(V)}return J.join(`
|
|
13
|
+
`)}if($&&typeof $==="object"){let J=$;if(typeof J.text==="string")return J.text}return""}function K6($){let J=j0($??void 0);if(!J)return;return J.split(`
|
|
14
|
+
`)[0]?.trim().slice(0,70)||void 0}function L6($){for(let J of["user","assistant"])for(let Z of $){if(!Z||typeof Z!=="object")continue;let X=Z;if(X.role!==J)continue;let Q=j0(h0(X.content));if(!Q)continue;return Q.split(`
|
|
15
|
+
`)[0]?.trim().slice(0,70)||void 0}return}function v0($){let J=$.metadata&&typeof $.metadata==="object"?j0($.metadata.title):void 0;if(J)return J.slice(0,70);let Z=K6($.prompt);if(Z)return Z;let X=$.messages?L6($.messages):void 0;if(X)return X;return`Session ${$.sessionId.slice(-6)}`}function r1($,J,Z,X){let Q=J.payload??{},V=()=>{let Y=Z.get(X);if(Y===void 0||!$.messages[Y]||$.messages[Y]?.role!=="assistant")Y=$.messages.length,$.messages.push({role:"assistant",content:[]}),Z.set(X,Y);let W=$.messages[Y];if(!Array.isArray(W.content))W.content=[];return W.content},j=(Y,W,F)=>{let K=V(),N=K.at(-1);if(N?.type===Y)N[W]=`${N[W]??""}${F}`;else K.push({type:Y,[W]:F})};switch(J.event){case"assistant.delta":if(typeof Q.text==="string")j("text","text",Q.text);return;case"reasoning.delta":if(typeof Q.text==="string"&&Q.text)j("thinking","thinking",Q.text);else if(Q.redacted===!0)V().push({type:"redacted_thinking",data:""});return;case"assistant.finished":Z.delete(X);return;case"assistant.media":if(Q.media)V().push({type:"media",media:structuredClone(Q.media)});return;case"tool.started":{let Y=String(Q.toolCallId??"");if(Y&&!$.messages.some((W)=>Array.isArray(W.content)&&W.content.some((F)=>F.type==="tool_use"&&F.id===Y)))V().push({type:"tool_use",id:Y,name:String(Q.toolName??"tool"),input:structuredClone(Q.input??{})});return}case"tool.finished":{let Y=String(Q.toolCallId??"");if(Y&&!$.messages.some((W)=>Array.isArray(W.content)&&W.content.some((F)=>F.type==="tool_result"&&F.tool_use_id===Y)))$.messages.push({role:"user",content:[{type:"tool_result",tool_use_id:Y,content:typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??""),is_error:Boolean(Q.error)}]}),Z.delete(X);return}case"usage.updated":$.usage=structuredClone(Q.totals??Q.delta??{});return;case"session.pending_prompts":{let Y=Array.isArray(Q.prompts)?Q.prompts:[];$.promptsInQueue=Y.map((W)=>({id:String(W.id??""),prompt:String(W.prompt??""),steer:W.delivery==="steer",attachmentCount:typeof W.attachmentCount==="number"?W.attachmentCount:0,userImages:Array.isArray(W.userImages)?W.userImages.filter((F)=>typeof F==="string"):void 0})).filter((W)=>W.id&&(W.prompt||W.attachmentCount));return}case"session.pending_prompt_submitted":{let Y=Q.prompt,W=String(Y?.id??"");if(!W||$.lastQueuedPromptStartId===W)return;if($.lastQueuedPromptStartId=W,$.promptsInQueue=$.promptsInQueue.filter((F)=>F.id!==W),Q.transcriptReflected!==!0)$.messages.push({role:"user",content:[{type:"text",text:String(Y?.prompt??"")}]});$.busy=!0,$.status="running",$.endedAt=void 0,Z.delete(X);return}case"run.started":case"session.attached":case"session.updated":{if(typeof J.sequence==="number"&&$.lastHubStatusSequence!==void 0&&J.sequence<$.lastHubStatusSequence)return;if(typeof J.sequence==="number")$.lastHubStatusSequence=J.sequence;let Y=Q.session,W=typeof Y?.status==="string"?Y.status:J.event==="run.started"?"running":$.status,F=W==="pending"?"running":W;if(J.event==="session.updated"&&F==="running"&&$.endedAt!==void 0&&!$.busy)return;let K=$.busy;if($.status=F,$.busy=F==="running",J.event==="run.started"){if(!K)Z.delete(X);$.endedAt=void 0}return}case"run.completed":case"run.failed":case"run.aborted":{if(typeof J.sequence==="number"&&$.lastHubStatusSequence!==void 0&&J.sequence<$.lastHubStatusSequence)return;if(typeof J.sequence==="number")$.lastHubStatusSequence=J.sequence;$.status=typeof Q.reason==="string"?Q.reason:J.event==="run.failed"?"error":J.event==="run.aborted"?"aborted":"completed",$.busy=!1,$.endedAt=Date.now(),Z.delete(X);return}}}function S0($){return $ instanceof Error&&$.name==="HubTransportError"&&["hub_connect_timeout","hub_connect_failed","hub_connection_closed","hub_connection_not_open"].includes(String($.code))}function m0($,J){return $ instanceof Error&&$.name==="HubCommandError"&&$.code==="hub_command_timeout"&&(!J||$.command===J)}var U="/workspace",z6=30000,_6=2000,q6=2000,s1="IMPORTANT: GitHub authentication is handled automatically by the infrastructure. An egress proxy transparently injects credentials into all GitHub traffic. You do NOT need to set up, configure, or manage any tokens, API keys, or credentials, and you must never run `gh auth login` or attempt to authenticate manually. "+"The GitHub CLI (`gh`) is installed and already authenticated — prefer it for GitHub work "+"(`gh pr create`, `gh pr diff`, `gh issue list`, `gh api`, ...). `git` push and pull are authenticated the same way. "+"Simply run the commands normally — credentials are injected transparently.";function I0($){if(!$)return U;if(W0.isAbsolute($)||$.includes("\\")||$.split("/").some((Z)=>!Z||Z==="."||Z===".."))throw new _("request_failed","The handoff workspace path must stay inside the repository.");let J=W0.join(U,$);if(!J.startsWith(`${U}/`))throw new _("request_failed","The handoff workspace path must stay inside the repository.");return J}function a0($){let J=$.metadata.cwd;return typeof J==="string"&&W0.normalize(J)===J&&(J===U||J.startsWith(`${U}/`))?J:U}function n1($){let J=$?.metadata&&typeof $.metadata==="object"?$.metadata:void 0,Z=J?.handoff&&typeof J.handoff==="object"?J.handoff:void 0;return String(Z?.sourceSessionId??"").trim()}class u0 extends Error{constructor($){super($ instanceof Error?$.message:"Cloud conversation creation was not dispatched.",{cause:$});this.name="CloudHandoffSeedRejectedError"}}class c0 extends _{constructor(){super("request_failed","The connection was interrupted and Cline could not confirm whether this message was queued. Check the cloud session before resending it.");this.name="CloudQueueUnconfirmedError"}}class e1 extends Error{constructor(){super("The cloud session was created, but its transcript was not persisted. This cloud runtime cannot durably seed handoff transcripts and must use @cline/core 0.0.72 or newer. Updating the cloud runtime or pod is required; retrying /cloud against this same pod will not help.");this.name="CloudHandoffSeedUnsupportedError"}}function x($){let J=$.expiredAt?Date.parse($.expiredAt):Number.NaN;return Number.isFinite(J)&&J<=Date.now()}function O6($){return $.trim().startsWith("ses-")}function A6($,J){let Z=new URL(`/api/v1/session/${encodeURIComponent(J)}`,$);return Z.protocol=Z.protocol==="https:"?"wss:":"ws:",Z.toString()}function p0($){return{config:{executionTarget:"cloud",provider:"cline",providerId:"cline",model:$.metadata.modelId??"",modelId:$.metadata.modelId??"",repoUrl:$.repoContext.repoUrl??"",branch:$.repoContext.branch??"",cwd:a0($),workspaceRoot:U},messages:[],promptsInQueue:[],busy:!1,startedAt:Date.parse($.createdAt)||Date.now(),endedAt:x($)&&$.expiredAt?Date.parse($.expiredAt):void 0,status:$.status,attachedViaHub:!0}}function l0($,J,Z){return{sessionId:$.id,origin:"cloud",executionTarget:"cloud",status:J,provider:"cline",model:$.metadata.modelId??"",repoUrl:$.repoContext.repoUrl??"",branch:$.repoContext.branch??"",cwd:a0($),workspaceRoot:U,...Z?.trim()?{prompt:Z.trim()}:{},metadata:{origin:"cloud",repoUrl:$.repoContext.repoUrl??"",git:{url:$.repoContext.repoUrl??"",branch:$.repoContext.branch??""}}}}function o1($){return{sessionId:$.id,origin:"cloud",executionTarget:"cloud",status:$.status,provider:"cline",model:$.metadata.modelId??"",cwd:a0($),workspaceRoot:U,repoUrl:$.repoContext.repoUrl??"",branch:$.repoContext.branch??"",startedAt:$.createdAt,...$.lastActivityAt?{lastActivityAt:$.lastActivityAt}:{},endedAt:x($)?$.expiredAt??void 0:$.status==="failed"?$.lastActivityAt??$.createdAt:void 0,updatedAt:$.updatedAt,...$.title?.trim()?{title:$.title.trim()}:{},metadata:{...$.title?.trim()?{title:$.title.trim()}:{},origin:"cloud",...$.metadata.provisioningPhase?{provisioningPhase:$.metadata.provisioningPhase}:{},repoUrl:$.repoContext.repoUrl??"",git:{url:$.repoContext.repoUrl??"",branch:$.repoContext.branch??""}}}}function B6($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function D6($,J){let Z=[...$??[]],X=new Set(Z.map((Q)=>Q.id));for(let Q of J)if(!X.has(Q.id))Z.push(Q);return Z}class U6{options;sessionGenerations=new Map;sessions=new Map;approvals=new Map;listeners=new Set;detachedSessions=new Set;restoredOptions=new Map;authoritativeMessages=new Map;streamingMessages=new Map;disposed=!1;connections=new Map;connectionPromises=new Map;knownSessions=new Map;unlistedSessions=new Map;pendingInitialTasks;lastListedSessions=[];discoveryRefresh;unconfirmedInnerCreates=new Set;createRequests=new Map;provisioningControllers=new Map;sendAbortTokens=new Map;titleWrites=new Map;deletingSessions=new Set;createHubClient;constructor($){this.options=$;this.pendingInitialTasks=$.pendingInitialTasks??new Map,this.createHubClient=$.createHubClient??((J)=>new u(J))}restoreCreationOptions($,J){if(this.restoredOptions.set($,structuredClone(J)),this.pendingInitialTasks.has($))this.pendingInitialTasks.set($,{...this.pendingInitialTasks.get($),...structuredClone(J)});let Z=this.sessions.get($);if(Z)Object.assign(Z.config,structuredClone(J))}seedSessionState($,J){if(!this.sessions.has($))this.sessions.set($,structuredClone(J))}stateFromRecord($){let J=p0($);return Object.assign(J.config,this.pendingInitialTasks.get($.id),this.restoredOptions.get($.id)),J}getSnapshot($){let J=this.knownSessions.get($),Z=this.sessions.get($)??(J?this.stateFromRecord(J):void 0);if(!Z)return;let X=this.connections.get($);return Y0({...Z,sessionId:$,record:J,approvals:Array.from(this.approvals.values()).filter((Q)=>Q.item.sessionId===$).map((Q)=>Q.item),connectionState:this.detachedSessions.has($)||this.disposed?"detached":X?.reconnectResolution||X?.rehydrationPromise?"reconnecting":X?X.connected?"connected":X.reconnecting?"reconnecting":"connecting":this.connectionPromises.has($)?"connecting":"detached",transcriptKnown:X?.transcriptKnown??Boolean(J&&x(J))})}subscribe($,J){let Z=(X)=>{if(!J||X.sessionId===J)$(X)};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}publish($){let J=$.type==="snapshot"?Object.freeze($):Y0($);for(let Z of this.listeners)try{Z(J)}catch(X){this.options.logger?.error?.("Cloud session subscriber failed",{error:X})}}publishSnapshot($,J=!1,Z){this.cancelScheduledSnapshot($);let X=this.getSnapshot($);if(X)this.publish({type:"snapshot",sessionId:$,snapshot:X,replace:J,cause:Z});else this.publish({type:"removed",sessionId:$})}snapshotTimers=new Map;cancelScheduledSnapshot($){clearTimeout(this.snapshotTimers.get($)),this.snapshotTimers.delete($)}scheduleSnapshot($){if(this.disposed||this.detachedSessions.has($)||this.snapshotTimers.has($))return;let J=setTimeout(()=>this.publishSnapshot($),100);J.unref?.(),this.snapshotTimers.set($,J)}notify($,J){let Z=String(J.sessionId??"");if($==="cloud_session_sync_failed")this.publish({type:"sync_failed",sessionId:Z,message:String(J.message??"Cloud synchronization failed")});else this.publishSnapshot(Z,$==="cloud_session_rehydrated",$==="chat_session_status"?"status":$==="chat_session_ended"?"ended":$==="tool_approval_state"?"approvals":void 0)}applyLiveEvent($,J){let Z=this.sessions.get($);if(Z)r1(Z,J,this.streamingMessages,$)}async respondApproval($,J,Z){this.assertSessionActive($);let X=this.approvals.get(`${$}:${J}`);if(!X){if(!this.connections.has($))throw Error("This cloud session connection is closed; reopen the session to respond.");throw new _("request_failed","This approval was already resolved or is no longer available.")}await X.resolve(Z)}async detach($){this.detachedSessions.add($),this.sessionGenerations.set($,(this.sessionGenerations.get($)??0)+1),this.connectionPromises.delete($),this.sendAbortTokens.set($,Symbol()),this.abortProvisioningControllers($,Error("Cloud viewer detached")),await this.disposeConnection($),this.publishSnapshot($)}isCloudSession($){return O6($)||this.knownSessions.has($)||this.connections.has($)||this.sessions.get($)?.config.executionTarget==="cloud"}getCachedDiscoveryRecord($){let J=this.knownSessions.get($);return J?o1(J):void 0}async getCrossScopeDiscoveryRecord($){let J=this.getCachedDiscoveryRecord($);if(!J)return;try{let X=(await this.options.api.status($)).status?.trim();return X?{...J,status:X}:J}catch(Z){if(Z instanceof _&&(Z.code==="session_not_found"||Z.code==="session_expired")){this.knownSessions.delete($),this.unlistedSessions.delete($),this.pendingInitialTasks.delete($);return}return J}}async list(){if(this.disposed)throw Error("Cloud session controller was disposed");let $=await this.resolveActiveOrganizationId(),J=(await this.options.api.list($)).map((X)=>this.preserveConnectedRuntimeModel(X));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedSessions=J;for(let X of J)this.knownSessions.set(X.id,X),this.unlistedSessions.delete(X.id);await Promise.all(Array.from(this.unlistedSessions.keys(),(X)=>this.getCrossScopeDiscoveryRecord(X)));let Z=await Promise.all(J.map(async(X)=>{if(X.status!=="provisioning")return X;let Q=await this.options.api.status(X.id).catch(()=>{return}),V=Q?.status?.trim();if(!V)return X;return{...X,status:V,metadata:{...X.metadata,...O0(Q?.phase)?{provisioningPhase:Q?.phase}:{},...Q?.statusReason?.trim()?{statusReason:Q.statusReason.trim()}:{}}}}));if(this.disposed)throw Error("Cloud session controller was disposed");for(let X of Z){this.knownSessions.set(X.id,X);let Q=this.sessions.get(X.id);if(Q?.status==="provisioning"&&X.status!=="provisioning")Q.status=X.status;let V=this.connections.get(X.id);if(V)V.remote=X;let j=x(X);if(j||X.status==="failed"){if(Q)Q.busy=!1,Q.status=j?"expired":"failed",Q.endedAt=j?Date.parse(X.expiredAt??"")||Date.now():Math.max(Q.endedAt??0,Date.parse(X.lastActivityAt??X.createdAt)||0)||void 0;if(V)this.disposeConnection(X.id).catch(()=>{return})}}this.lastListedSessions=Z;for(let X of Z)if(this.sessions.has(X.id))this.publishSnapshot(X.id);return Y0(Z)}async handoffTargetExists($){try{return await this.options.api.status($),!0}catch(J){if(J instanceof _&&(J.code==="session_not_found"||J.code==="session_expired"))return!1;throw J}}preserveConnectedRuntimeModel($){let J=this.connections.get($.id)?.remote.metadata,Z=J?.cwd??this.knownSessions.get($.id)?.metadata.cwd;return{...$,metadata:{...$.metadata,...J?.modelId?{modelId:J.modelId}:{},...Z?{cwd:Z}:{}}}}async resolveActiveOrganizationId($){return await this.options.getActiveOrganizationId?.($)}async listRepositories(){return await this.options.api.listRepositories(await this.resolveActiveOrganizationId())}async listModels(){if(this.disposed)throw Error("Cloud session manager was disposed");let $=await this.resolveActiveOrganizationId({fresh:!0}),J=await p1(this.options.apiBaseUrl,{isOrganizationSession:Boolean($)});if(this.disposed)throw Error("Cloud session manager was disposed");return J}async prepareHandoffRepository($){let J=await this.resolveActiveOrganizationId(),Z=await this.options.api.listRepositories(J);if(!Z.connected)throw new _("github_not_connected","Connect GitHub before handing this session off to cloud.",Z.connectUrl);let X=(Q)=>Q.trim().replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase();if(!Z.repositories.some((Q)=>X(Q.url)===X($)))throw new _("github_not_connected",`The GitHub integration cannot access ${$}. Grant repository access before handing off.`,Z.connectUrl);return J?{organizationId:J}:{}}async listBranches($,J={}){return await this.options.api.listBranches($,await this.resolveActiveOrganizationId(),J)}async listForDiscovery($={}){let J=this.discoveryRefresh??this.list().finally(()=>{if(this.discoveryRefresh===J)this.discoveryRefresh=void 0});this.discoveryRefresh=J;let Z=this.lastListedSessions;if($.timeoutMs===void 0)Z=await J;else{let V,j=await Promise.race([J.then((Y)=>({value:Y}),(Y)=>{if(!(Y instanceof _&&Y.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:Y});return{value:this.lastListedSessions}}),new Promise((Y)=>{V=setTimeout(()=>Y({value:this.lastListedSessions}),Math.max(0,$.timeoutMs??0))})]);if(V)clearTimeout(V);Z=j.value}return[...new Map([...this.unlistedSessions.values(),...Z].map((V)=>[V.id,V])).values()].map((V)=>{let j=o1(V),Y=this.sessions.get(V.id);if(!Y)return j;let W=Y.title?.trim()||V.title?.trim();return{...j,status:Y.status,prompt:Y.prompt,endedAt:Y.endedAt!==void 0?new Date(Y.endedAt).toISOString():j.endedAt,metadata:{...j.metadata??{},title:v0({sessionId:V.id,metadata:W?{title:W}:void 0,prompt:Y.prompt,messages:Y.messages})}}})}async create($){let J=$.requestId?.trim();if(!J)return await this.createOnce($);let Z=this.createRequests.get(J);if(Z)return await Z;let X=this.createOnce($).finally(()=>{if(this.createRequests.get(J)===X)this.createRequests.delete(J)});return this.createRequests.set(J,X),await X}trackProvisioningController($,J){let Z=this.provisioningControllers.get($);if(!Z)Z=new Set,this.provisioningControllers.set($,Z);return Z.add(J),()=>{if(Z.delete(J),Z.size===0)this.provisioningControllers.delete($)}}abortProvisioningControllers($,J){let Z=this.provisioningControllers.get($);if(!Z?.size)return!1;for(let X of Z)X.abort(J);return!0}async waitUntilReady($){this.detachedSessions.delete($),this.assertSessionActive($);let J=new AbortController,Z=this.trackProvisioningController($,J);try{await this.options.api.waitUntilReady($,AbortSignal.any([J.signal,AbortSignal.timeout(610000)])),J.signal.throwIfAborted(),this.assertSessionActive($),await this.refreshKnownSession($)}finally{Z()}}async seedHandoff($,J){I0(J.workspaceRelativePath),this.detachedSessions.delete($);let Z=await this.ensureConnection($,{createInner:!0,handoffSeed:J});if(!Z.innerSessionId)throw Error("Cloud Hub did not return an inner session id");return{innerSessionId:Z.innerSessionId}}async verifyHandoffTranscript($,J,Z={}){let X=await this.ensureConnection($),Q=X.innerSessionId;if(!Q)throw Error("Cloud Hub did not return an inner session id");let V=await X.client.command("session.messages",{sessionId:Q},Q);this.assertSessionActive($,X);let j=V.payload?.messages;if(!Array.isArray(j))throw Error("Cloud runtime returned no transcript after seeding.");if(J.length>0&&j.length===0)throw new e1;if(!(Z.allowAppendedMessages?j.length>=J.length&&K0(J,j.slice(0,J.length)):K0(J,j)))throw new L0(J.length,j.length);X.transcriptKnown=!0;let W=this.sessions.get($);if(W)W.messages=structuredClone(j),this.authoritativeMessages.set($,structuredClone(j)),this.streamingMessages.delete($),this.publishSnapshot($,!0)}async createOnce($){if(this.disposed)throw Error("Cloud session manager was disposed");let J=I0($.workspaceRelativePath),Z=$.organizationId===void 0?await this.resolveActiveOrganizationId({fresh:!0}):$.organizationId??void 0,X=$.handoff,Q=!X,V=await this.options.api.create({...$,organizationId:Z,...X&&{handoff:{...X,onOuterSessionCreated:async(z,L)=>{Q=L?.created===!0,await X.onOuterSessionCreated(z,L)}}}});if(!V?.sessionId?.trim())throw new _("request_failed","The cloud session service returned an unexpected response; please try again.");if(this.disposed){if(Q&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(V.sessionId,V.cleanupAuthToken,$.handoff?.onOuterSessionRemoved);throw Error("Cline account changed while the cloud session was starting")}let j={id:V.sessionId,status:V.status,sandboxUrl:V.sandboxUrl,repoContext:{repoUrl:$.repoUrl,...$.branch?.trim()?{branch:$.branch.trim()}:{}},metadata:{modelId:$.modelId,cwd:J},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.knownSessions.set(j.id,j),this.unlistedSessions.set(j.id,j);let{autoApproveTools:Y,thinking:W,reasoningEffort:F}=$;this.pendingInitialTasks.set(j.id,{autoApproveTools:Y,thinking:W,reasoningEffort:F});let K=this.stateFromRecord(j);K.prompt=$.initialPrompt?.trim()||void 0,K.config.mode=$.mode??"act",this.sessions.set(j.id,K);let N;try{if($.handoff){let z=await $.handoff.resolveMessages();this.assertSessionActive(j.id),N=(await this.seedHandoff(j.id,{sourceSessionId:$.handoff.sourceSessionId,messages:z,mode:$.mode,workspaceRelativePath:$.workspaceRelativePath,config:{autoApproveTools:$.autoApproveTools,thinking:$.thinking,reasoningEffort:$.reasoningEffort},onSeeding:$.handoff.onSeeding})).innerSessionId}}catch(z){if(this.disposed&&Q&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(j.id,V.cleanupAuthToken,$.handoff?.onOuterSessionRemoved);throw z}return this.assertSessionActive(j.id),this.notify("chat_session_status",{sessionId:j.id,status:K.status}),{sessionId:j.id,origin:"cloud",executionTarget:"cloud",status:j.status,provider:"cline",model:$.modelId,repoUrl:$.repoUrl,branch:$.branch??"",cwd:J,workspaceRoot:U,...N?{innerSessionId:N}:{},...K.prompt?{prompt:K.prompt}:{}}}async deleteProvisionedSessionAfterDispose($,J,Z){this.knownSessions.delete($),this.unlistedSessions.delete($),this.pendingInitialTasks.delete($),this.sessions.delete($),await this.options.api.delete($,J).then(()=>Z?.($)).catch((X)=>{this.options.logger?.log("Failed to clean up a cloud session created during an account change",{sessionId:$,error:X})})}async attach($,J){let Z=this.sessionGenerations.get($)??0;if(this.detachedSessions.delete($),J)this.restoreCreationOptions($,J);let X=await this.ensureKnownSession($);if(this.assertSessionActive($),Z!==(this.sessionGenerations.get($)??0))throw Error("Cloud viewer detached during attachment");if(!this.sessions.has($))this.sessions.set($,this.stateFromRecord(X));if(X.status==="provisioning"||X.status==="failed")return l0(X,X.status,this.sessions.get($)?.prompt);if(x(X))return await this.disposeConnection($),await this.attachExpired(X);let Q;try{Q=await this.ensureConnection($)}catch(Y){let W=await this.refreshKnownSession($);if(W&&x(W))return await this.disposeConnection($),await this.attachExpired(W);throw Y}await this.ensureAttached(Q);let V=Q.remote,j=this.sessions.get($);return l0(V,j?.status??V.status,j?.prompt)}async send($,J,Z,X,Q){let V=this.sendAbortTokens.get($),j=this.knownSessions.get($);if(j&&x(j))throw new _("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");let Y=await this.ensureConnection($,{createInner:!0}),W=()=>this.disposed||Y.disposed||this.deletingSessions.has($)||this.sendAbortTokens.get($)!==V,F=()=>{if(W())throw Error("Cloud session prompt cancelled")};if(F(),await Y.reconnectResolution,F(),await this.ensureAttached(Y),await Y.reconnectResolution,F(),!Y.transcriptKnown)await this.rehydrateAfterTransportDrop($,Y);F(),await this.updateModel(Y,X),await Y.reconnectResolution,F();let K=Y.innerSessionId;if(!K)throw Error("Cloud Hub session was not initialized");let N=this.sessions.get($),z=Z??(N?.busy?"queue":void 0),L=c(N?.messages??[],N?.promptsInQueue??[],J),G=z!=="queue"&&z!=="steer",q=N&&z!=="queue"?{role:"user",content:[{type:"text",text:J}]}:void 0;if(N&&q)N.messages=[...N.messages,q];let O=()=>{if(N&&q)N.messages=N.messages.filter((A)=>A!==q),this.publishSnapshot($)};if(N&&G){let A=N.status!=="running";if(N.busy=!0,N.status="running",N.prompt||=J,A)this.publishSnapshot($,!1,"status")}let B=this.knownSessions.get($);if(B&&!B.title?.trim()&&!this.titleWrites.has($)){let A=J1(J);if(A){if(B.title=A,N)N.title=A;let C=this.options.api.updateTitle?.($,A).then(()=>{}).catch(()=>{}).finally(()=>{if(this.titleWrites.get($)===C)this.titleWrites.delete($)});if(C)this.titleWrites.set($,C)}}let D=new Set,H=!1,f=()=>{if(H||W())return;H=!0,this.publish({type:"prompt_accepted",sessionId:$,prompt:J,delivery:z})};try{let A=await Y.client.command("session.send_input",{prompt:J,delivery:z,...Q?.length?{attachments:{userImages:Q}}:{}},K,{timeoutMs:z==="queue"?z6:null,onDispatch:(k)=>{D.add(k),Y.pendingInputs??=new Map,Y.pendingInputs.set(k,{clientId:Y.client.getClientId(),ownsBusyState:G,accept:f})},beforeDispatch:()=>{if(F(),Y.innerSessionId!==K)throw Error("The cloud session reconnected before the prompt could be sent. Please try again.")}});f();let C=z==="queue"||z!=="steer"&&A.payload?.result===void 0;if(C)O();return{sessionId:$,ok:!0,...C?{queued:!0}:{},result:A.payload?.result}}catch(A){if(W())throw O(),A;if(S0(A)||m0(A,"session.send_input")){let C;try{C=await this.rehydrateAfterTransportDrop($,Y)}catch(a){if(F(),O(),N&&G)N.busy=!1,N.status="error";if(z==="queue")throw new c0;throw a}if(F(),z==="queue")throw new c0;if(z==="steer")throw new _("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(c(C.messages,D6(C.prompts,C.submittedPrompts),J)<=L)throw new _("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");return{sessionId:$,ok:!0,...z==="queue"?{queued:!0}:{},recoveredAfterDisconnect:!0,status:C.status}}if(O(),N&&G)N.busy=!1,N.status="error";throw this.publishSnapshot($),A}finally{for(let A of D)Y.pendingInputs?.delete(A)}}async updateModel($,J){let Z=J?.trim();if(!Z||$.remote.metadata.modelId===Z)return;let X=$.innerSessionId;if(!X)throw Error("Cloud Hub session was not initialized");await $.client.command("session.update_connection",{sessionId:X,updates:{modelId:Z}},X,{beforeDispatch:()=>{if(this.assertSessionActive($.remote.id,$),$.innerSessionId!==X)throw Error("The cloud session reconnected before the model could be changed. Please try again.")}}),this.assertSessionActive($.remote.id,$),this.applyModel($,Z)}applyModel($,J){$.remote.metadata.modelId=J;let Z=this.sessions.get($.remote.id);if(Z)Z.config.model=J,Z.config.modelId=J}async rehydrateAfterTransportDrop($,J){if(this.assertSessionActive($,J),J.rehydrationPromise)return J.rehydrationRerunRequested=!0,await J.rehydrationPromise;let Z=(async()=>{let X;do J.rehydrationRerunRequested=!1,X=await this.performTransportRehydration($,J),this.assertSessionActive($,J);while(J.rehydrationRerunRequested&&!this.disposed);return X})().finally(()=>{if(J.rehydrationPromise===Z)J.rehydrationPromise=void 0,this.publishSnapshot($)});return J.rehydrationPromise=Z,await Z}async performTransportRehydration($,J){this.assertSessionActive($,J);let Z=J.innerSessionId;if(!Z)throw Error("Cloud Hub session was not initialized");J.bufferingEvents=!0,J.bufferedEvents=[],J.bufferedEventsDropped=0;try{await this.ensureAttached(J),this.assertSessionActive($,J);let X=await J.client.command("session.get",{includeSnapshot:!0},Z);this.assertSessionActive($,J);let Q=X.payload?.session&&typeof X.payload.session==="object"&&!Array.isArray(X.payload.session)?X.payload.session:void 0;this.applySessionModel(J,Q);let V=this.sessions.get($),j=this.authoritativeMessages.get($)??[],Y=String(Q?.status??V?.status??"running").trim(),W=Y==="pending"?"running":Y;if(W==="running"&&!J.transcriptKnown&&!J.pendingInputs?.size)J.externalRun??={progressHydrated:!0};let F=()=>J.client.command("session.messages",{sessionId:Z},Z),K=await F().catch((A)=>{if(!m0(A,"session.messages"))throw A;return this.assertSessionActive($,J),F()});if(this.assertSessionActive($,J),!Array.isArray(K.payload?.messages))throw Error("Cloud Hub returned an invalid transcript snapshot");let N=K.payload.messages,z=J.bufferedEventsDropped+J.bufferedEvents.length,L=await J.client.command("session.pending_prompts",{sessionId:Z},Z).catch(()=>{return});this.assertSessionActive($,J);let G=J.bufferedEventsDropped+J.bufferedEvents.length;if(V){let A=V.status!==W;if(this.authoritativeMessages.set($,structuredClone(N)),V.messages=structuredClone(N),this.streamingMessages.delete($),V.status=W,V.busy=W==="running",A)if(W==="completed"||W==="failed"||W==="aborted")V.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:$,reason:W==="failed"?"error":W});else this.notify("chat_session_status",{sessionId:$,status:W})}let q=L!==void 0&&L.ok!==!1&&Array.isArray(L.payload?.prompts),O=q?this.applyQueueSnapshot($,L):void 0;J.transcriptKnown=!0;let B=N;this.assertSessionActive($,J),this.notify("cloud_session_rehydrated",{sessionId:$,status:W,transcriptKnown:!0,messages:B}),this.assertSessionActive($,J);let D=J.bufferedEvents,H=g0(D),f=t1(D,N,{queueSnapshotApplied:q,queueSnapshotEventCutoff:Math.max(0,G-J.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,z-J.bufferedEventsDropped),baselineMessages:j});J.bufferedEvents=[],J.bufferingEvents=!1,J.syncFailureNotified=!1;for(let A of f)this.forwardEvent($,J,A);return{status:W,messages:N,prompts:O,submittedPrompts:H}}catch(X){let Q=J.bufferedEvents;J.bufferedEvents=[],J.bufferingEvents=!1,this.assertSessionActive($,J);for(let V of Q)this.forwardEvent($,J,V);if(!J.syncFailureNotified)J.syncFailureNotified=!0,this.notify("cloud_session_sync_failed",{sessionId:$,message:X instanceof Error?X.message:String(X)});throw X}}async abort($){if(this.sendAbortTokens.set($,Symbol()),this.abortProvisioningControllers($,Error("Cloud session prompt cancelled")))return{sessionId:$,ok:!0};let J=await this.ensureConnection($),Z=()=>{if(this.disposed||J.disposed)throw Error("Cloud session connection was disposed")};if(Z(),await J.client.connect(),await J.reconnectResolution,Z(),await this.resolveInnerSession($,J),J.innerSessionId){await this.ensureAttached(J),await J.reconnectResolution,Z();let Q=J.innerSessionId;if(!Q)throw Error("Cloud Hub session was not initialized");await J.client.command("run.abort",{sessionId:Q},Q,{beforeDispatch:()=>{if(Z(),J.innerSessionId!==Q)throw Error("The cloud session reconnected before Stop could be sent. Please try Stop again.")}})}Z();let X=this.sessions.get($);if(X)X.busy=!1,X.status="aborted";return this.publishSnapshot($),{sessionId:$,ok:!0}}async pendingPrompts($){if(this.knownSessions.get($)?.status==="provisioning")return{sessionId:$,promptsInQueue:[]};if(!(await this.ensureConnection($)).innerSessionId)return{sessionId:$,promptsInQueue:[]};let Z=await this.queueCommand($,"session.pending_prompts",{});return{sessionId:$,promptsInQueue:this.applyQueueSnapshot($,Z)}}async updatePendingPrompt($,J,Z){let X=await this.queueCommand($,"session.update_pending_prompt",{promptId:J,...Z});return{sessionId:$,updated:X.payload?.updated===!0,promptsInQueue:this.applyQueueSnapshot($,X)}}async removePendingPrompt($,J){let Z=await this.queueCommand($,"session.remove_pending_prompt",{promptId:J});return{sessionId:$,removed:Z.payload?.removed===!0,promptsInQueue:this.applyQueueSnapshot($,Z)}}async queueCommand($,J,Z){let X=await this.ensureConnection($),Q=X.innerSessionId;if(!Q)throw Error("Cloud Hub session was not initialized");await X.client.connect(),await X.reconnectResolution,await this.ensureAttached(X),await X.reconnectResolution;let V=await X.client.command(J,{sessionId:Q,...Z},Q,{beforeDispatch:()=>{if(this.assertSessionActive($,X),X.innerSessionId!==Q)throw Error("The cloud session reconnected before the queue request could be sent. Refresh the queue and try again.")}});return this.assertSessionActive($,X),V}applyQueueSnapshot($,J){if(!Array.isArray(J.payload?.prompts))throw Error("Cloud Hub returned an invalid pending-prompts snapshot");let X=J.payload.prompts.map((V)=>({id:typeof V.id==="string"?V.id:"",prompt:typeof V.prompt==="string"?V.prompt:"",steer:V.delivery==="steer",attachmentCount:typeof V.attachmentCount==="number"?V.attachmentCount:0,userImages:Array.isArray(V.userImages)?V.userImages.filter((j)=>typeof j==="string"):void 0})).filter((V)=>V.id),Q=this.sessions.get($);if(Q)Q.promptsInQueue=X;return this.publishSnapshot($,!1,"queue"),X}async readMessages($){let J=this.knownSessions.get($);if(J?.status==="provisioning"||J?.status==="failed")return[];if(J&&x(J))return await this.loadArchivedMessages(J)??[];try{let Z=await this.ensureConnection($);if(!Z.innerSessionId)return[];return(await this.rehydrateAfterTransportDrop($,Z)).messages}catch(Z){let X=await this.refreshKnownSession($)??J;if(X){let Q=await this.loadArchivedMessages(X).catch(()=>null);if(Q!==null)return Q}throw Z}}async updateTitle($,J){let Z=this.titleWrites.get($),X=(async()=>{await Z?.catch(()=>{}),this.assertSessionActive($),await this.options.api.updateTitle($,J);let Q=this.knownSessions.get($);if(Q)Q.title=J;let V=this.sessions.get($);if(V)V.title=J;this.publishSnapshot($)})();this.titleWrites.set($,X);try{await X}finally{if(this.titleWrites.get($)===X)this.titleWrites.delete($)}}async delete($){this.deletingSessions.add($),this.abortProvisioningControllers($);try{let J=this.connectionPromises.get($);if(J)await J.catch(()=>{return});await this.disposeConnection($);try{await this.options.api.delete($)}catch(Z){let X=Z instanceof _?Z.code:"";if(X!=="session_not_found"&&X!=="session_expired")throw Z}this.knownSessions.delete($),this.unlistedSessions.delete($),this.pendingInitialTasks.delete($),this.sessions.delete($),this.authoritativeMessages.delete($),this.restoredOptions.delete($),this.publish({type:"removed",sessionId:$}),this.sendAbortTokens.delete($);for(let[Z,X]of this.approvals)if(X.item.sessionId===$)this.approvals.delete(Z)}finally{this.deletingSessions.delete($)}}async dispose(){this.disposed=!0;for(let J of this.snapshotTimers.keys())this.cancelScheduledSnapshot(J);this.sendAbortTokens.clear();for(let J of this.provisioningControllers.values())for(let Z of J)Z.abort();this.provisioningControllers.clear();let $=new Set([...this.connections.keys(),...this.knownSessions.keys(),...this.sessions.keys()]);for(let[J,Z]of this.approvals)if($.has(Z.item.sessionId))this.approvals.delete(J);for(let J of $)this.sessions.delete(J),this.knownSessions.delete(J),this.publish({type:"removed",sessionId:J});if(this.knownSessions.clear(),this.unlistedSessions.clear(),!this.options.pendingInitialTasks)this.pendingInitialTasks.clear();this.listeners.clear(),await Promise.allSettled(Array.from(this.connections.keys()).map((J)=>this.disposeConnection(J)))}async attachExpired($){let J=this.sessions.get($.id)??p0($);return J.busy=!1,J.status="expired",this.sessions.set($.id,J),await this.loadArchivedMessages($).catch(()=>{return}),l0($,"expired")}async loadArchivedMessages($){let J=this.sessionGenerations.get($.id),Z=await this.options.api.history($.id);if(this.assertSessionActive($.id),this.sessionGenerations.get($.id)!==J)throw Error("Cloud session attachment changed while loading history");if(Z===null)return null;let X=this.sessions.get($.id)??p0($);return X.messages=structuredClone(Z),this.sessions.set($.id,X),this.authoritativeMessages.set($.id,structuredClone(X.messages)),this.publishSnapshot($.id,!0),Z}async refreshKnownSession($){let J=await this.resolveActiveOrganizationId(),Z=await this.options.api.list(J).catch(()=>{return});if(this.disposed)throw Error("Cloud session manager was disposed");if(!Z)return this.knownSessions.get($);for(let X of Z)this.knownSessions.set(X.id,X);return Z.find((X)=>X.id===$)}async ensureKnownSession($){let J=this.knownSessions.get($);if(J)return J;let Z=(await this.list()).find((X)=>X.id===$);if(!Z)throw new _("session_not_found",`Cloud session ${$} was not found.`);return this.knownSessions.get($)??structuredClone(Z)}assertSessionActive($,J){if(this.disposed||J?.disposed||this.detachedSessions.has($)||J?.generation!==void 0&&J.generation!==(this.sessionGenerations.get($)??0))throw Error("Cloud session connection was disposed");if(this.deletingSessions.has($))throw new _("session_not_found","This cloud session is being deleted.")}async ensureConnection($,J={}){let Z=this.sessionGenerations.get($)??0,X=()=>{if(this.assertSessionActive($),Z!==(this.sessionGenerations.get($)??0))throw Error("Cloud viewer detached during connection")};X();let Q=this.connectionPromises.get($),V=Q?await Q:this.connections.get($);if(V){if(this.assertSessionActive($,V),await V.reconnectResolution,this.assertSessionActive($,V),!V.innerSessionId)await V.client.connect(),await V.reconnectResolution,this.assertSessionActive($,V),await this.resolveInnerSession($,V,Boolean(J.handoffSeed)),this.assertSessionActive($,V);if(J.handoffSeed&&V.innerSessionId)await this.assertHandoffConnectionReusable(V,J.handoffSeed);if(J.createInner&&!V.innerSessionId)await this.createInnerSession(V,J.handoffSeed);return this.assertSessionActive($,V),V}let j=(async()=>{let Y=await this.ensureKnownSession($);if(X(),Y.status==="provisioning"){let N=new AbortController,z=this.trackProvisioningController($,N);try{if(await this.options.api.waitUntilReady($,N.signal,({phase:G})=>{Y.metadata.provisioningPhase=G,this.notify("chat_session_status",{sessionId:$,status:"provisioning",phase:G})}),this.disposed)throw Error("Cloud session manager was disposed");if(Y=await this.refreshKnownSession($)??Y,N.signal.throwIfAborted(),Y.status==="provisioning")Y.status="ready";let L=this.sessions.get($);if(L?.status==="provisioning")L.status="idle"}catch(L){if(L instanceof _&&L.code==="session_failed"){if(Y.status="failed",Y.metadata.statusReason=L.detail,Y.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set($,Y);let G=this.sessions.get($);if(G)G.status="error";this.notify("chat_session_status",{sessionId:$,status:"error"})}throw L}finally{z()}}if(X(),Y.status==="failed")throw new _("session_failed",Y.metadata.statusReason||"The cloud sandbox could not be prepared.");if(x(Y))throw new _("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");this.sessions.set($,this.sessions.get($)??this.stateFromRecord(Y));let W,F=0,K=this.createHubClient({url:A6(this.options.apiBaseUrl,$),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${$}-${G6()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:U,cwd:U,resolveConnectionHeaders:async()=>{X();let N=F>0;if(F+=1,W)W.connected=!1,W.reconnecting=N,this.publishSnapshot($);if(N){let L=W;if(L&&!L.disposed){L.transcriptKnown=!1,L.innerSessionId=void 0;let G=(async()=>{if(await this.resolveInnerSession($,L),L.innerSessionId)await this.rehydrateAfterTransportDrop($,L)})().catch(()=>this.disposeConnectionIfSessionGone($,L)).finally(()=>{if(L.reconnectResolution===G)L.reconnectResolution=void 0,L.connected=L.transcriptKnown,this.publishSnapshot($)});L.reconnectResolution=G}}let z=await this.options.getAuthToken();if(!z?.trim())throw new _("authentication_required","Sign in to Cline to reconnect this cloud session.");return X(),{Authorization:`Bearer ${z.trim()}`}}});W={generation:Z,remote:Y,client:K,bufferedEvents:[],bufferedEventsDropped:0,transcriptKnown:!1,seenEventIds:new Set,unsubscribe:()=>{}},W.unsubscribe=K.subscribe(()=>{},{sessionId:Y.metadata.taskId?.trim()||$}),this.connections.set($,W);try{if(await K.connect(),W.connected=!0,this.publishSnapshot($),this.assertSessionActive($,W),await this.resolveInnerSession($,W,Boolean(J.handoffSeed)),this.assertSessionActive($,W),J.handoffSeed&&W.innerSessionId)await this.assertHandoffConnectionReusable(W,J.handoffSeed);if(J.createInner&&!W.innerSessionId)await this.createInnerSession(W,J.handoffSeed);return this.assertSessionActive($,W),W}catch(N){if(S0(N)&&!this.disposed&&!W.disposed&&!this.deletingSessions.has($))throw N;if(this.connections.get($)===W)this.connections.delete($);if(W.disposed=!0,W.unsubscribe(),!this.disposed&&Z===(this.sessionGenerations.get($)??0))this.clearPendingApprovals($);throw await K.dispose().catch(()=>{return}),N}})().finally(()=>{if(this.connectionPromises.get($)===j)this.connectionPromises.delete($)});return this.connectionPromises.set($,j),await j}async resolveInnerSession($,J,Z=!1){if(this.assertSessionActive($,J),J.innerSessionId)return;let X=J.remote.metadata.taskId?.trim(),Q;if(X)try{let Y=await J.client.command("session.get",{sessionId:X},X);this.assertSessionActive($,J),Q=Y.payload?.session&&typeof Y.payload.session==="object"&&!Array.isArray(Y.payload.session)?Y.payload.session:void 0}catch(Y){if(!Q1(Y))throw Y}else{let Y=await J.client.command("session.list",{limit:100});this.assertSessionActive($,J),Q=Q0(Y.payload).filter(V0).sort((W,F)=>k0(F)-k0(W))[0]}let V=String(Q?.sessionId??"").trim();if(!V){if(!Z&&!this.pendingInitialTasks.has($))throw Error("This cloud session's task is unavailable. Start a new cloud session to continue.");return}this.pendingInitialTasks.delete($),J.innerSessionId=V,this.subscribeToInnerSession($,J);let j=y0(Q);if(j)this.applyModel(J,j);await this.ensureAttached(J)}async assertHandoffConnectionReusable($,J){let Z=await $.client.command("session.list",{limit:100});this.assertSessionActive($.remote.id,$);let X=Q0(Z.payload).filter(V0),[Q]=X;if(X.length!==1||String(Q?.sessionId??"").trim()!==$.innerSessionId||n1(Q)!==J.sourceSessionId)throw new _("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.")}async createInnerSession($,J){if(this.assertSessionActive($.remote.id,$),$.innerSessionCreation){if(await $.innerSessionCreation,J)await this.assertHandoffConnectionReusable($,J);return}let Z=(async()=>{if(J&&await this.adoptExistingHandoffSession($,J)){this.unconfirmedInnerCreates.delete($.remote.id);return}if(J?.recoverOnly||this.unconfirmedInnerCreates.has($.remote.id))throw new _("request_failed","Cloud conversation creation is still unconfirmed. Wait for it to appear before trying again.");await this.createInnerSessionOnce($,J)})().finally(()=>{$.innerSessionCreation=void 0});return $.innerSessionCreation=Z,await Z}async adoptExistingHandoffSession($,J){let Z=await $.client.command("session.list",{limit:100});this.assertSessionActive($.remote.id,$);let X=Q0(Z.payload).filter(V0);if(X.length===0)return!1;let[Q]=X,V=String(Q?.sessionId??"").trim();if(X.length!==1||!V||n1(Q)!==J.sourceSessionId)throw new _("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.");return $.innerSessionId=V,this.subscribeToInnerSession($.remote.id,$),this.applySessionModel($,Q),await this.ensureAttached($),!0}async createInnerSessionOnce($,J){let Z=$.remote.metadata.modelId?.trim();if(!Z)throw Error("Cloud session is missing its model id");let X=this.sessions.get($.remote.id),Q=I0(J?.workspaceRelativePath),V=J?.mode??"act";try{await J?.onSeeding?.(),this.assertSessionActive($.remote.id,$)}catch(L){if(J)throw new u0(L);throw L}let j=`cline/${($.remote.metadata.taskId?.trim()||$.remote.id).slice(-8).toLowerCase()}`,Y=`${s1}
|
|
16
|
+
|
|
17
|
+
SAVE YOUR WORK: This sandbox is temporary. Push your progress to origin so it remains available outside the sandbox. The branch \`${j}\` is a backup of your work-in-progress, not a finished deliverable, so commit to it freely even when the work is incomplete. Do all work for this task on that branch: create it from the current checkout before your first change (or check it out if it already exists), and never commit directly to the default branch. Commit regularly as you complete meaningful steps, using clear, descriptive messages. The first time you commit, push the branch with \`git push -u origin ${j}\`, and push again after each later commit. Do not force-push or amend commits that are already pushed unless the user explicitly asks.`,W=!1,F=$.client.command("session.create",{workspaceRoot:U,cwd:Q,...J?{initialMessages:J.messages}:{},sessionConfig:{...$.remote.metadata.taskId?.trim()?{sessionId:$.remote.metadata.taskId.trim()}:{},providerId:"cline",modelId:Z,workspaceRoot:U,cwd:Q,systemPrompt:J?`${s1}
|
|
18
|
+
|
|
19
|
+
This session was handed off from a local workspace to a fresh Linux clone of ${$.remote.repoContext.repoUrl??"the repository"}@${$.remote.repoContext.branch??"the selected branch"} at ${U}. Earlier transcript references to the local OS, absolute paths, environment, and tool availability are stale.`+(Q===U?"":`
|
|
20
|
+
|
|
21
|
+
Continue from the original repository subdirectory at ${Q}.`):Y,mode:V,enableTools:!0,...typeof(J?.config?.thinking??X?.config.thinking)==="boolean"?{thinking:J?.config?.thinking??X?.config.thinking}:{},...typeof(J?.config?.reasoningEffort??X?.config.reasoningEffort)==="string"?{reasoningEffort:J?.config?.reasoningEffort??X?.config.reasoningEffort}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:Z,interactive:!0,...J?{handoff:{from:"local",sourceSessionId:J.sourceSessionId,outerSessionId:$.remote.id}}:{}},runtimeOptions:{mode:V},modelSelection:{provider:"cline",model:Z},toolPolicies:{"*":{autoApprove:(J?.config?.autoApproveTools??X?.config.autoApproveTools)!==!1}}},void 0,{beforeDispatch:()=>this.assertSessionActive($.remote.id,$),onDispatch:()=>{W=!0}}),K;try{K=await F}catch(L){if(J&&!W)throw new u0(L);if(J&&(m0(L,"session.create")||S0(L)))this.unconfirmedInnerCreates.add($.remote.id);throw L}this.assertSessionActive($.remote.id,$);let N=K.payload?.session&&typeof K.payload.session==="object"?K.payload.session:void 0,z=String(N?.sessionId??K.payload?.sessionId??"").trim();if(!z){if(J)this.unconfirmedInnerCreates.add($.remote.id);throw Error("Cloud Hub did not return an inner session id")}if(this.unconfirmedInnerCreates.delete($.remote.id),this.pendingInitialTasks.delete($.remote.id),$.innerSessionId=z,$.remote.metadata.cwd=Q,X)X.config.cwd=Q,X.config.mode=V;this.subscribeToInnerSession($.remote.id,$),this.applySessionModel($,N),$.transcriptKnown=!J}handleEvent($,J,Z){if(this.disposed||J.disposed)return;if(J.innerSessionId&&Z.sessionId&&Z.sessionId!==J.innerSessionId)return;let X=Z.eventId?.trim();if(X&&!(Z.event==="approval.requested"&&Z.sequence===void 0)){if(J.seenEventIds.has(X))return;J.seenEventIds.add(X);while(J.seenEventIds.size>q6){let Q=J.seenEventIds.values().next().value;if(Q)J.seenEventIds.delete(Q)}}if(J.bufferingEvents){if(J.bufferedEvents.push(Z),J.bufferedEvents.length>_6)J.bufferedEvents.shift(),J.bufferedEventsDropped+=1,this.options.logger?.log("Cloud sync event buffer reached its limit",{sessionId:$,severity:"warn"});return}this.forwardEvent($,J,Z)}forwardEvent($,J,Z){if(this.disposed||J.disposed)return;if(Z.event==="session.attached"||Z.event==="session.updated"||Z.event==="session.created")this.applySessionModel(J,Z.payload?.session);if(Z.event==="approval.requested"){this.handleApprovalRequested($,J,Z);return}if(Z.event==="approval.resolved"){let j=String(Z.payload?.approvalId??"").trim();if(j)this.removeApproval($,j);return}if(Z.event==="run.started"){let j=this.sessions.get($)?.busy,Y=Z.payload?.requestId,W=typeof Y==="string"?J.pendingInputs?.get(Y):void 0;if(W&&Z.payload?.clientId===W.clientId){if(W.accept(),W.ownsBusyState)J.externalRun=void 0}else if(typeof Z.payload?.clientId==="string")J.externalRun??={progressHydrated:Boolean(j)}}let X=J.externalRun,Q=Z.event==="run.completed"||Z.event==="run.failed"||Z.event==="run.aborted",V=X&&!X.progressHydrated&&(Z.event==="assistant.delta"||Z.event==="reasoning.delta"||Z.event==="tool.started");if(X&&(V||Q)){if(X.progressHydrated=!0,Q)J.externalRun=void 0;let j=Boolean(J.rehydrationPromise);if(this.rehydrateAfterTransportDrop($,J).catch((Y)=>{if(this.disposed||J.disposed)return;this.notify("cloud_session_sync_failed",{sessionId:$,message:Y instanceof Error?Y.message:"Cloud transcript refresh failed"})}),!j){J.bufferedEvents.push(Z);return}}if(this.applyLiveEvent($,Z),this.publish({type:"hub_event",sessionId:$,event:{...Z,sessionId:$}}),Z.event==="assistant.delta"||Z.event==="reasoning.delta"||Z.event==="tool.updated")this.scheduleSnapshot($);else this.publishSnapshot($)}handleApprovalRequested($,J,Z){this.storePendingApproval($,J,Z.payload),this.sendApprovalSnapshot($)}storePendingApproval($,J,Z){let X=String(Z?.approvalId??"").trim();if(!X)return;let Q=`${$}:${X}`,V={approvalId:X,requestId:Q,sessionId:$,createdAt:new Date(typeof Z?.createdAt==="number"?Z.createdAt:Date.now()).toISOString(),toolCallId:String(Z?.toolCallId??""),toolName:String(Z?.toolName??"tool"),input:B6(Z?.inputJson),iteration:typeof Z?.iteration==="number"?Z.iteration:void 0,agentId:typeof Z?.agentId==="string"?Z.agentId:void 0,conversationId:typeof Z?.conversationId==="string"?Z.conversationId:void 0};this.approvals.set(Q,{item:V,resolve:async(j)=>{if(this.disposed||J.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");if(await this.ensureAttached(J),this.disposed||J.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");await J.client.command("approval.respond",{approvalId:X,approved:j.approved,reason:j.reason},J.innerSessionId)}})}removeApproval($,J){this.approvals.delete(`${$}:${J}`),this.sendApprovalSnapshot($)}clearPendingApprovals($){for(let[J,Z]of this.approvals)if(Z.item.sessionId===$)this.approvals.delete(J);this.sendApprovalSnapshot($)}sendApprovalSnapshot($){this.notify("tool_approval_state",{sessionId:$,items:Array.from(this.approvals.values()).filter((J)=>J.item.sessionId===$).map((J)=>J.item)})}async ensureAttached($){if(this.assertSessionActive($.remote.id,$),!$.innerSessionId)return;let J=await $.client.command("session.attach",{sessionId:$.innerSessionId},$.innerSessionId);this.assertSessionActive($.remote.id,$),this.applySessionModel($,J.payload?.session)}subscribeToInnerSession($,J){let Z=J.innerSessionId;if(!Z)return;J.unsubscribe(),this.clearPendingApprovals($),J.unsubscribe=J.client.subscribe((X)=>this.handleEvent($,J,X),{sessionId:Z})}applySessionModel($,J){if(!J||typeof J!=="object"||Array.isArray(J))return;let Z=y0(J);if(Z)this.applyModel($,Z);let X=J,Q=typeof X.cwd==="string"&&W0.normalize(X.cwd)===X.cwd&&(X.cwd===U||X.cwd.startsWith(`${U}/`))?X.cwd:void 0;if(Q){$.remote.metadata.cwd=Q;let Y=this.sessions.get($.remote.id);if(Y)Y.config.cwd=Q}let V=this.sessions.get($.remote.id),j=X.runtimeOptions?.mode;if(V&&(j==="act"||j==="plan"||j==="yolo"||j==="zen"))V.config.mode=j}async disposeConnection($){this.cancelScheduledSnapshot($);let J=this.connections.get($);if(this.connections.delete($),!J)return;J.disposed=!0,J.pendingInputs?.clear(),J.unsubscribe(),this.clearPendingApprovals($),await J.client.dispose()}async disposeConnectionIfSessionGone($,J){if(J.disposed||this.disposed)return;let Z;try{Z=await this.resolveActiveOrganizationId()}catch{return}let X=await this.options.api.list(Z).catch(()=>{return});if(!X||J.disposed)return;let Q=X.find((j)=>j.id===$),V=Q?this.preserveConnectedRuntimeModel(Q):void 0;if(!V){await this.disposeConnection($).catch(()=>{return});return}if(this.knownSessions.set($,V),J.remote=V,V.status==="failed"){let j=this.sessions.get($);if(j)j.busy=!1,j.status="failed",j.endedAt=Date.parse(V.updatedAt)||Date.now();await this.disposeConnection($).catch(()=>{return});return}if(x(V))await this.attachExpired(V).catch(()=>{return}),await this.disposeConnection($).catch(()=>{return})}}export{k0 as updatedAt,g0 as submittedPromptsFromEvents,h0 as stringifyMessageContent,y0 as sessionRowModelId,v0 as resolveSessionListTitle,t1 as reconcileBufferedCloudEvents,Q0 as readSessionRows,y6 as readCloudHandoffMetadata,f6 as preflightCloudHandoffGit,O0 as parseCloudProvisioningPhase,j0 as normalizeSessionTitle,s0 as normalizeGitHubRemoteUrl,g6 as mergeCloudHandoffMetadata,p1 as loadCloudModels,V0 as isRootSessionRow,O6 as isCloudOuterSessionId,J1 as deriveCloudSessionTitle,N2 as createCloudHandoffFingerprint,c as countPromptOccurrences,o1 as cloudSessionToDiscoveryRecord,K0 as cloudHandoffTranscriptsEqual,k6 as cloudHandoffFingerprintsEqual,h6 as clearCloudHandoffMetadata,v6 as buildCloudHandoffDashboardUrl,_ as CloudSessionError,U6 as CloudSessionController,A2 as CloudSessionApi,c0 as CloudQueueUnconfirmedError,L0 as CloudHandoffTranscriptMismatchError,e1 as CloudHandoffSeedUnsupportedError,u0 as CloudHandoffSeedRejectedError,P as CloudHandoffGitPreflightError,Z1 as CloudHandoffCreationRejectedError};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type CloudModel = {
|
|
2
|
+
id: string;
|
|
3
|
+
name: string;
|
|
4
|
+
catalogId: "cline" | "cline-pass" | "cline-cloud";
|
|
5
|
+
};
|
|
6
|
+
export declare function loadCloudModels(apiBaseUrl: string, options?: {
|
|
7
|
+
isOrganizationSession?: boolean;
|
|
8
|
+
fetchImpl?: typeof fetch;
|
|
9
|
+
}): Promise<CloudModel[]>;
|