@seavideo/cli 0.0.0-stage → 0.3.0

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 (110) hide show
  1. package/LICENSE +12 -0
  2. package/README.md +528 -2
  3. package/dist/bin/seavideo.js +11 -0
  4. package/dist/src/atomic-write.js +14 -0
  5. package/dist/src/canvas/api.js +172 -0
  6. package/dist/src/canvas/browser.js +40 -0
  7. package/dist/src/canvas/chrome-binary.js +109 -0
  8. package/dist/src/canvas/daemon.js +264 -0
  9. package/dist/src/canvas/engine-install.js +46 -0
  10. package/dist/src/canvas/engine-log.js +9 -0
  11. package/dist/src/canvas/engine.js +99 -0
  12. package/dist/src/canvas/entry.js +16 -0
  13. package/dist/src/canvas/env-lock.js +164 -0
  14. package/dist/src/canvas/launch.js +97 -0
  15. package/dist/src/canvas/lifecycle.js +65 -0
  16. package/dist/src/canvas/names.js +61 -0
  17. package/dist/src/canvas/params.js +38 -0
  18. package/dist/src/canvas/puppeteer.js +153 -0
  19. package/dist/src/canvas/screenshot.js +23 -0
  20. package/dist/src/canvas/session-record.js +77 -0
  21. package/dist/src/canvas/team.js +97 -0
  22. package/dist/src/canvas/tool-args.js +47 -0
  23. package/dist/src/canvas/tool-session.js +165 -0
  24. package/dist/src/canvas/tool-specs.js +54 -0
  25. package/dist/src/canvas/url.js +38 -0
  26. package/dist/src/cli/args.js +16 -0
  27. package/dist/src/cli/commands/auth.js +51 -0
  28. package/dist/src/cli/commands/canvas/common.js +31 -0
  29. package/dist/src/cli/commands/canvas/engine-choice.js +41 -0
  30. package/dist/src/cli/commands/canvas/index.js +5 -0
  31. package/dist/src/cli/commands/canvas/item.js +233 -0
  32. package/dist/src/cli/commands/canvas/list.js +168 -0
  33. package/dist/src/cli/commands/canvas/register.js +106 -0
  34. package/dist/src/cli/commands/canvas/render.js +229 -0
  35. package/dist/src/cli/commands/canvas/screenshot.js +52 -0
  36. package/dist/src/cli/commands/canvas/session.js +249 -0
  37. package/dist/src/cli/commands/canvas/teams.js +142 -0
  38. package/dist/src/cli/commands/config.js +74 -0
  39. package/dist/src/cli/commands/doctor.js +261 -0
  40. package/dist/src/cli/commands/engine.js +96 -0
  41. package/dist/src/cli/commands/env/create.js +160 -0
  42. package/dist/src/cli/commands/env/fields.js +26 -0
  43. package/dist/src/cli/commands/env/index.js +4 -0
  44. package/dist/src/cli/commands/env/list.js +44 -0
  45. package/dist/src/cli/commands/env/mutate.js +118 -0
  46. package/dist/src/cli/commands/login/flow-token.js +41 -0
  47. package/dist/src/cli/commands/login/index.js +12 -0
  48. package/dist/src/cli/commands/login/oauth.js +69 -0
  49. package/dist/src/cli/commands/login/save.js +26 -0
  50. package/dist/src/cli/commands/logout.js +92 -0
  51. package/dist/src/cli/commands/skill.js +185 -0
  52. package/dist/src/cli/commands/tool.js +279 -0
  53. package/dist/src/cli/commands/update.js +117 -0
  54. package/dist/src/cli/commands/wallet.js +69 -0
  55. package/dist/src/cli/commands/whoami.js +147 -0
  56. package/dist/src/cli/context.js +41 -0
  57. package/dist/src/cli/credential.js +93 -0
  58. package/dist/src/cli/elapsed.js +25 -0
  59. package/dist/src/cli/failure-screenshot.js +24 -0
  60. package/dist/src/cli/flags.js +1 -0
  61. package/dist/src/cli/hints.js +7 -0
  62. package/dist/src/cli/main.js +44 -0
  63. package/dist/src/cli/output-error.js +23 -0
  64. package/dist/src/cli/output.js +47 -0
  65. package/dist/src/cli/program.js +261 -0
  66. package/dist/src/cli/run.js +11 -0
  67. package/dist/src/cli/session.js +63 -0
  68. package/dist/src/config/base-url.js +26 -0
  69. package/dist/src/config/credential-vault.js +115 -0
  70. package/dist/src/config/dotenv.js +59 -0
  71. package/dist/src/config/envname.js +41 -0
  72. package/dist/src/config/paths.js +22 -0
  73. package/dist/src/config/preset-schema.js +67 -0
  74. package/dist/src/config/presets.js +132 -0
  75. package/dist/src/config/resolve.js +41 -0
  76. package/dist/src/config/secret-key.js +63 -0
  77. package/dist/src/config/store-schema.js +143 -0
  78. package/dist/src/config/store.js +273 -0
  79. package/dist/src/config/vault-crypto.js +44 -0
  80. package/dist/src/deps.js +191 -0
  81. package/dist/src/deps.types.js +1 -0
  82. package/dist/src/errors.js +24 -0
  83. package/dist/src/fs-retry.js +34 -0
  84. package/dist/src/i18n.js +1214 -0
  85. package/dist/src/loopback.js +134 -0
  86. package/dist/src/sdk/auth.js +20 -0
  87. package/dist/src/sdk/credential-expiry.js +67 -0
  88. package/dist/src/sdk/discovery.js +90 -0
  89. package/dist/src/sdk/http.js +98 -0
  90. package/dist/src/sdk/identity.js +17 -0
  91. package/dist/src/sdk/jwks.js +119 -0
  92. package/dist/src/sdk/oauth-protocol.js +226 -0
  93. package/dist/src/sdk/oauth.js +179 -0
  94. package/dist/src/sdk/provider/cn.js +34 -0
  95. package/dist/src/sdk/provider/index.js +16 -0
  96. package/dist/src/sdk/provider/oversea.js +41 -0
  97. package/dist/src/sdk/provider/types.js +1 -0
  98. package/dist/src/sdk/refresh.js +66 -0
  99. package/dist/src/semver.js +89 -0
  100. package/dist/src/skill/api.js +176 -0
  101. package/dist/src/text.js +3 -0
  102. package/dist/src/types.js +1 -0
  103. package/dist/src/update/check-cache.js +56 -0
  104. package/dist/src/update/install-layout.js +79 -0
  105. package/dist/src/update/notify.js +15 -0
  106. package/dist/src/update/npm-install.js +64 -0
  107. package/dist/src/update/passive.js +53 -0
  108. package/dist/src/update/registry.js +59 -0
  109. package/dist/src/wallet/api.js +107 -0
  110. package/package.json +67 -4
