zcode-app-cli 3.3.5-1

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 (169) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +642 -0
  3. package/bin/zcode.js +848 -0
  4. package/config.example.json +110 -0
  5. package/package.json +81 -0
  6. package/vendor/.node-bundle-meta.json +6 -0
  7. package/vendor/extraction.json +11 -0
  8. package/vendor/node_modules/@zcode/tui/dist/index.js +161875 -0
  9. package/vendor/node_modules/@zcode/tui/package.json +14 -0
  10. package/vendor/packages/android-emulator-plugin/.mcp.json +19 -0
  11. package/vendor/packages/android-emulator-plugin/.zcode-plugin/plugin.json +63 -0
  12. package/vendor/packages/android-emulator-plugin/README.md +134 -0
  13. package/vendor/packages/android-emulator-plugin/commands/android-dev.md +11 -0
  14. package/vendor/packages/android-emulator-plugin/dist/lib/path.d.ts +4 -0
  15. package/vendor/packages/android-emulator-plugin/dist/lib/path.js +17 -0
  16. package/vendor/packages/android-emulator-plugin/dist/lib/result.d.ts +5 -0
  17. package/vendor/packages/android-emulator-plugin/dist/lib/result.js +22 -0
  18. package/vendor/packages/android-emulator-plugin/dist/lib/run.d.ts +18 -0
  19. package/vendor/packages/android-emulator-plugin/dist/lib/run.js +99 -0
  20. package/vendor/packages/android-emulator-plugin/dist/mcp/server.d.ts +3 -0
  21. package/vendor/packages/android-emulator-plugin/dist/mcp/server.js +47607 -0
  22. package/vendor/packages/android-emulator-plugin/dist/providers/app.d.ts +39 -0
  23. package/vendor/packages/android-emulator-plugin/dist/providers/app.js +50 -0
  24. package/vendor/packages/android-emulator-plugin/dist/providers/avd.d.ts +37 -0
  25. package/vendor/packages/android-emulator-plugin/dist/providers/avd.js +185 -0
  26. package/vendor/packages/android-emulator-plugin/dist/providers/build.d.ts +68 -0
  27. package/vendor/packages/android-emulator-plugin/dist/providers/build.js +131 -0
  28. package/vendor/packages/android-emulator-plugin/dist/providers/config.d.ts +7 -0
  29. package/vendor/packages/android-emulator-plugin/dist/providers/config.js +29 -0
  30. package/vendor/packages/android-emulator-plugin/dist/providers/device.d.ts +20 -0
  31. package/vendor/packages/android-emulator-plugin/dist/providers/device.js +91 -0
  32. package/vendor/packages/android-emulator-plugin/dist/providers/logs.d.ts +15 -0
  33. package/vendor/packages/android-emulator-plugin/dist/providers/logs.js +31 -0
  34. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.d.ts +15 -0
  35. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.js +123 -0
  36. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.d.ts +13 -0
  37. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.js +211 -0
  38. package/vendor/packages/android-emulator-plugin/dist/providers/project.d.ts +33 -0
  39. package/vendor/packages/android-emulator-plugin/dist/providers/project.js +195 -0
  40. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.d.ts +14 -0
  41. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.js +73 -0
  42. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.d.ts +14 -0
  43. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.js +185 -0
  44. package/vendor/packages/android-emulator-plugin/dist/providers/ui.d.ts +92 -0
  45. package/vendor/packages/android-emulator-plugin/dist/providers/ui.js +146 -0
  46. package/vendor/packages/android-emulator-plugin/hooks/hooks.json +3 -0
  47. package/vendor/packages/android-emulator-plugin/package.json +35 -0
  48. package/vendor/packages/android-emulator-plugin/skills/android-dev/INSTALL_ENVIRONMENT.md +357 -0
  49. package/vendor/packages/android-emulator-plugin/skills/android-dev/SKILL.md +73 -0
  50. package/vendor/packages/android-emulator-plugin/templates/compose-app/README.md +5 -0
  51. package/vendor/packages/document-skills-plugin/.zcode-plugin/plugin.json +8 -0
  52. package/vendor/packages/document-skills-plugin/package.json +8 -0
  53. package/vendor/packages/document-skills-plugin/skills/docx/LICENSE.txt +13 -0
  54. package/vendor/packages/document-skills-plugin/skills/docx/SKILL.md +201 -0
  55. package/vendor/packages/document-skills-plugin/skills/docx/references/chart-templates.md +386 -0
  56. package/vendor/packages/document-skills-plugin/skills/docx/references/common-rules.md +419 -0
  57. package/vendor/packages/document-skills-plugin/skills/docx/references/decorations.md +537 -0
  58. package/vendor/packages/document-skills-plugin/skills/docx/references/design-system.md +1797 -0
  59. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-advanced.md +257 -0
  60. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-core.md +332 -0
  61. package/vendor/packages/document-skills-plugin/skills/docx/references/faq.md +323 -0
  62. package/vendor/packages/document-skills-plugin/skills/docx/references/math-formulas.md +276 -0
  63. package/vendor/packages/document-skills-plugin/skills/docx/references/ooxml.md +222 -0
  64. package/vendor/packages/document-skills-plugin/skills/docx/references/toc.md +264 -0
  65. package/vendor/packages/document-skills-plugin/skills/docx/routes/comment.md +88 -0
  66. package/vendor/packages/document-skills-plugin/skills/docx/routes/create.md +207 -0
  67. package/vendor/packages/document-skills-plugin/skills/docx/routes/edit.md +115 -0
  68. package/vendor/packages/document-skills-plugin/skills/docx/routes/format.md +120 -0
  69. package/vendor/packages/document-skills-plugin/skills/docx/routes/read.md +114 -0
  70. package/vendor/packages/document-skills-plugin/skills/docx/scenes/academic.md +783 -0
  71. package/vendor/packages/document-skills-plugin/skills/docx/scenes/contract.md +463 -0
  72. package/vendor/packages/document-skills-plugin/skills/docx/scenes/copywriting.md +139 -0
  73. package/vendor/packages/document-skills-plugin/skills/docx/scenes/exam.md +698 -0
  74. package/vendor/packages/document-skills-plugin/skills/docx/scenes/official-doc.md +411 -0
  75. package/vendor/packages/document-skills-plugin/skills/docx/scenes/report.md +340 -0
  76. package/vendor/packages/document-skills-plugin/skills/docx/scenes/resume.md +534 -0
  77. package/vendor/packages/document-skills-plugin/skills/docx/scripts/__init__.py +1 -0
  78. package/vendor/packages/document-skills-plugin/skills/docx/scripts/add_toc_placeholders.py +749 -0
  79. package/vendor/packages/document-skills-plugin/skills/docx/scripts/document.py +1333 -0
  80. package/vendor/packages/document-skills-plugin/skills/docx/scripts/postcheck.py +807 -0
  81. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/comments.xml +3 -0
  82. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtended.xml +3 -0
  83. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtensible.xml +3 -0
  84. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsIds.xml +3 -0
  85. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/people.xml +3 -0
  86. package/vendor/packages/document-skills-plugin/skills/docx/scripts/utilities.py +374 -0
  87. package/vendor/packages/document-skills-plugin/skills/docx/setup.sh +177 -0
  88. package/vendor/packages/document-skills-plugin/skills/pdf/LICENSE.txt +13 -0
  89. package/vendor/packages/document-skills-plugin/skills/pdf/SKILL.md +919 -0
  90. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/academic.md +1058 -0
  91. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/creative.md +770 -0
  92. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/poster.md +702 -0
  93. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process-advanced.md +284 -0
  94. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process.md +319 -0
  95. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/report.md +1659 -0
  96. package/vendor/packages/document-skills-plugin/skills/pdf/configs/components.md +153 -0
  97. package/vendor/packages/document-skills-plugin/skills/pdf/configs/fonts.md +93 -0
  98. package/vendor/packages/document-skills-plugin/skills/pdf/configs/visual_framework.md +263 -0
  99. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-academic.tex +130 -0
  100. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-altacv.tex +190 -0
  101. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/cover_validate.js +367 -0
  102. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/design_engine.py +2816 -0
  103. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2pdf-next.js +754 -0
  104. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2poster.js +256 -0
  105. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf.py +2959 -0
  106. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf_qa.py +901 -0
  107. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/poster_validate.py +1337 -0
  108. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/setup.sh +269 -0
  109. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/toc_validate.py +2075 -0
  110. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/charts.md +320 -0
  111. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover-backgrounds.md +384 -0
  112. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover.md +1442 -0
  113. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/fill-engine.md +527 -0
  114. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/geometry.md +142 -0
  115. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/overflow.md +630 -0
  116. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/pagination.md +367 -0
  117. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/palette.md +217 -0
  118. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/typography.md +20 -0
  119. package/vendor/packages/ios-simulator-plugin/.mcp.json +15 -0
  120. package/vendor/packages/ios-simulator-plugin/.zcode-plugin/plugin.json +34 -0
  121. package/vendor/packages/ios-simulator-plugin/README.md +111 -0
  122. package/vendor/packages/ios-simulator-plugin/commands/ios-dev.md +11 -0
  123. package/vendor/packages/ios-simulator-plugin/dist/lib/path.d.ts +4 -0
  124. package/vendor/packages/ios-simulator-plugin/dist/lib/path.js +18 -0
  125. package/vendor/packages/ios-simulator-plugin/dist/lib/result.d.ts +5 -0
  126. package/vendor/packages/ios-simulator-plugin/dist/lib/result.js +20 -0
  127. package/vendor/packages/ios-simulator-plugin/dist/lib/run.d.ts +17 -0
  128. package/vendor/packages/ios-simulator-plugin/dist/lib/run.js +83 -0
  129. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.d.ts +3 -0
  130. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.js +46833 -0
  131. package/vendor/packages/ios-simulator-plugin/dist/providers/build.d.ts +112 -0
  132. package/vendor/packages/ios-simulator-plugin/dist/providers/build.js +99 -0
  133. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.d.ts +21 -0
  134. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.js +26 -0
  135. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.d.ts +12 -0
  136. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.js +62 -0
  137. package/vendor/packages/ios-simulator-plugin/dist/providers/project.d.ts +35 -0
  138. package/vendor/packages/ios-simulator-plugin/dist/providers/project.js +288 -0
  139. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.d.ts +22 -0
  140. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.js +30 -0
  141. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.d.ts +60 -0
  142. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.js +116 -0
  143. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.d.ts +57 -0
  144. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.js +67 -0
  145. package/vendor/packages/ios-simulator-plugin/hooks/hooks.json +3 -0
  146. package/vendor/packages/ios-simulator-plugin/package.json +35 -0
  147. package/vendor/packages/ios-simulator-plugin/skills/ios-dev/SKILL.md +45 -0
  148. package/vendor/packages/ios-simulator-plugin/templates/swiftui-app/README.md +5 -0
  149. package/vendor/packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json +9 -0
  150. package/vendor/packages/restore-legacy-sessions-plugin/README.md +35 -0
  151. package/vendor/packages/restore-legacy-sessions-plugin/commands/restore-legacy-sessions.md +11 -0
  152. package/vendor/packages/restore-legacy-sessions-plugin/package.json +8 -0
  153. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md +92 -0
  154. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/restore-conversation.mjs +648 -0
  155. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/scan-legacy-sessions.mjs +422 -0
  156. package/vendor/packages/skill-creator-plugin/.zcode-plugin/plugin.json +8 -0
  157. package/vendor/packages/skill-creator-plugin/package.json +8 -0
  158. package/vendor/packages/skill-creator-plugin/skills/skill-creator/SKILL.md +159 -0
  159. package/vendor/packages/zcode-guide-plugin/.zcode-plugin/plugin.json +8 -0
  160. package/vendor/packages/zcode-guide-plugin/README.md +22 -0
  161. package/vendor/packages/zcode-guide-plugin/package.json +8 -0
  162. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-commands/SKILL.md +66 -0
  163. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-hooks/SKILL.md +66 -0
  164. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-mcp/SKILL.md +97 -0
  165. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-plugins/SKILL.md +59 -0
  166. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-skills/SKILL.md +61 -0
  167. package/vendor/packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md +99 -0
  168. package/vendor/zcode.cjs +2926 -0
  169. package/zcode-runtime.lock.json +8 -0
