@genspark/cli 1.15.4-beta.0 → 1.15.5

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 (65) hide show
  1. package/README.md +118 -12
  2. package/dist/acp-serve.d.ts +2 -2
  3. package/dist/acp-serve.d.ts.map +1 -1
  4. package/dist/acp-serve.js +7 -2
  5. package/dist/acp-serve.js.map +1 -1
  6. package/dist/client.d.ts +16 -0
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +52 -12
  9. package/dist/client.js.map +1 -1
  10. package/dist/commands/aidrive-contract.generated.d.ts.map +1 -1
  11. package/dist/commands/aidrive-contract.generated.js +62 -9
  12. package/dist/commands/aidrive-contract.generated.js.map +1 -1
  13. package/dist/commands/developer-input.d.ts +1 -1
  14. package/dist/commands/developer-input.d.ts.map +1 -1
  15. package/dist/commands/developer-input.js +14 -10
  16. package/dist/commands/developer-input.js.map +1 -1
  17. package/dist/commands/sb-box-session.d.ts +7 -6
  18. package/dist/commands/sb-box-session.d.ts.map +1 -1
  19. package/dist/commands/sb-box-session.js +21 -41
  20. package/dist/commands/sb-box-session.js.map +1 -1
  21. package/dist/commands/task-status-follow.d.ts +9 -0
  22. package/dist/commands/task-status-follow.d.ts.map +1 -1
  23. package/dist/commands/task-status-follow.js +24 -4
  24. package/dist/commands/task-status-follow.js.map +1 -1
  25. package/dist/commands/tts-stream.d.ts +68 -0
  26. package/dist/commands/tts-stream.d.ts.map +1 -0
  27. package/dist/commands/tts-stream.js +291 -0
  28. package/dist/commands/tts-stream.js.map +1 -0
  29. package/dist/confirm.d.ts.map +1 -1
  30. package/dist/confirm.js +18 -1
  31. package/dist/confirm.js.map +1 -1
  32. package/dist/humanApproval.d.ts +48 -0
  33. package/dist/humanApproval.d.ts.map +1 -0
  34. package/dist/humanApproval.js +86 -0
  35. package/dist/humanApproval.js.map +1 -0
  36. package/dist/index.js +169 -37
  37. package/dist/index.js.map +1 -1
  38. package/dist/mediaSummary.d.ts.map +1 -1
  39. package/dist/mediaSummary.js +4 -1
  40. package/dist/mediaSummary.js.map +1 -1
  41. package/dist/task-shim.d.ts +11 -2
  42. package/dist/task-shim.d.ts.map +1 -1
  43. package/dist/task-shim.js +21 -2
  44. package/dist/task-shim.js.map +1 -1
  45. package/docs/skills.md +5 -4
  46. package/gated-skills/gsk-issue/SKILL.md +50 -0
  47. package/gated-skills/gsk-m365-apps/SKILL.md +197 -0
  48. package/gated-skills/gsk-m365-apps/references/add-genspark-ai.md +399 -0
  49. package/gated-skills/gsk-m365-apps/scripts/install-genspark-connector.mjs +548 -0
  50. package/gated-skills/gsk-m365-apps/scripts/sync-microsoft-guidance.mjs +557 -0
  51. package/package.json +2 -1
  52. package/skills/gsk-aidrive/SKILL.md +52 -480
  53. package/skills/gsk-aidrive/command-reference.md +550 -0
  54. package/skills/gsk-connector/SKILL.md +5 -3
  55. package/skills/gsk-get-service-url/SKILL.md +1 -1
  56. package/skills/gsk-gmail/SKILL.md +17 -17
  57. package/skills/gsk-google-calendar/SKILL.md +3 -3
  58. package/skills/gsk-image-generation/SKILL.md +6 -3
  59. package/skills/gsk-outlook-calendar/SKILL.md +1 -1
  60. package/skills/gsk-phone-call/SKILL.md +33 -13
  61. package/skills/gsk-second-brain/SKILL.md +15 -16
  62. package/skills/gsk-shared/SKILL.md +1 -1
  63. package/skills/gsk-slack/SKILL.md +4 -1
  64. package/skills/gsk-team-brain/SKILL.md +208 -0
  65. package/skills/gsk-video-generation/SKILL.md +4 -4
