-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadapter.ts
More file actions
1388 lines (1288 loc) · 50.9 KB
/
Copy pathadapter.ts
File metadata and controls
1388 lines (1288 loc) · 50.9 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 { readFileSync } from "node:fs";
import { basename, dirname, resolve } from "node:path";
import JSZip from "jszip";
import { UserError } from "../../errors.ts";
import type {
AgentDecl,
ChannelDecl,
DeploymentDecl,
EnvironmentDecl,
IdentityDecl,
MemoryStoreDecl,
SkillDecl,
VaultDecl,
} from "../../types/config.ts";
import type { CloudAgent, CloudEnvironment, CloudVault } from "../../types/dto.ts";
import type { ProviderFileInfo } from "../../types/file.ts";
import type {
CreateMemoryInput,
MemoryListOptions,
MemoryStoreListOptions,
MemoryVersionListOptions,
UpdateMemoryInput,
UpdateMemoryStoreInput,
} from "../../types/memory.ts";
import type {
ForwardSessionBindings,
ProviderSessionInfo,
SessionBindings,
SessionFilter,
SessionListResult,
} from "../../types/session.ts";
import type {
EventListOptions,
EventStreamOptions,
ProviderSessionEvent,
ProviderSessionEventList,
} from "../../types/session-event.ts";
import type { SkillFile } from "../../types/skill-file.ts";
import type { ProviderSkillInfo } from "../../types/skill-info.ts";
import type { ResourceType } from "../../types/state.ts";
import { compactDeep, stripAgentsMetadata } from "../../utils/comparable.ts";
import { skillNameFromFiles } from "../../utils/skill-manifest.ts";
import { ApiError, toRemoteResource } from "../base-client.ts";
import { preserveDeploymentFilesOnConflict } from "../deployment-conflict.ts";
import type {
ComparableRemoteResource,
DeploymentContext,
DeploymentInfo,
DeploymentListFilter,
DeploymentListResult,
DeploymentRunResult,
DriftSupport,
ExportedResource,
ModelInfo,
ProviderAdapter,
ProviderResourceMode,
RemoteResource,
ResolvedAgentRefs,
ResolvedChannelRefs,
ResolvedDeploymentRefs,
ResolvedTemplateRefs,
} from "../interface.ts";
import { ProviderMemoryApi } from "../memory-api.ts";
import { extractCreatedEventId, listSessionEventsPaged } from "../session-event-response.ts";
import {
buildSessionInfo,
exportRemoteResources,
locateRemote,
notArchived,
toCloudAgent,
toCloudEnvironment,
toCloudVault,
toRestFileInfo,
toRestSkillInfo,
} from "../shared.ts";
import { QoderClient } from "./client.ts";
import {
agentToDecl,
envToDecl,
fileToDecl,
mapAgent,
mapCredential,
mapDeployment,
mapDeploymentUpdate,
mapEnvironment,
mapForwardEnvironment,
mapForwardTemplate,
mapMemoryStore,
mapSendMessage,
mapSession,
mapVault,
normalizeToolNameFromQoder,
skillToDecl,
toSessionEvent,
vaultToDecl,
} from "./mapper.ts";
function deriveForwardGateway(cloudGateway?: string): string {
if (!cloudGateway) return "https://api.qoder.com/api/v1/forward";
const trimmed = cloudGateway.replace(/\/$/, "");
return trimmed.endsWith("/cloud") ? `${trimmed.slice(0, -"/cloud".length)}/forward` : `${trimmed}/forward`;
}
function toDeploymentInfo(res: Record<string, unknown>): DeploymentInfo {
const sched = res.schedule as Record<string, unknown> | null | undefined;
return {
id: (res.id as string | undefined) ?? null,
status: (res.status as string) ?? "unknown",
paused_reason: (res.paused_reason as DeploymentInfo["paused_reason"] | null | undefined) ?? undefined,
schedule: sched
? { expression: sched.expression as string, timezone: sched.timezone as string | undefined }
: undefined,
attributes: res,
};
}
export class QoderAdapter implements ProviderAdapter {
readonly name = "qoder" as const;
readonly eventResume = true;
readonly memoryCapabilities = {
archive_store: true,
batch_create: false,
versions: true,
optimistic_concurrency: true,
memory_metadata: true,
} as const;
private client: QoderClient;
private memoryApi: ProviderMemoryApi;
private forwardClient: QoderClient;
private forwardMemoryApi: ProviderMemoryApi;
private projectName: string;
private forwardSessionIds = new Set<string>();
constructor(apiKey: string, gateway?: string, projectName?: string, forwardGateway?: string) {
this.client = new QoderClient({ apiKey, gateway });
this.memoryApi = new ProviderMemoryApi(this.client, {
pathStyle: "relative",
cursorParam: "after_id",
updatePrecondition: "content_sha256",
prefixParam: "prefix",
versionsSegment: "versions",
storeMetadataMode: "merge_patch",
supportsView: false,
supportsMemoryMetadata: true,
supportsPathUpdate: false,
supportsDeletePrecondition: false,
supportsIncludeArchived: true,
});
this.forwardClient = new QoderClient({
apiKey,
gateway: forwardGateway ?? deriveForwardGateway(gateway),
});
this.forwardMemoryApi = new ProviderMemoryApi(this.forwardClient, {
pathStyle: "relative",
cursorParam: "after_id",
updatePrecondition: "content_sha256",
prefixParam: "prefix",
versionsSegment: "versions",
storeMetadataMode: "merge_patch",
supportsView: false,
supportsMemoryMetadata: true,
supportsPathUpdate: false,
supportsDeletePrecondition: false,
supportsIncludeArchived: true,
});
this.projectName = projectName ?? "";
}
async validate(): Promise<void> {
await this.client.get("/agents?limit=1");
}
private static readonly ENDPOINT_MAP: Partial<Record<ResourceType, string>> = {
environment: "/environments",
agent: "/agents",
vault: "/vaults",
skill: "/skills",
memory_store: "/memory_stores",
file: "/files",
deployment: "/deployments",
};
async findResource(
type: ResourceType,
name: string,
id?: string | null,
mode?: ProviderResourceMode,
): Promise<RemoteResource | null> {
if (type === "template") {
const raw = await locateRemote(this.forwardClient, "/templates", name, id, (item) => item.status !== "archived");
return raw ? toRemoteResource(raw) : null;
}
if (type === "identity") {
try {
if (id) return toRemoteResource((await this.forwardClient.get(`/identities/${id}`)) as Record<string, unknown>);
const res = (await this.forwardClient.get(`/identities?external_id=${encodeURIComponent(name)}&limit=100`)) as {
data?: Record<string, unknown>[];
};
const raw = (res.data ?? []).find((item) => item.external_id === name);
return raw ? toRemoteResource(raw) : null;
} catch (err) {
if (ApiError.isNotFound(err)) return null;
throw err;
}
}
if (type === "channel") {
const raw = await locateRemote(this.forwardClient, "/channels", name, id, () => true);
return raw ? toRemoteResource(raw) : null;
}
// An Environment id referenced by a Forward Template may belong to either
// the Cloud/Managed API or the Forward API. With no ownership domain
// recorded, resolve the external id across both read APIs. Locally owned
// environments always pass an explicit mode and never use this fallback.
if (type === "environment" && id && mode === "auto") {
const managed = await locateRemote(this.client, "/environments", name, id, notArchived);
if (managed) return toRemoteResource(managed);
const forward = await locateRemote(this.forwardClient, "/environments", name, id, notArchived);
return forward ? toRemoteResource(forward) : null;
}
const client =
mode === "forward" &&
(type === "environment" || type === "skill" || type === "vault" || type === "memory_store" || type === "file")
? this.forwardClient
: this.client;
const raw = await locateRemote(client, QoderAdapter.ENDPOINT_MAP[type], name, id, notArchived);
return raw ? toRemoteResource(raw) : null;
}
async listAgents(filter?: { prefix?: string; limit?: number }): Promise<CloudAgent[]> {
// A prefix request must scan every page and filter locally so family members on
// page 2+ are not dropped from the resource center.
const prefix = filter?.prefix;
if (prefix) {
const all = await this.client.getAllPaged("/agents");
return all.map(toCloudAgent).filter((a) => (a.name ?? "").startsWith(prefix));
}
const res = (await this.client.get(`/agents?limit=${filter?.limit ?? 100}`)) as {
data?: Record<string, unknown>[];
};
return (res.data ?? []).map(toCloudAgent);
}
async listEnvironments(_filter?: { limit?: number }): Promise<CloudEnvironment[]> {
const all = await this.client.getAllPaged("/environments");
return all.map(toCloudEnvironment);
}
async listVaults(_filter?: { limit?: number }): Promise<CloudVault[]> {
const all = await this.client.getAllPaged("/vaults");
return all.map(toCloudVault);
}
async listFiles(): Promise<ProviderFileInfo[]> {
const all = await this.client.getAllPaged("/files");
return all.map(toRestFileInfo);
}
async getFileInfo(id: string): Promise<ProviderFileInfo> {
const res = (await this.client.get(`/files/${id}`)) as Record<string, unknown>;
return toRestFileInfo(res);
}
async getFileDownloadUrl(id: string): Promise<{ url: string; expires_at?: string }> {
const res = (await this.client.get(`/files/${id}/content`)) as Record<string, unknown>;
return {
url: res.url as string,
expires_at: typeof res.expires_at === "string" ? res.expires_at : undefined,
};
}
async listSkills(source?: "custom" | "official"): Promise<ProviderSkillInfo[]> {
// Qoder's built-in catalog is requested as `?source=qoder` (NOT `official`, which
// the API rejects with HTTP 400); the default page is the workspace custom catalog.
const path = source === "official" ? "/skills?source=qoder" : "/skills";
const all = await this.client.getAllPaged(path);
return all.map(toRestSkillInfo);
}
async getSkillInfo(id: string): Promise<ProviderSkillInfo> {
const res = (await this.client.get(`/skills/${id}`)) as Record<string, unknown>;
return toRestSkillInfo(res);
}
getDriftSupport(type: ResourceType): DriftSupport {
if (type === "agent" || type === "environment" || type === "template" || type === "identity" || type === "channel")
return "full";
if (type === "deployment") return "unsupported";
return QoderAdapter.ENDPOINT_MAP[type] ? "existence" : "unsupported";
}
async readComparableResource(
type: ResourceType,
id: string | null,
name: string,
decl?: unknown,
): Promise<ComparableRemoteResource | null> {
if (type !== "agent" && type !== "environment" && type !== "template" && type !== "identity" && type !== "channel")
return null;
if (type === "identity" || type === "channel") {
const remote = await this.findResource(type, name, id);
if (!remote?.id) return null;
const raw = (await this.forwardClient.get(
`/${type === "identity" ? "identities" : "channels"}/${remote.id}`,
)) as Record<string, unknown>;
const comparable = this.normalizeRemote(type, raw);
return { id: remote.id, type, comparable, snapshot: comparable };
}
let raw: Record<string, unknown> | null;
if ((type === "agent" || type === "environment") && decl !== undefined && this.projectName) {
const declaredName = (decl as { name?: unknown }).name;
const displayName = typeof declaredName === "string" ? declaredName : name;
raw = await this.readManagedResourceByIdentity(type, id, displayName);
} else {
const isTemplate = type === "template";
const endpoint = type === "agent" ? "/agents" : type === "environment" ? "/environments" : "/templates";
raw = await locateRemote(
isTemplate ? this.forwardClient : this.client,
endpoint,
name,
id,
isTemplate ? (item) => item.status !== "archived" : notArchived,
);
}
if (!raw) return null;
const comparable = this.normalizeRemote(type, raw);
return {
id: (raw.id as string | undefined) ?? id,
type,
version: raw.version as number | undefined,
comparable,
snapshot: comparable,
};
}
private async readManagedResourceByIdentity(
type: "agent" | "environment",
id: string | null,
displayName: string,
): Promise<Record<string, unknown> | null> {
const endpoint = type === "agent" ? "/agents" : "/environments";
if (id) {
try {
const raw = (await this.client.get(`${endpoint}/${id}`)) as Record<string, unknown>;
return this.matchesManagedResourceIdentity(type, raw, displayName) ? raw : null;
} catch (error) {
if (ApiError.isNotFound(error)) return null;
throw error;
}
}
const matches = (await this.client.getAllPaged(endpoint)).filter((raw) =>
this.matchesManagedResourceIdentity(type, raw, displayName),
);
if (matches.length !== 1) return null;
const matchedId = matches[0]?.id;
if (typeof matchedId !== "string") return null;
try {
const raw = (await this.client.get(`${endpoint}/${matchedId}`)) as Record<string, unknown>;
return this.matchesManagedResourceIdentity(type, raw, displayName) ? raw : null;
} catch (error) {
if (ApiError.isNotFound(error)) return null;
throw error;
}
}
private matchesManagedResourceIdentity(
type: "agent" | "environment",
raw: Record<string, unknown>,
displayName: string,
): boolean {
if (!notArchived(raw) || raw.name !== displayName) return false;
if (typeof raw.type === "string" && raw.type !== type) return false;
const metadata = raw.metadata;
if (!metadata || typeof metadata !== "object") return false;
return (
(metadata as Record<string, unknown>)["agents.project"] === this.projectName &&
(metadata as Record<string, unknown>)["agents.resource"] === displayName
);
}
normalizeDesiredResource(type: ResourceType, name: string, decl: unknown): unknown | null {
if (type === "environment") {
return this.normalizeRemote(
type,
mapEnvironment(name, decl as EnvironmentDecl, this.projectName) as Record<string, unknown>,
);
}
if (type === "agent") {
return this.normalizeRemote(
type,
mapAgent(name, decl as AgentDecl, { skill_ids: [] }, undefined, this.projectName) as Record<string, unknown>,
);
}
if (type === "template") return null;
if (type === "identity") {
const identity = decl as IdentityDecl;
if (identity.identity_id) return null;
return this.normalizeRemote(type, {
external_id: identity.external_id,
name: identity.name ?? name,
enabled: identity.enabled ?? true,
metadata: identity.metadata ?? {},
});
}
return null;
}
private normalizeRemote(type: ResourceType, raw: Record<string, unknown>): unknown {
if (type === "environment") {
const normalized = envToDecl(raw);
return compactDeep({
description: raw.description,
config: normalized.config,
metadata: stripAgentsMetadata(raw.metadata),
});
}
if (type === "template") {
return compactDeep({
name: raw.name,
description: raw.description,
model: raw.model,
system: raw.system,
tools: raw.tools,
mcp_servers: raw.mcp_servers,
skills: raw.skills,
multiagent: raw.multiagent,
environment_id: raw.environment_id,
tunnel_id: raw.tunnel_id,
vault_ids: Array.isArray(raw.vault_ids)
? raw.vault_ids
: Object.keys((raw.vaults ?? {}) as Record<string, unknown>),
files: raw.files,
environment_variables: raw.environment_variables,
metadata: stripAgentsMetadata(raw.metadata),
});
}
if (type === "identity") {
return compactDeep({
external_id: raw.external_id,
name: raw.name,
enabled: raw.enabled,
metadata: raw.metadata ?? {},
});
}
if (type === "channel") {
const channelConfig = (raw.channel_config ?? {}) as Record<string, unknown>;
const mode = (raw.identity_resolution as { mode?: string } | undefined)?.mode ?? "fixed";
const normalized: Record<string, unknown> = {
identity_resolution: { mode },
channel_type: raw.channel_type,
name: raw.name,
enabled: raw.enabled,
channel_config: {
response_options: channelConfig.response_options ?? {},
},
};
if (mode === "fixed") {
normalized.identity_id = raw.identity_id;
normalized.template_id = raw.template_id;
}
return compactDeep(normalized);
}
return compactDeep({
name: raw.name,
description: raw.description === "" ? undefined : raw.description,
model: normalizeModel(raw.model),
instructions: raw.system,
tools: normalizeQoderTools(raw.tools),
mcp_servers: normalizeQoderMcpServers(raw.mcp_servers),
metadata: stripAgentsMetadata(raw.metadata),
});
}
async createEnvironment(
name: string,
decl: EnvironmentDecl,
mode: ProviderResourceMode = "managed",
): Promise<RemoteResource> {
const body =
mode === "forward"
? mapForwardEnvironment(name, decl, this.projectName)
: mapEnvironment(name, decl, this.projectName);
const res = (await (mode === "forward" ? this.forwardClient : this.client).post("/environments", body)) as Record<
string,
unknown
>;
return toRemoteResource(res);
}
async updateEnvironment(
id: string,
name: string,
decl: EnvironmentDecl,
mode: ProviderResourceMode = "managed",
): Promise<RemoteResource> {
const body = (
mode === "forward"
? mapForwardEnvironment(name, decl, this.projectName)
: mapEnvironment(name, decl, this.projectName)
) as Record<string, unknown>;
const client = mode === "forward" ? this.forwardClient : this.client;
const current = (await client.get(`/environments/${id}`)) as Record<string, unknown>;
const currentMetadata = (current.metadata ?? {}) as Record<string, unknown>;
const metadata = { ...((body.metadata ?? {}) as Record<string, string | null>) };
for (const key of Object.keys(currentMetadata)) {
// Qoder injects created_by into environment responses but rejects it on writes,
// including deletion tombstones such as { created_by: null }.
if (key !== "created_by" && !key.startsWith("agents.") && !(key in metadata)) metadata[key] = null;
}
body.metadata = metadata;
const res = (await client.post(`/environments/${id}`, body)) as Record<string, unknown>;
return toRemoteResource(res);
}
async deleteEnvironment(id: string, cascade = false, mode: ProviderResourceMode = "managed"): Promise<void> {
if (mode === "forward") {
try {
await this.forwardClient.delete(`/environments/${id}`);
return;
} catch (err) {
const isConflict = err instanceof ApiError && (err.statusCode === 409 || err.responseBody.includes("in use"));
if (!isConflict) throw err;
if (!cascade) {
throw new UserError(
`Environment ${id} is referenced by one or more Forward sessions. ` +
`Use --cascade to archive the environment.`,
);
}
// Qoder Forward may retain a session reference after the session is
// gone. Its API requires archiving the environment in that case.
await this.forwardClient.post(`/environments/${id}/archive`, {});
return;
}
}
try {
await this.client.delete(`/environments/${id}`);
return;
} catch (err) {
const isConflict = err instanceof ApiError && (err.statusCode === 409 || err.responseBody.includes("in use"));
if (!isConflict) throw err;
}
// Environment is referenced by sessions.
// Scan every page: a single `?limit=100` page could miss blocking
// sessions past the first 100, leaving the environment undeletable.
const sessions = (await this.client.getAllPaged("/sessions")) as Array<{
id: string;
environment_id: string;
status: string;
}>;
const blocking = sessions.filter((s) => s.environment_id === id);
if (!cascade) {
const ids = blocking.map((s) => `${s.id} (${s.status})`).join(", ");
throw new UserError(
`Environment ${id} is referenced by ${blocking.length} session(s): ${ids}. ` +
`Use --cascade to delete them automatically.`,
);
}
for (const s of blocking) {
await this.client.delete(`/sessions/${s.id}`);
}
try {
await this.client.delete(`/environments/${id}`);
} catch (err) {
// The retry can still fail with 409 when the blocking sessions are
// invisible to the list endpoint (Qoder keeps a stale reference
// counter for sessions that have completed or been auto-cleaned).
// Fall back to archiving — Qoder's own error message recommends
// "Archive the environment instead", and an archived environment is
// inactive and no longer billable.
const stillConflict = err instanceof ApiError && (err.statusCode === 409 || err.responseBody.includes("in use"));
if (!stillConflict) throw err;
await this.client.post(`/environments/${id}/archive`, {});
}
}
async createVault(name: string, decl: VaultDecl, mode: ProviderResourceMode = "managed"): Promise<RemoteResource> {
const client = mode === "forward" ? this.forwardClient : this.client;
const body = mapVault(name, decl, this.projectName);
const res = (await client.post("/vaults", body)) as Record<string, unknown>;
const vaultId = res.id as string;
// Credentials are not accepted inline at vault creation; add each via the
// dedicated endpoint (mirrors the bailian adapter's two-step flow).
for (const cred of decl.credentials ?? []) {
await client.post(`/vaults/${vaultId}/credentials`, mapCredential(cred));
}
return toRemoteResource(res);
}
async deleteVault(id: string, mode: ProviderResourceMode = "managed"): Promise<void> {
await (mode === "forward" ? this.forwardClient : this.client).delete(`/vaults/${id}`);
}
async exportResources(type: ResourceType): Promise<ExportedResource[]> {
return exportRemoteResources(this.client, type, {
envToDecl,
vaultToDecl,
fileToDecl,
skillToDecl,
agentToDecl,
});
}
async createSkill(
name: string,
decl: SkillDecl,
files: SkillFile[],
mode: ProviderResourceMode = "managed",
): Promise<RemoteResource> {
const formData = await buildSkillFormData(name, decl, files);
const res = (await (mode === "forward" ? this.forwardClient : this.client).postFormData(
"/skills",
formData,
)) as Record<string, unknown>;
return toRemoteResource(res);
}
async updateSkill(
id: string,
name: string,
decl: SkillDecl,
files: SkillFile[],
mode: ProviderResourceMode = "managed",
): Promise<RemoteResource> {
const client = mode === "forward" ? this.forwardClient : this.client;
const packageName = skillNameFromFiles(files) ?? name;
const formData = await buildSkillFormData(packageName, decl, files, "files", false, true);
await client.postFormData(`/skills/${id}/versions`, formData);
const current = (await client.get(`/skills/${id}`)) as Record<string, unknown>;
return toRemoteResource(current);
}
async deleteSkill(id: string, mode: ProviderResourceMode = "managed"): Promise<void> {
await (mode === "forward" ? this.forwardClient : this.client).delete(`/skills/${id}`);
}
async createAgent(name: string, decl: AgentDecl, refs: ResolvedAgentRefs): Promise<RemoteResource> {
const body = mapAgent(name, decl, refs, undefined, this.projectName);
const res = (await this.client.post("/agents", body)) as Record<string, unknown>;
return toRemoteResource(res);
}
async updateAgent(id: string, name: string, decl: AgentDecl, refs: ResolvedAgentRefs): Promise<RemoteResource> {
const current = (await this.client.get(`/agents/${id}`)) as {
version: number;
};
const body = mapAgent(name, decl, refs, current.version, this.projectName);
const res = (await this.client.put(`/agents/${id}`, body)) as Record<string, unknown>;
return toRemoteResource(res);
}
async deleteAgent(id: string): Promise<void> {
await this.client.delete(`/agents/${id}`);
}
async createTemplate(name: string, decl: AgentDecl, refs: ResolvedTemplateRefs): Promise<RemoteResource> {
const body = mapForwardTemplate(name, decl, refs, this.projectName);
const res = (await this.forwardClient.post("/templates", body)) as Record<string, unknown>;
await this.reconcileForwardMemoryMounts(res.id as string, refs);
return toRemoteResource(res);
}
async updateTemplate(id: string, name: string, decl: AgentDecl, refs: ResolvedTemplateRefs): Promise<RemoteResource> {
const body = mapForwardTemplate(name, decl, refs, this.projectName) as Record<string, unknown>;
// Forward updates are merge-style; null explicitly clears a previously inherited BYOC tunnel.
if (!refs.tunnel_id) body.tunnel_id = null;
const res = (await this.forwardClient.post(`/templates/${id}`, body)) as Record<string, unknown>;
await this.reconcileForwardMemoryMounts(id, refs);
return toRemoteResource(res);
}
async archiveTemplate(id: string, ownedMemoryStoreIds: string[] = []): Promise<void> {
const owned = new Set(ownedMemoryStoreIds);
if (owned.size > 0) {
for (const identity of await this.forwardClient.getAllPaged("/identities")) {
if (typeof identity.id !== "string") continue;
const path = `/identities/${identity.id}/templates/${id}/memory_stores`;
try {
const mounts = (await this.forwardClient.get(path)) as { data?: Array<Record<string, unknown>> };
for (const mount of mounts.data ?? []) {
const storeId = mount.memory_store_id;
if (mount.system_managed !== true && typeof storeId === "string" && owned.has(storeId)) {
await this.forwardClient.delete(`${path}/${storeId}`);
}
}
} catch (error) {
if (!ApiError.isNotFound(error)) throw error;
}
}
}
await this.forwardClient.post(`/templates/${id}/archive`, {});
}
private async reconcileForwardMemoryMounts(templateId: string, refs: ResolvedTemplateRefs): Promise<void> {
if (refs.memory_store_ids === undefined) return;
const desired = new Set(refs.memory_store_ids ?? []);
if (!refs.identity_id) {
if (desired.size > 0) throw new UserError("Qoder Forward Memory Store mounts require an Identity.");
return;
}
const path = `/identities/${refs.identity_id}/templates/${templateId}/memory_stores`;
const current = (await this.forwardClient.get(path)) as { data?: Array<Record<string, unknown>> };
const explicit = (current.data ?? []).filter((mount) => mount.system_managed !== true);
const owned = new Set(refs.owned_memory_store_ids ?? refs.memory_store_ids ?? []);
for (const mount of explicit) {
const storeId = mount.memory_store_id;
if (typeof storeId === "string" && owned.has(storeId) && !desired.has(storeId)) {
await this.forwardClient.delete(`${path}/${storeId}`);
}
}
const mounted = new Set(
explicit.map((mount) => mount.memory_store_id).filter((id): id is string => typeof id === "string"),
);
for (const memoryStoreId of desired) {
if (!mounted.has(memoryStoreId)) await this.forwardClient.post(path, { memory_store_id: memoryStoreId });
}
}
async reconcileDefaultMemoryStore(
identityId: string,
templateId: string,
desired: { name: string; description?: string },
): Promise<{ status: "updated" | "unchanged" | "pending"; memory_store_id?: string }> {
const storeId = await this.findDefaultMemoryStoreId(identityId, templateId);
if (!storeId) return { status: "pending" };
const current = (await this.forwardClient.get(`/memory_stores/${storeId}`)) as Record<string, unknown>;
const descriptionChanged = desired.description !== undefined && current.description !== desired.description;
if (current.name === desired.name && !descriptionChanged) {
return { status: "unchanged", memory_store_id: storeId };
}
await this.forwardClient.post(`/memory_stores/${storeId}`, {
name: desired.name,
...(desired.description !== undefined ? { description: desired.description } : {}),
});
return { status: "updated", memory_store_id: storeId };
}
async findDefaultMemoryStoreId(identityId: string, templateId: string): Promise<string | null> {
const mounts = (await this.forwardClient.get(
`/identities/${identityId}/templates/${templateId}/memory_stores`,
)) as { data?: Array<Record<string, unknown>> };
const writableDefault = (mounts.data ?? []).find(
(mount) => mount.system_managed === true && mount.access === "read_write",
);
return typeof writableDefault?.memory_store_id === "string" ? writableDefault.memory_store_id : null;
}
async deleteDefaultMemoryStore(id: string): Promise<void> {
// Forward DELETE rejects the system-managed default Store while its
// non-detachable Identity/Template mount exists. The Cloud lifecycle API
// permanently deletes the same underlying Store and its stale binding.
await this.client.delete(`/memory_stores/${id}`);
}
async createIdentity(name: string, decl: IdentityDecl): Promise<RemoteResource> {
if (decl.identity_id) return { id: decl.identity_id, type: "identity" };
const res = (await this.forwardClient.post("/identities", {
external_id: decl.external_id,
name: decl.name ?? name,
enabled: decl.enabled ?? true,
metadata: decl.metadata ?? {},
})) as Record<string, unknown>;
return toRemoteResource(res);
}
async updateIdentity(id: string, name: string, decl: IdentityDecl): Promise<RemoteResource> {
if (decl.identity_id) return { id: decl.identity_id, type: "identity" };
const current = (await this.forwardClient.get(`/identities/${id}`)) as Record<string, unknown>;
const currentMetadata = (current.metadata ?? {}) as Record<string, unknown>;
const desiredMetadata = decl.metadata ?? {};
const metadata: Record<string, string> = { ...desiredMetadata };
for (const key of Object.keys(currentMetadata)) {
if (!(key in desiredMetadata)) metadata[key] = "";
}
const res = (await this.forwardClient.post(`/identities/${id}`, {
external_id: decl.external_id,
name: decl.name ?? name,
enabled: decl.enabled ?? true,
metadata,
})) as Record<string, unknown>;
return toRemoteResource(res);
}
async deleteIdentity(id: string): Promise<void> {
await this.forwardClient.delete(`/identities/${id}`);
}
async createChannel(name: string, decl: ChannelDecl, refs: ResolvedChannelRefs): Promise<RemoteResource> {
const res = (await this.forwardClient.post("/channels", this.mapChannel(name, decl, refs))) as Record<
string,
unknown
>;
return toRemoteResource(res);
}
async updateChannel(id: string, name: string, decl: ChannelDecl, refs: ResolvedChannelRefs): Promise<RemoteResource> {
const current = (await this.forwardClient.get(`/channels/${id}`)) as Record<string, unknown>;
const currentMode = (current.identity_resolution as { mode?: string } | undefined)?.mode ?? "fixed";
if (current.channel_type !== decl.type || currentMode !== (decl.mode ?? "fixed")) {
await this.deleteChannel(id);
return this.createChannel(name, decl, refs);
}
const body = this.mapChannel(name, decl, refs);
delete body.channel_type;
delete body.identity_resolution;
const res = (await this.forwardClient.post(`/channels/${id}`, body)) as Record<string, unknown>;
return toRemoteResource(res);
}
async deleteChannel(id: string): Promise<void> {
await this.forwardClient.delete(`/channels/${id}`);
}
private mapChannel(name: string, decl: ChannelDecl, refs: ResolvedChannelRefs): Record<string, unknown> {
const mode = decl.mode ?? "fixed";
const body: Record<string, unknown> = {
channel_type: decl.type,
name: decl.name ?? name,
enabled: decl.enabled ?? true,
channel_config: {
credentials: decl.credentials,
response_options: {
include_tool_calls: false,
include_thinking: false,
...(decl.options ?? {}),
},
},
};
if (mode === "pairing") {
body.identity_resolution = { mode: "pairing" };
} else {
body.identity_id = refs.identity_id;
body.template_id = refs.agent_id;
}
return body;
}
async createMemoryStore(
name: string,
decl: MemoryStoreDecl,
mode: ProviderResourceMode = "managed",
): Promise<RemoteResource> {
const body = mapMemoryStore(name, decl);
const client = mode === "forward" ? this.forwardClient : this.client;
const memoryApi = mode === "forward" ? this.forwardMemoryApi : this.memoryApi;
const res = (await client.post(
"/memory_stores",
body,
mode === "forward" ? { headers: { "Idempotency-Key": crypto.randomUUID() } } : undefined,
)) as Record<string, unknown>;
const storeId = res.id as string;
try {
for (const entry of decl.entries ?? []) {
await memoryApi.createMemory(storeId, { content: entry.content, path: entry.key });
}
} catch (error) {
await this.client.delete(`/memory_stores/${storeId}`).catch(() => undefined);
throw error;
}
return toRemoteResource(res);
}
async deleteMemoryStore(id: string, _mode: ProviderResourceMode = "managed"): Promise<void> {
// Memory Store persistence is shared across Qoder API domains. Permanent
// deletion belongs to the Cloud lifecycle API, which also clears stale
// Forward mounts left by archived Templates or deleted Identities.
await this.client.delete(`/memory_stores/${id}`);
}
listMemoryStores(options?: MemoryStoreListOptions) {
return this.memoryApi.listStores(options);
}
getMemoryStore(id: string) {
return this.memoryApi.getStore(id);
}
updateMemoryStore(id: string, input: UpdateMemoryStoreInput, mode: ProviderResourceMode = "managed") {
return (mode === "forward" ? this.forwardMemoryApi : this.memoryApi).updateStore(id, input);
}
archiveMemoryStore(id: string) {
return this.memoryApi.archiveStore(id);
}
createMemory(storeId: string, input: CreateMemoryInput, mode: ProviderResourceMode = "managed") {
return (mode === "forward" ? this.forwardMemoryApi : this.memoryApi).createMemory(storeId, input);
}
listMemories(storeId: string, options?: MemoryListOptions, mode: ProviderResourceMode = "managed") {
return (mode === "forward" ? this.forwardMemoryApi : this.memoryApi).listMemories(storeId, options);
}
getMemory(storeId: string, memoryId: string) {
return this.memoryApi.getMemory(storeId, memoryId);
}
updateMemory(storeId: string, memoryId: string, input: UpdateMemoryInput, mode: ProviderResourceMode = "managed") {
return (mode === "forward" ? this.forwardMemoryApi : this.memoryApi).updateMemory(storeId, memoryId, input);
}
deleteMemory(storeId: string, memoryId: string, expected?: string) {
return this.memoryApi.deleteMemory(storeId, memoryId, expected);
}
listMemoryVersions(storeId: string, options?: MemoryVersionListOptions) {
return this.memoryApi.listVersions(storeId, options);
}
getMemoryVersion(storeId: string, versionId: string) {
return this.memoryApi.getVersion(storeId, versionId);
}
redactMemoryVersion(storeId: string, versionId: string) {
return this.memoryApi.redactVersion(storeId, versionId);
}
async createDeployment(
name: string,
decl: DeploymentDecl,
refs: ResolvedDeploymentRefs,
basePath: string,
): Promise<RemoteResource> {
const uploaded = await this.uploadDeploymentFiles(decl, basePath);
const body = mapDeployment(name, decl, refs, this.projectName, uploaded);
try {
const res = (await this.client.post("/deployments", body)) as Record<string, unknown>;
return toRemoteResource(res);
} catch (error) {
preserveDeploymentFilesOnConflict(error, uploaded);
}
}
async updateDeployment(
id: string,
name: string,
decl: DeploymentDecl,
refs: ResolvedDeploymentRefs,
basePath: string,
preparedFiles?: ReadonlyMap<string, string>,
): Promise<RemoteResource> {
const uploaded = preparedFiles ? new Map(preparedFiles) : await this.uploadDeploymentFiles(decl, basePath);
const current = (await this.client.get(`/deployments/${id}`)) as Record<string, unknown>;
if (current.schedule && !decl.schedule) {
throw new UserError(
`Deployment '${name}' cannot remove its schedule through the documented Qoder update API; archive and recreate it as a manual deployment.`,
);
}
const body = mapDeploymentUpdate(
name,
decl,
refs,
this.projectName,
uploaded,
current.metadata as Record<string, unknown> | undefined,
);
const res = (await this.client.post(`/deployments/${id}`, body)) as Record<string, unknown>;
return toRemoteResource(res);
}
async deleteDeployment(id: string): Promise<void> {
await this.client.post(`/deployments/${id}/archive`, {});
}
async runDeployment(ctx: DeploymentContext): Promise<DeploymentRunResult> {
if (!ctx.id) {
throw new UserError(`Deployment '${ctx.name}' has no remote id; run \`agents apply\` first.`);
}
const res = (await this.client.post(`/deployments/${ctx.id}/run`, {})) as Record<string, unknown>;
return {
run_id: res.id as string | undefined,
session_id: (res.session_id as string | null) ?? null,
error: (res.error as { type: string; message: string } | null | undefined) ?? undefined,
};
}
async getDeployment(ctx: DeploymentContext): Promise<DeploymentInfo> {
if (!ctx.id) {
throw new UserError(`Deployment '${ctx.name}' has no remote id; run \`agents apply\` first.`);
}
const res = (await this.client.get(`/deployments/${ctx.id}`)) as Record<string, unknown>;
const sched = res.schedule as Record<string, unknown> | null | undefined;
return {
id: res.id as string,
status: (res.status as string) ?? "unknown",
paused_reason: res.paused_reason as { type: string; error?: { type: string } } | undefined,
schedule: sched
? {
expression: sched.expression as string,
timezone: sched.timezone as string,
}
: undefined,
attributes: res,
};
}
async listDeployments(filter?: DeploymentListFilter): Promise<DeploymentListResult> {
const params = new URLSearchParams();
if (filter?.agent_id) params.set("agent_id", filter.agent_id);
if (filter?.status) params.set("status", filter.status);
if (filter?.include_archived) params.set("include_archived", "true");
if (filter?.limit) params.set("limit", String(filter.limit));