-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadapter.ts
More file actions
1095 lines (1005 loc) · 38.7 KB
/
Copy pathadapter.ts
File metadata and controls
1095 lines (1005 loc) · 38.7 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 { ApiError, toRemoteResource } from "../base-client.ts";
import type {
ComparableRemoteResource,
DeploymentContext,
DeploymentInfo,
DeploymentListFilter,
DeploymentListResult,
DeploymentRunResult,
DriftSupport,
ExportedResource,
ModelInfo,
ProviderAdapter,
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,
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 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.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): 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;
}
const raw = await locateRemote(this.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,
): 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 };
}
const isTemplate = type === "template";
const endpoint = type === "agent" ? "/agents" : type === "environment" ? "/environments" : "/templates";
const 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,
};
}
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 config = (raw.config ?? {}) as Record<string, unknown>;
return compactDeep({
description: raw.description,
config: {
type: config.type ?? "cloud",
networking: config.networking,
packages: config.packages,
},
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>;
return compactDeep({
identity_id: raw.identity_id,
template_id: raw.template_id,
channel_type: raw.channel_type,
name: raw.name,
enabled: raw.enabled,
channel_config: {
response_options: channelConfig.response_options ?? {},
},
});
}
return compactDeep({
description: 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): Promise<RemoteResource> {
const body = mapEnvironment(name, decl, this.projectName);
const res = (await this.client.post("/environments", body)) as Record<string, unknown>;
return toRemoteResource(res);
}
async updateEnvironment(id: string, name: string, decl: EnvironmentDecl): Promise<RemoteResource> {
const body = mapEnvironment(name, decl, this.projectName);
const res = (await this.client.put(`/environments/${id}`, body)) as Record<string, unknown>;
return toRemoteResource(res);
}
async deleteEnvironment(id: string, cascade = false): Promise<void> {
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): Promise<RemoteResource> {
const body = mapVault(name, decl, this.projectName);
const res = (await this.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 this.client.post(`/vaults/${vaultId}/credentials`, mapCredential(cred));
}
return toRemoteResource(res);
}
async deleteVault(id: string): Promise<void> {
await 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[]): Promise<RemoteResource> {
const formData = await buildSkillFormData(name, decl, files);
const res = (await this.client.postFormData("/skills", formData)) as Record<string, unknown>;
return toRemoteResource(res);
}
async updateSkill(id: string, name: string, decl: SkillDecl, files: SkillFile[]): Promise<RemoteResource> {
await this.client.delete(`/skills/${id}`);
return this.createSkill(name, decl, files);
}
async deleteSkill(id: string): Promise<void> {
await 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> {
await this.registerForwardVaults(refs.vault_ids);
const body = mapForwardTemplate(name, decl, refs, this.projectName);
const res = (await this.forwardClient.post("/templates", body)) as Record<string, unknown>;
return toRemoteResource(res);
}
async updateTemplate(id: string, name: string, decl: AgentDecl, refs: ResolvedTemplateRefs): Promise<RemoteResource> {
await this.registerForwardVaults(refs.vault_ids);
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>;
return toRemoteResource(res);
}
async archiveTemplate(id: string): Promise<void> {
await this.forwardClient.post(`/templates/${id}/archive`, {});
}
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>;
if (current.channel_type !== decl.type) {
await this.deleteChannel(id);
return this.createChannel(name, decl, refs);
}
const body = this.mapChannel(name, decl, refs);
delete body.channel_type;
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> {
return {
identity_id: refs.identity_id,
template_id: refs.agent_id,
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 ?? {}),
},
},
};
}
private async registerForwardVaults(vaultIds: string[]): Promise<void> {
for (const id of vaultIds) {
await this.forwardClient.post("/resources/registry", {
type: "vault",
resource: { id },
});
}
}
async createMemoryStore(name: string, decl: MemoryStoreDecl): Promise<RemoteResource> {
const body = mapMemoryStore(name, decl);
const res = (await this.client.post("/memory_stores", body)) as Record<string, unknown>;
const storeId = res.id as string;
try {
for (const entry of decl.entries ?? []) {
await this.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): Promise<void> {
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) {
return this.memoryApi.updateStore(id, input);
}
archiveMemoryStore(id: string) {
return this.memoryApi.archiveStore(id);
}
createMemory(storeId: string, input: CreateMemoryInput) {
return this.memoryApi.createMemory(storeId, input);
}
listMemories(storeId: string, options?: MemoryListOptions) {
return this.memoryApi.listMemories(storeId, options);
}
getMemory(storeId: string, memoryId: string) {
return this.memoryApi.getMemory(storeId, memoryId);
}
updateMemory(storeId: string, memoryId: string, input: UpdateMemoryInput) {
return 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);
const res = (await this.client.post("/deployments", body)) as Record<string, unknown>;
return toRemoteResource(res);
}
async updateDeployment(
id: string,
name: string,
decl: DeploymentDecl,
refs: ResolvedDeploymentRefs,
basePath: string,
): Promise<RemoteResource> {
const uploaded = 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));
if (filter?.page) params.set("page", filter.page);
if (filter?.created_at_gte) params.set("created_at[gte]", filter.created_at_gte);
if (filter?.created_at_lte) params.set("created_at[lte]", filter.created_at_lte);
const query = params.toString();
const res = (await this.client.get(`/deployments${query ? `?${query}` : ""}`)) as Record<string, unknown>;
return {
deployments: ((res.data as Record<string, unknown>[] | undefined) ?? []).map(toDeploymentInfo),
has_more: Boolean(res.has_more),
next_page: (res.next_page as string | null | undefined) ?? undefined,
};
}
async pauseDeployment(ctx: DeploymentContext): Promise<DeploymentInfo> {
return this.setDeploymentPaused(ctx, true);
}
async unpauseDeployment(ctx: DeploymentContext): Promise<DeploymentInfo> {
return this.setDeploymentPaused(ctx, false);
}
private async setDeploymentPaused(ctx: DeploymentContext, paused: boolean): Promise<DeploymentInfo> {
if (!ctx.id) throw new UserError(`Deployment '${ctx.name}' has no remote id; run \`agents apply\` first.`);
const action = paused ? "pause" : "unpause";
const res = (await this.client.post(`/deployments/${ctx.id}/${action}`, {})) as Record<string, unknown>;
return toDeploymentInfo(res);
}
private async uploadDeploymentFiles(decl: DeploymentDecl, basePath: string): Promise<Map<string, string>> {
const map = new Map<string, string>();
for (const r of decl.resources ?? []) {
if (r.type === "file" && !r.file_id && r.source && !map.has(r.source)) {
map.set(r.source, await this.uploadSessionFile(r.source, basePath));
}
}
return map;
}
private async uploadSessionFile(source: string, basePath: string): Promise<string> {
const fullPath = resolve(dirname(basePath), source);
const content = readFileSync(fullPath);
const formData = new FormData();
formData.append("file", new File([new Uint8Array(content)], basename(fullPath)));
formData.append("purpose", "session_resource");
const res = (await this.client.postFormData("/files", formData)) as Record<string, unknown>;
return (res.file_id as string) ?? (res.id as string);
}
async createSession(bindings: SessionBindings): Promise<ProviderSessionInfo> {
if (bindings.delivery === "forward") {
if (!bindings.identity_id) {
throw new UserError("Qoder Forward sessions require an explicit resolved identity_id.");
}
const body: Record<string, unknown> = {
identity_id: bindings.identity_id,
template_id: bindings.template_id,
incremental_streaming_enabled: false,
};
if (bindings.title) body.title = bindings.title;
if (bindings.metadata) body.metadata = bindings.metadata;
if (bindings.files?.length) {
body.resources = bindings.files.map((file) => ({
type: "file",
file_id: file.file_id,
mount_path: file.mount_path,
}));
}
const res = (await this.forwardClient.post("/sessions", body)) as Record<string, unknown>;
const info = toForwardSessionInfo(res, bindings);
this.forwardSessionIds.add(info.id);
return info;
}
const body = mapSession(bindings);
const res = (await this.client.post("/sessions", body)) as Record<string, unknown>;
return toSessionInfo(res);
}
async listSessions(filter?: SessionFilter): Promise<SessionListResult> {
if (filter?.agent_id?.startsWith("tmpl_")) {
const params = new URLSearchParams({ template_id: filter.agent_id });
if (filter.limit) params.set("limit", String(filter.limit));
if (filter.page) params.set("after_id", filter.page);
const res = (await this.forwardClient.get(`/sessions?${params}`)) as Record<string, unknown>;
const data = (res.data ?? []) as Record<string, unknown>[];
const hasMore = (res.has_more as boolean | undefined) ?? false;
const nextPage = hasMore ? ((res.last_id as string | null | undefined) ?? undefined) : undefined;
for (const item of data) {
if (typeof item.id === "string") this.forwardSessionIds.add(item.id);
}
return {
sessions: data.map((item) => toForwardSessionInfo(item)),
has_more: hasMore,
next_page: nextPage,
};
}
const params = new URLSearchParams();
if (filter?.agent_id) params.set("agent_id", filter.agent_id);
if (filter?.limit) params.set("limit", String(filter.limit));
const qs = params.toString();
const res = (await this.client.get(`/sessions${qs ? `?${qs}` : ""}`)) as Record<string, unknown>;
const data = (res.data ?? []) as Record<string, unknown>[];
const nextPage = (res.next_page as string | null | undefined) ?? undefined;
return {
sessions: data.map(toSessionInfo),
has_more: (res.has_more as boolean) ?? nextPage != null,
next_page: nextPage,
};
}
async getSession(id: string): Promise<ProviderSessionInfo> {
if (this.forwardSessionIds.has(id)) return this.getForwardSession(id);
try {
const res = (await this.client.get(`/sessions/${id}`)) as Record<string, unknown>;
return toSessionInfo(res);
} catch (error) {
if (!ApiError.isNotFound(error)) throw error;
return this.getForwardSession(id);
}
}
async deleteSession(id: string): Promise<void> {
if (this.forwardSessionIds.has(id)) {
await this.forwardClient.post(`/sessions/${id}/archive`, {});
return;
}
try {
await this.client.delete(`/sessions/${id}`);
} catch (error) {
if (!ApiError.isNotFound(error)) throw error;
await this.forwardClient.post(`/sessions/${id}/archive`, {});
this.forwardSessionIds.add(id);
}
}
async sendSessionMessage(sessionId: string, message: string): Promise<string | undefined> {
const body = mapSendMessage(message);
if (this.forwardSessionIds.has(sessionId)) {
const res = (await this.forwardClient.post(`/sessions/${sessionId}/events`, body)) as Record<string, unknown>;
return extractCreatedEventId(res);
}
try {
const res = (await this.client.post(`/sessions/${sessionId}/events`, body)) as Record<string, unknown>;
return extractCreatedEventId(res);
} catch (error) {
if (!ApiError.isNotFound(error)) throw error;
const res = (await this.forwardClient.post(`/sessions/${sessionId}/events`, body)) as Record<string, unknown>;
this.forwardSessionIds.add(sessionId);
return extractCreatedEventId(res);
}
}
async *streamSessionEvents(sessionId: string, options?: EventStreamOptions): AsyncIterable<ProviderSessionEvent> {
if (this.forwardSessionIds.has(sessionId)) {
yield* this.streamForwardSessionEvents(sessionId, options);
return;
}
// Client-side fallback: skip events locally without passing after_id to
// the server. This avoids a conflict where the server honours after_id
// (omitting that event from the stream) and the client never finds the
// marker, causing all events to be silently dropped.
const path = `/sessions/${sessionId}/events/stream`;
let skipping = !!options?.after_id;
const afterId = options?.after_id;
try {
for await (const raw of this.client.sse(path)) {
if (skipping) {
const eventId = raw.id as string | undefined;
if (eventId === afterId) {
// Found our marker event; stop skipping from next event onward.
skipping = false;
}
continue;
}
yield toSessionEvent(raw);
}
} catch (error) {
if (!ApiError.isNotFound(error)) throw error;
this.forwardSessionIds.add(sessionId);
yield* this.streamForwardSessionEvents(sessionId, options);
}
}
async listSessionEvents(sessionId: string, options?: EventListOptions): Promise<ProviderSessionEventList> {
if (this.forwardSessionIds.has(sessionId)) return this.listForwardSessionEvents(sessionId, options);
// Qoder additionally accepts the Agents-style `after_id` resume marker, so it is
// forwarded (claude/bailian reject it); shared page-cursor handling lives in
// listSessionEventsPaged.
try {
return await listSessionEventsPaged(this.client, sessionId, options, toSessionEvent, { forwardAfterId: true });
} catch (error) {
if (!ApiError.isNotFound(error)) throw error;
this.forwardSessionIds.add(sessionId);
return this.listForwardSessionEvents(sessionId, options);
}
}
private async getForwardSession(id: string): Promise<ProviderSessionInfo> {
const res = (await this.forwardClient.get(`/sessions/${id}`)) as Record<string, unknown>;
this.forwardSessionIds.add(id);
return toForwardSessionInfo(res);
}
private async *streamForwardSessionEvents(
sessionId: string,
options?: EventStreamOptions,
): AsyncIterable<ProviderSessionEvent> {
const headers = options?.after_id ? { "Last-Event-ID": options.after_id } : undefined;
for await (const raw of this.forwardClient.sse(`/sessions/${sessionId}/events/stream`, { headers })) {
yield toSessionEvent(raw);
}
}
private async listForwardSessionEvents(
sessionId: string,
options?: EventListOptions,
): Promise<ProviderSessionEventList> {
const params = new URLSearchParams();
if (options?.limit) params.set("limit", String(options.limit));
if (options?.order) params.set("order", options.order);
const afterId = options?.after_id ?? options?.page_token ?? options?.page;
if (afterId) params.set("after_id", afterId);
const query = params.toString();
const res = (await this.forwardClient.get(`/sessions/${sessionId}/events${query ? `?${query}` : ""}`)) as Record<
string,
unknown
>;
const data = (res.data ?? []) as Record<string, unknown>[];
const hasMore = (res.has_more as boolean | undefined) ?? false;
return {
events: data.map(toSessionEvent),
has_more: hasMore,
next_page: hasMore ? ((res.last_id as string | null | undefined) ?? undefined) : undefined,
};
}
async listModels(): Promise<ModelInfo[]> {
const res = (await this.client.get("/models")) as { data: ModelInfo[] };
return res.data;
}
// --- Files ---
async uploadFile(filePath: string, options?: { name?: string; purpose?: string }): Promise<ProviderFileInfo> {
const resolved = resolve(filePath);
const content = readFileSync(resolved);
const fileName = options?.name ?? basename(resolved);
return this.uploadFileContent(new Uint8Array(content), fileName, {
purpose: options?.purpose,
});
}
async uploadFileContent(
content: Uint8Array,
filename: string,
options?: { mimeType?: string; purpose?: string },
): Promise<ProviderFileInfo> {
const formData = new FormData();
const bytes = new Uint8Array(content);
formData.append(