@air-jam/devtools 0.0.0-stage → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/dist/agent.d.ts +15 -0
  4. package/dist/agent.js +19 -0
  5. package/dist/agent.js.map +1 -0
  6. package/dist/chunk-5YAARMW5.js +36 -0
  7. package/dist/chunk-5YAARMW5.js.map +1 -0
  8. package/dist/chunk-6WQODT37.js +1019 -0
  9. package/dist/chunk-6WQODT37.js.map +1 -0
  10. package/dist/chunk-CKFT2ZJE.js +801 -0
  11. package/dist/chunk-CKFT2ZJE.js.map +1 -0
  12. package/dist/chunk-ER3Q2C4G.js +358 -0
  13. package/dist/chunk-ER3Q2C4G.js.map +1 -0
  14. package/dist/chunk-GUEZP773.js +851 -0
  15. package/dist/chunk-GUEZP773.js.map +1 -0
  16. package/dist/chunk-HIDNI56E.js +33 -0
  17. package/dist/chunk-HIDNI56E.js.map +1 -0
  18. package/dist/chunk-QKXS5D35.js +43 -0
  19. package/dist/chunk-QKXS5D35.js.map +1 -0
  20. package/dist/chunk-S4LSCEVE.js +261 -0
  21. package/dist/chunk-S4LSCEVE.js.map +1 -0
  22. package/dist/chunk-VKMJO6VN.js +360 -0
  23. package/dist/chunk-VKMJO6VN.js.map +1 -0
  24. package/dist/chunk-WFUR3MXY.js +67 -0
  25. package/dist/chunk-WFUR3MXY.js.map +1 -0
  26. package/dist/chunk-XEMR7KUE.js +361 -0
  27. package/dist/chunk-XEMR7KUE.js.map +1 -0
  28. package/dist/chunk-ZLPD7FY5.js +191 -0
  29. package/dist/chunk-ZLPD7FY5.js.map +1 -0
  30. package/dist/context.d.ts +13 -0
  31. package/dist/context.js +9 -0
  32. package/dist/context.js.map +1 -0
  33. package/dist/controller.d.ts +41 -0
  34. package/dist/controller.js +30 -0
  35. package/dist/controller.js.map +1 -0
  36. package/dist/dev.d.ts +15 -0
  37. package/dist/dev.js +20 -0
  38. package/dist/dev.js.map +1 -0
  39. package/dist/game-session-broker.d.ts +57 -0
  40. package/dist/game-session-broker.js +235 -0
  41. package/dist/game-session-broker.js.map +1 -0
  42. package/dist/game-session.d.ts +13 -0
  43. package/dist/game-session.js +24 -0
  44. package/dist/game-session.js.map +1 -0
  45. package/dist/games.d.ts +21 -0
  46. package/dist/games.js +14 -0
  47. package/dist/games.js.map +1 -0
  48. package/dist/harness/visual.d.ts +321 -0
  49. package/dist/harness/visual.js +41 -0
  50. package/dist/harness/visual.js.map +1 -0
  51. package/dist/logs.d.ts +9 -0
  52. package/dist/logs.js +58 -0
  53. package/dist/logs.js.map +1 -0
  54. package/dist/mcp-config.d.ts +63 -0
  55. package/dist/mcp-config.js +190 -0
  56. package/dist/mcp-config.js.map +1 -0
  57. package/dist/platform-auth.d.ts +112 -0
  58. package/dist/platform-auth.js +37 -0
  59. package/dist/platform-auth.js.map +1 -0
  60. package/dist/platform-game-media.d.ts +309 -0
  61. package/dist/platform-game-media.js +168 -0
  62. package/dist/platform-game-media.js.map +1 -0
  63. package/dist/platform-games.d.ts +65 -0
  64. package/dist/platform-games.js +251 -0
  65. package/dist/platform-games.js.map +1 -0
  66. package/dist/quality.d.ts +10 -0
  67. package/dist/quality.js +63 -0
  68. package/dist/quality.js.map +1 -0
  69. package/dist/release.d.ts +1094 -0
  70. package/dist/release.js +1347 -0
  71. package/dist/release.js.map +1 -0
  72. package/dist/tooling/agent-contract.d.ts +2 -0
  73. package/dist/tooling/agent-contract.js +193 -0
  74. package/dist/tooling/agent-contract.js.map +1 -0
  75. package/dist/tooling/hold-runtime-host.d.ts +2 -0
  76. package/dist/tooling/hold-runtime-host.js +229 -0
  77. package/dist/tooling/hold-runtime-host.js.map +1 -0
  78. package/dist/tooling/inspect-airjam-agent.d.ts +2 -0
  79. package/dist/tooling/inspect-airjam-agent.js +37 -0
  80. package/dist/tooling/inspect-airjam-agent.js.map +1 -0
  81. package/dist/tooling/list-visual-scenarios.d.ts +2 -0
  82. package/dist/tooling/list-visual-scenarios.js +62 -0
  83. package/dist/tooling/list-visual-scenarios.js.map +1 -0
  84. package/dist/tooling/managed-dev-supervisor.d.ts +2 -0
  85. package/dist/tooling/managed-dev-supervisor.js +51 -0
  86. package/dist/tooling/managed-dev-supervisor.js.map +1 -0
  87. package/dist/tooling/run-visual-capture.d.ts +2 -0
  88. package/dist/tooling/run-visual-capture.js +167 -0
  89. package/dist/tooling/run-visual-capture.js.map +1 -0
  90. package/dist/types-C6NrHt88.d.ts +775 -0
  91. package/dist/visual.d.ts +15 -0
  92. package/dist/visual.js +263 -0
  93. package/dist/visual.js.map +1 -0
  94. package/package.json +113 -3
  95. package/src/agent.ts +380 -0
  96. package/src/commands.ts +40 -0
  97. package/src/context.ts +229 -0
  98. package/src/controller.ts +1376 -0
  99. package/src/dev.ts +999 -0
  100. package/src/fs-utils.ts +93 -0
  101. package/src/game-action-observation.ts +96 -0
  102. package/src/game-session-broker.ts +301 -0
  103. package/src/game-session.ts +459 -0
  104. package/src/games.ts +266 -0
  105. package/src/harness/visual/prefab-contract.ts +29 -0
  106. package/src/harness/visual/prefab-runner.ts +178 -0
  107. package/src/harness/visual/runner.ts +546 -0
  108. package/src/harness/visual/scenario-contract.ts +9 -0
  109. package/src/harness/visual/scenario-helpers.ts +63 -0
  110. package/src/harness/visual/session.ts +369 -0
  111. package/src/harness/visual/types.ts +181 -0
  112. package/src/harness/visual.ts +7 -0
  113. package/src/helper-scripts.ts +49 -0
  114. package/src/logs.ts +67 -0
  115. package/src/mcp-config.ts +262 -0
  116. package/src/platform-auth.ts +455 -0
  117. package/src/platform-game-media.ts +209 -0
  118. package/src/platform-games.ts +315 -0
  119. package/src/quality.ts +82 -0
  120. package/src/release.ts +1697 -0
  121. package/src/runtime-owner-protocol.ts +130 -0
  122. package/src/tooling/agent-contract.ts +232 -0
  123. package/src/tooling/agent-declaration.ts +36 -0
  124. package/src/tooling/airjam-agent-inspection.ts +45 -0
  125. package/src/tooling/airjam-agent.ts +118 -0
  126. package/src/tooling/hold-runtime-host.ts +224 -0
  127. package/src/tooling/inspect-airjam-agent.ts +20 -0
  128. package/src/tooling/list-visual-scenarios.ts +64 -0
  129. package/src/tooling/managed-dev-supervisor.ts +71 -0
  130. package/src/tooling/run-visual-capture.ts +217 -0
  131. package/src/tooling/runtime-owner-actions.ts +42 -0
  132. package/src/tooling/visual-pack.ts +46 -0
  133. package/src/types.ts +951 -0
  134. package/src/visual.ts +304 -0
  135. package/src/workspace-contract.ts +32 -0
