-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapper.ts
More file actions
700 lines (636 loc) · 24.3 KB
/
Copy pathmapper.ts
File metadata and controls
700 lines (636 loc) · 24.3 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
import { UserError } from "../../errors.ts";
import type {
AgentDecl,
CredentialDecl,
DeploymentDecl,
EnvironmentDecl,
InitialEventDecl,
MemoryStoreDecl,
ModelSpec,
VaultDecl,
} from "../../types/config.ts";
import type { SessionEventType } from "../../types/dto.ts";
import type { ManagedSessionBindings } from "../../types/session.ts";
import type { ProviderSessionEvent } from "../../types/session-event.ts";
import { compactDeep, stripAgentsMetadata } from "../../utils/comparable.ts";
import { resolveSandboxMountPath } from "../../utils/sandbox-mount.ts";
import { permissionOverridesFromWire, resolveBuiltinTools, toPermissionPolicy } from "../../utils/tool-permissions.ts";
import type { ResolvedAgentRefs, ResolvedDeploymentRefs, ResolvedTemplateRefs } from "../interface.ts";
import { mapGithubRepositorySessionResource, resolveGithubRepositoryMountPath } from "../session-resource-mapper.ts";
import { injectMetadata, secretPlaceholder, slug } from "../sync-mapping.ts";
// Qoder's API expects builtin tool names in PascalCase. The configuration layer
// (agents.yaml / playbook JSON) uses snake_case or lowercase aliases and is
// converted mechanically. No per-tool overrides are applied.
function toPascalCase(name: string): string {
return name
.replace(/([a-z])([A-Z])/g, "$1 $2")
.replace(/[^a-zA-Z0-9]+/g, " ")
.trim()
.split(/\s+/)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
.join("");
}
export function normalizeToolNameForQoder(name: string): string {
return toPascalCase(name);
}
export function normalizeToolNameFromQoder(name: string): string {
return name
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
.replace(/([a-z])([A-Z])/g, "$1_$2")
.toLowerCase();
}
export function mapEnvironment(name: string, decl: EnvironmentDecl, projectName: string): unknown {
const envType = decl.config.type ?? "cloud";
const config: Record<string, unknown> = { type: envType };
if (decl.config.networking) config.networking = decl.config.networking;
else if (envType === "cloud") config.networking = { type: "unrestricted" };
if (decl.config.packages) config.packages = decl.config.packages;
return {
name,
description: decl.description ?? "",
config,
metadata: injectMetadata(decl.metadata, projectName, name),
};
}
// Qoder's create-vault endpoint accepts only display_name + metadata; credentials are
// added one-by-one via POST /vaults/{id}/credentials (see adapter.createVault).
export function mapVault(name: string, decl: VaultDecl, projectName: string): unknown {
const body: Record<string, unknown> = { display_name: decl.display_name };
if (projectName) body.metadata = injectMetadata(decl.metadata, projectName, name);
else if (decl.metadata) body.metadata = decl.metadata;
return body;
}
// A single credential for POST /vaults/{id}/credentials. Fields nest under `auth`;
// static_bearer uses `token`/`mcp_server_url`, environment_variable uses secret_name/value.
export function mapCredential(cred: CredentialDecl): unknown {
if (cred.type === "environment_variable") {
return {
auth: {
type: "environment_variable",
secret_name: cred.secret_name,
secret_value: cred.secret_value,
networking: cred.networking ?? { type: "unrestricted" },
},
display_name: cred.name,
};
}
return {
auth: {
type: cred.type,
mcp_server_url: cred.mcp_server_url,
token: cred.access_token,
},
display_name: cred.name,
};
}
// --- Reverse mapping (remote -> agents.yaml decl), used by `agents sync` ---
/**
* Reverse-map a remote Qoder VaultCredential into a credential decl. The `auth`
* object echoes non-sensitive fields (type / secret_name / mcp_server_url) but never
* the secret, so the secret is a `${ENV}` placeholder. display_name may be null, so a
* name is synthesized from mcp_server_url or the index.
*/
export function credToDecl(raw: Record<string, unknown>, vaultName: string, index: number): CredentialDecl {
const auth = (raw.auth ?? {}) as Record<string, unknown>;
const displayName = raw.display_name as string | null | undefined;
if (auth.type === "static_bearer") {
const name = displayName || slug(auth.mcp_server_url as string | undefined, `cred-${index + 1}`);
const decl: CredentialDecl = {
name,
type: "static_bearer",
mcp_server_url: (auth.mcp_server_url as string) ?? "",
access_token: secretPlaceholder(vaultName, name),
};
if (typeof auth.protocol === "string") decl.protocol = auth.protocol as "sse" | "streamable_http";
return decl;
}
// Default to environment_variable (Qoder's default credential type). Qoder never
// echoes a credential display_name, so the env var's own name is the best identifier.
const name = displayName || (auth.secret_name as string) || `cred-${index + 1}`;
const networking = auth.networking as { type: "unrestricted" | "limited" } | undefined;
const decl: CredentialDecl = {
name,
type: "environment_variable",
secret_name: (auth.secret_name as string) ?? name,
secret_value: secretPlaceholder(vaultName, name),
};
if (networking?.type) decl.networking = networking;
return decl;
}
/** Reverse-map a remote Qoder vault (+ its credentials) into a vault decl. */
export function vaultToDecl(
raw: Record<string, unknown>,
rawCredentials: Array<Record<string, unknown>>,
resourceName: string,
): Record<string, unknown> {
return compactDeep({
display_name: raw.display_name ?? raw.name ?? resourceName,
credentials: rawCredentials.map((c, i) => credToDecl(c, resourceName, i)),
metadata: stripAgentsMetadata(raw.metadata),
}) as Record<string, unknown>;
}
/** Reverse-map a remote file into a FileDecl-shaped object for agents.yaml. */
export function fileToDecl(raw: Record<string, unknown>, filename: string): Record<string, unknown> {
return compactDeep({
source: filename,
name: raw.filename as string | undefined,
purpose: raw.purpose as string | undefined,
}) as Record<string, unknown>;
}
/** Reverse-map a remote environment into an EnvironmentDecl-shaped object for agents.yaml. */
export function envToDecl(raw: Record<string, unknown>): Record<string, unknown> {
const config = (raw.config ?? {}) as Record<string, unknown>;
return compactDeep({
description: raw.description as string | undefined,
config: {
type: config.type ?? "cloud",
networking: config.networking,
packages: config.packages,
},
metadata: stripAgentsMetadata(raw.metadata),
}) as Record<string, unknown>;
}
/** Reverse-map a remote skill into a SkillDecl-shaped object for agents.yaml. */
export function skillToDecl(raw: Record<string, unknown>, name: string): Record<string, unknown> {
return compactDeep({
source: `./skills/${name}/`,
description: raw.description as string | undefined,
}) as Record<string, unknown>;
}
/** Reverse-map a remote agent into an AgentDecl-shaped object for agents.yaml. */
export function agentToDecl(raw: Record<string, unknown>): Record<string, unknown> {
const tools = raw.tools as Array<Record<string, unknown>> | undefined;
const mcpServers = raw.mcp_servers as Array<Record<string, unknown>> | undefined;
const skills = raw.skills as Array<Record<string, unknown>> | undefined;
// Reverse-map tools: extract builtin names from agent_toolset_20260401 and
// normalize API-side PascalCase names back to the snake_case configuration names.
let builtinTools: string[] | undefined;
let builtinPermissions: Record<string, "allow" | "ask"> | undefined;
if (tools?.length) {
const toolset = tools.find((t) => t.type === "agent_toolset_20260401");
if (toolset && Array.isArray(toolset.enabled_tools)) {
builtinTools = (toolset.enabled_tools as string[]).map((t) => normalizeToolNameFromQoder(t));
} else if (toolset) {
const configs = (toolset.configs ?? []) as Array<{
name: string;
enabled?: boolean;
permission_policy?: unknown;
}>;
builtinTools = configs.filter((c) => c.enabled !== false).map((c) => normalizeToolNameFromQoder(c.name));
builtinPermissions = permissionOverridesFromWire(configs, normalizeToolNameFromQoder);
}
}
// Reverse-map MCP servers
let mcpServerDecls: Array<Record<string, unknown>> | undefined;
if (mcpServers?.length) {
mcpServerDecls = mcpServers.map((s) => ({
name: s.name as string,
type: s.type as string,
url: s.url as string | undefined,
}));
}
// Reverse-map skills
let skillDecls: Array<Record<string, unknown>> | undefined;
if (skills?.length) {
skillDecls = skills.map((s) => ({
type: (s.type as string) === "qoder" ? "official" : (s.type as string),
skill_id: s.skill_id as string,
}));
}
return compactDeep({
description: raw.description as string | undefined,
model: raw.model,
instructions: raw.system as string | undefined,
tools: builtinTools?.length ? { builtin: builtinTools, permissions: builtinPermissions } : undefined,
mcp_servers: mcpServerDecls,
skills: skillDecls,
metadata: stripAgentsMetadata(raw.metadata),
}) as Record<string, unknown>;
}
export function mapMemoryStore(name: string, decl: MemoryStoreDecl): unknown {
return {
name,
description: decl.description,
metadata: decl.metadata,
};
}
export function mapDeployment(
name: string,
decl: DeploymentDecl,
refs: ResolvedDeploymentRefs,
projectName?: string,
uploadedFiles?: Map<string, string>,
): unknown {
const body: Record<string, unknown> = {
name,
agent:
refs.agent_version !== undefined
? { id: refs.agent_id, type: "agent", version: refs.agent_version }
: refs.agent_id,
environment_id: refs.environment_id,
initial_events: mapDeploymentInitialEvents(decl.initial_events),
};
// NOTE: tunnel_id is intentionally NOT sent — Qoder's /deployments API rejects
// it (HTTP 400 "unknown field"). Server-side deployment runs cannot carry a
// BYOC tunnel today; validate-config warns when a deployment declares one.
if (refs.vault_ids.length) body.vault_ids = refs.vault_ids;
const resources = mapDeploymentResources(decl, refs, uploadedFiles);
if (resources.length) body.resources = resources;
if (decl.schedule) {
body.schedule = {
type: "cron",
expression: decl.schedule.expression,
timezone: decl.schedule.timezone,
};
}
if (decl.description) body.description = decl.description;
if (decl.environment_variables !== undefined) body.environment_variables = decl.environment_variables;
if (projectName) {
body.metadata = injectMetadata(decl.metadata, projectName, name);
} else if (decl.metadata) {
body.metadata = decl.metadata;
}
return body;
}
export function mapDeploymentUpdate(
name: string,
decl: DeploymentDecl,
refs: ResolvedDeploymentRefs,
projectName?: string,
uploadedFiles?: Map<string, string>,
existingMetadata?: Record<string, unknown>,
): unknown {
const body = mapDeployment(name, decl, refs, projectName, uploadedFiles) as Record<string, unknown>;
body.vault_ids = refs.vault_ids;
body.resources = mapDeploymentResources(decl, refs, uploadedFiles);
if (decl.schedule) {
body.schedule = { type: "cron", expression: decl.schedule.expression, timezone: decl.schedule.timezone };
}
body.description = decl.description ?? "";
body.environment_variables = decl.environment_variables ?? null;
const desiredMetadata = projectName ? injectMetadata(decl.metadata, projectName, name) : (decl.metadata ?? {});
body.metadata = {
...Object.fromEntries(
Object.keys(existingMetadata ?? {})
.filter((key) => !(key in desiredMetadata))
.map((key) => [key, null]),
),
...desiredMetadata,
};
return body;
}
function mapDeploymentInitialEvents(events: InitialEventDecl[]): unknown[] {
return events.map((ev) => {
if (ev.type === "user.message" || ev.type === "system.message") {
return { type: ev.type, content: [{ type: "text", text: ev.content }] };
}
const out: Record<string, unknown> = { type: "user.define_outcome" };
if (ev.description) out.description = ev.description;
if (ev.rubric) {
out.rubric = { type: "text", content: ev.rubric };
} else if (ev.rubric_file) {
out.rubric = { type: "file", file_id: ev.rubric_file };
}
if (ev.max_iterations !== undefined) out.max_iterations = ev.max_iterations;
return out;
});
}
function mapDeploymentResources(
decl: DeploymentDecl,
refs: ResolvedDeploymentRefs,
uploadedFiles?: Map<string, string>,
): unknown[] {
const resources: unknown[] = [];
const seenStores = new Set<string>();
for (const r of decl.resources ?? []) {
if (r.type === "file") {
const fileId = r.file_id ?? (r.source ? uploadedFiles?.get(r.source) : undefined);
if (fileId) {
const entry: Record<string, unknown> = { type: "file", file_id: fileId };
if (r.mount_path) entry.mount_path = r.mount_path;
resources.push(entry);
}
} else if (r.type === "github_repository") {
const entry: Record<string, unknown> = { type: "github_repository", url: r.url };
if (r.authorization_token) entry.authorization_token = r.authorization_token;
if (r.checkout?.branch) entry.checkout = { type: "branch", name: r.checkout.branch };
else if (r.checkout?.commit) entry.checkout = { type: "commit", sha: r.checkout.commit };
if (r.mount_path) entry.mount_path = r.mount_path;
resources.push(entry);
} else if (r.type === "memory_store") {
const id = refs.memory_store_ids[r.memory_store];
if (id && !seenStores.has(id)) {
seenStores.add(id);
const entry: Record<string, unknown> = { type: "memory_store", memory_store_id: id };
if (r.access) entry.access = r.access;
if (r.instructions) entry.instructions = r.instructions;
resources.push(entry);
}
}
}
for (const m of decl.memory_stores ?? []) {
const id = refs.memory_store_ids[m];
if (id && !seenStores.has(id)) {
seenStores.add(id);
resources.push({ type: "memory_store", memory_store_id: id });
}
}
return resources;
}
export function mapAgent(
name: string,
decl: AgentDecl,
refs: ResolvedAgentRefs,
version?: number,
projectName?: string,
): unknown {
let model: string;
if (typeof decl.model === "string") {
model = decl.model;
} else {
const qoderModel: ModelSpec | undefined = decl.model.qoder;
if (!qoderModel) throw new UserError(`No Qoder model specified for agent '${name}'`);
model = typeof qoderModel === "string" ? qoderModel : qoderModel.id;
}
const body: Record<string, unknown> = {
name,
model,
system: decl.instructions,
};
if (version !== undefined) body.version = version;
if (decl.description) body.description = decl.description;
if (projectName) {
body.metadata = injectMetadata(decl.metadata, projectName, name);
} else if (decl.metadata) {
body.metadata = decl.metadata;
}
if (decl.tools) {
body.tools = [
{
type: "agent_toolset_20260401",
configs: resolveBuiltinTools(decl.tools, { toWireName: normalizeToolNameForQoder }).map((tool) => ({
name: tool.wireName,
enabled: true,
permission_policy: toPermissionPolicy(tool.permission),
})),
},
];
} else {
body.tools = [{ type: "agent_toolset_20260401" }];
}
if (decl.mcp_servers?.length) {
body.mcp_servers = decl.mcp_servers.map((s) => {
if (s.type === "official" || !s.url) {
throw new UserError(`Qoder MCP server '${s.name}' requires a url`);
}
return {
name: s.name,
type: "http",
url: s.url,
};
});
// Only add mcp_toolset tool entries when explicit configs are provided
const tools = body.tools as unknown[];
for (const s of decl.mcp_servers) {
const mcpTool = decl.tools?.mcp?.find((t) => t.mcp_server_name === s.name);
if (mcpTool) {
tools.push({
type: "mcp_toolset",
mcp_server_name: s.name,
configs: mcpTool.configs,
});
}
}
}
// Skills
if (refs.skill_ids.length) {
body.skills = refs.skill_ids.map((s) => ({
type: s.type === "official" ? "qoder" : s.type,
skill_id: s.skill_id,
}));
}
return body;
}
/** Compile one logical Agent declaration into Qoder's Forward Template baseline. */
export function mapForwardTemplate(
name: string,
decl: AgentDecl,
refs: ResolvedTemplateRefs,
projectName?: string,
): unknown {
let model: string;
if (typeof decl.model === "string") {
model = decl.model;
} else {
const qoderModel: ModelSpec | undefined = decl.model.qoder;
if (!qoderModel) throw new UserError(`No Qoder model specified for template '${name}'`);
model = typeof qoderModel === "string" ? qoderModel : qoderModel.id;
}
const body: Record<string, unknown> = {
name,
description: decl.description ?? "",
model,
system: decl.instructions,
environment_id: refs.environment_id,
vault_ids: refs.vault_ids,
};
if (refs.tunnel_id) body.tunnel_id = refs.tunnel_id;
if (projectName) body.metadata = injectMetadata(decl.metadata, projectName, name);
else body.metadata = decl.metadata ?? {};
if (decl.tools) {
body.tools = [
{
type: "agent_toolset_20260401",
configs: resolveBuiltinTools(decl.tools, { toWireName: normalizeToolNameForQoder }).map((tool) => ({
name: tool.wireName,
enabled: true,
permission_policy: toPermissionPolicy(tool.permission),
})),
},
];
} else {
body.tools = [{ type: "agent_toolset_20260401" }];
}
body.mcp_servers = (decl.mcp_servers ?? []).map((server) => {
if (server.type === "official" || !server.url) {
throw new UserError(`Qoder MCP server '${server.name}' requires a url`);
}
return { name: server.name, type: "http", url: server.url };
});
if (decl.mcp_servers?.length) {
const tools = body.tools as unknown[];
for (const server of decl.mcp_servers) {
const toolkit = decl.tools?.mcp?.find((item) => item.mcp_server_name === server.name);
if (toolkit) {
tools.push({
type: "mcp_toolset",
mcp_server_name: server.name,
configs: toolkit.configs,
});
}
}
}
body.skills = refs.skill_ids.map((skill) => ({
type: skill.type === "official" ? "qoder" : skill.type,
skill_id: skill.skill_id,
...(skill.version ? { version: skill.version } : {}),
enabled: true,
}));
return body;
}
export function mapSendMessage(text: string): unknown {
return {
events: [{ type: "user.message", content: [{ type: "text", text }] }],
};
}
const QODER_EVENT_MAP: Record<string, SessionEventType> = {
"agent.message": "message",
"user.message": "message",
"agent.tool_use": "tool_use",
"agent.tool_result": "tool_result",
"agent.mcp_tool_use": "tool_use",
"agent.mcp_tool_result": "tool_result",
"agent.thinking": "thinking",
"session.status_idle": "status",
"session.status_running": "status",
"session.status_terminated": "status",
"session.thread_status_idle": "status",
"session.error": "error",
};
export function toSessionEvent(raw: Record<string, unknown>): ProviderSessionEvent {
const rawType = (raw.type as string) ?? "";
const type: SessionEventType = QODER_EVENT_MAP[rawType] ?? "unknown";
const event: ProviderSessionEvent = { type, raw_type: rawType, raw };
if (typeof raw.id === "string") event.id = raw.id;
if (typeof raw.role === "string") event.role = raw.role;
if (type === "message") {
// Real `agent.message` / `user.message` events carry no `role`; the actor
// is encoded in the event type. Derive it so consumers can attribute turns.
event.role = roleFromType(rawType, raw.role);
event.content = extractContentText(raw);
} else if (type === "tool_use") {
event.tool_name = (raw.tool_name as string) ?? (raw.name as string) ?? "";
event.tool_input =
(raw.tool_input as string) ?? (typeof raw.input === "string" ? raw.input : JSON.stringify(raw.input ?? {}));
} else if (type === "tool_result") {
event.content = extractContentText(raw);
} else if (type === "status") {
// Only session-level idle/terminated are terminal; thread-level idle
// (session.thread_status_idle) is non-terminal and should not stop the stream.
// Additionally, session.status_idle with stop_reason "requires_action" means
// the agent paused for tool execution and will resume — treat it as non-terminal.
const stopReason = extractStopReason(raw.stop_reason);
if (rawType === "session.thread_status_idle") {
event.status = "running";
} else if (rawType === "session.status_idle" && stopReason === "requires_action") {
event.status = "running";
} else {
event.status = rawType.includes("idle") ? "idle" : rawType.includes("terminated") ? "terminated" : "running";
}
event.stop_reason = stopReason;
} else if (type === "error") {
event.content = extractErrorMessage(raw);
}
// `agent.artifact_delivered` is a structured delivery event (verified on the real qoder API to
// carry file_id/original_filename/content_type/size). It stays "unknown" in QODER_EVENT_MAP on
// purpose — the DeliverArtifacts tool_use/tool_result already show it in the timeline — but we
// lift the structured file into `artifact` so the webui can render a download card.
if (rawType === "agent.artifact_delivered") {
const fileId = raw.file_id;
if (typeof fileId === "string" && fileId) {
event.artifact = {
file_id: fileId,
filename: typeof raw.original_filename === "string" ? raw.original_filename : undefined,
content_type: typeof raw.content_type === "string" ? raw.content_type : undefined,
size: typeof raw.size === "number" ? raw.size : undefined,
};
}
}
return event;
}
function roleFromType(rawType: string, rawRole: unknown): string | undefined {
if (typeof rawRole === "string") return rawRole;
if (rawType.startsWith("user.")) return "user";
if (rawType.startsWith("agent.")) return "assistant";
return undefined;
}
function extractContentText(raw: Record<string, unknown>): string {
const content = raw.content;
if (typeof content === "string") return content;
if (Array.isArray(content)) {
return content
.map((c: Record<string, unknown>) => (c.text as string) ?? "")
.filter(Boolean)
.join("");
}
return "";
}
function extractStopReason(value: unknown): string | undefined {
if (typeof value === "string") return value;
if (value && typeof value === "object") {
const type = (value as Record<string, unknown>).type;
if (typeof type === "string") return type;
}
return undefined;
}
function extractErrorMessage(raw: Record<string, unknown>): string {
const err = raw.error;
if (typeof err === "string") return err;
if (err && typeof err === "object") {
const message = (err as Record<string, unknown>).message;
if (typeof message === "string") return message;
}
if (typeof raw.message === "string") return raw.message;
return "";
}
export function mapSession(bindings: ManagedSessionBindings): unknown {
const body: Record<string, unknown> = {
agent: bindings.agent_id,
environment_id: bindings.environment_id,
};
if (bindings.tunnel_id) body.tunnel_id = bindings.tunnel_id;
if (bindings.title) body.title = bindings.title;
if (bindings.metadata) body.metadata = bindings.metadata;
if (bindings.vault_ids.length) body.vault_ids = bindings.vault_ids;
// Memory stores and user-uploaded files share the `resources` array (vaults are separate
// via `vault_ids`). Every entry needs a non-empty `type`; file shape mirrors qoder's
// deployment mapping (`{ type: "file", file_id }`).
const resources: Record<string, unknown>[] = [];
for (const id of bindings.memory_store_ids) resources.push({ type: "memory_store", memory_store_id: id });
for (const f of bindings.files ?? [])
resources.push({ type: "file", file_id: f.file_id, mount_path: resolveSandboxMountPath("qoder", f.mount_path) });
for (const resource of bindings.resources ?? []) {
resources.push(
mapGithubRepositorySessionResource(resource, {
mapMountPath: (item) => resolveGithubRepositoryMountPath("qoder", item),
}),
);
}
if (resources.length) body.resources = resources;
return body;
}
export function mapDeploymentToSession(decl: DeploymentDecl, refs: ResolvedDeploymentRefs, fileIds: string[]): unknown {
const body: Record<string, unknown> = {
agent: refs.agent_id,
environment_id: refs.environment_id,
};
if (refs.tunnel_id) body.tunnel_id = refs.tunnel_id;
if (decl.description) body.title = decl.description;
if (refs.vault_ids.length) body.vault_ids = refs.vault_ids;
const resources: Record<string, unknown>[] = Object.values(refs.memory_store_ids).map((id) => ({
type: "memory_store",
memory_store_id: id,
}));
// fileIds are positionally aligned with the decl's file resources, so the mount_path
// from each `{ type: file, source, mount_path }` is recovered by index. Every entry
// needs a non-empty `type` (the API rejects a bare `{ file_id }`).
const fileResources = (decl.resources ?? []).filter((r) => r.type === "file");
fileIds.forEach((id, index) => {
const entry: Record<string, unknown> = { type: "file", file_id: id };
const mountPath = fileResources[index]?.mount_path;
if (mountPath) entry.mount_path = mountPath;
resources.push(entry);
});
if (resources.length) body.resources = resources;
return body;
}