@genspark/cli 1.15.4 → 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 (47) hide show
  1. package/README.md +31 -11
  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 +5 -0
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +23 -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 +21 -2
  12. package/dist/commands/aidrive-contract.generated.js.map +1 -1
  13. package/dist/commands/task-status-follow.d.ts +9 -0
  14. package/dist/commands/task-status-follow.d.ts.map +1 -1
  15. package/dist/commands/task-status-follow.js +24 -4
  16. package/dist/commands/task-status-follow.js.map +1 -1
  17. package/dist/confirm.d.ts.map +1 -1
  18. package/dist/confirm.js +18 -1
  19. package/dist/confirm.js.map +1 -1
  20. package/dist/humanApproval.d.ts +48 -0
  21. package/dist/humanApproval.d.ts.map +1 -0
  22. package/dist/humanApproval.js +86 -0
  23. package/dist/humanApproval.js.map +1 -0
  24. package/dist/index.js +88 -21
  25. package/dist/index.js.map +1 -1
  26. package/dist/mediaSummary.d.ts.map +1 -1
  27. package/dist/mediaSummary.js +4 -1
  28. package/dist/mediaSummary.js.map +1 -1
  29. package/dist/task-shim.d.ts +11 -2
  30. package/dist/task-shim.d.ts.map +1 -1
  31. package/dist/task-shim.js +21 -2
  32. package/dist/task-shim.js.map +1 -1
  33. package/docs/skills.md +1 -1
  34. package/gated-skills/gsk-issue/SKILL.md +7 -0
  35. package/gated-skills/gsk-m365-apps/SKILL.md +197 -0
  36. package/gated-skills/gsk-m365-apps/references/add-genspark-ai.md +399 -0
  37. package/gated-skills/gsk-m365-apps/scripts/install-genspark-connector.mjs +548 -0
  38. package/gated-skills/gsk-m365-apps/scripts/sync-microsoft-guidance.mjs +557 -0
  39. package/package.json +1 -1
  40. package/skills/gsk-aidrive/SKILL.md +14 -2
  41. package/skills/gsk-aidrive/command-reference.md +13 -3
  42. package/skills/gsk-image-generation/SKILL.md +6 -3
  43. package/skills/gsk-phone-call/SKILL.md +33 -13
  44. package/skills/gsk-second-brain/SKILL.md +2 -2
  45. package/skills/gsk-slack/SKILL.md +4 -1
  46. package/skills/gsk-team-brain/SKILL.md +89 -22
  47. package/skills/gsk-video-generation/SKILL.md +3 -3
@@ -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",
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",
@@ -35,8 +35,14 @@ gsk drive tree --url '<folder link>'
35
35
  gsk drive upload --local_file '<local file>' --upload_path '/<filename>' --on-conflict error