@@ -0,0 +1,23 @@
1
+ import { join } from 'node:path';
2
+ const MODE_DIR = 0o700;
3
+ const MODE_FILE = 0o600;
4
+ function safePart(value) {
5
+ return value.replace(/[^A-Za-z0-9._-]/g, '_');
6
+ }
7
+ export function screenshotName(at, canvasId, reason) {
8
+ const stamp = at.toISOString().replace(/:/g, '-').slice(0, 19);
9
+ return `${stamp}-${safePart(canvasId)}-${safePart(reason)}.png`;
10
+ }
11
+ export async function saveScreenshot(deps, input) {
12
+ const path = join(deps.dir, screenshotName(deps.clock(), input.canvasId, input.reason));
13
+ let result;
14
+ try {
15
+ await deps.fs.mkdir(deps.dir, { recursive: true, mode: MODE_DIR });
16
+ await deps.fs.writeFile(path, input.png, { mode: MODE_FILE });
17
+ result = path;
18
+ }
19
+ catch {
20
+ result = null;
21
+ }
22
+ return result;
23
+ }
@@ -0,0 +1,77 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { writeFileAtomic } from "../atomic-write.js";
3
+ export function sessionFingerprint(input) {
4
+ const joined = [input.env, input.id, input.flowWebBaseUrl, input.flowCredential].join('\n');
5
+ return createHash('sha256').update(joined).digest('hex').slice(0, 32);
6
+ }
7
+ export function parseSessionRecord(text) {
8
+ let raw = null;
9
+ try {
10
+ raw = JSON.parse(text);
11
+ }
12
+ catch {
13
+ }
14
+ let result = null;
15
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
16
+ result = null;
17
+ }
18
+ else {
19
+ const o = raw;
20
+ const id = o['id'];
21
+ const port = o['port'];
22
+ const pid = o['pid'];
23
+ const at = o['at'];
24
+ const usedAt = o['usedAt'];
25
+ const fingerprint = o['fingerprint'];
26
+ if (typeof id !== 'string' || id === '') {
27
+ result = null;
28
+ }
29
+ else if (typeof port !== 'number' || !Number.isInteger(port) || port <= 0) {
30
+ result = null;
31
+ }
32
+ else if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) {
33
+ result = null;
34
+ }
35
+ else if (typeof at !== 'string' || Number.isNaN(Date.parse(at))) {
36
+ result = null;
37
+ }
38
+ else if (typeof usedAt !== 'string' || Number.isNaN(Date.parse(usedAt))) {
39
+ result = null;
40
+ }
41
+ else if (typeof fingerprint !== 'string' || fingerprint === '') {
42
+ result = null;
43
+ }
44
+ else {
45
+ result = { id, port, pid, at, usedAt, fingerprint };
46
+ }
47
+ }
48
+ return result;
49
+ }
50
+ export async function readSessionRecord(file, deps) {
51
+ let result;
52
+ try {
53
+ result = parseSessionRecord(await deps.fs.readFile(file, 'utf8'));
54
+ }
55
+ catch {
56
+ result = null;
57
+ }
58
+ return result;
59
+ }
60
+ export async function writeSessionRecord(file, record, deps) {
61
+ await writeFileAtomic(deps, file, `${JSON.stringify(record, null, 2)}\n`, 0o600);
62
+ }
63
+ export async function clearSessionRecord(file, deps) {
64
+ try {
65
+ await deps.fs.unlink(file);
66
+ }
67
+ catch (err) {
68
+ if (err.code !== 'ENOENT')
69
+ throw err;
70
+ }
71
+ }
72
+ export async function touchSessionRecord(file, usedAt, deps) {
73
+ const current = await readSessionRecord(file, deps);
74
+ if (current === null)
75
+ return;
76
+ await writeSessionRecord(file, { ...current, usedAt }, deps);
77
+ }
@@ -0,0 +1,97 @@
1
+ import { CliError } from "../errors.js";
2
+ import { t } from "../i18n.js";
3
+ import { CANVAS_SUCCESS_CODE, requestJson } from "../sdk/http.js";
4
+ import { getProvider } from "../sdk/provider/index.js";
5
+ export const TEAM_PROJECT_PAGE_SIZE = 100;
6
+ function str(v) {
7
+ return typeof v === 'string' && v !== '' ? v : null;
8
+ }
9
+ function num(v) {
10
+ return typeof v === 'number' ? v : null;
11
+ }
12
+ function normalizeTeam(raw, envMap) {
13
+ const x = (raw ?? {});
14
+ const id = str(x['id']);
15
+ if (id === null)
16
+ throw new CliError('server', t('canvas.malformedTeam', {}, envMap));
17
+ return {
18
+ id,
19
+ name: str(x['name']) ?? '',
20
+ role: str(x['member_role']),
21
+ createdAt: str(x['created_at']) ?? str(x['createdAt']),
22
+ projectCount: num(x['project_count']),
23
+ canvasCount: num(x['graph_count']),
24
+ };
25
+ }
26
+ function normalizeProject(raw, teamId, envMap) {
27
+ const x = (raw ?? {});
28
+ const id = str(x['id']);
29
+ if (id === null)
30
+ throw new CliError('server', t('canvas.malformedProject', {}, envMap));
31
+ return {
32
+ id,
33
+ name: str(x['name']) ?? '',
34
+ teamId: str(x['teamId']) ?? teamId,
35
+ canvasCount: num(x['graphCount']) ?? num(x['graph_count']),
36
+ };
37
+ }
38
+ export function createTeamApi(deps, config, credential, flowToken) {
39
+ const provider = getProvider(config.platform);
40
+ const accountHttp = {
41
+ fetch: deps.fetch,
42
+ env: deps.env,
43
+ baseUrl: config.seavideoBaseUrl,
44
+ };
45
+ const accountHeaders = provider.authHeaders({ value: credential.value, source: 'config' });
46
+ const flowHttp = {
47
+ fetch: deps.fetch,
48
+ env: deps.env,
49
+ baseUrl: config.flowApiBaseUrl,
50
+ };
51
+ const flowHeaders = { authorization: `Bearer ${flowToken}` };
52
+ return {
53
+ async teams() {
54
+ const data = await requestJson(accountHttp, {
55
+ method: 'GET',
56
+ path: '/api/craft/v1/teams',
57
+ headers: accountHeaders,
58
+ });
59
+ const raw = Array.isArray(data?.items) ? data.items : [];
60
+ return raw.map((x) => normalizeTeam(x, deps.env));
61
+ },
62
+ async canvases(teamId, page, pageSize) {
63
+ const data = await requestJson(flowHttp, {
64
+ method: 'POST',
65
+ path: '/api/team-projects/list',
66
+ headers: flowHeaders,
67
+ body: { team_id: teamId, page, page_size: pageSize, keyword: null, is_trash: false },
68
+ successCode: CANVAS_SUCCESS_CODE,
69
+ });
70
+ const rawProjects = Array.isArray(data?.data) ? data.data : [];
71
+ const projects = [];
72
+ const canvases = [];
73
+ for (const raw of rawProjects) {
74
+ const project = normalizeProject(raw, teamId, deps.env);
75
+ projects.push(project);
76
+ const infos = raw['graph_info'];
77
+ if (!Array.isArray(infos))
78
+ continue;
79
+ for (const info of infos) {
80
+ const g = (info ?? {});
81
+ const id = str(g['id']);
82
+ if (id === null)
83
+ continue;
84
+ canvases.push({
85
+ id,
86
+ name: str(g['name']) ?? '',
87
+ projectId: project.id,
88
+ projectName: project.name,
89
+ });
90
+ }
91
+ }
92
+ const total = num(data?.pagination?.total) ?? projects.length;
93
+ const pages = num(data?.pagination?.total_pages) ?? 1;
94
+ return { projects, canvases, total, pages };
95
+ },
96
+ };
97
+ }
@@ -0,0 +1,47 @@
1
+ import { Ajv } from 'ajv';
2
+ import { CliError, errorMessage } from "../errors.js";
3
+ import { t } from "../i18n.js";
4
+ const ajv = new Ajv({ strict: true, allErrors: true });
5
+ const compiled = new WeakMap();
6
+ function validatorFor(schema, envMap) {
7
+ const cached = compiled.get(schema);
8
+ let result;
9
+ if (cached === undefined) {
10
+ try {
11
+ result = ajv.compile(schema);
12
+ }
13
+ catch (err) {
14
+ throw new CliError('server', t('tool.badSchema', {}, envMap), {
15
+ detail: errorMessage(err),
16
+ });
17
+ }
18
+ compiled.set(schema, result);
19
+ }
20
+ else {
21
+ result = cached;
22
+ }
23
+ return result;
24
+ }
25
+ export function validateToolArgs(tool, args, envMap) {
26
+ const validate = validatorFor(tool.inputSchema, envMap);
27
+ if (validate(args))
28
+ return;
29
+ const problems = formatErrors(validate.errors);
30
+ throw new CliError('usage', t('tool.invalidArgs', { name: tool.name }, envMap), {
31
+ detail: problems,
32
+ });
33
+ }
34
+ function formatErrors(errors) {
35
+ const list = errors;
36
+ return list
37
+ .map((err) => {
38
+ const where = toPointer(err.instancePath);
39
+ const missing = err.params['missingProperty'];
40
+ const suffix = typeof missing === 'string' ? `${where}/${missing}` : where;
41
+ return `${suffix === '' ? '(root)' : suffix}: ${err.message}`;
42
+ })
43
+ .join('\n');
44
+ }
45
+ function toPointer(instancePath) {
46
+ return instancePath.replace(/\/(\d+)/gu, '[$1]');
47
+ }
@@ -0,0 +1,165 @@
1
+ import { CliError } from "../errors.js";
2
+ import { t } from "../i18n.js";
3
+ export const DEFAULT_TOOL_TIMEOUT_MS = 30_000;
4
+ export function errorTextOf(result) {
5
+ let found = null;
6
+ for (const block of result.content) {
7
+ const text = block['text'];
8
+ if (found === null && typeof text === 'string' && text.trim() !== '')
9
+ found = text.trim();
10
+ else {
11
+ }
12
+ }
13
+ return found;
14
+ }
15
+ export function normalizeDefinition(raw, envMap) {
16
+ const o = (raw ?? {});
17
+ const name = o['name'];
18
+ if (typeof name !== 'string' || name === '') {
19
+ throw new CliError('server', t('tool.malformed', {}, envMap));
20
+ }
21
+ const description = typeof o['description'] === 'string' ? o['description'] : '';
22
+ return { name, description, inputSchema: normalizeSchema(o['inputSchema'], envMap) };
23
+ }
24
+ function normalizeSchema(raw, envMap) {
25
+ let schema;
26
+ if (raw === undefined || raw === null) {
27
+ schema = { type: 'object' };
28
+ }
29
+ else if (typeof raw === 'object') {
30
+ schema = raw;
31
+ }
32
+ else if (typeof raw === 'string') {
33
+ let parsed;
34
+ try {
35
+ parsed = JSON.parse(raw);
36
+ }
37
+ catch {
38
+ throw new CliError('server', t('tool.badSchema', {}, envMap));
39
+ }
40
+ if (typeof parsed === 'object' && parsed !== null) {
41
+ schema = parsed;
42
+ }
43
+ else {
44
+ throw new CliError('server', t('tool.badSchema', {}, envMap));
45
+ }
46
+ }
47
+ else {
48
+ throw new CliError('server', t('tool.badSchema', {}, envMap));
49
+ }
50
+ return schema;
51
+ }
52
+ export function normalizeResult(raw) {
53
+ let value = raw;
54
+ let result = null;
55
+ if (typeof value === 'string') {
56
+ try {
57
+ value = JSON.parse(value);
58
+ }
59
+ catch {
60
+ result = { content: [{ type: 'text', text: value }], isError: false };
61
+ }
62
+ }
63
+ else {
64
+ }
65
+ if (result === null) {
66
+ if (value === null || value === undefined) {
67
+ result = { content: [], isError: false };
68
+ }
69
+ else if (typeof value !== 'object') {
70
+ result = { content: [{ type: 'text', text: String(value) }], isError: false };
71
+ }
72
+ else {
73
+ const o = value;
74
+ const content = Array.isArray(o['content']) ? o['content'] : [];
75
+ const isError = o['isError'] === true;
76
+ result = isError ? { content, isError, errorSource: 'page' } : { content, isError };
77
+ if (o['structuredContent'] !== undefined)
78
+ result.structuredContent = o['structuredContent'];
79
+ else {
80
+ }
81
+ }
82
+ }
83
+ else {
84
+ }
85
+ return result;
86
+ }
87
+ export function classifyThrow(err, name, envMap) {
88
+ const message = err instanceof Error ? err.message : String(err);
89
+ let result;
90
+ if (message.includes(NOT_READY_MARKER)) {
91
+ result = new CliError('server', t('tool.notReady', { name }, envMap));
92
+ }
93
+ else if (message.includes('NotFoundError')) {
94
+ result = new CliError('usage', t('tool.notFound', { name }, envMap), {
95
+ detail: t('tool.notFoundDetail', {}, envMap),
96
+ });
97
+ }
98
+ else if (isSchemaRejection(message)) {
99
+ result = new CliError('usage', t('tool.invalidArgs', { name }, envMap), {
100
+ detail: message,
101
+ });
102
+ }
103
+ else {
104
+ result = new CliError('server', t('tool.callFailed', { name }, envMap), { detail: message });
105
+ }
106
+ return result;
107
+ }
108
+ export const NOT_READY_MARKER = 'SEAVIDEO_NOT_READY';
109
+ const SCHEMA_REJECTION_HINTS = ['invalid input', 'missing required', 'must be'];
110
+ function isSchemaRejection(message) {
111
+ return SCHEMA_REJECTION_HINTS.some((hint) => message.includes(hint));
112
+ }
113
+ export function createCanvasToolSession(deps, evaluate) {
114
+ const envMap = deps.env;
115
+ return {
116
+ async listTools() {
117
+ const raw = await evaluate(LIST_TOOLS_EXPR);
118
+ if (!Array.isArray(raw)) {
119
+ throw new CliError('server', t('tool.malformedList', {}, envMap));
120
+ }
121
+ return raw.map((item) => normalizeDefinition(item, envMap));
122
+ },
123
+ async callTool(name, args, timeoutMs = DEFAULT_TOOL_TIMEOUT_MS) {
124
+ return withTimeout(deps, timeoutMs, name, async () => {
125
+ try {
126
+ return normalizeResult(await evaluate(CALL_TOOL_EXPR(name, args)));
127
+ }
128
+ catch (err) {
129
+ throw classifyThrow(err, name, envMap);
130
+ }
131
+ });
132
+ },
133
+ };
134
+ }
135
+ async function withTimeout(deps, timeoutMs, name, run) {
136
+ let timer;
137
+ const timeout = new Promise((_, reject) => {
138
+ timer = setTimeout(() => {
139
+ reject(new CliError('timeout', t('tool.timeout', { name, ms: timeoutMs }, deps.env), {
140
+ detail: t('tool.timeoutDetail', {}, deps.env),
141
+ }));
142
+ }, timeoutMs);
143
+ });
144
+ try {
145
+ return await Promise.race([run(), timeout]);
146
+ }
147
+ finally {
148
+ clearTimeout(timer);
149
+ }
150
+ }
151
+ const LIST_TOOLS_EXPR = `(async () => {
152
+ const mc = document.modelContext;
153
+ if (!mc) return [];
154
+ const tools = await mc.getTools();
155
+ return tools.map(t => ({ name: t.name, description: t.description, inputSchema: t.inputSchema }));
156
+ })()`;
157
+ function CALL_TOOL_EXPR(name, args) {
158
+ return `(async () => {
159
+ const mc = document.modelContext;
160
+ if (!mc || typeof mc.executeTool !== 'function') {
161
+ throw new Error('${NOT_READY_MARKER}: modelContext.executeTool is unavailable');
162
+ }
163
+ return await mc.executeTool(${JSON.stringify(name)}, ${JSON.stringify(args)});
164
+ })()`;
165
+ }
@@ -0,0 +1,54 @@
1
+ import { join } from 'node:path';
2
+ import { writeFileAtomic } from "../atomic-write.js";
3
+ import { withRetry } from "../fs-retry.js";
4
+ const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?=\.|$)/iu;
5
+ export function specFileName(name) {
6
+ const escaped = name.replace(/[^A-Za-z0-9._-]/gu, (ch) => `%${ch.codePointAt(0).toString(16)}`);
7
+ return `${WINDOWS_RESERVED.test(escaped) ? `_${escaped}` : escaped}.json`;
8
+ }
9
+ export async function writeToolSpecs(deps, dir, tools) {
10
+ await withRetry(deps, () => deps.fs.rm(dir, { recursive: true, force: true }));
11
+ await deps.fs.mkdir(dir, { recursive: true, mode: 0o700 });
12
+ for (const tool of tools) {
13
+ await writeFileAtomic(deps, join(dir, specFileName(tool.name)), `${JSON.stringify(tool, null, 2)}\n`, 0o600);
14
+ }
15
+ }
16
+ export async function readToolSpecs(fs, dir) {
17
+ let result;
18
+ try {
19
+ const names = await fs.readdir(dir);
20
+ result = names.length === 0 ? null : await readAll(fs, dir, names);
21
+ }
22
+ catch {
23
+ result = null;
24
+ }
25
+ return result;
26
+ }
27
+ async function readAll(fs, dir, names) {
28
+ const result = [];
29
+ for (const file of [...names].sort())
30
+ result.push(await readOne(fs, join(dir, file)));
31
+ return result;
32
+ }
33
+ async function readOne(fs, path) {
34
+ const parsed = JSON.parse(await fs.readFile(path, 'utf8'));
35
+ const name = parsed['name'];
36
+ const description = parsed['description'];
37
+ const inputSchema = parsed['inputSchema'];
38
+ if (typeof name !== 'string' || name === '')
39
+ throw new Error(`bad tool spec: ${path}`);
40
+ return {
41
+ name,
42
+ description: typeof description === 'string' ? description : '',
43
+ inputSchema: typeof inputSchema === 'object' && inputSchema !== null
44
+ ? inputSchema
45
+ : { type: 'object' },
46
+ };
47
+ }
48
+ export async function clearToolSpecs(fs, dir) {
49
+ try {
50
+ await fs.rm(dir, { recursive: true, force: true });
51
+ }
52
+ catch {
53
+ }
54
+ }
@@ -0,0 +1,38 @@
1
+ import { CliError } from "../errors.js";
2
+ import { t } from "../i18n.js";
3
+ function trimSlash(url) {
4
+ return url.replace(/\/+$/, '');
5
+ }
6
+ export function requireFlowCredential(config, envMap = process.env) {
7
+ const token = config.flowCredential?.value;
8
+ if (token === undefined) {
9
+ throw new CliError('config', t('credential.flowMissing', { env: config.env }, envMap), {
10
+ detail: t('credential.flowMissingDetail', {}, envMap),
11
+ });
12
+ }
13
+ return token;
14
+ }
15
+ function assertGraphId(graphId, envMap) {
16
+ if (graphId === '') {
17
+ throw new CliError('usage', t('canvas.emptyGraphId', {}, envMap));
18
+ }
19
+ }
20
+ export function buildLoadUrl(config, graphId, envMap = process.env) {
21
+ assertGraphId(graphId, envMap);
22
+ return `${trimSlash(config.flowWebBaseUrl)}/workflow/${graphId}?token=${encodeURIComponent(requireFlowCredential(config, envMap))}`;
23
+ }
24
+ export function buildCanvasUrl(config, entry, graphId, envMap = process.env) {
25
+ let result;
26
+ if (entry === 'seaflow') {
27
+ result = buildLoadUrl(config, graphId, envMap);
28
+ }
29
+ else {
30
+ assertGraphId(graphId, envMap);
31
+ const inner = encodeURIComponent(`/workflow/${graphId}`);
32
+ result = `${trimSlash(config.seavideoBaseUrl)}/apps/seaflow/standalone?redirect=${inner}`;
33
+ }
34
+ return result;
35
+ }
36
+ export function maskUrlCredential(url) {
37
+ return url.replace(/([?&]token=)[^&#]*/gi, '$1***');
38
+ }
@@ -0,0 +1,16 @@
1
+ import { CliError } from "../errors.js";
2
+ import { t } from "../i18n.js";
3
+ export function parsePositiveInt(raw, field, envMap) {
4
+ if (!/^\d+$/.test(raw)) {
5
+ throw new CliError('usage', t('args.notPositiveInt', { field, value: raw }, envMap));
6
+ }
7
+ const n = Number(raw);
8
+ if (n < 1) {
9
+ throw new CliError('usage', t('args.notPositiveInt', { field, value: raw }, envMap));
10
+ }
11
+ return n;
12
+ }
13
+ export function pageInfoOf(total, page, pageSize) {
14
+ const pages = Math.max(1, Math.ceil(total / pageSize));
15
+ return { total, page, pageSize, pages, next: page < pages ? page + 1 : null };
16
+ }
@@ -0,0 +1,51 @@
1
+ import { style } from "../output.js";
2
+ import { hasNoCurrentEnv, loadEnv } from "../context.js";
3
+ import { t } from "../../i18n.js";
4
+ import { credentialUnrecoverable } from "../../sdk/credential-expiry.js";
5
+ export async function authStatusCommand(ctx, options) {
6
+ let result;
7
+ if (await hasNoCurrentEnv(ctx)) {
8
+ reportNoEnv(ctx, options);
9
+ result = 1;
10
+ }
11
+ else {
12
+ result = await reportStatus(ctx, options);
13
+ }
14
+ return result;
15
+ }
16
+ function reportNoEnv(ctx, options) {
17
+ const { deps } = ctx;
18
+ if (options.json === true) {
19
+ deps.stdout(`${JSON.stringify({ status: 'offline' }, null, 2)}\n`);
20
+ }
21
+ else {
22
+ deps.stdout(`${style.fail('✗')} ${t('auth.status.noEnv', {}, deps.env)}\n`);
23
+ deps.stderr(`${style.dim(` ${t('auth.status.noEnvDetail', {}, deps.env)}`)}\n`);
24
+ }
25
+ }
26
+ async function reportStatus(ctx, options) {
27
+ const { deps } = ctx;
28
+ const config = await loadEnv(ctx);
29
+ const env = config.env;
30
+ const credential = config.flowCredential;
31
+ const loggedIn = credential !== null &&
32
+ !credentialUnrecoverable(credential.value, credential.refreshToken, deps.clock().getTime());
33
+ let result;
34
+ if (options.json === true) {
35
+ deps.stdout(`${JSON.stringify({
36
+ status: loggedIn ? 'online' : 'offline',
37
+ env,
38
+ }, null, 2)}\n`);
39
+ result = loggedIn ? 0 : 1;
40
+ }
41
+ else if (!loggedIn) {
42
+ deps.stdout(`${style.fail('✗')} ${t('auth.status.notLoggedIn', { env }, deps.env)}\n`);
43
+ deps.stderr(`${style.dim(` ${t('auth.status.noCredential', { env }, deps.env)}`)}\n`);
44
+ result = 1;
45
+ }
46
+ else {
47
+ deps.stdout(`${style.ok('✓')} ${t('auth.status.loggedIn', { env }, deps.env)}\n`);
48
+ result = 0;
49
+ }
50
+ return result;
51
+ }
@@ -0,0 +1,31 @@
1
+ import { CliError } from "../../../errors.js";
2
+ import { t } from "../../../i18n.js";
3
+ import { createCanvasApi } from "../../../canvas/api.js";
4
+ import { requireSpace } from "../../../canvas/entry.js";
5
+ import { resolveFlowCredential } from "../../credential.js";
6
+ import { loadEnv } from "../../context.js";
7
+ export async function apiOf(ctx) {
8
+ const { deps } = ctx;
9
+ const loaded = await loadEnv(ctx);
10
+ const { token, config } = await resolveFlowCredential(ctx, loaded);
11
+ return { api: createCanvasApi(deps, config, token), config, flowToken: token };
12
+ }
13
+ export function assertSpace(ctx, projectId) {
14
+ const space = projectId === undefined ? 'personal' : 'team';
15
+ requireSpace(ctx.entry, space, ctx.deps.env);
16
+ return space;
17
+ }
18
+ export function requireAccountCredential(config, envMap) {
19
+ const credential = config.credential;
20
+ if (credential === null) {
21
+ throw new CliError('config', t('canvas.noCredentialForTeams', { env: config.env }, envMap), {
22
+ detail: t('canvas.noCredentialForTeamsDetail', {}, envMap),
23
+ });
24
+ }
25
+ return credential;
26
+ }
27
+ export function accountOf(config, flowToken) {
28
+ const credential = config.credential;
29
+ return credential === null ? null : { credential, flowToken };
30
+ }
31
+ export const MAX_ALL_PAGES = 200;
@@ -0,0 +1,41 @@
1
+ import { CliError } from "../../../errors.js";
2
+ import { detectCanvasEngine, ENGINE_PATH_ENV } from "../../../canvas/engine.js";
3
+ import { findSystemChrome } from "../../../canvas/chrome-binary.js";
4
+ import { t } from "../../../i18n.js";
5
+ import { cmdPrefix } from "../../hints.js";
6
+ export async function resolveEnginePath(ctx, headful) {
7
+ return headful ? requireSystemChrome(ctx) : requireHeadlessEngine(ctx);
8
+ }
9
+ async function requireHeadlessEngine(ctx) {
10
+ const engine = await detectCanvasEngine(ctx.deps);
11
+ if (!engine.found) {
12
+ throw new CliError('config', t('canvas.engineMissing', {}, ctx.deps.env), {
13
+ detail: t('doctor.engineInstallHint', {}, ctx.deps.env),
14
+ });
15
+ }
16
+ return engine.path;
17
+ }
18
+ async function requireSystemChrome(ctx) {
19
+ const override = ctx.deps.env[ENGINE_PATH_ENV];
20
+ let result;
21
+ if (override !== undefined && override !== '') {
22
+ result = override;
23
+ }
24
+ else {
25
+ const found = await findSystemChrome(ctx.deps);
26
+ if (found === null) {
27
+ const prefix = cmdPrefix(ctx);
28
+ throw new CliError('config', t('canvas.headfulChromeMissing', {}, ctx.deps.env), {
29
+ detail: t('canvas.headfulChromeMissingDetail', {
30
+ env: ENGINE_PATH_ENV,
31
+ useWithoutShow: `${prefix}canvas use <id>`,
32
+ engineInstall: `${prefix}engine install`,
33
+ }, ctx.deps.env),
34
+ });
35
+ }
36
+ else {
37
+ result = found;
38
+ }
39
+ }
40
+ return result;
41
+ }
@@ -0,0 +1,5 @@
1
+ export { canvasFolderListCommand, canvasListCommand } from "./list.js";
2
+ export { canvasProjectListCommand, canvasTeamListCommand, } from "./teams.js";
3
+ export { canvasCreateCommand, canvasDeleteCommand, canvasGetCommand, canvasUrlCommand, } from "./item.js";
4
+ export { canvasCloseCommand, canvasUseCommand, } from "./session.js";
5
+ export { canvasScreenshotCommand } from "./screenshot.js";