@@ -0,0 +1,262 @@
1
+ import { access, mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { inspectProject } from "./context.js";
5
+ export type AirJamMcpServerDeclaration = {
6
+ name: "airjam";
7
+ transport: "stdio";
8
+ command: "pnpm";
9
+ args: ["exec", "airjam-mcp"];
10
+ };
11
+
12
+ export type AirJamProjectLocalMcpConfig = {
13
+ mcpServers: {
14
+ airjam: {
15
+ command: string;
16
+ args: string[];
17
+ };
18
+ };
19
+ };
20
+
21
+ export type AirJamMcpClientProfile = "portable" | "codex" | "claude-desktop";
22
+
23
+ export type AirJamMcpClientProfileRender = {
24
+ profile: AirJamMcpClientProfile;
25
+ format: "json" | "toml";
26
+ scope: "project" | "client-global";
27
+ configPath: string | null;
28
+ content: string;
29
+ installCommand: string | null;
30
+ };
31
+
32
+ export type AirJamMcpRegistrationInspection = {
33
+ profile: AirJamMcpClientProfile;
34
+ configPath: string | null;
35
+ configPresent: boolean | null;
36
+ registered: boolean | null;
37
+ };
38
+
39
+ export type InspectMcpProjectSetupResult = {
40
+ projectDir: string;
41
+ server: AirJamMcpServerDeclaration;
42
+ package: {
43
+ dependencyPresent: boolean;
44
+ scriptPresent: boolean;
45
+ };
46
+ portableDeclaration: {
47
+ configPath: string;
48
+ present: boolean;
49
+ };
50
+ clients: {
51
+ codex: AirJamMcpRegistrationInspection;
52
+ claudeDesktop: AirJamMcpRegistrationInspection;
53
+ };
54
+ recommendedConfig: AirJamProjectLocalMcpConfig;
55
+ };
56
+
57
+ export const AIRJAM_PROJECT_MCP_FILE = ".mcp.json";
58
+ export const AIRJAM_CODEX_PROJECT_MCP_FILE = path.join(".codex", "config.toml");
59
+
60
+ export const createAirJamMcpServerDeclaration =
61
+ (): AirJamMcpServerDeclaration => ({
62
+ name: "airjam",
63
+ transport: "stdio",
64
+ command: "pnpm",
65
+ args: ["exec", "airjam-mcp"],
66
+ });
67
+
68
+ export const createProjectLocalMcpConfig = (): AirJamProjectLocalMcpConfig => {
69
+ const server = createAirJamMcpServerDeclaration();
70
+ return {
71
+ mcpServers: {
72
+ airjam: {
73
+ command: server.command,
74
+ args: [...server.args],
75
+ },
76
+ },
77
+ };
78
+ };
79
+
80
+ const pathExists = async (targetPath: string): Promise<boolean> => {
81
+ try {
82
+ await access(targetPath);
83
+ return true;
84
+ } catch {
85
+ return false;
86
+ }
87
+ };
88
+
89
+ const resolveClaudeDesktopConfigPath = (): string | null => {
90
+ if (process.platform === "darwin") {
91
+ return path.join(
92
+ os.homedir(),
93
+ "Library",
94
+ "Application Support",
95
+ "Claude",
96
+ "claude_desktop_config.json",
97
+ );
98
+ }
99
+ if (process.platform === "win32") {
100
+ const appData = process.env.APPDATA;
101
+ return appData
102
+ ? path.join(appData, "Claude", "claude_desktop_config.json")
103
+ : null;
104
+ }
105
+ return path.join(
106
+ os.homedir(),
107
+ ".config",
108
+ "Claude",
109
+ "claude_desktop_config.json",
110
+ );
111
+ };
112
+
113
+ const inspectJsonRegistration = async (
114
+ profile: AirJamMcpClientProfile,
115
+ configPath: string | null,
116
+ ): Promise<AirJamMcpRegistrationInspection> => {
117
+ if (!configPath) {
118
+ return { profile, configPath, configPresent: null, registered: null };
119
+ }
120
+ if (!(await pathExists(configPath))) {
121
+ return { profile, configPath, configPresent: false, registered: false };
122
+ }
123
+ try {
124
+ const parsed = JSON.parse(await readFile(configPath, "utf8")) as {
125
+ mcpServers?: Record<string, unknown>;
126
+ };
127
+ return {
128
+ profile,
129
+ configPath,
130
+ configPresent: true,
131
+ registered: Boolean(parsed.mcpServers?.airjam),
132
+ };
133
+ } catch {
134
+ return { profile, configPath, configPresent: true, registered: false };
135
+ }
136
+ };
137
+
138
+ const inspectCodexRegistration = async (
139
+ projectDir: string,
140
+ ): Promise<AirJamMcpRegistrationInspection> => {
141
+ const configPath = path.join(projectDir, AIRJAM_CODEX_PROJECT_MCP_FILE);
142
+ if (!(await pathExists(configPath))) {
143
+ return {
144
+ profile: "codex",
145
+ configPath,
146
+ configPresent: false,
147
+ registered: false,
148
+ };
149
+ }
150
+ const source = await readFile(configPath, "utf8");
151
+ return {
152
+ profile: "codex",
153
+ configPath,
154
+ configPresent: true,
155
+ registered: /^\s*\[mcp_servers\.airjam\]\s*$/m.test(source),
156
+ };
157
+ };
158
+
159
+ export const renderMcpClientProfile = ({
160
+ profile,
161
+ projectDir = process.cwd(),
162
+ }: {
163
+ profile: AirJamMcpClientProfile;
164
+ projectDir?: string;
165
+ }): AirJamMcpClientProfileRender => {
166
+ const server = createAirJamMcpServerDeclaration();
167
+ if (profile === "codex") {
168
+ const escapedCwd = projectDir
169
+ .replaceAll("\\", "\\\\")
170
+ .replaceAll('"', '\\"');
171
+ return {
172
+ profile,
173
+ format: "toml",
174
+ scope: "project",
175
+ configPath: path.join(projectDir, AIRJAM_CODEX_PROJECT_MCP_FILE),
176
+ content: `[mcp_servers.airjam]\ncommand = "${server.command}"\nargs = ["exec", "airjam-mcp"]\ncwd = "${escapedCwd}"\n`,
177
+ installCommand: `codex mcp add airjam -- ${server.command} ${server.args.join(" ")}`,
178
+ };
179
+ }
180
+
181
+ const config = createProjectLocalMcpConfig();
182
+ if (profile === "claude-desktop") {
183
+ // Desktop launches globally, not from the game's project directory.
184
+ config.mcpServers.airjam.args = [
185
+ "--dir",
186
+ path.resolve(projectDir),
187
+ ...server.args,
188
+ ];
189
+ }
190
+
191
+ return {
192
+ profile,
193
+ format: "json",
194
+ scope: profile === "portable" ? "project" : "client-global",
195
+ configPath:
196
+ profile === "portable"
197
+ ? path.join(projectDir, AIRJAM_PROJECT_MCP_FILE)
198
+ : resolveClaudeDesktopConfigPath(),
199
+ content: `${JSON.stringify(config, null, 2)}\n`,
200
+ installCommand: null,
201
+ };
202
+ };
203
+
204
+ export const inspectMcpProjectSetup = async ({
205
+ cwd = process.cwd(),
206
+ }: {
207
+ cwd?: string;
208
+ } = {}): Promise<InspectMcpProjectSetupResult> => {
209
+ const project = await inspectProject({ cwd });
210
+ const projectDir = project.context.rootDir;
211
+ const configPath = path.join(projectDir, AIRJAM_PROJECT_MCP_FILE);
212
+
213
+ return {
214
+ projectDir,
215
+ server: createAirJamMcpServerDeclaration(),
216
+ package: {
217
+ dependencyPresent: Boolean(project.airJamPackages["@air-jam/mcp-server"]),
218
+ scriptPresent: Boolean(project.scripts.mcp),
219
+ },
220
+ portableDeclaration: {
221
+ configPath,
222
+ present: await pathExists(configPath),
223
+ },
224
+ clients: {
225
+ codex: await inspectCodexRegistration(projectDir),
226
+ claudeDesktop: await inspectJsonRegistration(
227
+ "claude-desktop",
228
+ resolveClaudeDesktopConfigPath(),
229
+ ),
230
+ },
231
+ recommendedConfig: createProjectLocalMcpConfig(),
232
+ };
233
+ };
234
+
235
+ export const writeProjectLocalMcpConfig = async ({
236
+ cwd = process.cwd(),
237
+ force = false,
238
+ }: {
239
+ cwd?: string;
240
+ force?: boolean;
241
+ } = {}): Promise<InspectMcpProjectSetupResult> => {
242
+ const inspection = await inspectMcpProjectSetup({ cwd });
243
+ const configPath = inspection.portableDeclaration.configPath;
244
+
245
+ if (inspection.portableDeclaration.present && !force) {
246
+ throw new Error(
247
+ `MCP declaration already exists at ${configPath}. Re-run with force to overwrite it.`,
248
+ );
249
+ }
250
+
251
+ await mkdir(path.dirname(configPath), { recursive: true });
252
+ await writeFile(
253
+ configPath,
254
+ renderMcpClientProfile({
255
+ profile: "portable",
256
+ projectDir: inspection.projectDir,
257
+ }).content,
258
+ "utf8",
259
+ );
260
+
261
+ return inspectMcpProjectSetup({ cwd });
262
+ };
@@ -0,0 +1,455 @@
1
+ import {
2
+ type PlatformMachineErrorCode,
3
+ platformMachineApiErrorSchema,
4
+ platformMachineDevicePollResultSchema,
5
+ platformMachineDeviceStartResultSchema,
6
+ platformMachineLogoutResultSchema,
7
+ platformMachineMeResultSchema,
8
+ } from "@air-jam/sdk/platform-machine";
9
+ import { randomUUID } from "node:crypto";
10
+ import {
11
+ chmod,
12
+ mkdir,
13
+ readFile,
14
+ rename,
15
+ rm,
16
+ writeFile,
17
+ } from "node:fs/promises";
18
+ import { isIP } from "node:net";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+ import { z } from "zod";
22
+ import type {
23
+ AirJamPlatformAuthStatus,
24
+ AirJamPlatformMachineSessionStore,
25
+ GetPlatformMachineProfileOptions,
26
+ LoginPlatformWithDeviceFlowOptions,
27
+ LogoutPlatformMachineSessionOptions,
28
+ PollPlatformDeviceAuthorizationOptions,
29
+ StartPlatformDeviceAuthorizationOptions,
30
+ } from "./types.js";
31
+
32
+ export type {
33
+ AirJamPlatformAuthStatus,
34
+ AirJamPlatformMachineSessionStore,
35
+ GetPlatformMachineProfileOptions,
36
+ LoginPlatformWithDeviceFlowOptions,
37
+ LogoutPlatformMachineSessionOptions,
38
+ PollPlatformDeviceAuthorizationOptions,
39
+ StartPlatformDeviceAuthorizationOptions,
40
+ } from "./types.js";
41
+
42
+ const LOCAL_PLATFORM_FALLBACK = "http://localhost:3000";
43
+
44
+ export const resolveAirJamStateDirectory = (): string => {
45
+ const configured = process.env.AIRJAM_STATE_DIR?.trim();
46
+ if (!configured) return path.join(os.homedir(), ".airjam");
47
+ if (!path.isAbsolute(configured)) {
48
+ throw new Error("AIRJAM_STATE_DIR must be an absolute path.");
49
+ }
50
+ return path.normalize(configured);
51
+ };
52
+
53
+ const resolvePlatformAuthDirectory = () =>
54
+ path.join(resolveAirJamStateDirectory(), "auth");
55
+
56
+ const resolvePlatformAuthFile = () =>
57
+ path.join(resolvePlatformAuthDirectory(), "platform-session.json");
58
+
59
+ const storedPlatformSessionSchema = z.object({
60
+ version: z.literal(1),
61
+ platformBaseUrl: z.string().url(),
62
+ clientName: z.string().nullable(),
63
+ storedAt: z.string().min(1),
64
+ user: z.object({
65
+ id: z.string().min(1),
66
+ name: z.string().min(1),
67
+ email: z.string().email(),
68
+ role: z.enum(["creator", "ops_admin"]),
69
+ }),
70
+ session: z.object({
71
+ id: z.string().min(1),
72
+ token: z.string().min(1),
73
+ expiresAt: z.string().min(1),
74
+ createdAt: z.string().min(1),
75
+ userAgent: z.string().min(1),
76
+ }),
77
+ });
78
+
79
+ export class AirJamPlatformApiError extends Error {
80
+ readonly code: PlatformMachineErrorCode;
81
+ readonly status: number;
82
+
83
+ constructor({
84
+ code,
85
+ message,
86
+ status,
87
+ }: {
88
+ code: PlatformMachineErrorCode;
89
+ message: string;
90
+ status: number;
91
+ }) {
92
+ super(message);
93
+ this.name = "AirJamPlatformApiError";
94
+ this.code = code;
95
+ this.status = status;
96
+ }
97
+ }
98
+
99
+ export class AirJamStoredPlatformSessionError extends Error {
100
+ readonly storagePath: string;
101
+
102
+ constructor(storagePath: string, cause: unknown) {
103
+ super(`The stored Air Jam platform session is unreadable: ${storagePath}`, {
104
+ cause,
105
+ });
106
+ this.name = "AirJamStoredPlatformSessionError";
107
+ this.storagePath = storagePath;
108
+ }
109
+ }
110
+
111
+ const parsePlatformUrl = (rawUrl: string): URL => {
112
+ const trimmed = rawUrl.trim();
113
+ let url: URL;
114
+ try {
115
+ if (!trimmed) throw new Error("Empty URL");
116
+ const hasScheme = /^[a-z][a-z\d+.-]*:/iu.test(trimmed);
117
+ const hasHostPort = /^[^/?#]+:\d+(?:[/?#]|$)/u.test(trimmed);
118
+ if (
119
+ hasScheme &&
120
+ !hasHostPort &&
121
+ !/^[a-z][a-z\d+.-]*:\/\//iu.test(trimmed)
122
+ ) {
123
+ throw new Error("Invalid URL scheme");
124
+ }
125
+ url = new URL(hasScheme && !hasHostPort ? trimmed : `https://${trimmed}`);
126
+ } catch {
127
+ throw new Error("Invalid Air Jam platform URL.");
128
+ }
129
+
130
+ const loopback =
131
+ url.hostname === "localhost" ||
132
+ url.hostname === "[::1]" ||
133
+ (isIP(url.hostname) === 4 && url.hostname.startsWith("127."));
134
+ if (
135
+ (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) ||
136
+ url.username ||
137
+ url.password
138
+ ) {
139
+ throw new Error(
140
+ "Air Jam platform URLs require HTTPS, except HTTP on loopback, and must not contain credentials.",
141
+ );
142
+ }
143
+ return url;
144
+ };
145
+
146
+ export const resolvePlatformBaseUrl = (
147
+ value: string | undefined = process.env.AIRJAM_PLATFORM_URL,
148
+ ): string => {
149
+ const candidate =
150
+ value ??
151
+ process.env.AIR_JAM_PLATFORM_URL ??
152
+ process.env.NEXT_PUBLIC_AIR_JAM_PUBLIC_HOST ??
153
+ process.env.NEXT_PUBLIC_APP_URL ??
154
+ LOCAL_PLATFORM_FALLBACK;
155
+
156
+ return parsePlatformUrl(candidate).toString().replace(/\/$/, "");
157
+ };
158
+
159
+ const sleep = async (durationMs: number) =>
160
+ new Promise((resolve) => setTimeout(resolve, durationMs));
161
+
162
+ export const requestPlatformMachineApi = async <T>({
163
+ baseUrl,
164
+ pathname,
165
+ method = "GET",
166
+ body,
167
+ token,
168
+ schema,
169
+ }: {
170
+ baseUrl: string;
171
+ pathname: string;
172
+ method?: "GET" | "POST" | "PATCH";
173
+ body?: unknown;
174
+ token?: string;
175
+ schema: { parse: (value: unknown) => T };
176
+ }): Promise<T> => {
177
+ const platformUrl = parsePlatformUrl(baseUrl);
178
+ const requestUrl = new URL(pathname, platformUrl);
179
+ if (
180
+ requestUrl.origin !== platformUrl.origin ||
181
+ requestUrl.username ||
182
+ requestUrl.password
183
+ ) {
184
+ throw new Error(
185
+ "Platform agent API requests must stay on the platform origin.",
186
+ );
187
+ }
188
+ const response = await fetch(requestUrl, {
189
+ method,
190
+ // Redirects can replay device codes or credentials, even on the same origin.
191
+ redirect: "error",
192
+ headers: {
193
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
194
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
195
+ },
196
+ body: body === undefined ? undefined : JSON.stringify(body),
197
+ });
198
+
199
+ const payload = (await response.json().catch(() => null)) as unknown;
200
+
201
+ if (!response.ok) {
202
+ const parsedError = platformMachineApiErrorSchema.safeParse(payload);
203
+ if (parsedError.success) {
204
+ throw new AirJamPlatformApiError({
205
+ code: parsedError.data.error,
206
+ message: parsedError.data.message,
207
+ status: response.status,
208
+ });
209
+ }
210
+
211
+ throw new AirJamPlatformApiError({
212
+ code: "invalid_request",
213
+ message: `Platform agent API request failed: ${response.status}`,
214
+ status: response.status,
215
+ });
216
+ }
217
+
218
+ return schema.parse(payload);
219
+ };
220
+
221
+ export const readStoredPlatformMachineSession =
222
+ async (): Promise<AirJamPlatformMachineSessionStore | null> => {
223
+ const storagePath = resolvePlatformAuthFile();
224
+ let source: string;
225
+ try {
226
+ source = await readFile(storagePath, "utf8");
227
+ } catch (error) {
228
+ if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
229
+ return null;
230
+ }
231
+ throw error;
232
+ }
233
+
234
+ try {
235
+ return storedPlatformSessionSchema.parse(JSON.parse(source) as unknown);
236
+ } catch (error) {
237
+ throw new AirJamStoredPlatformSessionError(storagePath, error);
238
+ }
239
+ };
240
+
241
+ export const writeStoredPlatformMachineSession = async (
242
+ value: AirJamPlatformMachineSessionStore,
243
+ ): Promise<void> => {
244
+ const authDirectory = resolvePlatformAuthDirectory();
245
+ const storagePath = resolvePlatformAuthFile();
246
+ const temporaryPath = `${storagePath}.tmp-${process.pid}-${randomUUID()}`;
247
+ await mkdir(authDirectory, { recursive: true, mode: 0o700 });
248
+ await chmod(authDirectory, 0o700);
249
+ try {
250
+ await writeFile(
251
+ temporaryPath,
252
+ `${JSON.stringify(storedPlatformSessionSchema.parse(value), null, 2)}\n`,
253
+ { encoding: "utf8", flag: "wx", mode: 0o600 },
254
+ );
255
+ await rename(temporaryPath, storagePath);
256
+ await chmod(storagePath, 0o600);
257
+ } finally {
258
+ await rm(temporaryPath, { force: true });
259
+ }
260
+ };
261
+
262
+ export const clearStoredPlatformMachineSession = async (): Promise<void> => {
263
+ await rm(resolvePlatformAuthFile(), { force: true });
264
+ };
265
+
266
+ export const startPlatformDeviceAuthorization = async ({
267
+ platformUrl,
268
+ clientName,
269
+ }: StartPlatformDeviceAuthorizationOptions = {}) =>
270
+ requestPlatformMachineApi({
271
+ baseUrl: resolvePlatformBaseUrl(platformUrl),
272
+ pathname: "/api/cli/auth/device/start",
273
+ method: "POST",
274
+ body: {
275
+ ...(clientName?.trim() ? { clientName: clientName.trim() } : {}),
276
+ },
277
+ schema: platformMachineDeviceStartResultSchema,
278
+ });
279
+
280
+ export const pollPlatformDeviceAuthorization = async ({
281
+ platformUrl,
282
+ deviceCode,
283
+ }: PollPlatformDeviceAuthorizationOptions) =>
284
+ requestPlatformMachineApi({
285
+ baseUrl: resolvePlatformBaseUrl(platformUrl),
286
+ pathname: "/api/cli/auth/device/poll",
287
+ method: "POST",
288
+ body: {
289
+ deviceCode,
290
+ },
291
+ schema: platformMachineDevicePollResultSchema,
292
+ });
293
+
294
+ export const loginPlatformWithDeviceFlow = async ({
295
+ platformUrl,
296
+ clientName,
297
+ onPrompt,
298
+ }: LoginPlatformWithDeviceFlowOptions = {}) => {
299
+ const baseUrl = resolvePlatformBaseUrl(platformUrl);
300
+ const authorization = await startPlatformDeviceAuthorization({
301
+ platformUrl: baseUrl,
302
+ clientName,
303
+ });
304
+
305
+ await onPrompt?.(authorization);
306
+
307
+ const expiresAtMs = Date.parse(authorization.expiresAt);
308
+ while (Date.now() < expiresAtMs) {
309
+ await sleep(authorization.intervalSeconds * 1000);
310
+
311
+ try {
312
+ const authenticated = await pollPlatformDeviceAuthorization({
313
+ platformUrl: baseUrl,
314
+ deviceCode: authorization.deviceCode,
315
+ });
316
+
317
+ if (
318
+ parsePlatformUrl(authenticated.platformBaseUrl).origin !==
319
+ parsePlatformUrl(baseUrl).origin
320
+ ) {
321
+ throw new Error(
322
+ "The login response does not match the requested platform origin.",
323
+ );
324
+ }
325
+ const storedSession: AirJamPlatformMachineSessionStore = {
326
+ version: 1,
327
+ platformBaseUrl: baseUrl,
328
+ clientName: clientName?.trim() || null,
329
+ storedAt: new Date().toISOString(),
330
+ user: authenticated.user,
331
+ session: authenticated.session,
332
+ };
333
+
334
+ await writeStoredPlatformMachineSession(storedSession);
335
+
336
+ return {
337
+ authorization,
338
+ authenticated,
339
+ storedSession,
340
+ };
341
+ } catch (error) {
342
+ if (
343
+ error instanceof AirJamPlatformApiError &&
344
+ error.code === "authorization_pending"
345
+ ) {
346
+ continue;
347
+ }
348
+
349
+ throw error;
350
+ }
351
+ }
352
+
353
+ throw new AirJamPlatformApiError({
354
+ code: "expired_token",
355
+ message: "The Air Jam CLI login expired before it was approved.",
356
+ status: 410,
357
+ });
358
+ };
359
+
360
+ export const resolvePlatformMachineAuth = async ({
361
+ platformUrl,
362
+ token,
363
+ }: {
364
+ platformUrl?: string;
365
+ token?: string;
366
+ }) => {
367
+ if (token?.trim()) {
368
+ return {
369
+ baseUrl: resolvePlatformBaseUrl(platformUrl),
370
+ token: token.trim(),
371
+ };
372
+ }
373
+
374
+ const stored = await readStoredPlatformMachineSession();
375
+ if (!stored) {
376
+ throw new Error("No stored Air Jam platform session was found.");
377
+ }
378
+
379
+ const baseUrl = resolvePlatformBaseUrl(platformUrl ?? stored.platformBaseUrl);
380
+ if (
381
+ parsePlatformUrl(baseUrl).origin !==
382
+ parsePlatformUrl(stored.platformBaseUrl).origin
383
+ ) {
384
+ throw new Error(
385
+ "The stored Air Jam session belongs to a different platform origin. Log in to that platform or supply an explicit token.",
386
+ );
387
+ }
388
+ return {
389
+ baseUrl,
390
+ token: stored.session.token,
391
+ };
392
+ };
393
+
394
+ export const getPlatformMachineProfile = async ({
395
+ platformUrl,
396
+ token,
397
+ }: GetPlatformMachineProfileOptions = {}) => {
398
+ const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
399
+ return requestPlatformMachineApi({
400
+ baseUrl: resolved.baseUrl,
401
+ pathname: "/api/cli/auth/me",
402
+ token: resolved.token,
403
+ schema: platformMachineMeResultSchema,
404
+ });
405
+ };
406
+
407
+ export const logoutPlatformMachineSession = async ({
408
+ platformUrl,
409
+ token,
410
+ }: LogoutPlatformMachineSessionOptions = {}) => {
411
+ const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
412
+ const result = await requestPlatformMachineApi({
413
+ baseUrl: resolved.baseUrl,
414
+ pathname: "/api/cli/auth/logout",
415
+ method: "POST",
416
+ token: resolved.token,
417
+ schema: platformMachineLogoutResultSchema,
418
+ });
419
+ await clearStoredPlatformMachineSession();
420
+ return result;
421
+ };
422
+
423
+ export const getPlatformMachineAuthStatus =
424
+ async (): Promise<AirJamPlatformAuthStatus> => {
425
+ const stored = await readStoredPlatformMachineSession();
426
+
427
+ if (!stored) {
428
+ return {
429
+ authenticated: false,
430
+ storagePath: resolvePlatformAuthFile(),
431
+ platformBaseUrl: null,
432
+ clientName: null,
433
+ storedAt: null,
434
+ user: null,
435
+ session: null,
436
+ };
437
+ }
438
+
439
+ return {
440
+ authenticated: true,
441
+ storagePath: resolvePlatformAuthFile(),
442
+ platformBaseUrl: stored.platformBaseUrl,
443
+ clientName: stored.clientName,
444
+ storedAt: stored.storedAt,
445
+ user: stored.user,
446
+ session: {
447
+ id: stored.session.id,
448
+ expiresAt: stored.session.expiresAt,
449
+ createdAt: stored.session.createdAt,
450
+ userAgent: stored.session.userAgent,
451
+ },
452
+ };
453
+ };
454
+
455
+ export const getPlatformAuthStoragePath = () => resolvePlatformAuthFile();