@@ -0,0 +1,557 @@
1
+ #!/usr/bin/env node
2
+ // Fetch Microsoft's current agent guidance for managed apps (Copilot Managed Runtime) into a local
3
+ // cache and print where it is, as one JSON line.
4
+ //
5
+ // The guidance is Microsoft's MIT-licensed agent plugin, github.com/microsoft/Copilot-Managed-Runtime,
6
+ // plugins/copilot-managed-runtime (skills/, shared/, AGENTS.md, plugin.json). (Until 2026-11-05 it
7
+ // lived in microsoft/Managed-Apps, plugins/microsoft-managed-apps; that repository is archived.)
8
+ // Microsoft changes it every few days, so the gsk-m365-apps skill no longer copies it: it keeps only what is Genspark's
9
+ // and reads Microsoft's steps from here, at the latest commit.
10
+ //
11
+ // node sync-microsoft-guidance.mjs [--ref <branch|tag|sha>] [--max-age-hours <n>] [--offline] [--force]
12
+ //
13
+ // Output: {"path": ".../<commit>", "version": "2.1.8", "commit": "<sha>", "ref": "main",
14
+ // "fetched_at": "...", "stale": false, "cached": true|false, "cli_latest": "0.33.0", ...}
15
+ //
16
+ // - Network: api.github.com (resolve the ref), codeload.github.com (one tarball, < 1 MB) and
17
+ // registry.npmjs.org (latest ms CLI version, best effort). Nothing is executed: the files are
18
+ // Markdown and JSON the agent reads.
19
+ // - Cache: $GSK_M365_GUIDANCE_CACHE, else $XDG_CACHE_HOME/gsk/copilot-managed-runtime, else
20
+ // ~/.cache/gsk/copilot-managed-runtime; one directory per commit, the last 3 kept. Outside every
21
+ // skills directory, so Microsoft's own SKILL.md files never register as extra skills.
22
+ // - Pinning: --ref or $GSK_M365_GUIDANCE_REF (a tag or a commit) holds a known-good version.
23
+ // - Offline or GitHub down: the last cached copy of the same ref, marked "stale": true. No cached
24
+ // copy of that ref: exit 1 with {"error": "guidance_unavailable", ...}.
25
+ // - Proxy: Node's fetch ignores HTTPS_PROXY unless NODE_USE_ENV_PROXY=1 (Node >= 24, or 22.21+),
26
+ // so when a proxy is set the script re-runs itself once with it on.
27
+ import { spawnSync } from 'node:child_process'
28
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
29
+ import { homedir } from 'node:os'
30
+ import { dirname, join, normalize, resolve, sep } from 'node:path'
31
+ import { fileURLToPath } from 'node:url'
32
+ import { gunzipSync } from 'node:zlib'
33
+
34
+ export const REPO = 'microsoft/Copilot-Managed-Runtime'
35
+ export const PLUGIN_DIR = 'plugins/copilot-managed-runtime'
36
+ export const PLUGIN_NAME = 'copilot-managed-runtime'
37
+ export const CLI_PACKAGE = '@microsoft/cmr-cli' // formerly @microsoft/managed-apps-cli
38
+ export const DEFAULT_REF = 'main'
39
+ export const DEFAULT_MAX_AGE_HOURS = 24
40
+ export const KEEP_COMMITS = 3
41
+ const MAX_FILES = 2000
42
+ const MAX_BYTES = 20 * 1024 * 1024
43
+ export const MAX_COMPRESSED_BYTES = 25 * 1024 * 1024 // the tarball as downloaded
44
+ export const MAX_ARCHIVE_BYTES = 100 * 1024 * 1024 // the tarball once gunzipped
45
+ const SHA = /^[0-9a-f]{40}$/
46
+ const USER_AGENT = 'gsk-m365-apps-guidance-sync'
47
+
48
+ export class GuidanceError extends Error {
49
+ constructor(code, message) {
50
+ super(message)
51
+ this.code = code
52
+ }
53
+ }
54
+
55
+ // microsoft/Managed-Apps (plugins/microsoft-managed-apps) moved to REPO on 2026-11-05. A ref pinned
56
+ // before then may not exist here, or may carry the old plugin path.
57
+ const MOVED_REF_CODES = new Set(['download_failed', 'bad_archive', 'resolve_failed'])
58
+ export function explainPinnedRef(error, ref) {
59
+ if (ref === DEFAULT_REF || !(error instanceof GuidanceError) || !MOVED_REF_CODES.has(error.code)) return error
60
+ return new GuidanceError(
61
+ error.code,
62
+ `${error.message}. The pinned ref ${ref} (--ref or GSK_M365_GUIDANCE_REF) could not be read from ${REPO}/${PLUGIN_DIR}. ` +
63
+ 'Microsoft moved this guidance there from microsoft/Managed-Apps on 2026-11-05, so a pin set before then ' +
64
+ 'must be re-pinned to a tag or commit of the new repository, or removed to follow main.',
65
+ )
66
+ }
67
+
68
+ export function parseArgs(argv) {
69
+ const out = { ref: undefined, maxAgeHours: undefined, offline: false, force: false }
70
+ for (let i = 0; i < argv.length; i++) {
71
+ const arg = argv[i]
72
+ const value = () => {
73
+ const next = argv[++i]
74
+ if (next === undefined) throw new GuidanceError('bad_args', `${arg} needs a value`)
75
+ return next
76
+ }
77
+ if (arg === '--ref') out.ref = value()
78
+ else if (arg === '--max-age-hours') out.maxAgeHours = Number(value())
79
+ else if (arg === '--offline') out.offline = true
80
+ else if (arg === '--force') out.force = true
81
+ else throw new GuidanceError('bad_args', `Unknown argument ${arg}`)
82
+ }
83
+ if (out.maxAgeHours !== undefined && !(out.maxAgeHours >= 0)) {
84
+ throw new GuidanceError('bad_args', '--max-age-hours must be a number >= 0')
85
+ }
86
+ return out
87
+ }
88
+
89
+ export function defaultCacheRoot(env = process.env) {
90
+ if (env.GSK_M365_GUIDANCE_CACHE) return resolve(env.GSK_M365_GUIDANCE_CACHE)
91
+ const base = env.XDG_CACHE_HOME ? resolve(env.XDG_CACHE_HOME) : join(homedir(), '.cache')
92
+ return join(base, 'gsk', PLUGIN_NAME)
93
+ }
94
+
95
+ // ── tar (ustar + pax + GNU long names), enough for GitHub's codeload tarballs ──
96
+
97
+ // The proxy settings Node's fetch honours once NODE_USE_ENV_PROXY=1.
98
+ const PROXY_VARS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy']
99
+ const RELAUNCH_MARKER = 'GSK_M365_GUIDANCE_PROXY_CHILD'
100
+
101
+ /** Whether this Node's fetch can use HTTPS_PROXY via NODE_USE_ENV_PROXY: 24+, or 22.21+ (not 23). */
102
+ export function supportsEnvProxy(nodeVersion) {
103
+ const [major, minor] = String(nodeVersion).replace(/^v/, '').split('.').map(Number)
104
+ return major >= 24 || (major === 22 && minor >= 21)
105
+ }
106
+
107
+ /**
108
+ * What to do about a proxy before any network call:
109
+ * {action: 'proceed'} - no proxy, fetch already uses it, or no network is needed;
110
+ * {action: 'relaunch', env} - re-run this script once with NODE_USE_ENV_PROXY=1;
111
+ * {action: 'error', code, message} - a proxy is set but this Node cannot send fetch through it.
112
+ */
113
+ export function proxyDecision({ env = process.env, nodeVersion = process.version, offline = false } = {}) {
114
+ if (offline) return { action: 'proceed' }
115
+ const proxy = PROXY_VARS.find(name => env[name])
116
+ if (!proxy) return { action: 'proceed' }
117
+ if (!supportsEnvProxy(nodeVersion)) {
118
+ return {
119
+ action: 'error',
120
+ code: 'node_too_old',
121
+ message:
122
+ `${proxy} is set, but Node ${nodeVersion} cannot send fetch through a proxy. ` +
123
+ 'Use Node 24 or newer (the ms CLI itself needs Node >= 24.11), or at least Node 22.21.',
124
+ }
125
+ }
126
+ if (env.NODE_USE_ENV_PROXY || env[RELAUNCH_MARKER]) return { action: 'proceed' }
127
+ return { action: 'relaunch', env: { ...env, NODE_USE_ENV_PROXY: '1', [RELAUNCH_MARKER]: '1' } }
128
+ }
129
+
130
+ /** True when `argv1` (process.argv[1]) is this module, also when run through a symlink. */
131
+ export function isEntryPoint(moduleUrl, argv1) {
132
+ if (!argv1) return false
133
+ try {
134
+ return realpathSync(argv1) === realpathSync(fileURLToPath(moduleUrl))
135
+ } catch {
136
+ return false
137
+ }
138
+ }
139
+
140
+ const text = (buf, start, length) => {
141
+ const raw = buf.subarray(start, start + length)
142
+ const end = raw.indexOf(0)
143
+ return raw.subarray(0, end === -1 ? raw.length : end).toString('utf8')
144
+ }
145
+
146
+ // "<length> <key>=<value>\n" records. <length> counts bytes, so this walks the Buffer and decodes
147
+ // only each key and value (with a UTF-8 path, character and byte offsets differ).
148
+ export function paxRecords(data) {
149
+ const records = {}
150
+ let offset = 0
151
+ while (offset < data.length) {
152
+ const space = data.indexOf(0x20, offset)
153
+ if (space === -1) break
154
+ const length = Number(data.toString('latin1', offset, space))
155
+ if (!Number.isInteger(length) || length <= space - offset || offset + length > data.length) break
156
+ const end = offset + length - 1 // the record's trailing newline
157
+ const eq = data.indexOf(0x3d, space + 1)
158
+ if (eq > space + 1 && eq < end) records[data.toString('utf8', space + 1, eq)] = data.toString('utf8', eq + 1, end)
159
+ offset += length
160
+ }
161
+ return records
162
+ }
163
+
164
+ /** Entries of an uncompressed tar: {name, type: 'file'|'dir'|'other', data}, plus pax globals. */
165
+ export function parseTar(buffer) {
166
+ const entries = []
167
+ let globals = {}
168
+ let nextPath = null
169
+ let offset = 0
170
+ while (offset + 512 <= buffer.length) {
171
+ const header = buffer.subarray(offset, offset + 512)
172
+ if (header.every(b => b === 0)) break
173
+ const size = parseInt(text(header, 124, 12).trim() || '0', 8)
174
+ const flag = String.fromCharCode(header[156] || 48)
175
+ const prefix = text(header, 345, 155)
176
+ const name = text(header, 0, 100)
177
+ const data = buffer.subarray(offset + 512, offset + 512 + size)
178
+ offset += 512 + Math.ceil(size / 512) * 512
179
+ if (flag === 'g') {
180
+ globals = { ...globals, ...paxRecords(data) }
181
+ continue
182
+ }
183
+ if (flag === 'x') {
184
+ const records = paxRecords(data)
185
+ if (records.path) nextPath = records.path
186
+ continue
187
+ }
188
+ if (flag === 'L') {
189
+ nextPath = text(data, 0, data.length)
190
+ continue
191
+ }
192
+ const fullName = nextPath || (prefix ? `${prefix}/${name}` : name)
193
+ nextPath = null
194
+ const type = flag === '0' || flag === '\0' || flag === '7' ? 'file' : flag === '5' ? 'dir' : 'other'
195
+ entries.push({ name: fullName, type, data })
196
+ }
197
+ return { entries, globals }
198
+ }
199
+
200
+ /** The plugin's files, keyed by their path inside the plugin directory. Rejects unsafe paths. */
201
+ export function pluginFiles(entries) {
202
+ const files = new Map()
203
+ let bytes = 0
204
+ for (const entry of entries) {
205
+ if (entry.type !== 'file') continue
206
+ // codeload tarballs have one top directory: Copilot-Managed-Runtime-<sha>/...
207
+ const parts = entry.name.split('/')
208
+ const inner = parts.slice(1).join('/')
209
+ if (!inner.startsWith(`${PLUGIN_DIR}/`)) continue
210
+ const relative = inner.slice(PLUGIN_DIR.length + 1)
211
+ const clean = normalize(relative)
212
+ if (!relative || clean.startsWith('..') || clean.includes(`..${sep}`) || clean.startsWith(sep) || /^[A-Za-z]:/.test(clean)) {
213
+ throw new GuidanceError('unsafe_archive', `Refusing archive path ${entry.name}`)
214
+ }
215
+ bytes += entry.data.length
216
+ if (files.size >= MAX_FILES || bytes > MAX_BYTES) {
217
+ throw new GuidanceError('archive_too_large', 'The guidance archive is larger than expected')
218
+ }
219
+ files.set(clean, entry.data)
220
+ }
221
+ const manifest = files.get('plugin.json')
222
+ if (!manifest) throw new GuidanceError('bad_archive', `${PLUGIN_DIR}/plugin.json is missing at this ref`)
223
+ let parsed
224
+ try {
225
+ parsed = JSON.parse(manifest.toString('utf8'))
226
+ } catch {
227
+ throw new GuidanceError('bad_archive', 'plugin.json is not JSON')
228
+ }
229
+ if (parsed.name !== PLUGIN_NAME) throw new GuidanceError('bad_archive', `plugin.json names ${parsed.name}, not ${PLUGIN_NAME}`)
230
+ return { files, version: String(parsed.version || '') }
231
+ }
232
+
233
+ // ── cache ──
234
+
235
+ const statePath = root => join(root, 'current.json')
236
+
237
+ export function readState(root) {
238
+ try {
239
+ const state = JSON.parse(readFileSync(statePath(root), 'utf8'))
240
+ if (!SHA.test(state.commit || '')) return null
241
+ statSync(join(root, state.commit, 'plugin.json'))
242
+ return state
243
+ } catch {
244
+ return null
245
+ }
246
+ }
247
+
248
+ export function isFresh(state, { ref, maxAgeHours, now }) {
249
+ if (!state || state.ref !== ref) return false
250
+ if (SHA.test(ref)) return true // a commit never changes
251
+ const age = now - Date.parse(state.fetched_at || '')
252
+ return Number.isFinite(age) && age >= 0 && age < maxAgeHours * 3600 * 1000
253
+ }
254
+
255
+ function writeState(root, state) {
256
+ mkdirSync(root, { recursive: true })
257
+ const tmp = `${statePath(root)}.${process.pid}.tmp`
258
+ writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`)
259
+ renameSync(tmp, statePath(root))
260
+ }
261
+
262
+ /** Write one commit's files. A commit's content never changes, so an existing copy is kept. */
263
+ export function writePlugin(root, commit, files, { rename = renameSync } = {}) {
264
+ const target = join(root, commit)
265
+ if (existsSync(join(target, 'plugin.json'))) return target
266
+ const tmp = join(root, `.${commit}.${process.pid}.tmp`)
267
+ rmSync(tmp, { recursive: true, force: true })
268
+ for (const [relative, data] of files) {
269
+ const file = join(tmp, relative)
270
+ if (!file.startsWith(tmp + sep)) throw new GuidanceError('unsafe_archive', `Refusing ${relative}`)
271
+ mkdirSync(dirname(file), { recursive: true })
272
+ writeFileSync(file, data)
273
+ }
274
+ // Rename first, never remove a target blindly: another run may have just finished the same
275
+ // commit, and its copy (identical, commits are immutable) may be in use as MS_GUIDE.
276
+ const taken = error => error.code === 'ENOTEMPTY' || error.code === 'EEXIST' || error.code === 'EPERM'
277
+ try {
278
+ rename(tmp, target)
279
+ return target
280
+ } catch (error) {
281
+ if (!taken(error)) throw error
282
+ }
283
+ if (existsSync(join(target, 'plugin.json'))) {
284
+ rmSync(tmp, { recursive: true, force: true })
285
+ return target
286
+ }
287
+ // A leftover without plugin.json (an interrupted run). Move it aside atomically instead of
288
+ // deleting it in place: if another run completed the slot in the meantime, its copy comes back.
289
+ const aside = join(root, `.${commit}.${process.pid}.old`)
290
+ rmSync(aside, { recursive: true, force: true })
291
+ try {
292
+ rename(target, aside)
293
+ } catch (error) {
294
+ if (error.code !== 'ENOENT') throw error
295
+ }
296
+ if (existsSync(join(aside, 'plugin.json'))) {
297
+ try {
298
+ rename(aside, target)
299
+ } catch (error) {
300
+ if (!taken(error)) throw error
301
+ }
302
+ }
303
+ try {
304
+ rename(tmp, target)
305
+ } catch (error) {
306
+ if (!taken(error)) throw error
307
+ }
308
+ rmSync(tmp, { recursive: true, force: true })
309
+ rmSync(aside, { recursive: true, force: true })
310
+ if (!existsSync(join(target, 'plugin.json'))) {
311
+ throw new GuidanceError('cache_write_failed', `Could not write the guidance for ${commit} to ${target}`)
312
+ }
313
+ return target
314
+ }
315
+
316
+ export function prune(root, keep, current) {
317
+ let dirs
318
+ try {
319
+ dirs = readdirSync(root, { withFileTypes: true }).filter(d => d.isDirectory() && SHA.test(d.name))
320
+ } catch {
321
+ return []
322
+ }
323
+ const byAge = dirs
324
+ .map(d => ({ name: d.name, mtime: statSync(join(root, d.name)).mtimeMs }))
325
+ .sort((a, b) => b.mtime - a.mtime)
326
+ const removed = []
327
+ for (const dir of byAge.slice(keep)) {
328
+ if (dir.name === current) continue
329
+ rmSync(join(root, dir.name), { recursive: true, force: true })
330
+ removed.push(dir.name)
331
+ }
332
+ return removed
333
+ }
334
+
335
+ // ── network ──
336
+
337
+ async function resolveCommit(ref, fetchImpl) {
338
+ if (SHA.test(ref)) return ref
339
+ const response = await fetchImpl(`https://api.github.com/repos/${REPO}/commits/${encodeURIComponent(ref)}`, {
340
+ headers: { Accept: 'application/vnd.github.sha', 'User-Agent': USER_AGENT },
341
+ })
342
+ if (!response.ok) throw new GuidanceError('resolve_failed', `GitHub ${response.status} resolving ${ref}`)
343
+ const sha = (await response.text()).trim()
344
+ if (!SHA.test(sha)) throw new GuidanceError('resolve_failed', `GitHub returned no commit for ${ref}`)
345
+ return sha
346
+ }
347
+
348
+ const tooLarge = what => new GuidanceError('archive_too_large', `The guidance archive is larger than expected (${what})`)
349
+
350
+ /** The response body, refusing more than `maxBytes` whether or not content-length says so. */
351
+ async function readCapped(response, maxBytes) {
352
+ const declared = Number(response.headers.get('content-length'))
353
+ if (Number.isFinite(declared) && declared > maxBytes) {
354
+ await response.body?.cancel().catch(() => {})
355
+ throw tooLarge(`${declared} bytes to download`)
356
+ }
357
+ if (!response.body) {
358
+ const whole = Buffer.from(await response.arrayBuffer())
359
+ if (whole.length > maxBytes) throw tooLarge(`over ${maxBytes} bytes to download`)
360
+ return whole
361
+ }
362
+ const reader = response.body.getReader()
363
+ const chunks = []
364
+ let total = 0
365
+ for (;;) {
366
+ const { done, value } = await reader.read()
367
+ if (done) break
368
+ total += value.length
369
+ if (total > maxBytes) {
370
+ await reader.cancel().catch(() => {})
371
+ throw tooLarge(`over ${maxBytes} bytes to download`)
372
+ }
373
+ chunks.push(value)
374
+ }
375
+ return Buffer.concat(chunks, total)
376
+ }
377
+
378
+ async function downloadPlugin(commitOrRef, fetchImpl, { maxCompressedBytes, maxArchiveBytes }) {
379
+ const response = await fetchImpl(`https://codeload.github.com/${REPO}/tar.gz/${encodeURIComponent(commitOrRef)}`, {
380
+ headers: { 'User-Agent': USER_AGENT },
381
+ })
382
+ if (!response.ok) throw new GuidanceError('download_failed', `GitHub ${response.status} downloading ${commitOrRef}`)
383
+ const compressed = await readCapped(response, maxCompressedBytes)
384
+ let archive
385
+ try {
386
+ archive = gunzipSync(compressed, { maxOutputLength: maxArchiveBytes })
387
+ } catch (error) {
388
+ if (error.code === 'ERR_BUFFER_TOO_LARGE' || error instanceof RangeError) throw tooLarge(`over ${maxArchiveBytes} bytes unpacked`)
389
+ throw new GuidanceError('bad_archive', `The guidance archive is not valid gzip: ${error.message}`)
390
+ }
391
+ const { entries, globals } = parseTar(archive)
392
+ const { files, version } = pluginFiles(entries)
393
+ return { files, version, commit: SHA.test(globals.comment || '') ? globals.comment : null }
394
+ }
395
+
396
+ async function latestCliVersion(fetchImpl) {
397
+ try {
398
+ const response = await fetchImpl(`https://registry.npmjs.org/${CLI_PACKAGE}/latest`, {
399
+ headers: { Accept: 'application/json', 'User-Agent': USER_AGENT },
400
+ })
401
+ if (!response.ok) return null
402
+ const body = await response.json()
403
+ return typeof body.version === 'string' ? body.version : null
404
+ } catch {
405
+ return null
406
+ }
407
+ }
408
+
409
+ /** Whether the cached state is a copy of `ref`: the same ref, or the commit `ref` names. */
410
+ export function matchesRef(state, ref) {
411
+ return Boolean(state) && (state.ref === ref || (SHA.test(ref) && state.commit === ref))
412
+ }
413
+
414
+ const errorText = error => (error.cause?.message ? `${error.message} (${error.cause.message})` : error.message)
415
+
416
+ const describe = (root, state, extra) => ({
417
+ path: join(root, state.commit),
418
+ version: state.version,
419
+ commit: state.commit,
420
+ ref: state.ref,
421
+ fetched_at: state.fetched_at,
422
+ cli_latest: state.cli_latest ?? null,
423
+ source: `https://github.com/${REPO}/tree/${state.commit}/${PLUGIN_DIR}`,
424
+ ...extra,
425
+ })
426
+
427
+ export async function syncGuidance({
428
+ ref = DEFAULT_REF,
429
+ maxAgeHours = DEFAULT_MAX_AGE_HOURS,
430
+ offline = false,
431
+ force = false,
432
+ cacheRoot = defaultCacheRoot(),
433
+ fetchImpl = fetch,
434
+ now = Date.now(),
435
+ keep = KEEP_COMMITS,
436
+ maxCompressedBytes = MAX_COMPRESSED_BYTES,
437
+ maxArchiveBytes = MAX_ARCHIVE_BYTES,
438
+ } = {}) {
439
+ const requested = { requested_ref: ref }
440
+ const state = readState(cacheRoot)
441
+ if (!force && isFresh(state, { ref, maxAgeHours, now })) {
442
+ return describe(cacheRoot, state, { ...requested, stale: false, cached: true })
443
+ }
444
+ // A stale copy stands in only for the ref that was asked for: a pin never gets another version.
445
+ const staleCopy = (warning, reason) => {
446
+ if (matchesRef(state, ref)) return describe(cacheRoot, state, { ...requested, stale: true, cached: true, warning })
447
+ const cached = state ? `the cached guidance is ${state.ref} (${state.commit}), not ${ref}` : 'no cached guidance'
448
+ throw new GuidanceError('guidance_unavailable', `${reason}, and ${cached}`)
449
+ }
450
+ if (offline) return staleCopy('offline: using the last cached guidance', 'Offline')
451
+ try {
452
+ let commit = null
453
+ try {
454
+ commit = await resolveCommit(ref, fetchImpl)
455
+ } catch (error) {
456
+ if (!(error instanceof GuidanceError)) throw error
457
+ // api.github.com rate-limits anonymous callers; the tarball names its commit too.
458
+ }
459
+ const cliLatest = await latestCliVersion(fetchImpl)
460
+ const fetchedAt = new Date(now).toISOString()
461
+ // Read again: another run may have refreshed the cache while this one was on the network.
462
+ const current = readState(cacheRoot)
463
+ if (commit && current?.commit === commit) {
464
+ const next = { ...current, ref, fetched_at: fetchedAt, cli_latest: cliLatest ?? current.cli_latest ?? null }
465
+ writeState(cacheRoot, next)
466
+ return describe(cacheRoot, next, { ...requested, stale: false, cached: true })
467
+ }
468
+ const plugin = await downloadPlugin(commit || ref, fetchImpl, { maxCompressedBytes, maxArchiveBytes })
469
+ const resolved = commit || plugin.commit
470
+ if (!resolved) throw new GuidanceError('resolve_failed', `Could not tell which commit ${ref} is`)
471
+ writePlugin(cacheRoot, resolved, plugin.files)
472
+ const next = { commit: resolved, ref, version: plugin.version, fetched_at: fetchedAt, cli_latest: cliLatest }
473
+ writeState(cacheRoot, next)
474
+ prune(cacheRoot, keep, resolved)
475
+ return describe(cacheRoot, next, {
476
+ ...requested,
477
+ stale: false,
478
+ cached: false,
479
+ ...(state && state.commit !== resolved ? { previous: { commit: state.commit, version: state.version } } : {}),
480
+ })
481
+ } catch (caught) {
482
+ const error = explainPinnedRef(caught, ref)
483
+ if (matchesRef(state, ref)) return staleCopy(`could not refresh (${errorText(error)}); using the last cached guidance`)
484
+ if (error instanceof GuidanceError && !state) throw error
485
+ return staleCopy(null, `Could not download Microsoft's guidance: ${errorText(error)}`)
486
+ }
487
+ }
488
+
489
+ /**
490
+ * The CLI. Returns the result, or {relaunched: <exit code>} when a child process that sends fetch
491
+ * through the proxy did the run (and printed the output).
492
+ */
493
+ export async function main(argv = process.argv.slice(2), env = process.env, { nodeVersion = process.version, now = Date.now() } = {}) {
494
+ let ref = env.GSK_M365_GUIDANCE_REF || DEFAULT_REF
495
+ try {
496
+ const args = parseArgs(argv)
497
+ ref = args.ref || ref
498
+ const options = {
499
+ ref,
500
+ maxAgeHours: args.maxAgeHours ?? DEFAULT_MAX_AGE_HOURS,
501
+ offline: args.offline,
502
+ force: args.force,
503
+ cacheRoot: defaultCacheRoot(env),
504
+ now,
505
+ }
506
+ const print = result => {
507
+ process.stdout.write(`${JSON.stringify(result)}\n`)
508
+ return result
509
+ }
510
+ // A fresh copy of the requested ref needs no network: no proxy check, no relaunch.
511
+ const fresh = !args.force && isFresh(readState(options.cacheRoot), { ref, maxAgeHours: options.maxAgeHours, now })
512
+ const proxy = fresh ? { action: 'proceed' } : proxyDecision({ env, nodeVersion, offline: args.offline })
513
+ if (proxy.action === 'error') {
514
+ // This Node cannot reach GitHub through the proxy: the network step is skipped, and the last
515
+ // cached copy of the requested ref (if any) is served instead.
516
+ try {
517
+ const cached = await syncGuidance({ ...options, offline: true, force: false })
518
+ return print({ ...cached, warning: `${proxy.message} Using the last cached guidance.` })
519
+ } catch (error) {
520
+ if (error instanceof GuidanceError && error.code === 'guidance_unavailable') {
521
+ throw new GuidanceError(proxy.code, proxy.message)
522
+ }
523
+ throw error
524
+ }
525
+ }
526
+ if (proxy.action === 'relaunch') {
527
+ const child = spawnSync(process.execPath, [fileURLToPath(import.meta.url), ...argv], { env: proxy.env, stdio: 'inherit' })
528
+ if (child.error) throw new GuidanceError('relaunch_failed', `Could not re-run with NODE_USE_ENV_PROXY=1: ${child.error.message}`)
529
+ return { relaunched: child.status ?? 1 }
530
+ }
531
+ return print(await syncGuidance(options))
532
+ } catch (error) {
533
+ error.requestedRef = ref
534
+ throw error
535
+ }
536
+ }
537
+
538
+ if (isEntryPoint(import.meta.url, process.argv[1])) {
539
+ main().then(
540
+ result => {
541
+ if (result && 'relaunched' in result) process.exitCode = result.relaunched
542
+ },
543
+ error => {
544
+ const code = error instanceof GuidanceError ? error.code : 'unexpected'
545
+ process.stderr.write(`sync-microsoft-guidance: ${error.message}\n`)
546
+ process.stdout.write(
547
+ `${JSON.stringify({
548
+ error: code,
549
+ message: error.message,
550
+ requested_ref: error.requestedRef ?? null,
551
+ fallback: `https://github.com/${REPO}/tree/main/${PLUGIN_DIR}`,
552
+ })}\n`
553
+ )
554
+ process.exitCode = 1
555
+ }
556
+ )
557
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@genspark/cli",
3
- "version": "1.15.4-beta.0",
3
+ "version": "1.15.5",
4
4
  "description": "CLI tool for Genspark Tool API - search, crawl, analyze images, generate media",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -11,6 +11,7 @@
11
11
  "files": [
12
12
  "dist/",
13
13
  "skills/",
14
+ "gated-skills/",
14
15
  "docs/",
15
16
  "README.md"
16
17
  ],