package/bin/zcode.js ADDED
@@ -0,0 +1,848 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync } from "node:fs";
4
+ import { constants, homedir, tmpdir } from "node:os";
5
+ import { basename, dirname, join, posix, resolve, sep, win32 } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { hasNative, spawn as spawn$1 } from "zigpty";
8
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
9
+ import { chmod, link, mkdir, mkdtemp, open, readFile, rm, stat, writeFile } from "node:fs/promises";
10
+ //#region config.example.json
11
+ var config_example_default = {
12
+ provider: { "zai": {
13
+ "kind": "anthropic",
14
+ "name": "Z.AI Coding Plan",
15
+ "options": {
16
+ "apiKeyRequired": true,
17
+ "baseURL": "https://api.z.ai/api/anthropic"
18
+ },
19
+ "headers": {},
20
+ "models": {
21
+ "glm-5.2": { "name": "GLM-5.2" },
22
+ "glm-5.1": { "name": "GLM-5.1" }
23
+ }
24
+ } },
25
+ model: {
26
+ "main": "zai/glm-5.2",
27
+ "lite": "zai/glm-5.1"
28
+ },
29
+ modelCatalog: { "overrides": {} },
30
+ modelStream: { "idleTimeoutMs": 6e5 },
31
+ permission: {
32
+ "mode": "build",
33
+ "allowedTools": [],
34
+ "disallowedTools": [],
35
+ "autoApproveHighRisk": false,
36
+ "allowMediumRiskInAuto": false
37
+ },
38
+ storage: {
39
+ "dir": "~/.zcode",
40
+ "sessionDbPath": "~/.zcode/cli/db/db.sqlite"
41
+ },
42
+ network: { "timeout": 18e4 },
43
+ features: {
44
+ "compact": true,
45
+ "rewind": true,
46
+ "subagent": true,
47
+ "memory": true,
48
+ "skill": true,
49
+ "mcp": true
50
+ },
51
+ memory: {
52
+ "use": true,
53
+ "write": true,
54
+ "autoConsolidate": true,
55
+ "summaryMaxBytes": 8192
56
+ },
57
+ mcp: { "servers": {} },
58
+ plugins: {
59
+ "enabled": true,
60
+ "dirs": [],
61
+ "enabledPlugins": {},
62
+ "options": {},
63
+ "suppressedBuiltins": []
64
+ },
65
+ skills: {
66
+ "enabled": true,
67
+ "includeInstructions": true,
68
+ "metadataBudget": 2e4,
69
+ "roots": []
70
+ },
71
+ skill: {},
72
+ command: {},
73
+ logging: {
74
+ "level": "info",
75
+ "format": "text"
76
+ },
77
+ ui: {
78
+ "locale": "auto",
79
+ "theme": "auto",
80
+ "notifications": {
81
+ "method": "auto",
82
+ "condition": "unfocused"
83
+ }
84
+ },
85
+ toolConcurrency: { "maxConcurrency": 10 },
86
+ modelAnomalyGuard: {
87
+ "repeatedToolCallWarningThreshold": 3,
88
+ "maxBudgetWarningsPerTurn": 3
89
+ },
90
+ hooks: {
91
+ "enabled": false,
92
+ "timeoutMs": 6e4,
93
+ "maxOutputBytes": 32768,
94
+ "events": {
95
+ "SessionStart": [],
96
+ "UserPromptSubmit": [],
97
+ "PreToolUse": [],
98
+ "PermissionRequest": [],
99
+ "PostToolUse": [],
100
+ "PostToolUseFailure": [],
101
+ "Stop": []
102
+ }
103
+ }
104
+ };
105
+ //#endregion
106
+ //#region src/model-access.ts
107
+ function isNodeError(error) {
108
+ return error instanceof Error && "code" in error;
109
+ }
110
+ function errorMessage(error) {
111
+ return error instanceof Error ? error.message : String(error);
112
+ }
113
+ async function configFileExists(configPath) {
114
+ try {
115
+ if (!(await stat(configPath)).isFile()) throw new Error(`ZCode config path exists but is not a file: ${configPath}`);
116
+ return true;
117
+ } catch (error) {
118
+ if (isNodeError(error) && error.code === "ENOENT") return false;
119
+ throw error;
120
+ }
121
+ }
122
+ function userConfigPath(env = process.env, platform = process.platform, fallbackHome = homedir()) {
123
+ const path = platform === "win32" ? win32 : posix;
124
+ const configuredHome = (platform === "win32" ? env.USERPROFILE : env.HOME)?.trim();
125
+ return path.join(configuredHome || fallbackHome, ".zcode", "cli", "config.json");
126
+ }
127
+ async function ensureUserConfig(env = process.env) {
128
+ const configPath = userConfigPath(env);
129
+ const configDirectory = dirname(configPath);
130
+ try {
131
+ await mkdir(configDirectory, {
132
+ recursive: true,
133
+ mode: 448
134
+ });
135
+ } catch (error) {
136
+ throw new Error(`Unable to create ZCode config directory ${configDirectory}: ${errorMessage(error)}`, { cause: error });
137
+ }
138
+ if (await configFileExists(configPath)) return {
139
+ configPath,
140
+ created: false
141
+ };
142
+ const temporaryPath = join(configDirectory, `.${basename(configPath)}.${process.pid}.${randomUUID()}.tmp`);
143
+ let file;
144
+ try {
145
+ file = await open(temporaryPath, "wx", 384);
146
+ await file.writeFile(`${JSON.stringify(config_example_default, null, 2)}\n`, "utf8");
147
+ await file.sync();
148
+ } catch (error) {
149
+ if (file) {
150
+ await file.close().catch(() => {});
151
+ file = void 0;
152
+ }
153
+ await rm(temporaryPath, { force: true }).catch(() => {});
154
+ throw new Error(`Unable to initialize ZCode config file ${configPath}: ${errorMessage(error)}`, { cause: error });
155
+ } finally {
156
+ await file?.close();
157
+ }
158
+ try {
159
+ await link(temporaryPath, configPath);
160
+ return {
161
+ configPath,
162
+ created: true
163
+ };
164
+ } catch (error) {
165
+ if (isNodeError(error) && error.code === "EEXIST") {
166
+ if (!await configFileExists(configPath)) throw new Error(`ZCode config path exists but is not a file: ${configPath}`);
167
+ return {
168
+ configPath,
169
+ created: false
170
+ };
171
+ }
172
+ throw new Error(`Unable to create ZCode config file ${configPath}: ${errorMessage(error)}`, { cause: error });
173
+ } finally {
174
+ await rm(temporaryPath, { force: true }).catch(() => {});
175
+ }
176
+ }
177
+ async function readConfiguredModelAccess(env = process.env) {
178
+ const configPath = userConfigPath(env);
179
+ let config;
180
+ try {
181
+ config = JSON.parse(await readFile(configPath, "utf8"));
182
+ } catch {
183
+ return null;
184
+ }
185
+ const model = typeof config.model?.main === "string" ? config.model.main.trim() : "";
186
+ const separator = model.indexOf("/");
187
+ if (separator <= 0 || separator === model.length - 1) return null;
188
+ const providerId = model.slice(0, separator);
189
+ const modelId = model.slice(separator + 1);
190
+ const provider = config.provider?.[providerId];
191
+ const apiKey = provider?.options?.apiKey;
192
+ if (!provider?.models?.[modelId] || typeof apiKey !== "string" || !apiKey.trim()) return null;
193
+ return {
194
+ configPath,
195
+ model,
196
+ providerId
197
+ };
198
+ }
199
+ //#endregion
200
+ //#region src/command.ts
201
+ async function readText(stream) {
202
+ if (!stream) return "";
203
+ const chunks = [];
204
+ for await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
205
+ return Buffer.concat(chunks).toString("utf8");
206
+ }
207
+ async function captureCommand(command, args) {
208
+ const child = spawn(command, args, { stdio: [
209
+ "ignore",
210
+ "pipe",
211
+ "pipe"
212
+ ] });
213
+ let launchError = "";
214
+ const exited = new Promise((resolve) => {
215
+ let settled = false;
216
+ const finish = (code) => {
217
+ if (settled) return;
218
+ settled = true;
219
+ resolve(code);
220
+ };
221
+ child.once("error", (error) => {
222
+ launchError = error.message;
223
+ finish(1);
224
+ });
225
+ child.once("close", (code) => finish(code ?? 1));
226
+ });
227
+ const [code, stdout, stderr] = await Promise.all([
228
+ exited,
229
+ readText(child.stdout),
230
+ readText(child.stderr)
231
+ ]);
232
+ return {
233
+ code,
234
+ stdout,
235
+ stderr: stderr || launchError
236
+ };
237
+ }
238
+ //#endregion
239
+ //#region src/darwin-oauth-callback.ts
240
+ const launchServicesRegister = "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";
241
+ const managedBundlePrefix = "dev.zcode.cli.oauth-callback.";
242
+ const managedAppPrefix = "ZCode CLI OAuth Callback ";
243
+ const defaultTimeoutMs = 5 * 6e4;
244
+ const currentHandlerScript = String.raw`
245
+ ObjC.import("AppKit");
246
+ function run(argv) {
247
+ const url = $.NSURL.URLWithString(argv[0] + "://");
248
+ const appUrl = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL(url);
249
+ if (!appUrl || appUrl.isNil()) return "";
250
+ const bundle = $.NSBundle.bundleWithURL(appUrl);
251
+ return !bundle || bundle.isNil() ? "" : ObjC.unwrap(bundle.bundleIdentifier);
252
+ }
253
+ `;
254
+ const setHandlerScript = String.raw`
255
+ ObjC.import("CoreServices");
256
+ function run(argv) {
257
+ return String(Number($.LSSetDefaultHandlerForURLScheme($(argv[0]), $(argv[1]))));
258
+ }
259
+ `;
260
+ async function runCommand(command, args) {
261
+ return await captureCommand(command, args);
262
+ }
263
+ async function checkedRun(runner, command, args) {
264
+ const result = await runner(command, args);
265
+ if (result.code !== 0) {
266
+ const diagnostic = result.stderr.trim() || result.stdout.trim() || `status ${result.code}`;
267
+ throw new Error(`${basename(command)} failed: ${diagnostic}`);
268
+ }
269
+ return result.stdout.trim();
270
+ }
271
+ async function currentDefaultHandler(runner, scheme) {
272
+ return checkedRun(runner, "/usr/bin/osascript", [
273
+ "-l",
274
+ "JavaScript",
275
+ "-e",
276
+ currentHandlerScript,
277
+ scheme
278
+ ]);
279
+ }
280
+ async function setDefaultHandler(runner, scheme, bundleId) {
281
+ const status = await checkedRun(runner, "/usr/bin/osascript", [
282
+ "-l",
283
+ "JavaScript",
284
+ "-e",
285
+ setHandlerScript,
286
+ scheme,
287
+ bundleId
288
+ ]);
289
+ if (status !== "0") throw new Error(`Unable to register the ${scheme} callback handler (status ${status}).`);
290
+ }
291
+ function appleScriptString(value) {
292
+ return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
293
+ }
294
+ function shellQuote(value) {
295
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
296
+ }
297
+ function callbackAppleScript(callbackPath, scheme, previousHandler) {
298
+ const restoreCommand = [
299
+ "/usr/bin/osascript",
300
+ "-l",
301
+ "JavaScript",
302
+ "-e",
303
+ setHandlerScript,
304
+ scheme,
305
+ previousHandler || "none"
306
+ ].map(shellQuote).join(" ");
307
+ return [
308
+ "on open location theURL",
309
+ `set outputFile to POSIX file ${appleScriptString(callbackPath)}`,
310
+ "try",
311
+ "set fileHandle to open for access outputFile with write permission",
312
+ "set eof fileHandle to 0",
313
+ "write theURL to fileHandle as «class utf8»",
314
+ "close access fileHandle",
315
+ "on error",
316
+ "try",
317
+ "close access outputFile",
318
+ "end try",
319
+ "end try",
320
+ "try",
321
+ `do shell script ${appleScriptString(restoreCommand)}`,
322
+ "end try",
323
+ "quit",
324
+ "end open location"
325
+ ];
326
+ }
327
+ function recoveryPath(home) {
328
+ return join(home, ".zcode", "cli", "oauth-handler-recovery.json");
329
+ }
330
+ function applicationsDirectory(home) {
331
+ return join(home, "Applications");
332
+ }
333
+ function isManagedRecovery(record, home) {
334
+ if (!record || typeof record !== "object") return false;
335
+ const value = record;
336
+ if (typeof value.appPath !== "string" || typeof value.bundleId !== "string" || typeof value.pid !== "number" || typeof value.previousHandler !== "string" || typeof value.scheme !== "string") return false;
337
+ const appRoot = `${resolve(applicationsDirectory(home))}${sep}`;
338
+ return resolve(value.appPath).startsWith(appRoot) && basename(value.appPath).startsWith(managedAppPrefix) && value.bundleId.startsWith(managedBundlePrefix);
339
+ }
340
+ function processIsAlive(pid) {
341
+ if (!Number.isInteger(pid) || pid <= 0) return false;
342
+ try {
343
+ process.kill(pid, 0);
344
+ return true;
345
+ } catch {
346
+ return false;
347
+ }
348
+ }
349
+ async function readRecovery(home) {
350
+ try {
351
+ const parsed = JSON.parse(await readFile(recoveryPath(home), "utf8"));
352
+ return isManagedRecovery(parsed, home) ? parsed : null;
353
+ } catch {
354
+ return null;
355
+ }
356
+ }
357
+ async function unregisterApp(runner, appPath) {
358
+ await runner(launchServicesRegister, ["-u", appPath]).catch(() => ({
359
+ code: 1,
360
+ stderr: "",
361
+ stdout: ""
362
+ }));
363
+ }
364
+ async function recoverStaleDarwinOAuthHandler(options) {
365
+ const runner = options.runCommand ?? runCommand;
366
+ const home = options.env?.HOME || homedir();
367
+ const path = recoveryPath(home);
368
+ const record = await readRecovery(home);
369
+ if (!record) {
370
+ await rm(path, { force: true });
371
+ return;
372
+ }
373
+ if (record.pid !== process.pid && processIsAlive(record.pid)) throw new Error("Another Z.AI login is already waiting for authorization.");
374
+ if (await currentDefaultHandler(runner, record.scheme).catch(() => "") === record.bundleId) await setDefaultHandler(runner, record.scheme, record.previousHandler || "none");
375
+ await unregisterApp(runner, record.appPath);
376
+ await rm(record.appPath, {
377
+ recursive: true,
378
+ force: true
379
+ });
380
+ await rm(path, { force: true });
381
+ }
382
+ function abortReason(signal) {
383
+ return signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("Login cancelled.");
384
+ }
385
+ async function delay(milliseconds, signal) {
386
+ if (signal?.aborted) throw abortReason(signal);
387
+ await new Promise((resolveDelay, rejectDelay) => {
388
+ const timer = setTimeout(() => {
389
+ signal?.removeEventListener("abort", onAbort);
390
+ resolveDelay();
391
+ }, milliseconds);
392
+ const onAbort = () => {
393
+ clearTimeout(timer);
394
+ rejectDelay(abortReason(signal));
395
+ };
396
+ signal?.addEventListener("abort", onAbort, { once: true });
397
+ });
398
+ }
399
+ async function createDarwinUrlCallbackReceiver(options) {
400
+ if (process.platform !== "darwin") throw new Error("The native zcode:// callback receiver is only available on macOS.");
401
+ if (!/^[a-z][a-z0-9+.-]*$/u.test(options.scheme)) throw new Error(`Invalid callback scheme: ${options.scheme}`);
402
+ const runner = options.runCommand ?? runCommand;
403
+ const home = options.env?.HOME || homedir();
404
+ await recoverStaleDarwinOAuthHandler({
405
+ ...options,
406
+ runCommand: runner
407
+ });
408
+ const nonce = crypto.randomUUID().replaceAll("-", "");
409
+ const shortNonce = nonce.slice(0, 10);
410
+ const bundleId = `${managedBundlePrefix}${nonce}`;
411
+ const appPath = join(applicationsDirectory(home), `${managedAppPrefix}${shortNonce}.app`);
412
+ const temporaryDirectory = await mkdtemp(join(tmpdir(), "zcode-cli-oauth-"));
413
+ const callbackPath = join(temporaryDirectory, "callback.url");
414
+ const recovery = recoveryPath(home);
415
+ let previousHandler = "";
416
+ let handlerChanged = false;
417
+ let disposePromise;
418
+ const cleanup = async () => {
419
+ const current = await currentDefaultHandler(runner, options.scheme).catch(() => "");
420
+ if (handlerChanged && current === bundleId) await setDefaultHandler(runner, options.scheme, previousHandler || "none").catch(() => {});
421
+ await unregisterApp(runner, appPath);
422
+ await rm(appPath, {
423
+ recursive: true,
424
+ force: true
425
+ });
426
+ await rm(temporaryDirectory, {
427
+ recursive: true,
428
+ force: true
429
+ });
430
+ if ((await readRecovery(home))?.bundleId === bundleId) await rm(recovery, { force: true });
431
+ };
432
+ try {
433
+ previousHandler = await currentDefaultHandler(runner, options.scheme);
434
+ await mkdir(applicationsDirectory(home), { recursive: true });
435
+ await mkdir(join(home, ".zcode", "cli"), { recursive: true });
436
+ await writeFile(callbackPath, "", { mode: 384 });
437
+ await chmod(callbackPath, 384);
438
+ const compileArgs = ["-o", appPath];
439
+ for (const line of callbackAppleScript(callbackPath, options.scheme, previousHandler)) compileArgs.push("-e", line);
440
+ await checkedRun(runner, "/usr/bin/osacompile", compileArgs);
441
+ const infoPlist = join(appPath, "Contents", "Info.plist");
442
+ await checkedRun(runner, "/usr/bin/plutil", [
443
+ "-insert",
444
+ "CFBundleIdentifier",
445
+ "-string",
446
+ bundleId,
447
+ infoPlist
448
+ ]);
449
+ await checkedRun(runner, "/usr/bin/plutil", [
450
+ "-insert",
451
+ "LSUIElement",
452
+ "-bool",
453
+ "true",
454
+ infoPlist
455
+ ]);
456
+ await checkedRun(runner, "/usr/bin/plutil", [
457
+ "-insert",
458
+ "CFBundleURLTypes",
459
+ "-json",
460
+ JSON.stringify([{
461
+ CFBundleTypeRole: "Viewer",
462
+ CFBundleURLName: "ZCode CLI OAuth Callback",
463
+ CFBundleURLSchemes: [options.scheme]
464
+ }]),
465
+ infoPlist
466
+ ]);
467
+ await checkedRun(runner, "/usr/bin/codesign", [
468
+ "--force",
469
+ "--deep",
470
+ "--sign",
471
+ "-",
472
+ appPath
473
+ ]);
474
+ await checkedRun(runner, launchServicesRegister, ["-f", appPath]);
475
+ const record = {
476
+ appPath,
477
+ bundleId,
478
+ pid: process.pid,
479
+ previousHandler,
480
+ scheme: options.scheme
481
+ };
482
+ await writeFile(recovery, `${JSON.stringify(record, null, 2)}\n`, { mode: 384 });
483
+ await chmod(recovery, 384);
484
+ await setDefaultHandler(runner, options.scheme, bundleId);
485
+ handlerChanged = true;
486
+ if (await currentDefaultHandler(runner, options.scheme) !== bundleId) throw new Error(`macOS did not activate the ${options.scheme} callback handler.`);
487
+ } catch (error) {
488
+ await cleanup();
489
+ throw error;
490
+ }
491
+ return {
492
+ dispose() {
493
+ return disposePromise ??= cleanup();
494
+ },
495
+ async waitForCallback(signal, timeoutMs = defaultTimeoutMs) {
496
+ const startedAt = Date.now();
497
+ while (Date.now() - startedAt < timeoutMs) {
498
+ if (signal?.aborted) throw abortReason(signal);
499
+ const callback = await readFile(callbackPath, "utf8").catch(() => "");
500
+ if (callback.trim()) return callback.trim();
501
+ await delay(100, signal);
502
+ }
503
+ throw new Error("Authorization timed out. Please retry login.");
504
+ }
505
+ };
506
+ }
507
+ //#endregion
508
+ //#region src/zai-oauth.ts
509
+ const authorizeEndpoint = "https://chat.z.ai/api/oauth/authorize";
510
+ const clientId = "client_P8X5CMWmlaRO9gyO-KSqtg";
511
+ const redirectUri = "zcode://zai-auth/callback";
512
+ const supportedLoginFlags = /* @__PURE__ */ new Set([
513
+ "--json",
514
+ "--no-browser",
515
+ "--oauth",
516
+ "--verbose"
517
+ ]);
518
+ function classifyZaiOAuthInvocation(args) {
519
+ const positionals = args.filter((argument) => !argument.startsWith("-"));
520
+ if (positionals.length !== 1 || positionals[0] !== "login") return null;
521
+ if (args.some((argument) => argument.startsWith("-") && !supportedLoginFlags.has(argument))) return null;
522
+ return {
523
+ json: args.includes("--json"),
524
+ noBrowser: args.includes("--no-browser"),
525
+ runtimeArgs: args.filter((argument) => argument !== "--oauth")
526
+ };
527
+ }
528
+ function buildZaiAuthorizeUrl(state) {
529
+ const url = new URL(authorizeEndpoint);
530
+ url.search = new URLSearchParams({
531
+ client_id: clientId,
532
+ redirect_uri: redirectUri,
533
+ response_type: "code",
534
+ state
535
+ }).toString();
536
+ return url.toString();
537
+ }
538
+ function statesMatch(actual, expected) {
539
+ const actualBytes = Buffer.from(actual);
540
+ const expectedBytes = Buffer.from(expected);
541
+ return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
542
+ }
543
+ function safeAuthorizationError(value) {
544
+ return value.replace(/[\u0000-\u001f\u007f-\u009f]/gu, " ").slice(0, 300);
545
+ }
546
+ function parseZaiOAuthCallback(callbackUrl, expectedState) {
547
+ let url;
548
+ try {
549
+ url = new URL(callbackUrl);
550
+ } catch {
551
+ throw new Error("Z.AI returned an invalid OAuth callback URL.");
552
+ }
553
+ const path = `/${url.pathname.replace(/^\/+|\/+$/gu, "")}`;
554
+ if (url.protocol !== "zcode:" || url.hostname !== "zai-auth" || path !== "/callback") throw new Error("Z.AI returned an unexpected OAuth callback target.");
555
+ const state = url.searchParams.get("state") || "";
556
+ if (!state || !statesMatch(state, expectedState)) throw new Error("Z.AI OAuth state did not match. Please retry login.");
557
+ const authorizationError = url.searchParams.get("error_description") || url.searchParams.get("error");
558
+ if (authorizationError) throw new Error(`Z.AI authorization failed: ${safeAuthorizationError(authorizationError)}`);
559
+ const code = url.searchParams.get("code") || url.searchParams.get("authCode") || "";
560
+ if (!code) throw new Error("Z.AI OAuth callback did not include an authorization code.");
561
+ return {
562
+ callbackUrl,
563
+ code,
564
+ state
565
+ };
566
+ }
567
+ async function openBrowser(url) {
568
+ const result = await captureCommand("/usr/bin/open", [url]);
569
+ return result.code === 0 ? { opened: true } : {
570
+ opened: false,
571
+ reason: result.stderr.trim() || `open exited with status ${result.code}`
572
+ };
573
+ }
574
+ async function runZaiOAuthLogin(options) {
575
+ if ((options.platform ?? process.platform) !== "darwin") throw new Error("Z.AI browser login requires macOS for the registered zcode:// callback. Use the Z.AI Coding Plan API Key option in /login on this platform.");
576
+ const env = options.env ?? process.env;
577
+ const state = options.state ?? randomBytes(32).toString("hex");
578
+ const output = options.output ?? process.stdout;
579
+ const receiver = await (options.createReceiver ?? ((receiverOptions) => createDarwinUrlCallbackReceiver(receiverOptions)))({
580
+ env,
581
+ scheme: "zcode"
582
+ });
583
+ let disposed = false;
584
+ const dispose = async () => {
585
+ if (disposed) return;
586
+ disposed = true;
587
+ await receiver.dispose();
588
+ };
589
+ try {
590
+ const authorizeUrl = buildZaiAuthorizeUrl(state);
591
+ if (options.invocation.noBrowser) output.write(`Open this URL to sign in:\n${authorizeUrl}\nWaiting for the zcode:// callback...\n`);
592
+ else {
593
+ output.write(`Opening browser for Z.AI authorization.\nFallback URL:\n${authorizeUrl}\n`);
594
+ const result = await (options.openBrowser ?? openBrowser)(authorizeUrl);
595
+ if (!result.opened) output.write(`Browser open failed: ${result.reason ?? "unknown error"}\nOpen the fallback URL manually.\n`);
596
+ }
597
+ const callbackUrl = await receiver.waitForCallback(options.abortSignal, options.timeoutMs);
598
+ parseZaiOAuthCallback(callbackUrl, state);
599
+ await dispose();
600
+ output.write("Authorization received. Completing official ZCode setup...\n");
601
+ return await options.completeLogin({
602
+ callbackUrl,
603
+ state
604
+ }, options.invocation.runtimeArgs);
605
+ } finally {
606
+ await dispose();
607
+ }
608
+ }
609
+ //#endregion
610
+ //#region src/launcher.ts
611
+ const packageRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
612
+ const runtimePath = join(packageRoot, "vendor", "zcode.cjs");
613
+ const launcherPath = join(packageRoot, "bin", "zcode.js");
614
+ const NON_TUI_COMMANDS = /* @__PURE__ */ new Set([
615
+ "app-server",
616
+ "commands",
617
+ "doctor",
618
+ "login",
619
+ "logout",
620
+ "plugins",
621
+ "skills",
622
+ "version"
623
+ ]);
624
+ const NON_TUI_FLAGS = /* @__PURE__ */ new Set([
625
+ "-h",
626
+ "--help",
627
+ "-v",
628
+ "--version",
629
+ "-p",
630
+ "--prompt",
631
+ "--json",
632
+ "--target"
633
+ ]);
634
+ const FLAGS_WITH_VALUES = /* @__PURE__ */ new Set([
635
+ "-p",
636
+ "--prompt",
637
+ "--attach",
638
+ "--cwd",
639
+ "--disallowedTools",
640
+ "--disallowed-tools",
641
+ "--locale",
642
+ "--mode",
643
+ "--resume",
644
+ "--target"
645
+ ]);
646
+ function isTuiInvocation(args) {
647
+ if (args.some((argument) => NON_TUI_FLAGS.has(argument))) return false;
648
+ let command;
649
+ for (let index = 0; index < args.length; index += 1) {
650
+ const argument = args[index];
651
+ if (argument.startsWith("--") && argument.includes("=")) continue;
652
+ if (FLAGS_WITH_VALUES.has(argument)) {
653
+ index += 1;
654
+ continue;
655
+ }
656
+ if (!argument.startsWith("-")) {
657
+ command = argument;
658
+ break;
659
+ }
660
+ }
661
+ if (command === "tui") return true;
662
+ return command ? !NON_TUI_COMMANDS.has(command) : true;
663
+ }
664
+ function resolveNodeExecutable() {
665
+ return process.env.ZCODE_NODE?.trim() || process.execPath;
666
+ }
667
+ function normalizeLoginArgs(args) {
668
+ if (args.length === 1 && args[0] === "login") return {
669
+ args,
670
+ checkConfiguredAccess: true
671
+ };
672
+ if (args[0] === "login" && args.includes("--oauth")) return {
673
+ args: args.filter((argument) => argument !== "--oauth"),
674
+ checkConfiguredAccess: false
675
+ };
676
+ return {
677
+ args,
678
+ checkConfiguredAccess: false
679
+ };
680
+ }
681
+ function runtimeEnvironment(extra = {}) {
682
+ const env = { ...process.env };
683
+ delete env.ZCODE_CLI_OAUTH_CALLBACK_STDIN;
684
+ const merged = {
685
+ ...env,
686
+ ...extra,
687
+ ZCODE_APP_CLI_EXECUTABLE: process.execPath,
688
+ ZCODE_APP_CLI_ENTRY: launcherPath
689
+ };
690
+ return Object.fromEntries(Object.entries(merged).filter((entry) => typeof entry[1] === "string"));
691
+ }
692
+ function signalExitCode(signal) {
693
+ if (!signal) return 1;
694
+ const number = constants.signals[signal];
695
+ return typeof number === "number" ? 128 + number : 1;
696
+ }
697
+ async function waitForChild(child) {
698
+ return await new Promise((resolveExit) => {
699
+ let settled = false;
700
+ const finish = (code) => {
701
+ if (settled) return;
702
+ settled = true;
703
+ resolveExit(code);
704
+ };
705
+ child.once("error", (error) => {
706
+ console.error(`Error: ${error.message}`);
707
+ finish(1);
708
+ });
709
+ child.once("exit", (code, signal) => finish(code ?? signalExitCode(signal)));
710
+ });
711
+ }
712
+ async function runWithInheritedStdio(node, args) {
713
+ const child = spawn(node, [runtimePath, ...args], {
714
+ cwd: process.cwd(),
715
+ env: runtimeEnvironment(),
716
+ stdio: "inherit"
717
+ });
718
+ const forwardSignal = (signal) => {
719
+ if (!child.killed) child.kill(signal);
720
+ };
721
+ const onSigint = () => forwardSignal("SIGINT");
722
+ const onSigterm = () => forwardSignal("SIGTERM");
723
+ process.once("SIGINT", onSigint);
724
+ process.once("SIGTERM", onSigterm);
725
+ try {
726
+ return await waitForChild(child);
727
+ } finally {
728
+ process.off("SIGINT", onSigint);
729
+ process.off("SIGTERM", onSigterm);
730
+ }
731
+ }
732
+ async function runInNativeTerminal(node, args) {
733
+ if (!hasNative) throw new Error("zigpty has no native binding for this platform. Reinstall zcode-app-cli on a supported target.");
734
+ const wasRaw = process.stdin.isRaw ?? false;
735
+ const inputDecoder = new TextDecoder();
736
+ const pty = spawn$1(node, [runtimePath, ...args], {
737
+ cols: process.stdout.columns ?? 80,
738
+ rows: process.stdout.rows ?? 24,
739
+ cwd: process.cwd(),
740
+ env: {
741
+ ...runtimeEnvironment(),
742
+ TERM: process.env.TERM ?? "xterm-256color"
743
+ },
744
+ name: process.env.TERM ?? "xterm-256color",
745
+ encoding: null
746
+ });
747
+ const output = pty.onData((data) => process.stdout.write(data));
748
+ const onInput = (data) => {
749
+ if (pty.exitCode === null) pty.write(typeof data === "string" ? data : inputDecoder.decode(data, { stream: true }));
750
+ };
751
+ const onResize = () => {
752
+ if (pty.exitCode === null) pty.resize(process.stdout.columns ?? 80, process.stdout.rows ?? 24);
753
+ };
754
+ const onSigint = () => pty.kill("SIGINT");
755
+ const onSigterm = () => pty.kill("SIGTERM");
756
+ try {
757
+ process.stdin.setRawMode?.(true);
758
+ process.stdin.resume();
759
+ process.stdin.on("data", onInput);
760
+ process.stdout.on("resize", onResize);
761
+ process.once("SIGINT", onSigint);
762
+ process.once("SIGTERM", onSigterm);
763
+ return await pty.exited;
764
+ } finally {
765
+ output.dispose();
766
+ process.stdin.off("data", onInput);
767
+ process.stdout.off("resize", onResize);
768
+ process.off("SIGINT", onSigint);
769
+ process.off("SIGTERM", onSigterm);
770
+ process.stdin.setRawMode?.(wasRaw);
771
+ if (!wasRaw) process.stdin.pause();
772
+ pty.close();
773
+ }
774
+ }
775
+ async function completeOfficialZaiLogin(node, payload, runtimeArgs, abortSignal) {
776
+ if (abortSignal.aborted) return 130;
777
+ const child = spawn(node, [runtimePath, ...runtimeArgs], {
778
+ cwd: process.cwd(),
779
+ env: runtimeEnvironment({ ZCODE_CLI_OAUTH_CALLBACK_STDIN: "1" }),
780
+ stdio: [
781
+ "pipe",
782
+ "inherit",
783
+ "inherit"
784
+ ]
785
+ });
786
+ const onAbort = () => child.kill("SIGINT");
787
+ abortSignal.addEventListener("abort", onAbort, { once: true });
788
+ try {
789
+ child.stdin?.end(JSON.stringify(payload));
790
+ return await waitForChild(child);
791
+ } finally {
792
+ abortSignal.removeEventListener("abort", onAbort);
793
+ }
794
+ }
795
+ async function main(args) {
796
+ if (!existsSync(runtimePath)) {
797
+ console.error("ZCode runtime is missing. Reinstall the package or run `bun run sync:local` in the source checkout.");
798
+ return 1;
799
+ }
800
+ try {
801
+ await ensureUserConfig();
802
+ } catch (error) {
803
+ console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
804
+ return 1;
805
+ }
806
+ const login = normalizeLoginArgs(args);
807
+ const zaiOAuth = classifyZaiOAuthInvocation(args);
808
+ if (login.checkConfiguredAccess) {
809
+ const access = await readConfiguredModelAccess();
810
+ if (access) {
811
+ console.log(`Model access is already configured for ${access.model}; OAuth login is not required.\nConfig: ${access.configPath}\nRun \`zcode login --oauth\` to force Z.AI OAuth.`);
812
+ return 0;
813
+ }
814
+ }
815
+ const node = resolveNodeExecutable();
816
+ if (zaiOAuth) {
817
+ const abortController = new AbortController();
818
+ const cancel = () => abortController.abort(/* @__PURE__ */ new Error("Login cancelled."));
819
+ process.once("SIGINT", cancel);
820
+ process.once("SIGTERM", cancel);
821
+ try {
822
+ return await runZaiOAuthLogin({
823
+ abortSignal: abortController.signal,
824
+ completeLogin: (payload, runtimeArgs) => completeOfficialZaiLogin(node, payload, runtimeArgs, abortController.signal),
825
+ invocation: zaiOAuth,
826
+ output: zaiOAuth.json ? process.stderr : process.stdout
827
+ });
828
+ } catch (error) {
829
+ console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
830
+ return abortController.signal.aborted ? 130 : 1;
831
+ } finally {
832
+ process.off("SIGINT", cancel);
833
+ process.off("SIGTERM", cancel);
834
+ }
835
+ }
836
+ const interactive = isTuiInvocation(login.args) && process.stdin.isTTY && process.stdout.isTTY;
837
+ try {
838
+ return interactive ? await runInNativeTerminal(node, login.args) : await runWithInheritedStdio(node, login.args);
839
+ } catch (error) {
840
+ console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
841
+ return 1;
842
+ }
843
+ }
844
+ //#endregion
845
+ //#region bin/zcode.ts
846
+ process.exitCode = await main(process.argv.slice(2));
847
+ //#endregion
848
+ export {};