Repository navigation
Expand file tree
/
Copy pathuseWorkspaceAssistantSession.ts
More file actions
1727 lines (1636 loc) · 67 KB
/
Copy pathuseWorkspaceAssistantSession.ts
File metadata and controls
1727 lines (1636 loc) · 67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { UseChatHelpers } from "@ai-sdk/vue";
import type { ChatTransport, UIMessage, UIMessageChunk } from "ai";
import type { EffectScope } from "vue";
import type {
AgentApprovalDecision,
AgentApprovalMode,
AgentMcpManifest,
KokoMcpCancelFrame,
KokoMcpCancelResultFrame,
KokoMcpRequestFrame,
KokoMcpResponseFrame
} from "#koko/composables/agent/types";
import type { AgentSessionController } from "#koko/composables/agent/useAgentSession";
import type { ConnectionFormInfo } from "~/composables/useAssetConnection";
import type { AssetItem, ConnectionInfo, PermedAccount, PermedProtocol } from "~/types";
import { useChat } from "@ai-sdk/vue";
import { effectScope, markRaw, reactive, shallowReactive } from "vue";
import {
agentChatEventLifecycle,
agentChatStreamMessage,
agentChatTextId,
closeAgentChatText
} from "#koko/composables/agent/agentChatStream";
import { AgentToolRelay } from "#koko/composables/agent/agentToolRelay";
import { AGENT_MCP_BINDING_META_KEY, AGENT_PROTOCOL_VERSION, isRecord } from "#koko/composables/agent/types";
import { useAgentSession } from "#koko/composables/agent/useAgentSession";
import type { WorkspaceTerminalTask } from "~/composables/useWorkspaceTerminalTasks";
import {
createWorkspaceTerminalTasks,
resolveWorkspaceTerminalTarget,
workspaceTerminalTools
} from "~/composables/useWorkspaceTerminalTasks";
import type { WorkspacePane } from "~/composables/useWorkspaceTabs";
import {
WorkspaceOperationError,
localShellOperationTools,
workspaceOperationTools,
validateWorkspaceToolArguments,
executeWorkspaceOperation,
useWorkspaceAssistantTools,
requireWorkspaceEmptyPane
} from "~/composables/useWorkspaceAssistantTools";
import { useConnectMethods, isConnectMethodAvailable } from "~/composables/useConnectMethods";
import { getAssetDetailRequest } from "~/composables/useApiRequest";
import { useConnectionLauncher } from "~/composables/useConnectionLauncher";
import { useWorkspaceTabs } from "~/composables/useWorkspaceTabs";
import { useWorkspaceUiAutomation, WorkspaceUiAutomationError } from "~/composables/useWorkspaceUiAutomation";
import { useUserInfoStore } from "~/store/modules/userInfo";
import { isDesktopRuntime } from "~/utils/runtime";
export const DEFAULT_WORKSPACE_ASSISTANT_SCOPE = "global";
const WORKSPACE_TOOL_REVISION = 3;
const CONNECTION_PLAN_TTL_MS = 5 * 60_000;
const CONNECTION_PLAN_LIMIT = 8;
const COMPLETED_INVOCATION_LIMIT = 256;
export type WorkspaceAssistantEventData = Record<string, any>;
export type WorkspaceAssistantChatMessage = UIMessage<
WorkspaceAssistantEventData,
Record<string, WorkspaceAssistantEventData>
>;
interface WorkspaceConnectionPlan {
id: string;
digest: string;
expiresAt: number;
organizationId: string;
contextKey: string;
uiRevision: number;
assetId: string;
assetName: string;
protocol: string;
connectMethod: string;
targetPane?: WorkspacePane;
accountIdentity: string;
personalCredentialIdentity: string;
state: "ready" | "connecting" | "consumed";
}
interface WorkspaceSearchGuard {
candidateIds: Set<string>;
candidateCount: number;
ambiguityPending: boolean;
}
export function workspaceAssistantSearchDecision(ambiguityPending: boolean, candidateCount: number) {
const count = Math.max(0, Math.floor(candidateCount));
const pending = ambiguityPending || count > 1;
return {
ambiguityPending: pending,
selectionRequired: pending,
status: count === 0 ? "no_matches" : pending ? "selection_required" : "match_found"
} as const;
}
export function workspaceAssistantNeedsAssetSelection(
guard: Pick<WorkspaceSearchGuard, "ambiguityPending" | "candidateCount">,
hasValidUserSelection: boolean
) {
return (guard.ambiguityPending || guard.candidateCount > 1) && !hasValidUserSelection;
}
export function workspaceAssistantPlanExpired(expiresAt: number, now = Date.now()) {
return expiresAt <= now;
}
export function workspaceAssistantClaimConnectionPlan(plan: { state: string }) {
if (plan.state !== "ready") return false;
plan.state = "connecting";
return true;
}
export function workspaceAssistantPreparationInvalidReason(input: {
aborted: boolean;
expectedOrganizationId: string;
currentOrganizationId: string;
expectedContextKey: string;
currentContextKey: string;
expectedUiRevision: number;
currentUiRevision: number;
}) {
if (input.aborted) return "aborted";
if (input.currentOrganizationId !== input.expectedOrganizationId) return "organization_changed";
if (input.currentContextKey !== input.expectedContextKey) return "context_changed";
if (input.currentUiRevision !== input.expectedUiRevision) return "stale_ui";
return "";
}
interface WorkspaceInvocation {
fingerprint: string;
promise: Promise<Record<string, unknown>>;
}
interface WorkspaceToolRuntime extends WorkspaceAssistantRuntime {
automation: ReturnType<typeof useWorkspaceUiAutomation>;
launcher: ReturnType<typeof useConnectionLauncher>;
tabs: ReturnType<typeof useWorkspaceTabs>;
userInfoStore: ReturnType<typeof useUserInfoStore>;
plans: Map<string, WorkspaceConnectionPlan>;
invocations: Map<string, WorkspaceInvocation>;
invocationOrder: string[];
activeCalls: Map<string, AbortController>;
searchGuard: WorkspaceSearchGuard;
}
interface WorkspaceAssistantRuntime {
operations: ReturnType<typeof useWorkspaceAssistantTools>;
methods: ReturnType<typeof useConnectMethods>;
automation: ReturnType<typeof useWorkspaceUiAutomation>;
launcher: ReturnType<typeof useConnectionLauncher>;
tabs: ReturnType<typeof useWorkspaceTabs>;
userInfoStore: ReturnType<typeof useUserInfoStore>;
}
export interface WorkspaceAssistantSession {
kind: "workspace";
tabId: string;
target: string;
runTarget: string;
runContext: Record<string, unknown> | null;
terminalTasks: WorkspaceTerminalTask[];
scopeId: string;
organizationId: string;
contextKey: string;
agent: AgentSessionController;
chat: UseChatHelpers<WorkspaceAssistantChatMessage>;
enabled: boolean;
approvalMode: AgentApprovalMode;
inputLocked: boolean;
taskActive: boolean;
draft: string;
runtimeState: string;
errorCode: string;
errorText: string;
}
export function workspaceAssistantMessages(session: Pick<WorkspaceAssistantSession, "chat"> | null | undefined) {
return session ? [...session.chat.messages.value] : [];
}
class WorkspaceAssistantError extends Error {
constructor(
readonly code: string,
message: string
) {
super(message);
this.name = "WorkspaceAssistantError";
}
}
interface ActiveResponse {
controller: ReadableStreamDefaultController<UIMessageChunk>;
started: boolean;
openTextIds: Set<string>;
abortSignal?: AbortSignal;
abortHandler?: () => void;
}
interface PendingChatDispatch {
resolve: () => void;
reject: (error: Error) => void;
}
class WorkspaceAssistantTransport implements ChatTransport<WorkspaceAssistantChatMessage> {
private activeResponse: ActiveResponse | null = null;
private readonly pendingDispatches: PendingChatDispatch[] = [];
constructor(private readonly getSession: () => WorkspaceAssistantSession) {}
sendMessages: ChatTransport<WorkspaceAssistantChatMessage>["sendMessages"] = async ({ messages, abortSignal }) => {
const dispatch = this.pendingDispatches.shift();
const session = this.getSession();
if (!session.enabled || !session.agent.state.available) {
const error = new WorkspaceAssistantError("unavailable", "Workspace Assistant is unavailable");
dispatch?.reject(error);
throw error;
}
if (this.activeResponse) {
const error = new WorkspaceAssistantError("response_active", "Another Workspace Assistant request is active");
dispatch?.reject(error);
throw error;
}
const message = messages.at(-1);
if (!message || message.role !== "user") {
const error = new WorkspaceAssistantError("invalid_message", "Workspace Assistant requires a user message");
dispatch?.reject(error);
throw error;
}
let response: ActiveResponse | null = null;
try {
let controller!: ReadableStreamDefaultController<UIMessageChunk>;
const stream = new ReadableStream<UIMessageChunk>({
start(streamController) {
controller = streamController;
},
cancel: () => {
if (response) this.clear(response);
}
});
response = { controller, started: false, openTextIds: new Set(), abortSignal };
this.activeResponse = response;
const abortHandler = () => this.finish(response!);
if (abortSignal) {
response.abortHandler = abortHandler;
abortSignal.addEventListener("abort", abortHandler, { once: true });
}
if (abortSignal?.aborted) throw new DOMException("Workspace Assistant request was aborted", "AbortError");
session.taskActive = true;
await session.agent.actions.sendMessage({
...message,
metadata: { ...message.metadata, domain: "workspace", targetId: session.scopeId }
});
dispatch?.resolve();
return stream;
} catch (cause) {
const error =
cause instanceof WorkspaceAssistantError
? cause
: new WorkspaceAssistantError(
"send_failed",
cause instanceof Error ? cause.message : "Failed to send Workspace Assistant request"
);
dispatch?.reject(error);
if (response) this.fail(response, error);
throw error;
}
};
reconnectToStream: ChatTransport<WorkspaceAssistantChatMessage>["reconnectToStream"] = async () => null;
receive(message: WorkspaceAssistantChatMessage) {
const response = this.activeResponse;
if (!response || message.role !== "assistant") return false;
if (!response.started) {
response.controller.enqueue({ type: "start", messageId: message.id, messageMetadata: message.metadata });
response.started = true;
} else if (message.metadata) {
response.controller.enqueue({ type: "message-metadata", messageMetadata: message.metadata });
}
for (const [index, part] of message.parts.entries()) {
if (part.type === "text") {
const isDelta = message.metadata?.agentEventType === "message.delta";
const id = agentChatTextId(response, message.id, index);
if (!response.openTextIds.has(id)) {
response.controller.enqueue({ type: "text-start", id });
response.openTextIds.add(id);
}
response.controller.enqueue({ type: "text-delta", id, delta: part.text });
if (!isDelta) {
response.controller.enqueue({ type: "text-end", id });
response.openTextIds.delete(id);
}
continue;
}
if (part.type.startsWith("data-") && "data" in part) {
closeAgentChatText(response);
response.controller.enqueue({ type: part.type, id: `${message.id}-${index}`, data: part.data });
}
}
return true;
}
finish(response = this.activeResponse) {
if (!response) return;
closeAgentChatText(response);
if (response.started) response.controller.enqueue({ type: "finish", finishReason: "stop" });
response.controller.close();
this.clear(response);
}
disconnect() {
const error = new WorkspaceAssistantError("unavailable", "Workspace Assistant session disconnected");
for (const dispatch of this.pendingDispatches.splice(0)) dispatch.reject(error);
this.finish();
}
waitForNextDispatch() {
let resolve!: () => void;
let reject!: (error: Error) => void;
const promise = new Promise<void>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
this.pendingDispatches.push({ resolve, reject });
return promise;
}
cancelPendingDispatch(error: Error) {
this.pendingDispatches.shift()?.reject(error);
}
private fail(response: ActiveResponse, error: Error) {
response.controller.error(error);
this.clear(response);
}
private clear(response: ActiveResponse) {
if (response.abortSignal && response.abortHandler) {
response.abortSignal.removeEventListener("abort", response.abortHandler);
}
if (this.activeResponse === response) this.activeResponse = null;
}
}
const sessions = shallowReactive(new Map<string, WorkspaceAssistantSession>());
const transports = new WeakMap<WorkspaceAssistantSession, WorkspaceAssistantTransport>();
const chatScopes = new WeakMap<WorkspaceAssistantSession, EffectScope>();
const runtimes = new WeakMap<WorkspaceAssistantSession, WorkspaceToolRuntime>();
const terminalManagers = new WeakMap<WorkspaceAssistantSession, ReturnType<typeof createWorkspaceTerminalTasks>>();
export function useWorkspaceAssistantRuntime(): WorkspaceAssistantRuntime {
return {
operations: useWorkspaceAssistantTools(),
methods: useConnectMethods(),
automation: useWorkspaceUiAutomation(),
launcher: useConnectionLauncher(),
tabs: useWorkspaceTabs(),
userInfoStore: useUserInfoStore()
};
}
const readOnlyAnnotations = {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false
};
const readOnlyNonIdempotentAnnotations = {
...readOnlyAnnotations,
idempotentHint: false
};
export function workspaceAssistantManifest(
resourceSessionId: string,
context: { scopeId: string; organizationId: string; uiRevision: number; tabId?: string; localShell?: boolean }
): AgentMcpManifest {
return {
profile: "workspace",
resourceSessionId,
revision: WORKSPACE_TOOL_REVISION,
context: {
session_kind: "workspace",
interaction_mode: "workspace_and_terminal_tasks",
scope_id: context.scopeId,
organization_id: context.organizationId,
ui_revision: context.uiRevision,
...(context.tabId ? { tab_id: context.tabId } : {}),
...(context.localShell ? { local_shell_available: true } : {})
},
tools: [
...workspaceOperationTools,
...workspaceTerminalTools,
...(context.localShell ? localShellOperationTools : []),
{
name: "get_asset_connection_options",
description:
"Revalidate an authorized asset and list credential-free protocol, account and connection method choices. Use only a choice explicitly specified by the user or the sole available choice. Does not connect.",
inputSchema: {
type: "object",
additionalProperties: false,
required: ["asset_id"],
properties: { asset_id: { type: "string", minLength: 1, maxLength: 128 } }
},
annotations: readOnlyAnnotations
},
{
name: "search_connectable_assets",
title: "Search connectable assets",
description:
"Search current authorized assets and mirror results in the asset tree. Never merge recent/favorite references into candidates. Matches may include comments; candidate_count counts matching asset IDs, not all assets. Multiple matches require selection.",
inputSchema: {
type: "object",
additionalProperties: false,
required: ["query"],
properties: {
query: { type: "string", minLength: 1, maxLength: 256 },
limit: { type: "integer", minimum: 1, maximum: 20, default: 10 }
}
},
annotations: readOnlyAnnotations
},
{
name: "prepare_asset_connection",
title: "Prepare an asset connection",
description:
"Revalidate one authorized asset and prepare a short-lived local connection plan. Use protocol/account_id only when explicitly selected by the user or uniquely available; use connect_method from get_asset_connection_options. Optional pane_id must identify an empty pane. External client connections and missing choices open prefilled setup for user action. Never return credentials.",
inputSchema: {
type: "object",
additionalProperties: false,
required: ["asset_id"],
properties: {
asset_id: { type: "string", minLength: 1, maxLength: 128 },
protocol: { type: "string", minLength: 1, maxLength: 64 },
account_id: { type: "string", minLength: 1, maxLength: 256 },
connect_method: { type: "string", minLength: 1, maxLength: 128 },
pane_id: { type: "string", minLength: 1, maxLength: 1024 }
}
},
annotations: readOnlyNonIdempotentAnnotations
},
{
name: "connect_asset",
title: "Connect an asset",
description:
"Consume an unexpired Luna-local connection plan after explicit approval and ask Luna's existing connection launcher to start the session. Use the returned pane_id with get_workspace_state (pane_id, wait_ms) to observe remote connection readiness; session_started alone is not proof of remote login. A plan is single-use and cannot be replayed.",
inputSchema: {
type: "object",
additionalProperties: false,
required: ["plan_id", "plan_digest", "asset_id", "protocol", "account_id", "connect_method"],
properties: {
plan_id: { type: "string", minLength: 1, maxLength: 160 },
plan_digest: { type: "string", minLength: 16, maxLength: 160 },
asset_id: { type: "string", minLength: 1, maxLength: 128 },
asset_name: { type: "string", maxLength: 256 },
protocol: { type: "string", minLength: 1, maxLength: 64 },
account_id: { type: "string", minLength: 1, maxLength: 256 },
connect_method: { type: "string", minLength: 1, maxLength: 128 }
}
},
annotations: {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: false
}
}
]
};
}
function boundedString(value: unknown, maximum: number) {
return String(value ?? "")
.trim()
.slice(0, maximum);
}
function opaqueId(prefix: string) {
const random = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(16).slice(2)}`;
return `${prefix}-${random}`;
}
export function workspaceAssistantScopeId() {
return opaqueId("workspace-scope");
}
function stableJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
if (isRecord(value)) {
return `{${Object.keys(value)
.sort()
.map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`)
.join(",")}}`;
}
return JSON.stringify(value) ?? "null";
}
async function connectionPlanDigest(value: Record<string, unknown>) {
const nonce = opaqueId("nonce");
const input = new TextEncoder().encode(stableJson({ ...value, nonce }));
if (globalThis.crypto?.subtle) {
const digest = await globalThis.crypto.subtle.digest("SHA-256", input);
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
}
// Desktop and supported browsers provide WebCrypto. This opaque verifier is
// only a compatibility fallback and is still checked against the local plan.
return opaqueId("workspace-verifier");
}
function choiceValue(value: unknown) {
if (typeof value === "string") return value;
if (isRecord(value)) return boundedString(value.name || value.value || value.label, 256);
return "";
}
function normalizeCandidate(value: unknown) {
if (!isRecord(value)) return null;
const id = boundedString(value.id || value.assetId || value.asset_id, 128);
if (!id) return null;
return {
id,
name: boundedString(value.name, 256),
address: boundedString(value.address, 256),
platform: choiceValue(value.platform),
zone: choiceValue(value.zone),
category: choiceValue(value.category),
type: choiceValue(value.type),
is_active: value.isActive !== false && value.is_active !== false
};
}
function uniqueProtocols(protocols: PermedProtocol[]) {
const names = protocols
.filter((protocol) => protocol?.public !== false)
.map((protocol) => boundedString(protocol.name, 64).toLowerCase())
.filter(Boolean);
return [...new Set(names)];
}
export function workspaceAssistantConnectionChoices(asset: AssetItem, protocolValue = "", accountId = "") {
const protocols = uniqueProtocols(asset.permedProtocols || []);
const accounts = uniqueAccounts(asset.permedAccounts || []);
const protocol = protocolValue
? protocols.find((value) => value === protocolValue.toLowerCase())
: protocols.length === 1
? protocols[0]
: undefined;
const account = accountId
? accounts.find((value) => accountIdentity(value) === accountId)
: accounts.length === 1
? accounts[0]
: undefined;
if (protocolValue && !protocol)
throw new WorkspaceAssistantError("invalid_protocol", "The selected protocol is not authorized");
if (accountId && !account)
throw new WorkspaceAssistantError("invalid_account", "The selected account is not authorized");
return { protocols, accounts, protocol, account };
}
function uniqueAccounts(accounts: PermedAccount[]) {
const seen = new Set<string>();
return accounts.filter((account) => {
const key = accountIdentity(account);
if (!key || seen.has(key)) return false;
seen.add(key);
return true;
});
}
function accountIdentity(account: PermedAccount) {
return boundedString(account.id || account.alias || account.name || account.username, 256);
}
export function workspaceAssistantConnectionForUniqueAccount(
protocol: string,
account: PermedAccount,
saved: ConnectionInfo | undefined
): ConnectionFormInfo | null {
const alias = boundedString(account.alias, 64);
const savedMatchesProtocol = saved?.protocol?.toLowerCase() === protocol;
const base = {
protocol,
manualUsername: "",
manualPassword: "",
dynamicPassword: "",
rememberSecret: false,
rememberSelection: false,
preserveStoredSelection: true,
connectMethod: savedMatchesProtocol ? saved?.connectMethod || "" : "",
connectOptions: savedMatchesProtocol ? { ...(saved?.connectOptions || {}) } : {},
availableProtocols: [protocol]
};
if (!alias.startsWith("@")) {
return {
...base,
account: account.name,
accountId: account.id,
accountMode: "hosted"
};
}
if (alias === "@ANON") return { ...base, account: "@ANON", accountMode: "anonymous" };
if (alias === "@INPUT" && savedMatchesProtocol && saved?.personalCredentialId) {
return {
...base,
account: account.name || alias,
accountMode: "manual",
manualUsername: saved.manualUsername || "",
personalCredentialId: saved.personalCredentialId,
personalCredentialVersion: saved.personalCredentialVersion,
personalCredentialSecretType: saved.personalCredentialSecretType || "password"
};
}
if (alias === "@USER" && savedMatchesProtocol && saved?.rememberSecret && saved.dynamicPassword) {
return {
...base,
account: account.name || alias,
accountMode: "dynamic",
dynamicPassword: saved.dynamicPassword,
rememberSecret: true
};
}
return null;
}
// Keep credential references local; a changed selection requires a new connection plan.
export function workspaceAssistantPersonalCredentialIdentity(connection: ConnectionFormInfo) {
return stableJson({
id: connection.personalCredentialId || "",
version: connection.personalCredentialVersion ?? null
});
}
function currentOrganizationId(userInfoStore: ReturnType<typeof useUserInfoStore>) {
return boundedString(userInfoStore.currentUser?.org?.id, 128);
}
function currentWorkspaceContextKey(userInfoStore: ReturnType<typeof useUserInfoStore>) {
return stableJson({
site: boundedString(userInfoStore.currentSite, 512),
account_id: boundedString(userInfoStore.currentAccountId, 256),
organization_id: currentOrganizationId(userInfoStore)
});
}
async function loadAuthorizedAsset(assetId: string, runtime: WorkspaceToolRuntime): Promise<AssetItem> {
const candidates = [
runtime.automation.snapshot.value?.focusedAsset,
...(runtime.automation.snapshot.value?.candidates || [])
];
const candidate = candidates.map(normalizeCandidate).find((item) => item?.id === assetId) || null;
const organizationId = currentOrganizationId(runtime.userInfoStore);
const detail = await getAssetDetailRequest(assetId, organizationId);
const resolvedId = boundedString(detail.id || assetId, 128);
if (resolvedId !== assetId)
throw new WorkspaceAssistantError("asset_mismatch", "Authorized asset lookup was inconsistent");
const protocols = (detail.permed_protocols || detail.permedProtocols || []) as PermedProtocol[];
const accounts = (detail.permed_accounts || detail.permedAccounts || []) as PermedAccount[];
return {
id: resolvedId,
name: boundedString(detail.name || candidate?.name, 256),
address: boundedString(detail.address || candidate?.address, 256),
org_id: boundedString(detail.org_id || organizationId, 128) || undefined,
platform: choiceValue(detail.platform) || candidate?.platform || "",
zone: choiceValue(detail.zone) || candidate?.zone || "",
category: choiceValue(detail.category) || candidate?.category || "",
type: choiceValue(detail.type) || candidate?.type || "",
isActive: detail.is_active !== false && candidate?.is_active !== false,
permedProtocols: protocols,
permedAccounts: accounts,
savedConnection: runtime.userInfoStore.getConnectionInfoForAsset(assetId) || undefined
};
}
export function workspaceAssistantSearchCandidates(value: unknown) {
if (!Array.isArray(value)) return [];
const candidates = new Map<string, NonNullable<ReturnType<typeof normalizeCandidate>>>();
for (const entry of value) {
const candidate = normalizeCandidate(entry);
if (candidate) candidates.set(candidate.id, candidate);
}
return [...candidates.values()];
}
function pruneConnectionPlans(runtime: WorkspaceToolRuntime, assetId = "", reserveSlot = false) {
const now = Date.now();
for (const [planId, plan] of runtime.plans) {
if (
plan.state === "consumed" ||
plan.expiresAt <= now ||
(assetId && plan.assetId === assetId && plan.state === "ready")
) {
runtime.plans.delete(planId);
}
}
if (reserveSlot) {
for (const [planId, plan] of runtime.plans) {
if (runtime.plans.size < CONNECTION_PLAN_LIMIT) break;
if (plan.state === "ready") runtime.plans.delete(planId);
}
}
if (reserveSlot && runtime.plans.size >= CONNECTION_PLAN_LIMIT) {
throw new WorkspaceAssistantError("plan_limit", "Too many workspace connections are already starting");
}
}
function assertWorkspacePreparationCurrent(
runtime: WorkspaceToolRuntime,
expectedOrganizationId: string,
expectedContextKey: string,
expectedUiRevision: number,
signal: AbortSignal
) {
const reason = workspaceAssistantPreparationInvalidReason({
aborted: signal.aborted,
expectedOrganizationId,
currentOrganizationId: currentOrganizationId(runtime.userInfoStore),
expectedContextKey,
currentContextKey: currentWorkspaceContextKey(runtime.userInfoStore),
expectedUiRevision,
currentUiRevision: runtime.automation.uiRevision.value
});
if (reason === "aborted") throw new DOMException("Workspace connection preparation was cancelled", "AbortError");
if (reason === "organization_changed") {
throw new WorkspaceAssistantError("organization_changed", "The active organization changed during preparation");
}
if (reason === "context_changed") {
throw new WorkspaceAssistantError("context_changed", "The active site or account changed during preparation");
}
if (reason === "stale_ui") {
throw new WorkspaceAssistantError("stale_ui", "The workspace changed during connection preparation");
}
}
async function executeWorkspaceTool(
session: WorkspaceAssistantSession,
name: string,
args: Record<string, unknown>,
signal: AbortSignal
): Promise<Record<string, unknown>> {
const runtime = runtimes.get(session);
if (!runtime) throw new WorkspaceAssistantError("session_closed", "Workspace Assistant session is closed");
const automation = runtime.automation;
const scopedTabs = () => (session.tabId ? runtime.tabs.tabs.value.filter((tab) => tab.id === session.tabId) : []);
const assertCurrent = () => {
if (signal.aborted) throw new DOMException("Workspace tool call was cancelled", "AbortError");
if (session.contextKey !== currentWorkspaceContextKey(runtime.userInfoStore))
throw new WorkspaceAssistantError("context_changed", "The active site, account or organization changed");
if (session.tabId && !runtime.tabs.getTabById(session.tabId))
throw new WorkspaceAssistantError("session_closed", "The workspace tab was closed");
};
assertCurrent();
const localShell = scopedTabs().some((tab) => tab.panes.some((pane) => pane.protocol === "local-shell"));
const definition = workspaceAssistantManifest("", {
scopeId: session.scopeId,
organizationId: session.organizationId,
uiRevision: automation.uiRevision.value,
tabId: session.tabId,
localShell
}).tools.find((tool) => tool.name === name);
if (!definition) throw new WorkspaceAssistantError("unknown_tool", "Unknown workspace tool");
validateWorkspaceToolArguments(definition, args);
const terminalManager = terminalManagers.get(session);
if (name === "list_terminal_targets")
return {
targets: terminalManager?.list() || [],
default_terminal_target: session.runContext?.default_terminal_target || null
};
if (name === "start_terminal_task") {
if (!terminalManager) throw new WorkspaceAssistantError("session_closed", "Terminal task manager is unavailable");
try {
return await terminalManager.start(String(args.target_id), String(args.prompt));
} catch (cause) {
throw new WorkspaceAssistantError(
"terminal_task_failed",
cause instanceof Error ? cause.message : "Terminal task failed"
);
}
}
if (name === "get_terminal_task") {
if (!terminalManager) throw new WorkspaceAssistantError("session_closed", "Terminal task manager is unavailable");
try {
return await terminalManager.read(String(args.task_id), Number(args.wait_ms) || 0, signal);
} catch (cause) {
if (signal.aborted) throw cause;
throw new WorkspaceAssistantError(
"terminal_task_failed",
cause instanceof Error ? cause.message : "Terminal task failed"
);
}
}
if (
[...workspaceOperationTools, ...localShellOperationTools].some((tool) => tool.name === name) &&
!(name === "navigate_workspace" && args.target === "asset")
) {
if (localShellOperationTools.some((tool) => tool.name === name) && session.runTarget !== "auto") {
throw new WorkspaceAssistantError("target_mismatch", "Select Automatic before using the Local Shell");
}
return executeWorkspaceOperation(
runtime.operations,
name,
args,
signal,
session.organizationId,
assertCurrent,
session.tabId
);
}
const availableMethods = async (protocol: string, assetId: string) => {
const methods = await runtime.methods.getMethodsForProtocol(protocol, assetId);
assertCurrent();
return methods.filter(
(method) =>
(isDesktopRuntime() || method.type === "web") &&
isConnectMethodAvailable(method.value, methods, protocol, runtime.operations.preferences.appConfig.value)
);
};
if (name === "get_asset_connection_options") {
const asset = await loadAuthorizedAsset(String(args.asset_id), runtime);
assertCurrent();
const protocols = [];
for (const protocol of uniqueProtocols(asset.permedProtocols || []).slice(0, 32)) {
protocols.push({
protocol,
methods: (await availableMethods(protocol, asset.id))
.slice(0, 32)
.map((method) => ({ value: method.value, label: method.label, type: method.type }))
});
}
const accounts = uniqueAccounts(asset.permedAccounts || []);
return {
status: asset.isActive ? "ok" : "asset_inactive",
asset: normalizeCandidate(asset),
protocols,
accounts: accounts
.slice(0, 50)
.map((account) => ({ account_id: accountIdentity(account), name: account.name, username: account.username })),
accounts_truncated: accounts.length > 50
};
}
if (name === "search_connectable_assets") {
const query = boundedString(args.query, 256);
if (!query) throw new WorkspaceAssistantError("invalid_arguments", "A non-empty asset search query is required");
const limit = Math.max(1, Math.min(20, Math.floor(Number(args.limit) || 10)));
const ack = await automation.setSearch(query, { signal });
assertCurrent();
const matchedCandidates = workspaceAssistantSearchCandidates(ack.candidates);
const candidateCount = matchedCandidates.length;
const candidates = matchedCandidates.slice(0, limit);
runtime.searchGuard.candidateIds = new Set(matchedCandidates.map((candidate) => candidate.id));
runtime.searchGuard.candidateCount = candidateCount;
const searchDecision = workspaceAssistantSearchDecision(runtime.searchGuard.ambiguityPending, candidateCount);
runtime.searchGuard.ambiguityPending = searchDecision.ambiguityPending;
if (searchDecision.selectionRequired) automation.requestAssetSelection();
else automation.clearAssetSelectionRequest();
return {
status: searchDecision.status,
source: "authorized",
permission_status: "authorized",
organization_id: session.organizationId,
returned_count: candidates.length,
query,
revision: ack.revision,
candidate_count: candidateCount,
candidates,
candidates_truncated: candidateCount > candidates.length,
user_selection_required: searchDecision.selectionRequired,
...(runtime.searchGuard.ambiguityPending ? { reason: "unresolved_asset_ambiguity" } : {})
};
}
if (name === "navigate_workspace" && args.target === "asset") {
const assetId = boundedString(args.id, 128);
const asset = await loadAuthorizedAsset(assetId, runtime);
assertCurrent();
if (!assetId) throw new WorkspaceAssistantError("invalid_arguments", "asset_id is required");
const ack = await automation.focusAsset(assetId, {
query: (asset.name || asset.address).slice(0, 256),
signal
});
const focusedAsset = normalizeCandidate(ack.focusedAsset);
return {
status: "revealed",
revision: ack.revision,
asset: focusedAsset || { id: assetId }
};
}
if (name === "prepare_asset_connection") {
const assetId = boundedString(args.asset_id, 128);
if (!assetId) throw new WorkspaceAssistantError("invalid_arguments", "asset_id is required");
if (!runtime.searchGuard.candidateIds.has(assetId)) {
return {
status: "search_required",
reason: "asset_not_in_latest_search",
user_selection_required: true
};
}
const uiSnapshot = automation.snapshot.value;
const preparationOrganizationId = currentOrganizationId(runtime.userInfoStore);
const preparationContextKey = currentWorkspaceContextKey(runtime.userInfoStore);
const selectionReceipt = uiSnapshot.selectionReceipt;
const hasValidUserSelection =
uiSnapshot.focusedAssetSource === "user" &&
uiSnapshot.focusedAsset?.id === assetId &&
selectionReceipt?.assetId === assetId &&
selectionReceipt.revision === uiSnapshot.revision;
if (workspaceAssistantNeedsAssetSelection(runtime.searchGuard, hasValidUserSelection)) {
return {
status: "selection_required",
reason: runtime.searchGuard.ambiguityPending ? "unresolved_asset_ambiguity" : "multiple_assets",
user_selection_required: true,
candidate_count: runtime.searchGuard.candidateCount
};
}
const asset = await loadAuthorizedAsset(assetId, runtime);
assertWorkspacePreparationCurrent(
runtime,
preparationOrganizationId,
preparationContextKey,
uiSnapshot.revision,
signal
);
if (!asset.isActive) throw new WorkspaceAssistantError("asset_inactive", "The selected asset is inactive");
runtime.searchGuard.ambiguityPending = runtime.searchGuard.ambiguityPending && !hasValidUserSelection;
if (hasValidUserSelection) {
runtime.searchGuard.candidateIds = new Set([assetId]);
runtime.searchGuard.candidateCount = 1;
}
const reveal = hasValidUserSelection
? { revision: uiSnapshot.revision }
: await automation.focusAsset(assetId, { query: asset.name || asset.address, signal });
assertWorkspacePreparationCurrent(
runtime,
preparationOrganizationId,
preparationContextKey,
reveal.revision,
signal
);
const {
protocols,
accounts,
protocol: selectedProtocol,
account: selectedAccount
} = workspaceAssistantConnectionChoices(asset, String(args.protocol || ""), String(args.account_id || ""));
const connection =
selectedProtocol && selectedAccount
? workspaceAssistantConnectionForUniqueAccount(selectedProtocol, selectedAccount, asset.savedConnection)
: null;
const targetPane = args.pane_id
? requireWorkspaceEmptyPane(scopedTabs(), String(args.pane_id), preparationOrganizationId)
: undefined;
const assertEmptyTarget = () => {
if (targetPane) requireWorkspaceEmptyPane(scopedTabs(), targetPane.id, preparationOrganizationId, targetPane);
};
const methods = selectedProtocol ? await availableMethods(selectedProtocol, asset.id) : [];
assertWorkspacePreparationCurrent(
runtime,
preparationOrganizationId,
preparationContextKey,
reveal.revision,
signal
);
assertEmptyTarget();
const requestedMethod = String(args.connect_method || "");
if (requestedMethod && !methods.some((method) => method.value === requestedMethod))
throw new WorkspaceAssistantError("invalid_method", "The selected connection method is unavailable");
if (connection)
connection.connectMethod =
requestedMethod ||
methods.find((method) => method.value === connection.connectMethod)?.value ||
methods[0]?.value ||
"";
const externalMethod =
connection && methods.find((method) => method.value === connection.connectMethod)?.type !== "web";
if (!connection || !connection.connectMethod || externalMethod) {
pruneConnectionPlans(runtime, asset.id);
const setupPane = runtime.tabs.openSetupSession(asset, {
protocol: selectedProtocol,
paneId: targetPane?.id,
newTab: !targetPane
});
return {
status: !selectedProtocol || !selectedAccount ? "selection_required" : "user_action_required",
setup_opened: true,
pane_id: setupPane.id,
asset: normalizeCandidate(asset),
revision: reveal.revision,
protocol_count: protocols.length,
account_count: accounts.length,
user_selection_required: true,
reason: !selectedProtocol
? "multiple_protocols"
: !selectedAccount
? "multiple_accounts"