36
36
  ```
37
37
 
38
- Reuse the returned `entry_locator` workspace, source and path together. A file
39
- shared with the user can be read through that address without access to its
38
+ Prefer a returned file `id`/`entry_id` over retyping its name. `ls` and `find`
39
+ show ID, Workspace and Source columns: read with `gsk drive read --id '<file-id>'`
40
+ and that row's workspace/source (`id_locator`), omitting an absent source.
41
+ Following a shortcut can change the source; use the returned address instead
42
+ of the original listing's source. For path-based operations, reuse the returned
43
+ `entry_locator` workspace, source and path together. When only a path is available,
44
+ copy it exactly, including spaces and punctuation; never construct a Drive URL
45
+ from a display name. A file shared with the user can be read without access to its
40
46
  whole parent location. Call the tool under the current identity and follow any
41
47
  refusal; a share or shortcut never grants more than the source permits.
42
48
 
@@ -48,6 +54,12 @@ checked after a miss. Return the tool's user-facing `url`, never an internal
48
54
  download URL. Existing Office files are edited through `wo-peer`, not by
49
55
  downloading and uploading a replacement.
50
56
 
57
+ On `Entry not available`, first check the selected directory or run `find` and
58
+ retry with the returned ID. A failed path lookup alone does not establish a
59
+ permission denial; stop when the tool explicitly denies access. Preserve JSON
60
+ results and use `--char_limit` and cursors instead of piping to `head` or `tail`:
61
+ the last command's exit code can hide a failed Drive call.
62
+
51
63
  ## Load the relevant reference when needed
52
64
 
53
65
  Read [the command reference](command-reference.md) when the user
@@ -63,7 +63,13 @@ For specific facts or calculations, find the relevant original passages.
63
63
  | Get a cached file/folder overview | `gsk drive overview --id '<entry-id>'` |
64
64
  | Inspect missing directory structure | `gsk drive tree --id '<folder-id>'` |
65
65
 
66
- Add `--source '<source-id>'` for a shared selection. `--path` can replace `--id`.
66
+ Prefer the `id`/`entry_id` returned by `ls`, `find` or search over a copied file
67
+ name. Pair it with the returned row's Workspace and Source (`id_locator`),
68
+ not the original listing's source: following a shortcut can change the drive.
69
+ Omit a missing source for My Drive; an ID does not replace its permission context.
70
+ If only a path is available, copy it exactly, including spaces and punctuation. On `Entry not
71
+ available`, check the selected listing or `find` for the correct ID before
72
+ concluding the file cannot be accessed. Stop on an explicit access denial.
67
73
  Use short search queries; words in one search are ANDed. `--queries` accepts
68
74
  several complementary searches, or several literal phrases for file grep.
69
75
  `read --query` and `grep` match literal source phrases; use `search` for topic questions.
@@ -440,11 +446,12 @@ in the UI.
440
446
  | `--task_tags_remove` | No | For task_update: remove tag names case-insensitively; missing names are a no-op. Cannot also add the same name or replace/clear tags. (array) |
441
447
  | `--task_filter_tags` | No | For task_list: require ALL exact tag names (case-insensitive). Combines with status/assignee/priority filters using AND; empty means no tag filter. (array) |
442
448
  | `--ref` | No | For link into a Work Hub: Genspark project UUID or project URL, agentbase:<database UUID>, or meeting:<meeting UUID>. Use path instead for an original My Drive or Team Drive file/folder; source selects the destination Workspace. (string) |
443
- | `<action>` (positional) | Yes | Action to perform. create: Create a Work Hub with its own Drive; requires workspace=sb_workspace. ls: List a directory, or discover shared sources when no source is selected. find: Find files by name keyword; scope selects mine, shared or all. tag_add: Add shared file/folder tags without changing other tags. References keep local tags. tag_rm: Remove shared tags by case-insensitive name, preserving other tags. mkdir: Create a directory in the selected Drive. rm: Move the selected entry to recoverable trash; removing a shortcut preserves its source. With workspace=sb_workspace and only source, delete the entire Workspace (owner only). move: Move or rename within one Drive source; never overwrite an existing file. get_readable_url: Get temporary file bytes URL and the separate document URL for people. download_video: Import an internet video into Drive (YouTube is billed by delivered size). download_audio: Import internet audio into Drive (YouTube is billed by delivered size). download_file: Import an external file URL into Drive; local downloads use download. compress: Create an archive from a Drive folder. decompress: Extract an archive in Drive. share: Grant access to an entry; recipient and general-access forms use existing sharing rules. unshare: Revoke an entry's recipient or general access. access: Inspect who can open the selected entry. link: Place a shortcut in a managed Drive. For a Work Hub, use path for an original My Drive/Team Drive entry or ref for a Genspark project, meeting, or AgentBase resource. unlink: Remove the selected shortcut and its grant without deleting source bytes. upload: Upload a local file or inline content into Drive; local and inline conflict policies differ. list_trash: List recoverable entries in My Drive trash. restore: Restore a trash entry by its stable entry_id, optionally into another folder. tree: Browse bounded directory structure; continue with the returned cursor. search: Search names and indexed content; continue with the returned cursor. read: Read persisted extracted text by locator, batch ids, or a returned read cursor. overview: Read cached summaries; missing summaries prepare asynchronously without blocking reads. copy: Copy entries into a writable Drive, or inspect/continue an existing job with job_id. info: Read a Work Hub's shared context: brief, team instructions, your access, memo, open tasks and the commands that work in it. update: Update a Work Hub's brief or team instructions. Omitted or blank fields stay unchanged; use clear to erase a field. task_list: List Workspace tasks; status, assignee, priority and all requested tags combine as AND filters. task_add: Add a Work Hub task with optional status, due date, assignee, links, priority, details and tags. task_update: Change a Work Hub task's fields; omitted or blank values leave fields unchanged. task_done: Mark a Work Hub task done; task_update --task_status open reopens it. task_rm: Delete a Work Hub task. task_comment_add: Add a shared task comment as yourself; retry the same request_id and body without duplicating it. grep: Find literal phrases in one file; continue with the returned cursor. (string, one of: create, ls, find, tag_add, tag_rm, mkdir, rm, move, get_readable_url, download, download_video, download_audio, download_file, compress, decompress, share, unshare, access, link, unlink, upload, list_trash, restore, tree, search, read, overview, copy, info, update, task_list, task_add, task_update, task_done, task_rm, task_comment_add, grep) |
449
+ | `<action>` (positional) | Yes | Action to perform. create: Create a Work Hub with its own Drive; requires workspace=sb_workspace. ls: List a directory, or discover shared sources when no source is selected. find: Find files by name keyword; scope selects mine, shared or all. tag_add: Add shared file/folder tags without changing other tags. References keep local tags. tag_rm: Remove shared tags by case-insensitive name, preserving other tags. mkdir: Create a directory in the selected Drive. rm: Move the selected entry to recoverable trash; removing a shortcut preserves its source. With workspace=sb_workspace and only source, delete the entire Workspace (owner only). move: Move or rename within one Drive source; never overwrite an existing file. get_readable_url: Get temporary file bytes URL and the separate document URL for people. download_video: Import an internet video into Drive (YouTube is billed by delivered size). download_audio: Import internet audio into Drive (YouTube is billed by delivered size). download_file: Import an external file URL into Drive; local downloads use download. compress: Create an archive from a Drive folder. decompress: Extract an archive in Drive. share: Grant access to an entry; recipient and general-access forms use existing sharing rules. unshare: Revoke an entry's recipient or general access. access: Inspect who can open the selected entry. link: Place a shortcut in a managed Drive. For a Work Hub, use path for an original My Drive/Team Drive entry or ref for a Genspark project, meeting, or AgentBase resource. unlink: Remove the selected shortcut and its grant without deleting source bytes. upload: Upload a local file or inline content into Drive; local and inline conflict policies differ. list_trash: List recoverable entries in My Drive trash. restore: Restore a trash entry by its stable entry_id, optionally into another folder. tree: Browse bounded directory structure; continue with the returned cursor. search: Search names and indexed content; continue with the returned cursor. find_workspaces: Rank your Work Hubs for a request by name, recent work and matching files; pick one, then work in it with its source_id. read: Read persisted extracted text by locator, batch ids, or a returned read cursor. overview: Read cached summaries; missing summaries prepare asynchronously without blocking reads. copy: Copy entries into a writable Drive, or inspect/continue an existing job with job_id. info: Read a Work Hub's shared context: brief, team instructions, your access, memo, open tasks and the commands that work in it. update: Update a Work Hub's brief or team instructions. Omitted or blank fields stay unchanged; use clear to erase a field. task_list: List Workspace tasks; status, assignee, priority and all requested tags combine as AND filters. task_add: Add a Work Hub task with optional status, due date, assignee, links, priority, details and tags. task_update: Change a Work Hub task's fields; omitted or blank values leave fields unchanged. task_done: Mark a Work Hub task done; task_update --task_status open reopens it. task_rm: Delete a Work Hub task. task_comment_add: Add a shared task comment as yourself; retry the same request_id and body without duplicating it. grep: Find literal phrases in one file; continue with the returned cursor. (string, one of: create, ls, find, tag_add, tag_rm, mkdir, rm, move, get_readable_url, download, download_video, download_audio, download_file, compress, decompress, share, unshare, access, link, unlink, upload, list_trash, restore, tree, search, find_workspaces, read, overview, copy, info, update, task_list, task_add, task_update, task_done, task_rm, task_comment_add, grep) |
444
450
  | `--workspace` | No | AI Drive location. my_drive owns your bytes and quota; shared_drive selects all managed Team, GenTeam, Hub, Work Hub, and authorized knowledge drives; sb_workspace selects only Work Hub drives; team_drive selects only Team Drives; genteam selects only GenTeam channel and DM drives. shared_with_me is an ACL-filtered view across both kinds of container and owns no bytes or quota. GenTeam drives are flat: upload files or share source folders at the root; no native mkdir. In GenTeam channel and DM drives, moving, renaming, and deleting native files needs a channel admin; Team Drive editors can do all three. (string, one of: my_drive, shared_with_me, shared_drive, sb_workspace, team_drive, genteam, default: `my_drive`) |
445
451
  | `--source` | No | Stable source_id returned by ls in a shared workspace. It identifies the storage-owning drive and entry; names are accepted only when unique. For My Drive use workspace=my_drive and omit source; my_drive and Second Brain memo repo ids are not source_ids. (string) |
446
452
  | `--share` | No | Deprecated alias for source, retained for older gsk scripts. (string) |
447
453
  | `--scope` | No | For find only: search My Drive, accessible shared sources, or both. Use all when only a filename is known. Cannot combine with source/id/url; a specific source keeps the existing directory search behavior. Aggregate search is bounded; inspect coverage before concluding a file is absent. (string, one of: mine, shared, all) |
454
+ | `--source_cursor` | No | For a find across sources (scope shared/all, no source/id/url/path): search the sources coverage reported as not yet searched. Pass back the exact coverage.next_source_cursor value with the same query and scope; it returns more sources, not more matches from the ones already searched. (string) |
448
455
  | `--to` | No | Who to share with, for share/unshare: an email address; My Drive also accepts 'org' / 'group:<uid>' and 'channel:<server_id>:<channel_id>' (a GenTeam channel you belong to — the file is opened to its members and, unless post_card is false, posted there as a card). Managed Drive sources use email or general_access; a Team Drive source (workspace=shared_drive, source=<source_id>) also takes 'channel:…' — for its root, or for one entry inside it named by path (relative to the source) or id — when you manage sharing there. A Work Hub root (workspace=sb_workspace, source=<source_id>) accepts only channel:…; its sharing manager can share, change view/edit, or revoke, as in the UI. Also accepted by upload into My Drive: the file is shared the moment it lands and the reply carries the link that opens for them. A new email share notifies that person with the link. A Team Drive email share needs manager rights and an existing account; My Drive can share with an address before it signs up. (string) |
449
456
  | `--post_card` | No | For share to a channel: also post the document card into the channel (default true). A Work Hub posts the UI's share notice only on first share. false grants access without a message. (boolean, default: `True`) |
450
457
  | `--permission` | No | What the recipient or delegated mount may do: view or edit (share/link). The public link audience can only ever view. (string, one of: view, edit, default: `view`) |
@@ -478,6 +485,9 @@ in the UI.
478
485
  | `--overwrite` | No | Set to true to replace the file at upload_path in place (upload only). It keeps the file's id, so a share link already handed out opens the new bytes. Without it, a file_content upload fails when the name exists and a local-file upload is saved as name(1).ext under a new id. Local-file uploads also take --on-conflict overwrite, which gsk 1.10 and later honor; gsk 1.13.1 and earlier ignore --overwrite for them. An overwrite of a .docx, .xlsx, .pptx or .md that is open in a collaboration room is refused with error_code DOCUMENT_IN_COLLABORATION: do not retry it; edit the document through its live room (wo-peer), or upload under a new name and tell the user. (boolean) |
479
486
  | `--content_type` | No | MIME type of the content. If not provided, will be auto-detected from filename. Common types: text/plain, text/markdown, application/json, text/csv (string) |
480
487
  | `--confirmed` | No | Set to true to confirm upload when: (1) file size > 1MB, or (2) content contains potentially sensitive patterns. If confirmation is required but not provided, upload will fail with a warning. (boolean) |
488
+ | `--batch_paths` | No | Compile-only ls: directories relative to path, up to 64 per paged batch. (array) |
489
+ | `--batch_cursor` | No | Compile ls page cursor; keep the same batch_paths. (string) |
490
+ | `--batch_version` | No | Compile inventory source_version from the first page. (string) |
481
491
  | `--ids` | No | Read up to 16 ids, automatically limited to 6 concurrent reads, with one shared output budget. Overview accepts up to 6 ids. Copy takes up to 16 ids from one source in one job. Retain source; omit id/path/offset. (array) |
482
492
  | `--queries` | No | Search: up to 4 queries, each with its own cursor. Grep: up to 16 literal phrases, matching any. Use query or queries, not both. (array) |
483
493
  | `--include_passages` | No | Search: return original passages and citation URLs with hits (default true); false returns navigation only. (boolean, default: `True`) |
@@ -497,7 +507,7 @@ Use the canonical actions below. `gsk drive <action> --help` shows the operation
497
507
 
498
508
  ## Address by id or URL
499
509
 
500
- - Most actions accept `--id <entry_id>` instead of a path: a folder id for `ls`/`find`/`upload`/`mkdir`, a file id for `get_readable_url`/`download`/`rm`/`move`/`share`/`access`. Ids appear in `ls`/`find` rows and in Drive URLs (`#p_fid=…`, `?id=…`, `/s/<owner>/<id>`). Your own drive is tried first, then folders shared with you. (`restore` takes `--entry_id`; `link` names its My Drive entry with `--path`.)
510
+ - Most actions accept `--id <entry_id>` instead of a path: a folder id for `ls`/`find`/`upload`/`mkdir`, a file id for `read`/`get_readable_url`/`download`/`rm`/`move`/`share`/`access`. Ids appear in `ls`/`find` rows and in Drive URLs (`#p_fid=…`, `?id=…`, `/s/<owner>/<id>`). Your own drive is tried first, then folders shared with you. (`restore` takes `--entry_id`; `link` names its My Drive entry with `--path`.)
501
511
  - Add `--owner <cogen_id>` when the URL names one (`/s/<owner>/<id>`, `?link=<owner>:<folder>`), or just pass the whole address with `--url <browser-url>` — the ids are extracted for you.
502
512
  - With a folder id, a `--path`/`--upload_path` you also pass is RELATIVE to that folder: `mkdir --id <folder> --path reports` creates `<folder>/reports`; `upload --id <folder> --local_file x.pdf` lands in the folder.
503
513
  - A web Drive address `/.shared-workspace/<source_id>/…` (the `path=` of a browser URL) works as `--path` and as `--upload_path`: it selects that shared drive under the same edit permission as `--source`. Pass it alone; together with `--source`, `--id` or `--url` it is refused.