@innovatorved/code-lab 0.4.0 → 0.6.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 (82) hide show
  1. package/ARCHITECTURE.md +4 -4
  2. package/CHANGELOG.md +36 -0
  3. package/README.md +6 -30
  4. package/dist/code-lab-sql.esm.js +1 -1
  5. package/dist/code-lab-sql.umd.js +2 -2
  6. package/dist/code-lab.css +32 -5818
  7. package/dist/code-lab.d.ts +1 -1
  8. package/dist/code-lab.esm.js +4655 -64400
  9. package/dist/code-lab.js +4540 -64286
  10. package/dist/code-lab.umd.js +4540 -64286
  11. package/dist/diagnostics.d.ts +3 -0
  12. package/dist/extensions/cpp.d.ts +2 -2
  13. package/dist/extensions/cpp.esm.js +1804 -14725
  14. package/dist/extensions/cpp.js +1804 -14725
  15. package/dist/extensions/guided-lab.esm.js +2938 -16127
  16. package/dist/extensions/guided-lab.js +2938 -16127
  17. package/dist/extensions/python.d.ts +2 -2
  18. package/dist/extensions/python.esm.js +1765 -14698
  19. package/dist/extensions/python.js +1765 -14698
  20. package/dist/index.d.ts +1 -1
  21. package/dist/packages/settings/src/configuration-service.d.ts +7 -0
  22. package/dist/packages/settings/src/index.d.ts +1 -1
  23. package/dist/packages/ui/src/index.d.ts +2 -2
  24. package/dist/packages/ui/src/plugin-registry.d.ts +1 -0
  25. package/dist/packages/ui/src/settings-dialog.d.ts +31 -3
  26. package/dist/packages/ui/src/themes.d.ts +5 -0
  27. package/dist/preview-sw.js +4 -188
  28. package/dist/runtime.esm.js +109 -10284
  29. package/dist/runtime.js +107 -10284
  30. package/dist/schemas.d.ts +2 -2
  31. package/dist/schemas.esm.js +2938 -16127
  32. package/dist/schemas.js +2941 -16130
  33. package/dist/scm.d.ts +296 -14
  34. package/dist/shell.esm.js +811 -9178
  35. package/dist/shell.js +811 -9178
  36. package/dist/storage.d.ts +56 -0
  37. package/dist/terminal.esm.js +20 -1347
  38. package/dist/terminal.js +20 -1347
  39. package/dist/workbench/command-palette.d.ts +16 -1
  40. package/dist/workbench/diff-editor.d.ts +27 -1
  41. package/dist/workbench/icons.d.ts +6 -2
  42. package/dist/workbench/index.d.ts +33 -1
  43. package/dist/workbench/intellisense.d.ts +194 -0
  44. package/dist/workbench/styles.d.ts +1 -1
  45. package/dist/workbench/xterm-adapter.d.ts +122 -0
  46. package/package.json +8 -2
  47. package/packages/commands/package.json +1 -1
  48. package/packages/core/package.json +1 -1
  49. package/packages/editor/package.json +1 -1
  50. package/packages/fs/package.json +1 -1
  51. package/packages/preview/package.json +1 -1
  52. package/packages/runtime/package.json +1 -1
  53. package/packages/settings/package.json +1 -1
  54. package/packages/settings/src/builtin-schemas.ts +17 -6
  55. package/packages/settings/src/configuration-service.ts +72 -6
  56. package/packages/settings/src/index.ts +1 -0
  57. package/packages/sql/package.json +1 -1
  58. package/packages/terminal/package.json +1 -1
  59. package/packages/ui/package.json +1 -1
  60. package/packages/ui/src/index.ts +4 -0
  61. package/packages/ui/src/plugin-registry.ts +17 -2
  62. package/packages/ui/src/settings-dialog.ts +393 -99
  63. package/packages/ui/src/themes.ts +183 -24
  64. package/src/code-lab.css +2763 -444
  65. package/src/diagnostics.ts +139 -7
  66. package/src/extensions/cpp.ts +337 -71
  67. package/src/extensions/python.ts +375 -75
  68. package/src/index.ts +1 -1
  69. package/src/runtime.ts +272 -43
  70. package/src/schemas.ts +2 -2
  71. package/src/scm.ts +2172 -74
  72. package/src/shell.ts +1999 -193
  73. package/src/storage.ts +401 -5
  74. package/src/terminal.ts +148 -12
  75. package/src/workbench/command-palette.ts +289 -48
  76. package/src/workbench/diff-editor.ts +240 -78
  77. package/src/workbench/icons.ts +250 -46
  78. package/src/workbench/index.ts +7 -1
  79. package/src/workbench/intellisense.ts +1859 -0
  80. package/src/workbench/styles.ts +25 -19
  81. package/src/workbench/xterm-adapter.ts +1566 -0
  82. package/src/workbench.ts +13446 -3881
package/src/shell.ts CHANGED
@@ -65,6 +65,17 @@
65
65
  return null;
66
66
  }
67
67
 
68
+ function getScmModule() {
69
+ if (typeof root !== 'undefined' && root && root.CodeLabScm) return root.CodeLabScm;
70
+ if (typeof globalThis !== 'undefined' && globalThis.CodeLabScm) return globalThis.CodeLabScm;
71
+ try {
72
+ if (typeof require !== 'undefined') return require('./scm.js');
73
+ } catch (err) {
74
+ _shellLogger.debug('Optional ./scm.js require skipped in shell.', err);
75
+ }
76
+ return null;
77
+ }
78
+
68
79
  function hasVirtualRuntime() {
69
80
  const rm = getRuntimeModule();
70
81
  return Boolean(rm && typeof rm.executeInVirtualRuntime === 'function');
@@ -78,6 +89,103 @@
78
89
  throw new Error('Virtual runtime engine is not available');
79
90
  }
80
91
 
92
+ async function executeJsInShellRuntime(runOpts, ctx) {
93
+ const rm = getRuntimeModule();
94
+ if (!rm || typeof rm.executeInVirtualRuntime !== 'function') {
95
+ throw new Error('Virtual runtime engine is not available');
96
+ }
97
+
98
+ let sourceCode = typeof runOpts.replCode === 'string' ? runOpts.replCode : '';
99
+ if (!sourceCode && typeof runOpts.entry === 'string' && ctx && ctx.vfs && typeof ctx.vfs.existsSync === 'function') {
100
+ try {
101
+ const absEntry = typeof ctx.resolvePath === 'function' ? ctx.resolvePath(runOpts.entry) : runOpts.entry;
102
+ const candidate = ctx.vfs.existsSync(absEntry) ? absEntry : (ctx.vfs.existsSync(runOpts.entry) ? runOpts.entry : '');
103
+ if (candidate) {
104
+ sourceCode = String(ctx.vfs.readFileSync(candidate, 'utf8') || '');
105
+ }
106
+ } catch (_err) {
107
+ void _err;
108
+ }
109
+ }
110
+
111
+ // Best-effort preload external npm packages if imported and not already in VFS node_modules
112
+ let preloadedNpmModules = runOpts.npmModules;
113
+ const BUILTIN_SPECS = new Set([
114
+ 'assert', 'buffer', 'child_process', 'cluster', 'console', 'constants', 'crypto', 'dgram',
115
+ 'diagnostics_channel', 'dns', 'domain', 'events', 'fs', 'http', 'http2', 'https', 'inspector',
116
+ 'module', 'net', 'os', 'path', 'perf_hooks', 'process', 'punycode', 'querystring', 'readline',
117
+ 'repl', 'sqlite', 'stream', 'string_decoder', 'sys', 'test', 'timers', 'tls', 'tty', 'url',
118
+ 'util', 'v8', 'vm', 'wasi', 'worker_threads', 'zlib'
119
+ ]);
120
+ let hasExternalPkg = false;
121
+ if (sourceCode && !(runOpts.isBackground || (ctx && ctx.isBackground))) {
122
+ const specRe = /(?:from\s+|require\s*\(\s*)['"]([^./'"]+)['"]/g;
123
+ let sm;
124
+ while ((sm = specRe.exec(sourceCode)) !== null) {
125
+ const spec = sm[1];
126
+ if (spec.startsWith('node:') || spec.startsWith('bun:')) continue;
127
+ const rootPkg = spec.startsWith('@') ? spec.split('/').slice(0, 2).join('/') : spec.split('/')[0];
128
+ if (!BUILTIN_SPECS.has(rootPkg)) {
129
+ hasExternalPkg = true;
130
+ break;
131
+ }
132
+ }
133
+ }
134
+ if (hasExternalPkg && typeof rm.preloadNpmPackages === 'function') {
135
+ try {
136
+ const loaded = await rm.preloadNpmPackages({ [runOpts.entry || 'eval.js']: sourceCode });
137
+ if (loaded && typeof loaded === 'object') {
138
+ preloadedNpmModules = Object.assign({}, loaded, preloadedNpmModules || {});
139
+ }
140
+ } catch (err) {
141
+ _shellLogger.debug('preloadNpmPackages skipped in shell:', err);
142
+ }
143
+ }
144
+
145
+ const onRequestStdin =
146
+ (ctx && typeof ctx.onRequestStdin === 'function' ? ctx.onRequestStdin : null) ||
147
+ (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.onRequestStdin === 'function'
148
+ ? ctx.shell.options.onRequestStdin
149
+ : undefined);
150
+
151
+ const portTable = ctx && ctx.shell ? ctx.shell.portTable : null;
152
+ const hasActivePortServers = Boolean(
153
+ portTable && typeof portTable.listServers === 'function' && portTable.listServers().length > 0
154
+ );
155
+ const needsPortTable = Boolean(
156
+ runOpts.isBackground ||
157
+ (ctx && ctx.isBackground) ||
158
+ hasActivePortServers ||
159
+ /(?:\bcreateServer\b|\.listen\s*\(|\bBun\.serve\b|\blocalhost\b|127\.0\.0\.1)/.test(sourceCode)
160
+ );
161
+
162
+ const resolvedInstanceId =
163
+ runOpts.instanceId ||
164
+ (ctx && ctx.shell && ctx.shell.options && ctx.shell.options.instanceId
165
+ ? ctx.shell.options.instanceId
166
+ : undefined);
167
+
168
+ const mergedOpts = {
169
+ ...runOpts,
170
+ ...(resolvedInstanceId ? { instanceId: resolvedInstanceId } : {}),
171
+ concurrent: true,
172
+ npmModules: preloadedNpmModules,
173
+ onRequestStdin
174
+ };
175
+
176
+ if (!needsPortTable && typeof Worker !== 'undefined' && typeof rm.executeInWorker === 'function') {
177
+ const workerOpts = { ...mergedOpts };
178
+ delete workerOpts.activePortTable;
179
+ delete workerOpts.portTable;
180
+ return rm.executeInWorker(workerOpts);
181
+ }
182
+
183
+ return rm.executeInVirtualRuntime({
184
+ ...mergedOpts,
185
+ activePortTable: portTable
186
+ });
187
+ }
188
+
81
189
  function createVirtualPortTable(...args) {
82
190
  const rm = getRuntimeModule();
83
191
  if (rm && typeof rm.createVirtualPortTable === 'function') {
@@ -121,12 +229,13 @@
121
229
 
122
230
  resolve(cwd, ...paths) {
123
231
  let resolved = cwd.startsWith('/') ? cwd : '/' + cwd;
232
+ const homeDir = PosixPath._homeDir || '/home/codelab';
124
233
  for (const p of paths) {
125
234
  if (!p) continue;
126
235
  if (p.startsWith('/')) {
127
236
  resolved = p;
128
237
  } else if (p === '~' || p.startsWith('~/')) {
129
- resolved = '/home/user' + p.slice(1);
238
+ resolved = homeDir + p.slice(1);
130
239
  } else {
131
240
  resolved = resolved.endsWith('/') ? resolved + p : resolved + '/' + p;
132
241
  }
@@ -1592,12 +1701,15 @@
1592
1701
  // =========================================================================
1593
1702
  function createFallbackVfs() {
1594
1703
  const files = new Map();
1595
- const dirs = new Set(['/', '/tmp', '/workspace', '/etc', '/home', '/home/user']);
1704
+ const dirs = new Set(['/', '/tmp', '/workspace', '/etc', '/home', '/home/user', '/home/codelab']);
1596
1705
  let _activeStdin = '';
1706
+ let _currentCwd = '/workspace';
1597
1707
 
1598
1708
  function norm(p) {
1599
1709
  const s = String(p);
1600
- return PosixPath.normalize(s.startsWith('/') ? s : '/workspace/' + s);
1710
+ if (s.startsWith('/')) return PosixPath.normalize(s);
1711
+ const base = _currentCwd && _currentCwd.startsWith('/') ? _currentCwd : '/workspace';
1712
+ return PosixPath.normalize(base.endsWith('/') ? base + s : base + '/' + s);
1601
1713
  }
1602
1714
 
1603
1715
  const emitter = {
@@ -1706,6 +1818,25 @@
1706
1818
  _setActiveStdin(text) {
1707
1819
  _activeStdin = text === null || text === undefined ? '' : String(text);
1708
1820
  },
1821
+ _setCwd(dir) {
1822
+ if (dir && typeof dir === 'string') {
1823
+ _currentCwd = PosixPath.normalize(dir);
1824
+ }
1825
+ },
1826
+ _getRawFileBytes(p) {
1827
+ const np = norm(p);
1828
+ const f = files.get(np);
1829
+ return f && f.rawBytes instanceof Uint8Array ? f.rawBytes : null;
1830
+ },
1831
+ _getAllRawFiles() {
1832
+ const out = {};
1833
+ for (const [k, f] of files.entries()) {
1834
+ if (f && f.rawBytes instanceof Uint8Array) {
1835
+ out[k] = f.rawBytes;
1836
+ }
1837
+ }
1838
+ return out;
1839
+ },
1709
1840
  writeFileSync(p, data) {
1710
1841
  const np = norm(p);
1711
1842
  const parent = PosixPath.dirname(np);
@@ -1830,7 +1961,16 @@
1830
1961
  const s = norm(src);
1831
1962
  const d = norm(dst);
1832
1963
  if (!files.has(s)) throw new Error(`ENOENT: no such file or directory, copy '${src}'`);
1833
- files.set(d, { data: files.get(s).data, mtimeMs: Date.now() });
1964
+ const srcEntry = files.get(s);
1965
+ const rawCopy = srcEntry.rawBytes instanceof Uint8Array
1966
+ ? new Uint8Array(srcEntry.rawBytes)
1967
+ : null;
1968
+ files.set(d, {
1969
+ data: srcEntry.data,
1970
+ rawBytes: rawCopy,
1971
+ mtimeMs: Date.now(),
1972
+ mode: srcEntry.mode !== undefined ? srcEntry.mode : 0o100644
1973
+ });
1834
1974
  }
1835
1975
  };
1836
1976
  }
@@ -1839,6 +1979,11 @@
1839
1979
  // 6. DIFF & LCS UTILITIES (For `diff -u` and `git diff`)
1840
1980
  // =========================================================================
1841
1981
  function computeUnifiedDiff(file1Name, file2Name, text1, text2) {
1982
+ const scm = getScmModule();
1983
+ if (scm && typeof scm.computeUnifiedHunkDiff === 'function') {
1984
+ const hunkDiff = scm.computeUnifiedHunkDiff(file1Name, file2Name, text1, text2, 3);
1985
+ return hunkDiff ? (hunkDiff.endsWith('\n') ? hunkDiff : hunkDiff + '\n') : '';
1986
+ }
1842
1987
  const lines1 = text1.length > 0 ? text1.split('\n') : [];
1843
1988
  const lines2 = text2.length > 0 ? text2.split('\n') : [];
1844
1989
 
@@ -1931,13 +2076,21 @@
1931
2076
  if (httpMatch) {
1932
2077
  owner = httpMatch[1];
1933
2078
  repo = httpMatch[2];
1934
- branch = httpMatch[4] || branch || null;
1935
- subpath = httpMatch[5] ? httpMatch[5].replace(/^\/+|\/+$/g, '') : null;
2079
+ const rawTail = httpMatch[4] ? (httpMatch[5] ? `${httpMatch[4]}/${httpMatch[5].replace(/^\/+|\/+$/g, '')}` : httpMatch[4]) : null;
2080
+ const slashBranchPrefix = rawTail && /^(?:feature|feat|fix|bugfix|hotfix|release|chore|refactor|docs|test|ci|depend|dependabot)\/[^/]+$/.test(rawTail);
2081
+ if (slashBranchPrefix && !branch) {
2082
+ branch = rawTail;
2083
+ subpath = null;
2084
+ } else {
2085
+ branch = httpMatch[4] || branch || null;
2086
+ subpath = httpMatch[5] ? httpMatch[5].replace(/^\/+|\/+$/g, '') : null;
2087
+ }
1936
2088
  return {
1937
2089
  owner,
1938
2090
  repo,
1939
2091
  branch,
1940
2092
  subpath,
2093
+ rawTreeTail: rawTail,
1941
2094
  fullName: `${owner}/${repo}`,
1942
2095
  httpsUrl: `https://github.com/${owner}/${repo}`,
1943
2096
  gitUrl: `https://github.com/${owner}/${repo}.git`,
@@ -2006,6 +2159,415 @@
2006
2159
  return snap;
2007
2160
  }
2008
2161
 
2162
+ function computeGitShortHash(input) {
2163
+ const str = String(input || '');
2164
+ let h1 = 0xdeadbeef ^ str.length;
2165
+ let h2 = 0x41c6ce57 ^ str.length;
2166
+ for (let i = 0; i < str.length; i++) {
2167
+ const ch = str.charCodeAt(i);
2168
+ h1 = Math.imul(h1 ^ ch, 2654435761);
2169
+ h2 = Math.imul(h2 ^ ch, 1597334677);
2170
+ }
2171
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
2172
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
2173
+ const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
2174
+ return combined.toString(16).padStart(7, '0').slice(0, 7);
2175
+ }
2176
+
2177
+ function normalizeGitRelPath(rawPath, repoRoot) {
2178
+ if (!rawPath || typeof rawPath !== 'string') return '';
2179
+ let p = rawPath.trim().replace(/\\/g, '/');
2180
+ if (!p) return '';
2181
+ const cleanRoot = PosixPath.normalize(repoRoot || '/workspace');
2182
+ const prefix = cleanRoot === '/' ? '/' : cleanRoot + '/';
2183
+ if (p === cleanRoot) return '';
2184
+ if (p.startsWith(prefix)) {
2185
+ p = p.slice(prefix.length);
2186
+ } else if (p.startsWith('/workspace/')) {
2187
+ p = p.slice('/workspace/'.length);
2188
+ }
2189
+ while (p.startsWith('./')) p = p.slice(2);
2190
+ if (p.startsWith('/')) p = p.replace(/^\/+/, '');
2191
+
2192
+ const out = [];
2193
+ for (const seg of p.split('/')) {
2194
+ if (!seg || seg === '.') continue;
2195
+ if (seg === '..') {
2196
+ if (out.length === 0) return '';
2197
+ out.pop();
2198
+ continue;
2199
+ }
2200
+ out.push(seg);
2201
+ }
2202
+ const normalized = out.join('/');
2203
+ if (
2204
+ !normalized ||
2205
+ normalized === '.git' ||
2206
+ normalized.startsWith('.git/') ||
2207
+ normalized.includes('/.git/') ||
2208
+ normalized.endsWith('/.git') ||
2209
+ normalized === 'node_modules' ||
2210
+ normalized.startsWith('node_modules/') ||
2211
+ normalized.includes('/node_modules/') ||
2212
+ normalized.endsWith('/node_modules')
2213
+ ) {
2214
+ return '';
2215
+ }
2216
+ return normalized;
2217
+ }
2218
+
2219
+ function isUnbornShellHead(gitState) {
2220
+ return (
2221
+ (!Array.isArray(gitState && gitState.commits) || gitState.commits.length === 0) &&
2222
+ !(gitState && gitState.headCommit)
2223
+ );
2224
+ }
2225
+
2226
+ function isEffectiveShellStagedChange(gitState, relPath, stagedVal, resolvedHeadFiles) {
2227
+ if (!relPath) return false;
2228
+ const headFiles =
2229
+ resolvedHeadFiles || (gitState && (gitState.headSnapshot || gitState.headFiles)) || {};
2230
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
2231
+ const normalizedVal = stagedVal === undefined || stagedVal === null ? null : String(stagedVal);
2232
+
2233
+ if (normalizedVal === null) {
2234
+ return inHead;
2235
+ }
2236
+ if (!inHead || isUnbornShellHead(gitState)) {
2237
+ return true;
2238
+ }
2239
+ return normalizedVal !== headFiles[relPath];
2240
+ }
2241
+
2242
+ function applyShellStagedEntry(gitState, map, rawPath, rawVal, resolvedHeadFiles) {
2243
+ const root = (gitState && gitState.repoRoot) || '/workspace';
2244
+ const rel = normalizeGitRelPath(rawPath, root);
2245
+ if (!rel) return;
2246
+ const normalizedVal = rawVal === undefined || rawVal === null ? null : String(rawVal);
2247
+ if (isEffectiveShellStagedChange(gitState, rel, normalizedVal, resolvedHeadFiles)) {
2248
+ map.set(rel, normalizedVal);
2249
+ } else {
2250
+ map.delete(rel);
2251
+ }
2252
+ }
2253
+
2254
+ function pruneShellStagedMap(gitState, map, resolvedHeadFiles) {
2255
+ if (!(map instanceof Map)) return;
2256
+ const root = (gitState && gitState.repoRoot) || '/workspace';
2257
+ const headFiles =
2258
+ resolvedHeadFiles || (gitState && (gitState.headSnapshot || gitState.headFiles)) || {};
2259
+ for (const [rawK, rawV] of Array.from(map.entries())) {
2260
+ const rel = normalizeGitRelPath(rawK, root);
2261
+ if (rel !== rawK) {
2262
+ map.delete(rawK);
2263
+ }
2264
+ if (!rel) {
2265
+ map.delete(rawK);
2266
+ continue;
2267
+ }
2268
+ const normalizedVal = rawV === undefined || rawV === null ? null : String(rawV);
2269
+ if (isEffectiveShellStagedChange(gitState, rel, normalizedVal, headFiles)) {
2270
+ map.set(rel, normalizedVal);
2271
+ } else {
2272
+ map.delete(rel);
2273
+ }
2274
+ }
2275
+ }
2276
+
2277
+ function getBootSnapshotForDir(shell, initDir) {
2278
+ if (!shell || !shell._initialBootSnapshot || !shell._initialBootRoot) return {};
2279
+ const normInit = PosixPath.normalize(initDir);
2280
+ const normBoot = shell._initialBootRoot;
2281
+ if (normInit === normBoot) {
2282
+ return shell._initialBootSnapshot;
2283
+ }
2284
+ const prefix = normBoot === '/' ? '/' : normBoot + '/';
2285
+ if (normInit.startsWith(prefix)) {
2286
+ const subRel = normInit.slice(prefix.length) + '/';
2287
+ const subSnap = {};
2288
+ for (const [k, v] of Object.entries(shell._initialBootSnapshot)) {
2289
+ if (k.startsWith(subRel)) {
2290
+ subSnap[k.slice(subRel.length)] = v;
2291
+ }
2292
+ }
2293
+ return subSnap;
2294
+ }
2295
+ return {};
2296
+ }
2297
+
2298
+ function attachShellStagedMapShim(map, vfsRef, getRepoRoot, getGitState) {
2299
+ if (!(map instanceof Map)) return map;
2300
+ if (!map._hasShellStagedShim) {
2301
+ Object.defineProperty(map, '_hasShellStagedShim', {
2302
+ value: true,
2303
+ enumerable: false,
2304
+ configurable: true,
2305
+ writable: true
2306
+ });
2307
+ Object.defineProperty(map, 'add', {
2308
+ value(rawPath) {
2309
+ const gs = typeof getGitState === 'function' ? getGitState() : null;
2310
+ const root =
2311
+ typeof getRepoRoot === 'function'
2312
+ ? getRepoRoot()
2313
+ : ((gs && gs.repoRoot) || '/workspace');
2314
+ const rel = normalizeGitRelPath(rawPath, root);
2315
+ if (!rel) return map;
2316
+ let content = null;
2317
+ if (vfsRef && typeof vfsRef.existsSync === 'function') {
2318
+ const abs = PosixPath.join(root, rel);
2319
+ if (vfsRef.existsSync(abs)) {
2320
+ if (typeof vfsRef.statSync === 'function') {
2321
+ try {
2322
+ if (vfsRef.statSync(abs).isDirectory()) return map;
2323
+ } catch (err) {
2324
+ _shellLogger.debug('Failed statting staged path in VFS.', abs, err);
2325
+ }
2326
+ }
2327
+ if (typeof vfsRef.readFileSync === 'function') {
2328
+ try {
2329
+ content = String(vfsRef.readFileSync(abs, 'utf8'));
2330
+ } catch (err) {
2331
+ _shellLogger.debug('Failed reading staged file from VFS.', abs, err);
2332
+ return map;
2333
+ }
2334
+ }
2335
+ }
2336
+ }
2337
+ if (gs) {
2338
+ applyShellStagedEntry(gs, map, rel, content);
2339
+ } else {
2340
+ map.set(rel, content);
2341
+ }
2342
+ return map;
2343
+ },
2344
+ enumerable: false,
2345
+ configurable: true,
2346
+ writable: true
2347
+ });
2348
+ }
2349
+ return map;
2350
+ }
2351
+
2352
+ function ensureShellStagedMap(gitState, vfsRef, repoRoot) {
2353
+ const getRoot = () => (gitState && gitState.repoRoot) || repoRoot || '/workspace';
2354
+ const getGs = () => gitState;
2355
+ if (gitState.staged instanceof Map) {
2356
+ attachShellStagedMapShim(gitState.staged, vfsRef, getRoot, getGs);
2357
+ pruneShellStagedMap(gitState, gitState.staged);
2358
+ gitState.stagedFiles = gitState.staged;
2359
+ return gitState.staged;
2360
+ }
2361
+ const nextMap = attachShellStagedMapShim(new Map(), vfsRef, getRoot, getGs);
2362
+ if (gitState.staged && typeof gitState.staged[Symbol.iterator] === 'function') {
2363
+ for (const item of gitState.staged) {
2364
+ if (Array.isArray(item) && item.length >= 2) {
2365
+ applyShellStagedEntry(
2366
+ gitState,
2367
+ nextMap,
2368
+ item[0],
2369
+ item[1] === null ? null : String(item[1])
2370
+ );
2371
+ } else if (typeof item === 'string') {
2372
+ nextMap.add(item);
2373
+ }
2374
+ }
2375
+ }
2376
+ gitState.staged = nextMap;
2377
+ gitState.stagedFiles = nextMap;
2378
+ return nextMap;
2379
+ }
2380
+
2381
+ function parseGitHeadBranch(vfs, repoRoot) {
2382
+ if (!vfs || typeof vfs.existsSync !== 'function' || typeof vfs.readFileSync !== 'function') {
2383
+ return null;
2384
+ }
2385
+ const candidates = [
2386
+ PosixPath.join(repoRoot, '.git/HEAD'),
2387
+ '/workspace/.git/HEAD'
2388
+ ];
2389
+ for (const headFile of candidates) {
2390
+ if (vfs.existsSync(headFile)) {
2391
+ try {
2392
+ const raw = String(vfs.readFileSync(headFile, 'utf8')).trim();
2393
+ const m = /^ref:\s*refs\/heads\/([^\s]+)$/.exec(raw);
2394
+ if (m && m[1]) return m[1];
2395
+ } catch (err) {
2396
+ _shellLogger.debug('Could not parse .git/HEAD branch.', headFile, err);
2397
+ }
2398
+ }
2399
+ }
2400
+ return null;
2401
+ }
2402
+
2403
+ function createUnifiedShellGitState(vfs, cwd, options = {}) {
2404
+ const cleanCwd = PosixPath.normalize(cwd || '/workspace');
2405
+ const hasDotGit = Boolean(
2406
+ vfs &&
2407
+ typeof vfs.existsSync === 'function' &&
2408
+ (vfs.existsSync(PosixPath.join(cleanCwd, '.git')) ||
2409
+ vfs.existsSync(PosixPath.join(cleanCwd, '.git/HEAD')) ||
2410
+ vfs.existsSync('/workspace/.git') ||
2411
+ vfs.existsSync('/workspace/.git/HEAD'))
2412
+ );
2413
+
2414
+ let _initialized = Boolean(options.gitInitialized === true || hasDotGit);
2415
+ let _repoRoot = cleanCwd;
2416
+ const detectedBranch = hasDotGit ? parseGitHeadBranch(vfs, cleanCwd) : null;
2417
+ const initialBranch = detectedBranch || 'main';
2418
+
2419
+ let _headFiles = _initialized ? snapshotWorktree(vfs, cleanCwd) : {};
2420
+ let _headCommit = _initialized
2421
+ ? computeGitShortHash(JSON.stringify(_headFiles) + ':init')
2422
+ : '';
2423
+ const initTs = Date.now();
2424
+ let _commits = _initialized
2425
+ ? [
2426
+ {
2427
+ hash: _headCommit,
2428
+ author: 'CodeLab Developer <dev@codelab.internal>',
2429
+ date: new Date(initTs).toUTCString(),
2430
+ timestamp: initTs,
2431
+ message: 'Initial commit',
2432
+ files: Object.assign({}, _headFiles)
2433
+ }
2434
+ ]
2435
+ : [];
2436
+
2437
+ const gs = {
2438
+ branch: initialBranch,
2439
+ branches: new Set([initialBranch]),
2440
+ remoteUrl: null,
2441
+ remotes: {}
2442
+ };
2443
+
2444
+ let _stagedMap = attachShellStagedMapShim(new Map(), vfs, () => _repoRoot, () => gs);
2445
+
2446
+ Object.defineProperties(gs, {
2447
+ initialized: {
2448
+ enumerable: true,
2449
+ configurable: true,
2450
+ get() {
2451
+ if (_initialized) return true;
2452
+ const root = _repoRoot || cleanCwd;
2453
+ if (
2454
+ vfs &&
2455
+ typeof vfs.existsSync === 'function' &&
2456
+ (vfs.existsSync(PosixPath.join(root, '.git')) ||
2457
+ vfs.existsSync(PosixPath.join(root, '.git/HEAD')))
2458
+ ) {
2459
+ _initialized = true;
2460
+ return true;
2461
+ }
2462
+ return false;
2463
+ },
2464
+ set(v) {
2465
+ _initialized = Boolean(v);
2466
+ }
2467
+ },
2468
+ repoRoot: {
2469
+ enumerable: true,
2470
+ configurable: true,
2471
+ get() {
2472
+ return _repoRoot;
2473
+ },
2474
+ set(v) {
2475
+ _repoRoot = PosixPath.normalize(String(v || cleanCwd));
2476
+ }
2477
+ },
2478
+ headCommit: {
2479
+ enumerable: true,
2480
+ configurable: true,
2481
+ get() {
2482
+ return _headCommit;
2483
+ },
2484
+ set(v) {
2485
+ _headCommit = String(v || '');
2486
+ }
2487
+ },
2488
+ headSnapshot: {
2489
+ enumerable: true,
2490
+ configurable: true,
2491
+ get() {
2492
+ return _headFiles;
2493
+ },
2494
+ set(v) {
2495
+ _headFiles = v && typeof v === 'object' ? v : {};
2496
+ }
2497
+ },
2498
+ headFiles: {
2499
+ enumerable: true,
2500
+ configurable: true,
2501
+ get() {
2502
+ return _headFiles;
2503
+ },
2504
+ set(v) {
2505
+ _headFiles = v && typeof v === 'object' ? v : {};
2506
+ }
2507
+ },
2508
+ staged: {
2509
+ enumerable: true,
2510
+ configurable: true,
2511
+ get() {
2512
+ return _stagedMap;
2513
+ },
2514
+ set(v) {
2515
+ if (v instanceof Map) {
2516
+ _stagedMap = attachShellStagedMapShim(v, vfs, () => _repoRoot, () => gs);
2517
+ pruneShellStagedMap(gs, _stagedMap);
2518
+ } else {
2519
+ const converted = attachShellStagedMapShim(new Map(), vfs, () => _repoRoot, () => gs);
2520
+ if (v && typeof v[Symbol.iterator] === 'function') {
2521
+ for (const item of v) {
2522
+ if (typeof item === 'string') {
2523
+ converted.add(item);
2524
+ } else if (Array.isArray(item) && item.length >= 2) {
2525
+ applyShellStagedEntry(
2526
+ gs,
2527
+ converted,
2528
+ item[0],
2529
+ item[1] === null ? null : String(item[1])
2530
+ );
2531
+ }
2532
+ }
2533
+ }
2534
+ _stagedMap = converted;
2535
+ }
2536
+ }
2537
+ },
2538
+ stagedFiles: {
2539
+ enumerable: true,
2540
+ configurable: true,
2541
+ get() {
2542
+ return _stagedMap;
2543
+ },
2544
+ set(v) {
2545
+ if (v instanceof Map) {
2546
+ _stagedMap = attachShellStagedMapShim(v, vfs, () => _repoRoot, () => gs);
2547
+ pruneShellStagedMap(gs, _stagedMap);
2548
+ }
2549
+ }
2550
+ },
2551
+ commits: {
2552
+ enumerable: true,
2553
+ configurable: true,
2554
+ get() {
2555
+ return _commits;
2556
+ },
2557
+ set(v) {
2558
+ _commits = Array.isArray(v) ? v : [];
2559
+ if (_commits.length > 0 && _commits[0] && _commits[0].hash) {
2560
+ _headCommit = String(_commits[0].hash);
2561
+ } else if (_commits.length === 0) {
2562
+ _headCommit = '';
2563
+ }
2564
+ }
2565
+ }
2566
+ });
2567
+
2568
+ return gs;
2569
+ }
2570
+
2009
2571
  const BINARY_OR_HEAVY_EXT_RE = /\.(png|jpg|jpeg|gif|webp|ico|bmp|tiff|woff|woff2|ttf|eot|otf|mp3|mp4|wav|ogg|webm|avi|mov|pdf|zip|tar|gz|tgz|bz2|7z|rar|exe|dll|so|dylib|wasm|pyc|pyo|class|jar|war|ear|bin|dat|iso|dmg|pkg|deb|rpm|o|a|lib|DS_Store)$/i;
2010
2572
 
2011
2573
  function scoreRepoFilePriority(relPath) {
@@ -2080,7 +2642,10 @@
2080
2642
 
2081
2643
  if (!repoNotFound) {
2082
2644
  const branchCandidates = requestedBranch
2083
- ? [requestedBranch]
2645
+ ? Array.from(new Set([
2646
+ requestedBranch,
2647
+ (!options.branch && parsed.rawTreeTail && parsed.rawTreeTail !== requestedBranch) ? parsed.rawTreeTail : null
2648
+ ].filter(Boolean)))
2084
2649
  : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2085
2650
 
2086
2651
  for (const cand of branchCandidates) {
@@ -2093,6 +2658,9 @@
2093
2658
  const treeJson = await treeRes.json();
2094
2659
  if (treeJson && Array.isArray(treeJson.tree)) {
2095
2660
  resolvedBranch = cand;
2661
+ if (parsed.rawTreeTail && cand === parsed.rawTreeTail) {
2662
+ parsed.subpath = null;
2663
+ }
2096
2664
  rawTreeEntries = treeJson.tree
2097
2665
  .filter((item) => item && item.type === 'blob' && item.path)
2098
2666
  .map((item) => ({ path: item.path.replace(/^\/+/, ''), size: item.size || 0 }));
@@ -2266,18 +2834,23 @@
2266
2834
  if (commitsRes && commitsRes.ok) {
2267
2835
  const commitsJson = await commitsRes.json();
2268
2836
  if (Array.isArray(commitsJson) && commitsJson.length > 0) {
2269
- commits = commitsJson.map((c) => ({
2270
- hash: String(c.sha || 'a1b2c3d').slice(0, 7),
2271
- author:
2272
- c.commit && c.commit.author
2273
- ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2274
- : `${owner} <${owner}@users.noreply.github.com>`,
2275
- date:
2276
- c.commit && c.commit.author && c.commit.author.date
2277
- ? new Date(c.commit.author.date).toUTCString()
2278
- : new Date().toUTCString(),
2279
- message: c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit'
2280
- }));
2837
+ commits = commitsJson.map((c, idx) => {
2838
+ const msgText = c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit';
2839
+ const fallbackHash = computeGitShortHash(`${owner}/${repo}:${resolvedBranch}:${idx}:${msgText}`);
2840
+ const ts = c.commit && c.commit.author && c.commit.author.date
2841
+ ? Date.parse(c.commit.author.date) || Date.now()
2842
+ : Date.now();
2843
+ return {
2844
+ hash: String(c.sha || fallbackHash).slice(0, 7),
2845
+ author:
2846
+ c.commit && c.commit.author
2847
+ ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2848
+ : `${owner} <${owner}@users.noreply.github.com>`,
2849
+ date: new Date(ts).toUTCString(),
2850
+ timestamp: ts,
2851
+ message: msgText
2852
+ };
2853
+ });
2281
2854
  }
2282
2855
  }
2283
2856
  } catch (err) {
@@ -2285,11 +2858,14 @@
2285
2858
  }
2286
2859
 
2287
2860
  if (commits.length === 0) {
2861
+ const cloneTs = Date.now();
2862
+ const cloneHash = computeGitShortHash(`${owner}/${repo}:${resolvedBranch}:${filesWritten}`);
2288
2863
  commits = [
2289
2864
  {
2290
- hash: 'a1b2c3d',
2865
+ hash: cloneHash,
2291
2866
  author: `${owner} <${owner}@users.noreply.github.com>`,
2292
- date: new Date().toUTCString(),
2867
+ date: new Date(cloneTs).toUTCString(),
2868
+ timestamp: cloneTs,
2293
2869
  message: `Clone ${owner}/${repo} (${resolvedBranch})`
2294
2870
  }
2295
2871
  ];
@@ -2683,7 +3259,15 @@
2683
3259
  depSpecs.push({ name: peer, range: peers[peer] || null });
2684
3260
  }
2685
3261
 
2686
- return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
3262
+ return {
3263
+ ok: true,
3264
+ version,
3265
+ entry,
3266
+ files,
3267
+ deps: depSpecs,
3268
+ pkgBin: meta.bin || null,
3269
+ pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null
3270
+ };
2687
3271
  }
2688
3272
 
2689
3273
  function installTargetDirs(ctx, name) {
@@ -2712,6 +3296,7 @@
2712
3296
  }
2713
3297
  const modPkgPath = PosixPath.join(dir, 'package.json');
2714
3298
  const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
3299
+ if (info.pkgBin) modPkg.bin = info.pkgBin;
2715
3300
  if (info.pkgExports && typeof info.pkgExports === 'object') {
2716
3301
  const normalized = { '.': './' + (info.entry || 'index.js') };
2717
3302
  for (const key of Object.keys(info.pkgExports)) {
@@ -2723,6 +3308,27 @@
2723
3308
  }
2724
3309
  ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
2725
3310
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
3311
+
3312
+ // Populate node_modules/.bin/<binName> shims when package declares `bin`
3313
+ if (info.pkgBin) {
3314
+ const nodeModulesRoot = dir.slice(0, dir.length - name.length - 1);
3315
+ const binDir = PosixPath.join(nodeModulesRoot, '.bin');
3316
+ ensureDirSync(ctx.vfs, binDir, ctx.emitMutation);
3317
+ const binEntries = typeof info.pkgBin === 'string'
3318
+ ? { [name.includes('/') ? name.split('/').pop() : name]: info.pkgBin }
3319
+ : (typeof info.pkgBin === 'object' ? info.pkgBin : {});
3320
+ for (const [binName, relBin] of Object.entries(binEntries)) {
3321
+ if (!binName || !relBin) continue;
3322
+ const targetScript = PosixPath.join(dir, String(relBin).replace(/^\.\//, ''));
3323
+ const shimPath = PosixPath.join(binDir, binName);
3324
+ const shimSource = `// Auto-generated bin shim for ${name}\nrequire(${JSON.stringify(targetScript)});\n`;
3325
+ ctx.vfs.writeFileSync(shimPath, shimSource);
3326
+ if (typeof ctx.vfs.chmodSync === 'function') {
3327
+ try { ctx.vfs.chmodSync(shimPath, 0o755); } catch (_err) { void _err; }
3328
+ }
3329
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', shimPath);
3330
+ }
3331
+ }
2726
3332
  }
2727
3333
  }
2728
3334
 
@@ -2931,7 +3537,27 @@
2931
3537
  }
2932
3538
  const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
2933
3539
  if (fallback) return fallback;
2934
- return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
3540
+ const binPrefix = `${PosixPath.join(ctx.cwd || '/workspace', 'node_modules/.bin')}:/workspace/node_modules/.bin`;
3541
+ const scriptEnv = {
3542
+ ...ctx.env,
3543
+ PATH: ctx.env && ctx.env.PATH ? `${binPrefix}:${ctx.env.PATH}` : `${binPrefix}:/usr/local/bin:/usr/bin:/bin`
3544
+ };
3545
+ const subRes = await ctx.shell.execute(cmd, {
3546
+ cwd: ctx.cwd,
3547
+ env: scriptEnv,
3548
+ stdin: ctx.stdin,
3549
+ signal: ctx.signal,
3550
+ onStdout: ctx.onStdout,
3551
+ onStderr: ctx.onStderr,
3552
+ onRequestStdin: ctx.onRequestStdin || (ctx.shell && ctx.shell.options ? ctx.shell.options.onRequestStdin : undefined)
3553
+ });
3554
+ return {
3555
+ code: subRes.code !== undefined ? subRes.code : 0,
3556
+ stdout: subRes.stdout || '',
3557
+ stderr: subRes.stderr || '',
3558
+ alreadyStreamed: Boolean(ctx.onStdout),
3559
+ aborted: subRes.aborted
3560
+ };
2935
3561
  }
2936
3562
 
2937
3563
  // ---------------------------------------------------------------------------
@@ -3561,14 +4187,19 @@
3561
4187
  },
3562
4188
 
3563
4189
  async cd(args, ctx) {
4190
+ const homeDir = (ctx.env && ctx.env.HOME) || '/home/codelab';
4191
+ PosixPath._homeDir = homeDir;
3564
4192
  let target = args[0];
3565
4193
  if (!target || target === '~') {
3566
- target = ctx.env.HOME || '/workspace';
4194
+ target = homeDir;
3567
4195
  } else if (target === '-') {
3568
4196
  target = ctx.env.OLDPWD || ctx.cwd;
3569
4197
  }
3570
4198
 
3571
4199
  const resolved = ctx.resolvePath(target);
4200
+ if (resolved === homeDir && !ctx.vfs.existsSync(resolved) && typeof ctx.vfs.mkdirSync === 'function') {
4201
+ try { ctx.vfs.mkdirSync(resolved, { recursive: true }); } catch (_err) { void _err; }
4202
+ }
3572
4203
  if (!ctx.vfs.existsSync(resolved)) {
3573
4204
  return { code: 1, stdout: '', stderr: `cd: ${target}: No such file or directory\n` };
3574
4205
  }
@@ -3588,6 +4219,9 @@
3588
4219
  ctx.cwd = resolved;
3589
4220
  ctx.env.OLDPWD = oldPwd;
3590
4221
  ctx.env.PWD = resolved;
4222
+ if (ctx.vfs && typeof ctx.vfs._setCwd === 'function') {
4223
+ ctx.vfs._setCwd(resolved);
4224
+ }
3591
4225
  if (ctx.shell) {
3592
4226
  ctx.shell.cwd = resolved;
3593
4227
  ctx.shell.env.OLDPWD = oldPwd;
@@ -5478,26 +6112,56 @@
5478
6112
  // -----------------------------------------------------------------------
5479
6113
  async git(args, ctx) {
5480
6114
  const subcmd = args[0] || 'status';
6115
+ if (subcmd === 'version' || subcmd === '--version' || subcmd === '-v') {
6116
+ return { code: 0, stdout: 'git version 2.45.0 (CodeLab Virtual Git)\n', stderr: '' };
6117
+ }
6118
+ if (subcmd === 'help' || subcmd === '--help' || subcmd === '-h') {
6119
+ return {
6120
+ code: 0,
6121
+ stdout:
6122
+ 'usage: git <command> [<args>]\n\nCommon commands: init, clone, status, add, diff, commit, restore, reset, rm, branch, checkout, switch, merge, stash, tag, show, blame, remote, fetch, pull, push, log\n',
6123
+ stderr: ''
6124
+ };
6125
+ }
6126
+
5481
6127
  const gitState = ctx.shell.gitState;
5482
6128
  if (!(gitState.branches instanceof Set)) {
5483
6129
  gitState.branches = new Set(Array.isArray(gitState.branches) ? gitState.branches : [gitState.branch || 'main']);
5484
6130
  }
5485
- if (!gitState.headSnapshot) {
5486
- gitState.headSnapshot = snapshotWorktree(ctx.vfs, gitState.repoRoot || ctx.cwd);
5487
- }
5488
6131
  if (!gitState.remotes) {
5489
6132
  gitState.remotes = gitState.remoteUrl ? { origin: gitState.remoteUrl } : {};
5490
6133
  }
5491
6134
 
5492
- const repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6135
+ let repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6136
+ const stagedMap = ensureShellStagedMap(gitState, ctx.vfs, repoRoot);
6137
+
5493
6138
  const toRepoRel = (p) => {
5494
6139
  const abs = ctx.resolvePath(p);
5495
6140
  const prefix = repoRoot === '/' ? '/' : repoRoot + '/';
5496
6141
  if (abs === repoRoot) return '.';
5497
- if (abs.startsWith(prefix)) return abs.slice(prefix.length);
5498
- return p.replace(/^\.\//, '');
6142
+ if (abs.startsWith(prefix)) return normalizeGitRelPath(abs.slice(prefix.length), repoRoot);
6143
+ return '';
5499
6144
  };
5500
6145
 
6146
+ if (subcmd !== 'init' && subcmd !== 'clone') {
6147
+ const hasDotGitInFs = Boolean(
6148
+ ctx.vfs &&
6149
+ typeof ctx.vfs.existsSync === 'function' &&
6150
+ (ctx.vfs.existsSync(PosixPath.join(repoRoot, '.git')) ||
6151
+ ctx.vfs.existsSync(PosixPath.join(ctx.cwd, '.git')))
6152
+ );
6153
+ if (!gitState.initialized && !hasDotGitInFs) {
6154
+ return {
6155
+ code: 128,
6156
+ stdout: '',
6157
+ stderr: 'fatal: not a git repository (or any of the parent directories): .git\n'
6158
+ };
6159
+ }
6160
+ if (hasDotGitInFs && !gitState.initialized) {
6161
+ gitState.initialized = true;
6162
+ }
6163
+ }
6164
+
5501
6165
  if (subcmd === 'clone') {
5502
6166
  let branchOpt = null;
5503
6167
  const positional = [];
@@ -5544,7 +6208,6 @@
5544
6208
  dirDisplayName = parsed.repo;
5545
6209
  }
5546
6210
 
5547
- // Stream clone progress to the terminal as it happens (no end-of-run buffering).
5548
6211
  const canStream = typeof ctx.onStdout === 'function';
5549
6212
  const streamLine = (text) => { if (canStream && text) ctx.onStdout(text); };
5550
6213
  streamLine(`Cloning into '${dirDisplayName}'...\n`);
@@ -5578,14 +6241,18 @@
5578
6241
  }
5579
6242
  });
5580
6243
 
6244
+ const clonedHead = Object.assign({}, result.headSnapshot);
6245
+ gitState.initialized = true;
5581
6246
  gitState.branch = result.branch;
5582
6247
  gitState.branches.add(result.branch);
5583
6248
  gitState.remoteUrl = result.url;
5584
6249
  gitState.remotes.origin = result.url;
5585
6250
  gitState.repoRoot = targetDir;
5586
- gitState.headSnapshot = Object.assign({}, result.headSnapshot);
6251
+ gitState.headSnapshot = clonedHead;
6252
+ gitState.headFiles = clonedHead;
5587
6253
  gitState.commits = result.commits;
5588
- gitState.staged.clear();
6254
+ gitState.headCommit = (result.commits && result.commits[0] && result.commits[0].hash) || '';
6255
+ stagedMap.clear();
5589
6256
 
5590
6257
  const count = Math.max(1, result.filesWritten);
5591
6258
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
@@ -5611,62 +6278,179 @@
5611
6278
  }
5612
6279
 
5613
6280
  if (subcmd === 'init') {
5614
- const initDir = args[1] && !args[1].startsWith('-') ? ctx.resolvePath(args[1]) : ctx.cwd;
6281
+ let initBranch = gitState.branch || 'main';
6282
+ let emptyHead = false;
6283
+ let dirArg = null;
6284
+ for (let i = 1; i < args.length; i++) {
6285
+ const a = args[i];
6286
+ if ((a === '-b' || a === '--initial-branch') && i + 1 < args.length) {
6287
+ initBranch = args[++i];
6288
+ } else if (a.startsWith('--initial-branch=')) {
6289
+ initBranch = a.slice('--initial-branch='.length) || initBranch;
6290
+ } else if (a === '--empty-head') {
6291
+ emptyHead = true;
6292
+ } else if (!a.startsWith('-') && !dirArg) {
6293
+ dirArg = a;
6294
+ }
6295
+ }
6296
+ const initDir = PosixPath.normalize(dirArg ? ctx.resolvePath(dirArg) : ctx.cwd);
5615
6297
  const gitDir = PosixPath.join(initDir, '.git');
6298
+ const wasReinitSameDir =
6299
+ Boolean(gitState.initialized) &&
6300
+ PosixPath.normalize(gitState.repoRoot || ctx.cwd) === initDir &&
6301
+ !emptyHead;
5616
6302
  ensureDirSync(ctx.vfs, gitDir, ctx.emitMutation);
5617
- const branchName = gitState.branch || 'main';
5618
- ctx.vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${branchName}\n`);
6303
+ if (!wasReinitSameDir || !ctx.vfs.existsSync(PosixPath.join(gitDir, 'HEAD'))) {
6304
+ ctx.vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${initBranch}\n`);
6305
+ }
5619
6306
  ctx.vfs.writeFileSync(
5620
6307
  PosixPath.join(gitDir, 'config'),
5621
6308
  `[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n`
5622
6309
  );
5623
6310
  ctx.emitMutation('create', PosixPath.join(gitDir, 'HEAD'));
6311
+
6312
+ if (wasReinitSameDir && !isUnbornShellHead(gitState)) {
6313
+ gitState.branches.add(gitState.branch || initBranch);
6314
+ return {
6315
+ code: 0,
6316
+ stdout: `Reinitialized existing Git repository in ${gitDir}/\n`,
6317
+ stderr: ''
6318
+ };
6319
+ }
6320
+
6321
+ const initSnap = {};
6322
+ if (!emptyHead) {
6323
+ const currentLive = snapshotWorktree(ctx.vfs, initDir);
6324
+ const bootSnap = getBootSnapshotForDir(ctx.shell, initDir);
6325
+ for (const [rel, content] of Object.entries(currentLive)) {
6326
+ if (Object.prototype.hasOwnProperty.call(bootSnap, rel) && bootSnap[rel] === content) {
6327
+ initSnap[rel] = content;
6328
+ }
6329
+ }
6330
+ }
6331
+ gitState.initialized = true;
6332
+ gitState.branch = initBranch;
6333
+ gitState.branches.add(initBranch);
5624
6334
  gitState.repoRoot = initDir;
5625
- gitState.headSnapshot = snapshotWorktree(ctx.vfs, initDir);
5626
- gitState.staged.clear();
5627
- return { code: 0, stdout: `Initialized empty Git repository in ${gitDir}/\n`, stderr: '' };
6335
+ gitState.headSnapshot = initSnap;
6336
+ gitState.headFiles = initSnap;
6337
+ gitState.commits = [];
6338
+ gitState.headCommit = '';
6339
+ stagedMap.clear();
6340
+ return {
6341
+ code: 0,
6342
+ stdout: `${wasReinitSameDir ? 'Reinitialized existing' : 'Initialized empty'} Git repository in ${gitDir}/\n`,
6343
+ stderr: ''
6344
+ };
5628
6345
  }
5629
6346
 
6347
+ repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6348
+ const scmMod = getScmModule();
6349
+
6350
+ const buildIgnoreChecker = (liveMap) => {
6351
+ const rawIgnore = liveMap && typeof liveMap['.gitignore'] === 'string'
6352
+ ? liveMap['.gitignore']
6353
+ : ((gitState.headSnapshot && typeof gitState.headSnapshot['.gitignore'] === 'string') ? gitState.headSnapshot['.gitignore'] : '');
6354
+ if (!rawIgnore) return () => false;
6355
+ if (scmMod && typeof scmMod.parseGitignoreRules === 'function' && typeof scmMod.isIgnoredByRules === 'function') {
6356
+ const rules = scmMod.parseGitignoreRules(rawIgnore);
6357
+ return (relPath) => scmMod.isIgnoredByRules(relPath, rules);
6358
+ }
6359
+ return () => false;
6360
+ };
6361
+
6362
+ const saveCurrentBranchTip = () => {
6363
+ if (scmMod && typeof scmMod.saveBranchTip === 'function') {
6364
+ scmMod.saveBranchTip(gitState);
6365
+ return;
6366
+ }
6367
+ if (!gitState.branchHeads || typeof gitState.branchHeads !== 'object') gitState.branchHeads = {};
6368
+ const curBranch = gitState.branch || 'main';
6369
+ gitState.branchHeads[curBranch] = {
6370
+ headCommit: gitState.headCommit || '',
6371
+ headSnapshot: Object.assign({}, gitState.headSnapshot || gitState.headFiles || {}),
6372
+ commits: Array.isArray(gitState.commits) ? gitState.commits.map((c) => Object.assign({}, c)) : []
6373
+ };
6374
+ };
6375
+
5630
6376
  if (subcmd === 'status') {
5631
- const isShort = args.includes('-s') || args.includes('--short');
6377
+ const isShort = args.includes('-s') || args.includes('--short') || args.includes('--porcelain');
5632
6378
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5633
- const headFiles = gitState.headSnapshot || {};
6379
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6380
+ const isIgnored = buildIgnoreChecker(liveFiles);
6381
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6382
+ const unbornHead = isUnbornShellHead(gitState);
5634
6383
 
5635
6384
  const stagedList = [];
5636
- for (const relPath of gitState.staged) {
6385
+ const unstagedList = [];
6386
+ const untrackedList = [];
6387
+ const stagedKeysSorted = Array.from(stagedMap.keys()).sort();
6388
+
6389
+ for (const relPath of stagedKeysSorted) {
6390
+ const stagedVal = stagedMap.get(relPath);
5637
6391
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
5638
6392
  const inLive = Object.prototype.hasOwnProperty.call(liveFiles, relPath);
5639
- if (!inHead && inLive) {
5640
- stagedList.push({ status: 'new file', short: 'A ', path: relPath });
5641
- } else if (inHead && !inLive) {
5642
- stagedList.push({ status: 'deleted', short: 'D ', path: relPath });
6393
+
6394
+ if (stagedVal === null) {
6395
+ if (inHead) {
6396
+ stagedList.push({ status: 'deleted', code: 'D', path: relPath });
6397
+ }
6398
+ if (inLive && !isIgnored(relPath)) {
6399
+ untrackedList.push(relPath);
6400
+ }
5643
6401
  } else {
5644
- stagedList.push({ status: 'modified', short: 'M ', path: relPath });
6402
+ if (!inHead || unbornHead) {
6403
+ stagedList.push({ status: 'new file', code: 'A', path: relPath });
6404
+ } else if (stagedVal !== headFiles[relPath]) {
6405
+ stagedList.push({ status: 'modified', code: 'M', path: relPath });
6406
+ }
6407
+
6408
+ if (!inLive) {
6409
+ unstagedList.push({ status: 'deleted', code: 'D', path: relPath });
6410
+ } else if (liveFiles[relPath] !== stagedVal) {
6411
+ unstagedList.push({ status: 'modified', code: 'M', path: relPath });
6412
+ }
5645
6413
  }
5646
6414
  }
5647
6415
 
5648
- const unstagedList = [];
5649
6416
  for (const relPath of Object.keys(headFiles).sort()) {
5650
- if (gitState.staged.has(relPath)) continue;
6417
+ if (stagedMap.has(relPath)) continue;
5651
6418
  if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5652
- unstagedList.push({ status: 'deleted', short: ' D', path: relPath });
6419
+ unstagedList.push({ status: 'deleted', code: 'D', path: relPath });
5653
6420
  } else if (liveFiles[relPath] !== headFiles[relPath]) {
5654
- unstagedList.push({ status: 'modified', short: ' M', path: relPath });
6421
+ unstagedList.push({ status: 'modified', code: 'M', path: relPath });
5655
6422
  }
5656
6423
  }
5657
6424
 
5658
- const untrackedList = [];
5659
6425
  for (const relPath of Object.keys(liveFiles).sort()) {
5660
- if (!Object.prototype.hasOwnProperty.call(headFiles, relPath) && !gitState.staged.has(relPath)) {
5661
- untrackedList.push(relPath);
6426
+ if (!Object.prototype.hasOwnProperty.call(headFiles, relPath) && !stagedMap.has(relPath)) {
6427
+ if (!isIgnored(relPath)) {
6428
+ untrackedList.push(relPath);
6429
+ }
5662
6430
  }
5663
6431
  }
5664
6432
 
6433
+ unstagedList.sort((a, b) => a.path.localeCompare(b.path));
6434
+ untrackedList.sort();
6435
+
5665
6436
  if (isShort) {
6437
+ const shortByPath = new Map();
6438
+ for (const item of stagedList) {
6439
+ shortByPath.set(item.path, { idx: item.code, wt: ' ' });
6440
+ }
6441
+ for (const item of unstagedList) {
6442
+ const prev = shortByPath.get(item.path);
6443
+ if (prev) prev.wt = item.code;
6444
+ else shortByPath.set(item.path, { idx: ' ', wt: item.code });
6445
+ }
5666
6446
  let sOut = '';
5667
- for (const item of stagedList) sOut += `${item.short} ${item.path}\n`;
5668
- for (const item of unstagedList) sOut += `${item.short} ${item.path}\n`;
5669
- for (const p of untrackedList) sOut += `?? ${p}\n`;
6447
+ for (const p of Array.from(shortByPath.keys()).sort()) {
6448
+ const pair = shortByPath.get(p);
6449
+ sOut += `${pair.idx}${pair.wt} ${p}\n`;
6450
+ }
6451
+ for (const p of untrackedList) {
6452
+ sOut += `?? ${p}\n`;
6453
+ }
5670
6454
  return { code: 0, stdout: sOut, stderr: '' };
5671
6455
  }
5672
6456
 
@@ -5703,24 +6487,43 @@
5703
6487
 
5704
6488
  if (subcmd === 'diff') {
5705
6489
  const isStaged = args.includes('--staged') || args.includes('--cached');
5706
- const fileFilters = args.slice(1).filter((a) => !a.startsWith('-')).map(toRepoRel);
6490
+ const rawFilterArgs = args.slice(1).filter((a) => !a.startsWith('-'));
6491
+ const fileFilters = rawFilterArgs.map(toRepoRel);
6492
+ const matchAllInRepo = fileFilters.length === 0 || fileFilters.includes('.');
5707
6493
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5708
- const headFiles = gitState.headSnapshot || {};
5709
- const allKeys = Array.from(new Set([...Object.keys(headFiles), ...Object.keys(liveFiles)])).sort();
6494
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6495
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6496
+ const unbornHead = isUnbornShellHead(gitState);
6497
+ const allKeys = Array.from(
6498
+ new Set([...Object.keys(headFiles), ...Object.keys(liveFiles), ...Array.from(stagedMap.keys())])
6499
+ ).sort();
5710
6500
 
5711
6501
  let stdout = '';
5712
6502
  for (const relPath of allKeys) {
5713
- if (fileFilters.length > 0 && !fileFilters.includes(relPath)) continue;
5714
- if (isStaged && !gitState.staged.has(relPath)) continue;
5715
- if (!isStaged && !Object.prototype.hasOwnProperty.call(headFiles, relPath) && !gitState.staged.has(relPath)) {
5716
- continue;
5717
- }
5718
- const oldText = Object.prototype.hasOwnProperty.call(headFiles, relPath) ? headFiles[relPath] : '';
5719
- const newText = Object.prototype.hasOwnProperty.call(liveFiles, relPath) ? liveFiles[relPath] : '';
5720
- if (oldText !== newText) {
5721
- const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
5722
- if (uDiff) {
5723
- stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
6503
+ if (!matchAllInRepo && !fileFilters.includes(relPath)) continue;
6504
+ if (isStaged) {
6505
+ if (!stagedMap.has(relPath)) continue;
6506
+ const stagedVal = stagedMap.get(relPath);
6507
+ if (!isEffectiveShellStagedChange(gitState, relPath, stagedVal, headFiles)) continue;
6508
+ const oldText =
6509
+ !unbornHead && Object.prototype.hasOwnProperty.call(headFiles, relPath)
6510
+ ? headFiles[relPath]
6511
+ : '';
6512
+ const newText = stagedVal === null ? '' : String(stagedVal);
6513
+ if (oldText !== newText) {
6514
+ const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
6515
+ if (uDiff) stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
6516
+ }
6517
+ } else {
6518
+ const isTrackedOrStaged =
6519
+ Object.prototype.hasOwnProperty.call(headFiles, relPath) || stagedMap.has(relPath);
6520
+ if (!isTrackedOrStaged) continue;
6521
+ const baseVal = stagedMap.has(relPath) ? stagedMap.get(relPath) : headFiles[relPath];
6522
+ const oldText = baseVal === null || baseVal === undefined ? '' : String(baseVal);
6523
+ const newText = Object.prototype.hasOwnProperty.call(liveFiles, relPath) ? liveFiles[relPath] : '';
6524
+ if (oldText !== newText) {
6525
+ const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
6526
+ if (uDiff) stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
5724
6527
  }
5725
6528
  }
5726
6529
  }
@@ -5729,39 +6532,89 @@
5729
6532
 
5730
6533
  if (subcmd === 'add') {
5731
6534
  const targets = args.slice(1);
6535
+ const forceAdd = targets.includes('-f') || targets.includes('--force');
5732
6536
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5733
- const headFiles = gitState.headSnapshot || {};
6537
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6538
+ const isIgnored = forceAdd ? () => false : buildIgnoreChecker(liveFiles);
6539
+
6540
+ const stagePath = (relPath, explicitTarget = false) => {
6541
+ const clean = normalizeGitRelPath(relPath, repoRoot);
6542
+ if (!clean) return;
6543
+ const inLive = Object.prototype.hasOwnProperty.call(liveFiles, clean);
6544
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, clean);
6545
+ if (!inHead && !stagedMap.has(clean) && !explicitTarget && isIgnored(clean)) {
6546
+ return;
6547
+ }
6548
+ if (inLive) {
6549
+ applyShellStagedEntry(gitState, stagedMap, clean, liveFiles[clean], headFiles);
6550
+ } else if (inHead) {
6551
+ applyShellStagedEntry(gitState, stagedMap, clean, null, headFiles);
6552
+ } else {
6553
+ stagedMap.delete(clean);
6554
+ }
6555
+ };
5734
6556
 
5735
6557
  if (targets.includes('.') || targets.includes('-A') || targets.includes('--all') || targets.includes('-u')) {
5736
6558
  const includeUntracked = !targets.includes('-u');
5737
6559
  for (const relPath of Object.keys(liveFiles)) {
5738
6560
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
5739
6561
  if (!inHead && includeUntracked) {
5740
- gitState.staged.add(relPath);
5741
- } else if (inHead && liveFiles[relPath] !== headFiles[relPath]) {
5742
- gitState.staged.add(relPath);
6562
+ stagePath(relPath, false);
6563
+ } else if (inHead) {
6564
+ stagePath(relPath, false);
5743
6565
  }
5744
6566
  }
5745
6567
  for (const relPath of Object.keys(headFiles)) {
5746
6568
  if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5747
- gitState.staged.add(relPath);
6569
+ stagePath(relPath, false);
6570
+ }
6571
+ }
6572
+ for (const stagedKey of Array.from(stagedMap.keys())) {
6573
+ if (
6574
+ !Object.prototype.hasOwnProperty.call(liveFiles, stagedKey) &&
6575
+ !Object.prototype.hasOwnProperty.call(headFiles, stagedKey)
6576
+ ) {
6577
+ stagedMap.delete(stagedKey);
5748
6578
  }
5749
6579
  }
5750
6580
  } else {
5751
6581
  for (const f of targets) {
5752
6582
  if (f.startsWith('-')) continue;
5753
6583
  const rel = toRepoRel(f);
6584
+ if (!rel) continue;
5754
6585
  if (rel === '.') {
5755
- for (const k of Object.keys(liveFiles)) {
5756
- if (liveFiles[k] !== headFiles[k]) gitState.staged.add(k);
6586
+ for (const k of Object.keys(liveFiles)) stagePath(k, false);
6587
+ for (const k of Object.keys(headFiles)) {
6588
+ if (!Object.prototype.hasOwnProperty.call(liveFiles, k)) stagePath(k, false);
6589
+ }
6590
+ for (const stagedKey of Array.from(stagedMap.keys())) {
6591
+ if (
6592
+ !Object.prototype.hasOwnProperty.call(liveFiles, stagedKey) &&
6593
+ !Object.prototype.hasOwnProperty.call(headFiles, stagedKey)
6594
+ ) {
6595
+ stagedMap.delete(stagedKey);
6596
+ }
5757
6597
  }
5758
6598
  } else {
5759
6599
  const dirPrefix = rel.replace(/\/+$/, '') + '/';
5760
- const matchedSubfiles = Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix));
6600
+ const matchedSubfiles = Array.from(
6601
+ new Set([
6602
+ ...Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix)),
6603
+ ...Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix)),
6604
+ ...Array.from(stagedMap.keys()).filter((k) => k.startsWith(dirPrefix))
6605
+ ])
6606
+ );
5761
6607
  if (matchedSubfiles.length > 0) {
5762
- for (const k of matchedSubfiles) gitState.staged.add(k);
6608
+ for (const k of matchedSubfiles) stagePath(k, false);
5763
6609
  } else {
5764
- gitState.staged.add(rel);
6610
+ if (!Object.prototype.hasOwnProperty.call(headFiles, rel) && !stagedMap.has(rel) && isIgnored(rel)) {
6611
+ return {
6612
+ code: 1,
6613
+ stdout: '',
6614
+ stderr: `The following paths are ignored by one of your .gitignore files:\n${rel}\nhint: Use -f if you really want to add them.\n`
6615
+ };
6616
+ }
6617
+ stagePath(rel, true);
5765
6618
  }
5766
6619
  }
5767
6620
  }
@@ -5771,40 +6624,77 @@
5771
6624
 
5772
6625
  if (subcmd === 'commit') {
5773
6626
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5774
- const headFiles = gitState.headSnapshot || {};
5775
- if (args.includes('-a') || args.includes('-am')) {
6627
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6628
+ const autoStageTracked = args.some(
6629
+ (a) =>
6630
+ a === '-a' ||
6631
+ a === '--all' ||
6632
+ (a.startsWith('-') && !a.startsWith('--') && a !== '-m' && a.includes('a'))
6633
+ );
6634
+ if (autoStageTracked) {
5776
6635
  for (const relPath of Object.keys(headFiles)) {
5777
- if (liveFiles[relPath] !== headFiles[relPath]) {
5778
- gitState.staged.add(relPath);
6636
+ if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
6637
+ applyShellStagedEntry(gitState, stagedMap, relPath, null, headFiles);
6638
+ } else {
6639
+ applyShellStagedEntry(gitState, stagedMap, relPath, liveFiles[relPath], headFiles);
5779
6640
  }
5780
6641
  }
5781
6642
  }
5782
6643
 
5783
- let msg = 'Commit changes';
5784
- const mIdx = args.findIndex((a) => a === '-m' || a === '-am');
6644
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6645
+
6646
+ if (stagedMap.size === 0) {
6647
+ return {
6648
+ code: 1,
6649
+ stdout: `On branch ${gitState.branch}\nnothing to commit, working tree clean\n`,
6650
+ stderr: ''
6651
+ };
6652
+ }
6653
+
6654
+ let msg = 'Commit changes';
6655
+ const mIdx = args.findIndex(
6656
+ (a) => a === '-m' || a === '-am' || a === '-ma'
6657
+ );
5785
6658
  if (mIdx !== -1 && mIdx + 1 < args.length) msg = args[mIdx + 1];
5786
6659
 
5787
- for (const relPath of gitState.staged) {
5788
- if (Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5789
- gitState.headSnapshot[relPath] = liveFiles[relPath];
6660
+ const nextHead = Object.assign({}, headFiles);
6661
+ const summaryParts = [];
6662
+ for (const [relPath, stagedVal] of stagedMap.entries()) {
6663
+ summaryParts.push(`${relPath}:${stagedVal === null ? '<DEL>' : stagedVal}`);
6664
+ if (stagedVal === null) {
6665
+ delete nextHead[relPath];
5790
6666
  } else {
5791
- delete gitState.headSnapshot[relPath];
6667
+ nextHead[relPath] = String(stagedVal);
5792
6668
  }
5793
6669
  }
5794
6670
 
5795
- const hash = Math.random().toString(16).slice(2, 9);
6671
+ const commitTs = Date.now();
6672
+ const hash = computeGitShortHash(
6673
+ `${gitState.headCommit || ''}:${msg}:${commitTs}:${gitState.commits.length}:${summaryParts.join('|')}`
6674
+ );
6675
+ const count = stagedMap.size;
6676
+ gitState.headSnapshot = nextHead;
6677
+ gitState.headFiles = nextHead;
5796
6678
  gitState.commits.unshift({
5797
6679
  hash,
5798
- author: `${ctx.env.USER || 'codelab'} <dev@codelab.internal>`,
5799
- date: new Date().toUTCString(),
5800
- message: msg
6680
+ author: `${ctx.env.USER || 'CodeLab Developer'} <dev@codelab.internal>`,
6681
+ date: new Date(commitTs).toUTCString(),
6682
+ timestamp: commitTs,
6683
+ message: msg,
6684
+ files: Object.assign({}, nextHead)
5801
6685
  });
5802
- const count = gitState.staged.size || 1;
5803
- gitState.staged.clear();
5804
- return { code: 0, stdout: `[${gitState.branch} ${hash}] ${msg}\n ${count} file changed\n`, stderr: '' };
6686
+ gitState.headCommit = hash;
6687
+ stagedMap.clear();
6688
+ saveCurrentBranchTip();
6689
+ return {
6690
+ code: 0,
6691
+ stdout: `[${gitState.branch} ${hash}] ${msg}\n ${count} file${count === 1 ? '' : 's'} changed\n`,
6692
+ stderr: ''
6693
+ };
5805
6694
  }
5806
6695
 
5807
6696
  if (subcmd === 'branch') {
6697
+ saveCurrentBranchTip();
5808
6698
  const dIdx = args.findIndex((a) => a === '-d' || a === '-D');
5809
6699
  if (dIdx !== -1 && dIdx + 1 < args.length) {
5810
6700
  const target = args[dIdx + 1];
@@ -5812,20 +6702,34 @@
5812
6702
  return { code: 1, stdout: '', stderr: `error: Cannot delete branch '${target}' checked out\n` };
5813
6703
  }
5814
6704
  gitState.branches.delete(target);
6705
+ if (gitState.branchHeads) delete gitState.branchHeads[target];
5815
6706
  return { code: 0, stdout: `Deleted branch ${target}.\n`, stderr: '' };
5816
6707
  }
5817
6708
  const mIdx = args.findIndex((a) => a === '-m' || a === '-M');
5818
6709
  if (mIdx !== -1 && mIdx + 1 < args.length) {
6710
+ const oldName = gitState.branch;
5819
6711
  const newName = args[mIdx + 1];
5820
- gitState.branches.delete(gitState.branch);
6712
+ gitState.branches.delete(oldName);
5821
6713
  gitState.branch = newName;
5822
6714
  gitState.branches.add(newName);
6715
+ if (gitState.branchHeads && gitState.branchHeads[oldName]) {
6716
+ gitState.branchHeads[newName] = gitState.branchHeads[oldName];
6717
+ delete gitState.branchHeads[oldName];
6718
+ }
5823
6719
  return { code: 0, stdout: '', stderr: '' };
5824
6720
  }
5825
6721
  const nonFlags = args.slice(1).filter((a) => !a.startsWith('-'));
5826
6722
  if (nonFlags.length > 0) {
5827
6723
  for (const bName of nonFlags) {
5828
6724
  gitState.branches.add(bName);
6725
+ if (!gitState.branchHeads) gitState.branchHeads = {};
6726
+ if (!gitState.branchHeads[bName]) {
6727
+ gitState.branchHeads[bName] = {
6728
+ headCommit: gitState.headCommit || '',
6729
+ headSnapshot: Object.assign({}, gitState.headSnapshot || gitState.headFiles || {}),
6730
+ commits: Array.isArray(gitState.commits) ? gitState.commits.map((c) => Object.assign({}, c)) : []
6731
+ };
6732
+ }
5829
6733
  }
5830
6734
  return { code: 0, stdout: '', stderr: '' };
5831
6735
  }
@@ -5842,11 +6746,18 @@
5842
6746
  }
5843
6747
 
5844
6748
  if (subcmd === 'checkout' || subcmd === 'switch') {
6749
+ const forceCheckout = args.includes('-f') || args.includes('--force');
5845
6750
  const bIdx = args.findIndex((a) => a === '-b' || a === '-B' || a === '-c' || a === '-C');
5846
6751
  if (bIdx !== -1 && bIdx + 1 < args.length) {
5847
6752
  const newBranch = args[bIdx + 1];
6753
+ saveCurrentBranchTip();
5848
6754
  gitState.branches.add(newBranch);
5849
6755
  gitState.branch = newBranch;
6756
+ saveCurrentBranchTip();
6757
+ const headPath = PosixPath.join(repoRoot, '.git/HEAD');
6758
+ if (ctx.vfs.existsSync(PosixPath.join(repoRoot, '.git'))) {
6759
+ ctx.vfs.writeFileSync(headPath, `ref: refs/heads/${newBranch}\n`);
6760
+ }
5850
6761
  return { code: 0, stdout: `Switched to a new branch '${newBranch}'\n`, stderr: '' };
5851
6762
  }
5852
6763
 
@@ -5856,14 +6767,28 @@
5856
6767
  }
5857
6768
 
5858
6769
  if (gitState.branches.has(target) && !args.includes('--')) {
6770
+ if (scmMod && typeof scmMod.checkoutBranch === 'function') {
6771
+ const chkRes = scmMod.checkoutBranch(ctx.shell, target, undefined, { force: forceCheckout });
6772
+ if (!chkRes.ok) {
6773
+ return { code: 1, stdout: '', stderr: (chkRes.error || `error: cannot checkout '${target}'`) + '\n' };
6774
+ }
6775
+ const headPath = PosixPath.join(repoRoot, '.git/HEAD');
6776
+ if (ctx.vfs.existsSync(PosixPath.join(repoRoot, '.git'))) {
6777
+ ctx.vfs.writeFileSync(headPath, `ref: refs/heads/${target}\n`);
6778
+ }
6779
+ return { code: 0, stdout: `Switched to branch '${target}'\n`, stderr: '' };
6780
+ }
6781
+ saveCurrentBranchTip();
5859
6782
  gitState.branch = target;
5860
6783
  return { code: 0, stdout: `Switched to branch '${target}'\n`, stderr: '' };
5861
6784
  }
5862
6785
 
5863
6786
  const rel = toRepoRel(target);
5864
- if (gitState.headSnapshot && Object.prototype.hasOwnProperty.call(gitState.headSnapshot, rel)) {
6787
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6788
+ if (rel && Object.prototype.hasOwnProperty.call(headFiles, rel)) {
5865
6789
  const abs = PosixPath.join(repoRoot, rel);
5866
- ctx.vfs.writeFileSync(abs, gitState.headSnapshot[rel]);
6790
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6791
+ ctx.vfs.writeFileSync(abs, headFiles[rel]);
5867
6792
  ctx.emitMutation('change', abs);
5868
6793
  return { code: 0, stdout: `Updated 1 path from the index\n`, stderr: '' };
5869
6794
  }
@@ -5873,17 +6798,223 @@
5873
6798
 
5874
6799
  if (subcmd === 'restore') {
5875
6800
  const isStaged = args.includes('--staged') || args.includes('-S');
5876
- const targets = args.slice(1).filter((a) => !a.startsWith('-'));
6801
+ const isWorktree = args.includes('--worktree') || args.includes('-W') || !isStaged;
6802
+ const targets = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6803
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
5877
6804
  for (const t of targets) {
5878
6805
  const rel = toRepoRel(t);
6806
+ if (!rel) continue;
5879
6807
  if (isStaged) {
5880
- gitState.staged.delete(rel);
5881
- } else if (gitState.headSnapshot && Object.prototype.hasOwnProperty.call(gitState.headSnapshot, rel)) {
6808
+ if (rel === '.') {
6809
+ stagedMap.clear();
6810
+ } else {
6811
+ const cleanRel = rel.replace(/\/+$/, '');
6812
+ const dirPrefix = cleanRel + '/';
6813
+ stagedMap.delete(cleanRel);
6814
+ for (const k of Array.from(stagedMap.keys())) {
6815
+ if (k.startsWith(dirPrefix)) {
6816
+ stagedMap.delete(k);
6817
+ }
6818
+ }
6819
+ }
6820
+ }
6821
+ if (isWorktree) {
6822
+ if (rel === '.') {
6823
+ for (const [k, v] of Object.entries(headFiles)) {
6824
+ const abs = PosixPath.join(repoRoot, k);
6825
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6826
+ ctx.vfs.writeFileSync(abs, v);
6827
+ ctx.emitMutation('change', abs);
6828
+ }
6829
+ } else {
6830
+ const cleanRel = rel.replace(/\/+$/, '');
6831
+ const dirPrefix = cleanRel + '/';
6832
+ const subHeadKeys = Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix));
6833
+ if (subHeadKeys.length > 0 && !Object.prototype.hasOwnProperty.call(headFiles, cleanRel)) {
6834
+ for (const k of subHeadKeys) {
6835
+ const sourceText =
6836
+ !isStaged && stagedMap.has(k) && stagedMap.get(k) !== null
6837
+ ? stagedMap.get(k)
6838
+ : headFiles[k];
6839
+ const abs = PosixPath.join(repoRoot, k);
6840
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6841
+ ctx.vfs.writeFileSync(abs, String(sourceText));
6842
+ ctx.emitMutation('change', abs);
6843
+ }
6844
+ } else {
6845
+ const sourceText =
6846
+ !isStaged && stagedMap.has(cleanRel) && stagedMap.get(cleanRel) !== null
6847
+ ? stagedMap.get(cleanRel)
6848
+ : (Object.prototype.hasOwnProperty.call(headFiles, cleanRel) ? headFiles[cleanRel] : undefined);
6849
+ if (sourceText !== undefined) {
6850
+ const abs = PosixPath.join(repoRoot, cleanRel);
6851
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6852
+ ctx.vfs.writeFileSync(abs, String(sourceText));
6853
+ ctx.emitMutation('change', abs);
6854
+ }
6855
+ }
6856
+ }
6857
+ }
6858
+ }
6859
+ return { code: 0, stdout: '', stderr: '' };
6860
+ }
6861
+
6862
+ if (subcmd === 'reset') {
6863
+ const isHard = args.includes('--hard');
6864
+ const isSoft = args.includes('--soft');
6865
+ const mode = isHard ? 'hard' : (isSoft ? 'soft' : 'mixed');
6866
+ const rawPositional = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6867
+
6868
+ // Check if first positional arg is a commit ref (HEAD, HEAD~N, HEAD^, branch, tag, or commit hash)
6869
+ const firstArg = rawPositional[0];
6870
+ const isCommitRef = firstArg && (
6871
+ firstArg === 'HEAD' ||
6872
+ /^HEAD(?:~\d*|\^+)$/i.test(firstArg) ||
6873
+ (scmMod && typeof scmMod.resolveCommitRef === 'function' && scmMod.resolveCommitRef(gitState, firstArg) !== null)
6874
+ );
6875
+
6876
+ if (isCommitRef && rawPositional.length === 1 && firstArg !== 'HEAD' && scmMod && typeof scmMod.resetToRef === 'function') {
6877
+ const resetRes = scmMod.resetToRef(ctx.shell, firstArg, mode);
6878
+ if (!resetRes.ok) {
6879
+ return { code: 128, stdout: '', stderr: (resetRes.error || `fatal: ambiguous argument '${firstArg}'`) + '\n' };
6880
+ }
6881
+ const out = isHard && resetRes.commit
6882
+ ? `HEAD is now at ${resetRes.commit.hash} ${resetRes.commit.message}\n`
6883
+ : '';
6884
+ return { code: 0, stdout: out, stderr: '' };
6885
+ }
6886
+
6887
+ const fileArgs = rawPositional.filter((a) => a !== 'HEAD');
6888
+ if (fileArgs.length > 0 && !isHard && !isSoft) {
6889
+ for (const f of fileArgs) {
6890
+ const rel = toRepoRel(f);
6891
+ if (!rel) continue;
6892
+ if (rel === '.') {
6893
+ stagedMap.clear();
6894
+ } else {
6895
+ const cleanRel = rel.replace(/\/+$/, '');
6896
+ const dirPrefix = cleanRel + '/';
6897
+ stagedMap.delete(cleanRel);
6898
+ for (const k of Array.from(stagedMap.keys())) {
6899
+ if (k.startsWith(dirPrefix)) {
6900
+ stagedMap.delete(k);
6901
+ }
6902
+ }
6903
+ }
6904
+ }
6905
+ return { code: 0, stdout: '', stderr: '' };
6906
+ }
6907
+
6908
+ if (!isSoft) {
6909
+ stagedMap.clear();
6910
+ }
6911
+ if (isHard) {
6912
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6913
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6914
+ for (const rel of Object.keys(liveFiles)) {
6915
+ if (!Object.prototype.hasOwnProperty.call(headFiles, rel)) {
6916
+ const abs = PosixPath.join(repoRoot, rel);
6917
+ if (typeof ctx.vfs.rmSync === 'function') {
6918
+ ctx.vfs.rmSync(abs, { force: true });
6919
+ } else if (typeof ctx.vfs.unlinkSync === 'function' && ctx.vfs.existsSync(abs)) {
6920
+ ctx.vfs.unlinkSync(abs);
6921
+ }
6922
+ ctx.emitMutation('delete', abs);
6923
+ }
6924
+ }
6925
+ for (const [rel, text] of Object.entries(headFiles)) {
5882
6926
  const abs = PosixPath.join(repoRoot, rel);
5883
- ctx.vfs.writeFileSync(abs, gitState.headSnapshot[rel]);
6927
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6928
+ ctx.vfs.writeFileSync(abs, text);
5884
6929
  ctx.emitMutation('change', abs);
5885
6930
  }
5886
6931
  }
6932
+ saveCurrentBranchTip();
6933
+ return { code: 0, stdout: '', stderr: '' };
6934
+ }
6935
+
6936
+ if (subcmd === 'rm') {
6937
+ const cachedOnly = args.includes('--cached');
6938
+ const isRecursive = args.some((a) => a === '-r' || a === '-rf' || a === '-fr');
6939
+ const targets = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6940
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6941
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6942
+
6943
+ if (targets.length === 0) {
6944
+ return { code: 128, stdout: '', stderr: 'usage: git rm [--cached] [-r] [-f] <file>...\n' };
6945
+ }
6946
+
6947
+ const removeSingleRel = (rel) => {
6948
+ if (!rel) return;
6949
+ const abs = PosixPath.join(repoRoot, rel);
6950
+ if (!cachedOnly && ctx.vfs.existsSync(abs)) {
6951
+ if (typeof ctx.vfs.rmSync === 'function') {
6952
+ ctx.vfs.rmSync(abs, { force: true, recursive: isRecursive });
6953
+ } else if (typeof ctx.vfs.unlinkSync === 'function') {
6954
+ ctx.vfs.unlinkSync(abs);
6955
+ }
6956
+ ctx.emitMutation('delete', abs);
6957
+ }
6958
+ if (Object.prototype.hasOwnProperty.call(headFiles, rel)) {
6959
+ stagedMap.set(rel, null);
6960
+ } else {
6961
+ stagedMap.delete(rel);
6962
+ }
6963
+ };
6964
+
6965
+ for (const t of targets) {
6966
+ const rel = toRepoRel(t);
6967
+ if (!rel) continue;
6968
+ if (rel === '.') {
6969
+ if (isRecursive) {
6970
+ const allRel = Array.from(
6971
+ new Set([
6972
+ ...Object.keys(headFiles),
6973
+ ...Object.keys(liveFiles),
6974
+ ...Array.from(stagedMap.keys())
6975
+ ])
6976
+ );
6977
+ for (const sub of allRel) removeSingleRel(sub);
6978
+ }
6979
+ continue;
6980
+ }
6981
+ const dirPrefix = rel.replace(/\/+$/, '') + '/';
6982
+ const subMatches = isRecursive
6983
+ ? Array.from(
6984
+ new Set([
6985
+ ...Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix)),
6986
+ ...Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix)),
6987
+ ...Array.from(stagedMap.keys()).filter((k) => k.startsWith(dirPrefix))
6988
+ ])
6989
+ )
6990
+ : [];
6991
+ if (subMatches.length > 0) {
6992
+ for (const sub of subMatches) removeSingleRel(sub);
6993
+ if (!cachedOnly) removeDirRecursive(ctx.vfs, PosixPath.join(repoRoot, rel), ctx.emitMutation);
6994
+ } else {
6995
+ const abs = PosixPath.join(repoRoot, rel);
6996
+ if (
6997
+ !isRecursive &&
6998
+ ctx.vfs &&
6999
+ typeof ctx.vfs.existsSync === 'function' &&
7000
+ ctx.vfs.existsSync(abs) &&
7001
+ typeof ctx.vfs.statSync === 'function'
7002
+ ) {
7003
+ try {
7004
+ if (ctx.vfs.statSync(abs).isDirectory()) {
7005
+ return {
7006
+ code: 128,
7007
+ stdout: '',
7008
+ stderr: `fatal: not removing '${t}' recursively without -r\n`
7009
+ };
7010
+ }
7011
+ } catch (err) {
7012
+ _shellLogger.debug('Failed statting path in git rm.', abs, err);
7013
+ }
7014
+ }
7015
+ removeSingleRel(rel);
7016
+ }
7017
+ }
5887
7018
  return { code: 0, stdout: '', stderr: '' };
5888
7019
  }
5889
7020
 
@@ -5934,7 +7065,9 @@
5934
7065
  signal: ctx.signal,
5935
7066
  onFile: (absPath) => ctx.emitMutation('change', absPath)
5936
7067
  });
5937
- gitState.headSnapshot = Object.assign({}, result.headSnapshot);
7068
+ const pulledHead = Object.assign({}, result.headSnapshot);
7069
+ gitState.headSnapshot = pulledHead;
7070
+ gitState.headFiles = pulledHead;
5938
7071
  return {
5939
7072
  code: 0,
5940
7073
  stdout: `From ${remoteUrl.replace(/\.git$/, '')}\n * branch ${result.branch} -> FETCH_HEAD\nAlready up to date.\n`,
@@ -5949,6 +7082,144 @@
5949
7082
  }
5950
7083
  }
5951
7084
 
7085
+ if (subcmd === 'stash') {
7086
+ if (!Array.isArray(gitState.stashes)) gitState.stashes = [];
7087
+ const action = args[1] && !args[1].startsWith('-') ? args[1] : 'push';
7088
+ if (action === 'list') {
7089
+ const lines = gitState.stashes.map((s, idx) => `stash@{${idx}}: ${s.message}`);
7090
+ return { code: 0, stdout: lines.length ? lines.join('\n') + '\n' : '', stderr: '' };
7091
+ }
7092
+ if (action === 'clear') {
7093
+ gitState.stashes = [];
7094
+ return { code: 0, stdout: '', stderr: '' };
7095
+ }
7096
+ if (action === 'drop') {
7097
+ const idxMatch = (args[2] || 'stash@{0}').match(/(\d+)/);
7098
+ const idx = idxMatch ? parseInt(idxMatch[1], 10) : 0;
7099
+ if (idx < 0 || idx >= gitState.stashes.length) {
7100
+ return { code: 1, stdout: '', stderr: `error: stash@{${idx}} is not a valid reference\n` };
7101
+ }
7102
+ gitState.stashes.splice(idx, 1);
7103
+ return { code: 0, stdout: `Dropped stash@{${idx}}\n`, stderr: '' };
7104
+ }
7105
+ if (action === 'pop' || action === 'apply') {
7106
+ const idxMatch = (args[2] || 'stash@{0}').match(/(\d+)/);
7107
+ const idx = idxMatch ? parseInt(idxMatch[1], 10) : 0;
7108
+ if (scmMod && typeof scmMod.stashApply === 'function') {
7109
+ const res = scmMod.stashApply(ctx.shell, idx, action === 'pop');
7110
+ if (!res.ok) return { code: 1, stdout: '', stderr: (res.error || 'No stash entries found.') + '\n' };
7111
+ return { code: 0, stdout: `Restored working directory from stash@{${idx}}\n`, stderr: '' };
7112
+ }
7113
+ return { code: 1, stdout: '', stderr: 'No stash entries found.\n' };
7114
+ }
7115
+ if (action === 'push' || action === 'save') {
7116
+ let msg = undefined;
7117
+ const mIdx = args.findIndex((a) => a === '-m' || a === '--message');
7118
+ if (mIdx !== -1 && args[mIdx + 1]) msg = args[mIdx + 1];
7119
+ else if (action === 'save' && args[2]) msg = args.slice(2).join(' ');
7120
+ const includeUntracked = args.includes('-u') || args.includes('--include-untracked');
7121
+ if (scmMod && typeof scmMod.stashPush === 'function') {
7122
+ const res = scmMod.stashPush(ctx.shell, msg, includeUntracked);
7123
+ if (!res.ok) {
7124
+ return { code: 1, stdout: '', stderr: (res.label || 'not a git repository') + '\n' };
7125
+ }
7126
+ return { code: 0, stdout: (res.label || 'No local changes to save') + '\n', stderr: '' };
7127
+ }
7128
+ }
7129
+ return { code: 1, stdout: '', stderr: `git stash: unknown subcommand '${action}'\n` };
7130
+ }
7131
+
7132
+ if (subcmd === 'merge') {
7133
+ const noFf = args.includes('--no-ff');
7134
+ const sourceBranch = args.slice(1).find((a) => !a.startsWith('-'));
7135
+ if (!sourceBranch) {
7136
+ return { code: 1, stdout: '', stderr: 'fatal: No branch specified to merge.\n' };
7137
+ }
7138
+ if (scmMod && typeof scmMod.mergeBranch === 'function') {
7139
+ const res = scmMod.mergeBranch(ctx.shell, sourceBranch, undefined, { noFf });
7140
+ if (!res.ok && (!res.conflicts || res.conflicts.length === 0)) {
7141
+ return { code: 1, stdout: '', stderr: (res.error || `merge: ${sourceBranch} - not something we can merge`) + '\n' };
7142
+ }
7143
+ if (res.conflicts && res.conflicts.length > 0) {
7144
+ return {
7145
+ code: 1,
7146
+ stdout: res.conflicts.map((f) => `CONFLICT (content): Merge conflict in ${f}`).join('\n') + '\nAutomatic merge failed; fix conflicts and then commit the result.\n',
7147
+ stderr: ''
7148
+ };
7149
+ }
7150
+ if (res.fastForward && res.commit) {
7151
+ return { code: 0, stdout: `Updating ..${res.commit.hash}\nFast-forward\n`, stderr: '' };
7152
+ }
7153
+ if (res.commit) {
7154
+ return { code: 0, stdout: `Merge made by the 'ort' strategy.\n[${gitState.branch} ${res.commit.hash}] ${res.commit.message}\n`, stderr: '' };
7155
+ }
7156
+ return { code: 0, stdout: 'Already up to date.\n', stderr: '' };
7157
+ }
7158
+ return { code: 1, stdout: '', stderr: 'git merge: SCM module unavailable\n' };
7159
+ }
7160
+
7161
+ if (subcmd === 'tag') {
7162
+ if (!gitState.tags || typeof gitState.tags !== 'object') gitState.tags = {};
7163
+ if (args[1] === '-d' && args[2]) {
7164
+ if (!gitState.tags[args[2]]) {
7165
+ return { code: 1, stdout: '', stderr: `error: tag '${args[2]}' not found.\n` };
7166
+ }
7167
+ delete gitState.tags[args[2]];
7168
+ return { code: 0, stdout: `Deleted tag '${args[2]}'\n`, stderr: '' };
7169
+ }
7170
+ const tagName = args.slice(1).find((a) => !a.startsWith('-'));
7171
+ if (!tagName) {
7172
+ const list = Object.keys(gitState.tags).sort();
7173
+ return { code: 0, stdout: list.length ? list.join('\n') + '\n' : '', stderr: '' };
7174
+ }
7175
+ if (!gitState.headCommit) {
7176
+ return { code: 128, stdout: '', stderr: `fatal: Failed to resolve 'HEAD' as a valid ref.\n` };
7177
+ }
7178
+ gitState.tags[tagName] = gitState.headCommit;
7179
+ return { code: 0, stdout: '', stderr: '' };
7180
+ }
7181
+
7182
+ if (subcmd === 'show') {
7183
+ const ref = args.slice(1).find((a) => !a.startsWith('-')) || 'HEAD';
7184
+ if (scmMod && typeof scmMod.showCommit === 'function') {
7185
+ const out = scmMod.showCommit(gitState, ref);
7186
+ if (!out) return { code: 128, stdout: '', stderr: `fatal: bad object ${ref}\n` };
7187
+ return { code: 0, stdout: out, stderr: '' };
7188
+ }
7189
+ return { code: 128, stdout: '', stderr: `fatal: bad object ${ref}\n` };
7190
+ }
7191
+
7192
+ if (subcmd === 'blame') {
7193
+ const fileArg = args.slice(1).find((a) => !a.startsWith('-'));
7194
+ if (!fileArg) return { code: 128, stdout: '', stderr: 'usage: git blame <file>\n' };
7195
+ const rel = toRepoRel(fileArg);
7196
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
7197
+ if (scmMod && typeof scmMod.blameFile === 'function') {
7198
+ const out = scmMod.blameFile(gitState, rel, liveFiles);
7199
+ if (!out && !Object.prototype.hasOwnProperty.call(liveFiles, rel)) {
7200
+ return { code: 128, stdout: '', stderr: `fatal: no such path '${fileArg}' in HEAD\n` };
7201
+ }
7202
+ return { code: 0, stdout: out, stderr: '' };
7203
+ }
7204
+ return { code: 128, stdout: '', stderr: `fatal: no such path '${fileArg}' in HEAD\n` };
7205
+ }
7206
+
7207
+ if (subcmd === 'push') {
7208
+ const remoteUrl = gitState.remoteUrl || (gitState.remotes && gitState.remotes.origin);
7209
+ if (!remoteUrl) {
7210
+ return {
7211
+ code: 128,
7212
+ stdout: '',
7213
+ stderr: 'fatal: No configured push destination.\nEither specify the URL from the command-line or configure a remote repository using\n\n git remote add <name> <url>\n'
7214
+ };
7215
+ }
7216
+ return {
7217
+ code: 128,
7218
+ stdout: '',
7219
+ stderr: `fatal: Authentication required to push to '${remoteUrl}' from browser sandbox.\n`
7220
+ };
7221
+ }
7222
+
5952
7223
  if (subcmd === 'log') {
5953
7224
  const oneline = args.includes('--oneline');
5954
7225
  let limit = gitState.commits.length;
@@ -5961,16 +7232,22 @@
5961
7232
  if (oneline) {
5962
7233
  stdout += `${c.hash} ${c.message}\n`;
5963
7234
  } else {
7235
+ const authorStr = c.author || 'CodeLab Developer <dev@codelab.internal>';
7236
+ const dateStr = c.date || (c.timestamp ? new Date(c.timestamp).toUTCString() : new Date(0).toUTCString());
5964
7237
  stdout += `commit ${c.hash}\n`;
5965
- stdout += `Author: ${c.author}\n`;
5966
- stdout += `Date: ${c.date}\n\n`;
7238
+ stdout += `Author: ${authorStr}\n`;
7239
+ stdout += `Date: ${dateStr}\n\n`;
5967
7240
  stdout += ` ${c.message}\n\n`;
5968
7241
  }
5969
7242
  }
5970
7243
  return { code: 0, stdout, stderr: '' };
5971
7244
  }
5972
7245
 
5973
- return { code: 0, stdout: `git: '${subcmd}' executed\n`, stderr: '' };
7246
+ return {
7247
+ code: 1,
7248
+ stdout: '',
7249
+ stderr: `git: '${subcmd}' is not a git command. See 'git --help'.\n`
7250
+ };
5974
7251
  },
5975
7252
 
5976
7253
  // -----------------------------------------------------------------------
@@ -6029,14 +7306,98 @@
6029
7306
  if (!hasVirtualRuntime()) {
6030
7307
  return { code: 1, stdout: '', stderr: 'node: Virtual runtime engine is not available\n' };
6031
7308
  }
6032
- if (args.length === 0 || args[0] === '-v' || args[0] === '--version') {
6033
- if (args[0] === '-v' || args[0] === '--version') return { code: 0, stdout: 'v22.0.0\n', stderr: '' };
7309
+ if (args[0] === '-v' || args[0] === '--version') {
7310
+ return { code: 0, stdout: 'v22.0.0\n', stderr: '' };
7311
+ }
7312
+ if (args.length === 0 || args[0] === '-i' || args[0] === '--interactive') {
7313
+ const onRequestStdin =
7314
+ (typeof ctx.onRequestStdin === 'function' ? ctx.onRequestStdin : null) ||
7315
+ (ctx.shell && ctx.shell.options && typeof ctx.shell.options.onRequestStdin === 'function'
7316
+ ? ctx.shell.options.onRequestStdin
7317
+ : null);
7318
+ if (ctx.stdin && !onRequestStdin) {
7319
+ const res = await executeJsInShellRuntime({
7320
+ mode: 'repl',
7321
+ replCode: ctx.stdin,
7322
+ printReplResult: true,
7323
+ stdin: '',
7324
+ env: ctx.env,
7325
+ cwd: ctx.cwd,
7326
+ vfs: ctx.vfs,
7327
+ pid: ctx.pid,
7328
+ isBackground: ctx.isBackground,
7329
+ onStdout: ctx.onStdout,
7330
+ onStderr: ctx.onStderr,
7331
+ signal: ctx.signal
7332
+ }, ctx);
7333
+ return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
7334
+ }
7335
+ if (onRequestStdin && !ctx.stdin) {
7336
+ const banner = 'Welcome to Node.js v22.0.0.\nType ".help" for more information.\n';
7337
+ let fullOut = banner;
7338
+ let fullErr = '';
7339
+ if (ctx.onStdout) ctx.onStdout(banner);
7340
+ const replSessionId = 'node_repl_' + Date.now() + '_' + Math.random().toString(36).slice(2, 7);
7341
+ const rm = getRuntimeModule();
7342
+ try {
7343
+ while (!(ctx.signal && ctx.signal.aborted)) {
7344
+ const line = await onRequestStdin('> ');
7345
+ if (line === null || line === undefined) break;
7346
+ const trimmed = String(line).trim();
7347
+ if (trimmed === '.exit') break;
7348
+ if (trimmed === '.help') {
7349
+ const helpMsg =
7350
+ '.break Sometimes you get stuck, this gets you out\n' +
7351
+ '.clear Break, and also clear the local context\n' +
7352
+ '.exit Exit the REPL\n' +
7353
+ '.help Print this help message\n';
7354
+ fullOut += helpMsg;
7355
+ if (ctx.onStdout) ctx.onStdout(helpMsg);
7356
+ continue;
7357
+ }
7358
+ if (trimmed === '.clear' || trimmed === '.break') {
7359
+ if (trimmed === '.clear' && rm && typeof rm.clearReplSession === 'function') {
7360
+ rm.clearReplSession(replSessionId);
7361
+ }
7362
+ continue;
7363
+ }
7364
+ if (!trimmed) continue;
7365
+ const stepRes = await executeInVirtualRuntime({
7366
+ mode: 'repl',
7367
+ replSessionId,
7368
+ replCode: String(line),
7369
+ printReplResult: true,
7370
+ env: ctx.env,
7371
+ cwd: ctx.cwd,
7372
+ vfs: ctx.vfs,
7373
+ activePortTable: ctx.shell ? ctx.shell.portTable : null,
7374
+ pid: ctx.pid,
7375
+ onRequestStdin,
7376
+ onStdout: (t) => {
7377
+ fullOut += t;
7378
+ if (ctx.onStdout) ctx.onStdout(t);
7379
+ },
7380
+ onStderr: (t) => {
7381
+ fullErr += t;
7382
+ if (ctx.onStderr) ctx.onStderr(t);
7383
+ },
7384
+ signal: ctx.signal
7385
+ });
7386
+ void stepRes;
7387
+ }
7388
+ } finally {
7389
+ if (rm && typeof rm.clearReplSession === 'function') {
7390
+ rm.clearReplSession(replSessionId);
7391
+ }
7392
+ }
7393
+ return { code: 0, stdout: fullOut, stderr: fullErr, alreadyStreamed: true };
7394
+ }
6034
7395
  return { code: 0, stdout: 'Welcome to Node.js v22.0.0.\nType ".help" for more information.\n', stderr: '' };
6035
7396
  }
6036
7397
 
6037
7398
  if (args[0] === '-e' || args[0] === '--eval') {
6038
7399
  const code = args[1] || '';
6039
- const res = await executeInVirtualRuntime({
7400
+ const res = await executeJsInShellRuntime({
6040
7401
  mode: 'repl',
6041
7402
  replCode: code,
6042
7403
  printReplResult: false,
@@ -6044,19 +7405,18 @@
6044
7405
  env: ctx.env,
6045
7406
  cwd: ctx.cwd,
6046
7407
  vfs: ctx.vfs,
6047
- activePortTable: ctx.shell.portTable,
6048
7408
  pid: ctx.pid,
6049
7409
  isBackground: ctx.isBackground,
6050
7410
  onStdout: ctx.onStdout,
6051
7411
  onStderr: ctx.onStderr,
6052
7412
  signal: ctx.signal
6053
- });
7413
+ }, ctx);
6054
7414
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
6055
7415
  }
6056
7416
 
6057
7417
  if (args[0] === '-p' || args[0] === '--print') {
6058
7418
  const code = args[1] || '';
6059
- const res = await executeInVirtualRuntime({
7419
+ const res = await executeJsInShellRuntime({
6060
7420
  mode: 'repl',
6061
7421
  replCode: code,
6062
7422
  printReplResult: true,
@@ -6064,13 +7424,12 @@
6064
7424
  env: ctx.env,
6065
7425
  cwd: ctx.cwd,
6066
7426
  vfs: ctx.vfs,
6067
- activePortTable: ctx.shell.portTable,
6068
7427
  pid: ctx.pid,
6069
7428
  isBackground: ctx.isBackground,
6070
7429
  onStdout: ctx.onStdout,
6071
7430
  onStderr: ctx.onStderr,
6072
7431
  signal: ctx.signal
6073
- });
7432
+ }, ctx);
6074
7433
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
6075
7434
  }
6076
7435
 
@@ -6085,7 +7444,7 @@
6085
7444
  for (const item of ctx.vfs.readdirSync(dir)) {
6086
7445
  const full = PosixPath.join(dir, item);
6087
7446
  const st = ctx.vfs.statSync(full);
6088
- if (st.isDirectory() && item !== 'node_modules') {
7447
+ if (st.isDirectory() && item !== 'node_modules' && item !== '.git') {
6089
7448
  findTests(full);
6090
7449
  } else if (item.endsWith('.test.js') || item.endsWith('.test.ts') || item === 'test.js') {
6091
7450
  filesToRun.push(full);
@@ -6099,20 +7458,19 @@
6099
7458
  let combinedErr = '';
6100
7459
  let allOk = true;
6101
7460
  for (const f of filesToRun) {
6102
- const res = await executeInVirtualRuntime({
7461
+ const res = await executeJsInShellRuntime({
6103
7462
  mode: 'test',
6104
7463
  entry: f,
6105
7464
  stdin: ctx.stdin || '',
6106
7465
  env: ctx.env,
6107
7466
  cwd: ctx.cwd,
6108
7467
  vfs: ctx.vfs,
6109
- activePortTable: ctx.shell.portTable,
6110
7468
  pid: ctx.pid,
6111
7469
  isBackground: ctx.isBackground,
6112
7470
  onStdout: ctx.onStdout,
6113
7471
  onStderr: ctx.onStderr,
6114
7472
  signal: ctx.signal
6115
- });
7473
+ }, ctx);
6116
7474
  combinedOut += res.stdout;
6117
7475
  combinedErr += res.stderr;
6118
7476
  if (!res.ok) allOk = false;
@@ -6126,7 +7484,7 @@
6126
7484
  }
6127
7485
 
6128
7486
  const scriptArgs = args.slice(1);
6129
- const res = await executeInVirtualRuntime({
7487
+ const res = await executeJsInShellRuntime({
6130
7488
  mode: 'run',
6131
7489
  entry: scriptFile,
6132
7490
  argv: ['node', scriptFile, ...scriptArgs],
@@ -6134,13 +7492,12 @@
6134
7492
  env: ctx.env,
6135
7493
  cwd: ctx.cwd,
6136
7494
  vfs: ctx.vfs,
6137
- activePortTable: ctx.shell.portTable,
6138
7495
  pid: ctx.pid,
6139
7496
  isBackground: ctx.isBackground,
6140
7497
  onStdout: ctx.onStdout,
6141
7498
  onStderr: ctx.onStderr,
6142
7499
  signal: ctx.signal
6143
- });
7500
+ }, ctx);
6144
7501
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
6145
7502
  },
6146
7503
 
@@ -6264,12 +7621,72 @@
6264
7621
  },
6265
7622
 
6266
7623
  async python3(args, ctx) {
6267
- if (args.length === 0) {
7624
+ if (args[0] === '--version' || args[0] === '-V') {
6268
7625
  return { code: 0, stdout: 'Python 3.12.8 (CPython WebAssembly via Pyodide)\n', stderr: '' };
6269
7626
  }
6270
7627
 
6271
- if (args[0] === '--version' || args[0] === '-V') {
6272
- return { code: 0, stdout: 'Python 3.12.8 (CPython WebAssembly via Pyodide)\n', stderr: '' };
7628
+ const pyCompiler =
7629
+ (ctx.shell && ctx.shell.options && ctx.shell.options.pythonCompiler) ||
7630
+ (typeof globalThis !== 'undefined' && globalThis.__codelabPythonCompiler) ||
7631
+ (typeof window !== 'undefined' && window.__codelabPythonCompiler);
7632
+
7633
+ const onRequestStdin =
7634
+ (typeof ctx.onRequestStdin === 'function' ? ctx.onRequestStdin : null) ||
7635
+ (ctx.shell && ctx.shell.options && typeof ctx.shell.options.onRequestStdin === 'function'
7636
+ ? ctx.shell.options.onRequestStdin
7637
+ : undefined);
7638
+
7639
+ if (args.length === 0 || args[0] === '-i') {
7640
+ if (!ctx.stdin && !onRequestStdin) {
7641
+ return { code: 0, stdout: 'Python 3.12.8 (CPython WebAssembly via Pyodide)\n', stderr: '' };
7642
+ }
7643
+ if (typeof pyCompiler !== 'function') {
7644
+ return {
7645
+ code: 1,
7646
+ stdout: '',
7647
+ stderr:
7648
+ 'python3: Python WebAssembly toolchain is not enabled. Enable pythonExtension from "@innovatorved/code-lab/extensions/python".\n'
7649
+ };
7650
+ }
7651
+ if (ctx.stdin && !onRequestStdin) {
7652
+ let outText = '';
7653
+ let errText = '';
7654
+ const res = await pyCompiler({
7655
+ source: ctx.stdin,
7656
+ stdin: '',
7657
+ env: ctx.env,
7658
+ cwd: ctx.cwd,
7659
+ vfs: ctx.vfs,
7660
+ signal: ctx.signal,
7661
+ onStdout: (t) => { outText += t; if (ctx.onStdout) ctx.onStdout(t); },
7662
+ onStderr: (t) => { errText += t; if (ctx.onStderr) ctx.onStderr(t); }
7663
+ });
7664
+ return { code: res && res.ok ? 0 : ((res && res.exitCode) || 1), stdout: outText, stderr: errText };
7665
+ }
7666
+ const banner = 'Python 3.12.8 (CPython WebAssembly via Pyodide)\nType "exit()" or Ctrl+D to exit.\n';
7667
+ let fullOut = banner;
7668
+ let fullErr = '';
7669
+ if (ctx.onStdout) ctx.onStdout(banner);
7670
+ while (!(ctx.signal && ctx.signal.aborted)) {
7671
+ const line = await onRequestStdin('>>> ');
7672
+ if (line === null || line === undefined) break;
7673
+ const trimmed = String(line).trim();
7674
+ if (trimmed === 'exit()' || trimmed === 'quit()') break;
7675
+ if (!trimmed) continue;
7676
+ await pyCompiler({
7677
+ source: String(line),
7678
+ repl: true,
7679
+ stdin: '',
7680
+ env: ctx.env,
7681
+ cwd: ctx.cwd,
7682
+ vfs: ctx.vfs,
7683
+ signal: ctx.signal,
7684
+ onRequestStdin,
7685
+ onStdout: (t) => { fullOut += t; if (ctx.onStdout) ctx.onStdout(t); },
7686
+ onStderr: (t) => { fullErr += t; if (ctx.onStderr) ctx.onStderr(t); }
7687
+ });
7688
+ }
7689
+ return { code: 0, stdout: fullOut, stderr: fullErr, alreadyStreamed: true };
6273
7690
  }
6274
7691
 
6275
7692
  let codeToRun = undefined;
@@ -6281,11 +7698,6 @@
6281
7698
  entryFile = ctx.resolvePath(args[0]);
6282
7699
  }
6283
7700
 
6284
- const pyCompiler =
6285
- (ctx.shell && ctx.shell.options && ctx.shell.options.pythonCompiler) ||
6286
- (typeof globalThis !== 'undefined' && globalThis.__codelabPythonCompiler) ||
6287
- (typeof window !== 'undefined' && window.__codelabPythonCompiler);
6288
-
6289
7701
  if (typeof pyCompiler !== 'function') {
6290
7702
  return {
6291
7703
  code: 1,
@@ -6304,6 +7716,8 @@
6304
7716
  env: ctx.env,
6305
7717
  cwd: ctx.cwd,
6306
7718
  vfs: ctx.vfs,
7719
+ signal: ctx.signal,
7720
+ onRequestStdin,
6307
7721
  onStdout: (t) => {
6308
7722
  outText += t;
6309
7723
  if (ctx.onStdout) ctx.onStdout(t);
@@ -6485,7 +7899,7 @@
6485
7899
 
6486
7900
  if (sub === '-e') {
6487
7901
  const code = args[1] || '';
6488
- const res = await executeInVirtualRuntime({
7902
+ const res = await executeJsInShellRuntime({
6489
7903
  mode: 'repl',
6490
7904
  replCode: code,
6491
7905
  printReplResult: false,
@@ -6493,13 +7907,12 @@
6493
7907
  env: ctx.env,
6494
7908
  cwd: ctx.cwd,
6495
7909
  vfs: ctx.vfs,
6496
- activePortTable: ctx.shell.portTable,
6497
7910
  pid: ctx.pid,
6498
7911
  isBackground: ctx.isBackground,
6499
7912
  onStdout: ctx.onStdout,
6500
7913
  onStderr: ctx.onStderr,
6501
7914
  signal: ctx.signal
6502
- });
7915
+ }, ctx);
6503
7916
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
6504
7917
  }
6505
7918
 
@@ -6514,7 +7927,7 @@
6514
7927
  for (const item of ctx.vfs.readdirSync(dir)) {
6515
7928
  const full = PosixPath.join(dir, item);
6516
7929
  const st = ctx.vfs.statSync(full);
6517
- if (st.isDirectory() && item !== 'node_modules') {
7930
+ if (st.isDirectory() && item !== 'node_modules' && item !== '.git') {
6518
7931
  findTests(full);
6519
7932
  } else if (item.endsWith('.test.js') || item.endsWith('.test.ts')) {
6520
7933
  filesToRun.push(full);
@@ -6528,20 +7941,19 @@
6528
7941
  let combinedErr = '';
6529
7942
  let allOk = true;
6530
7943
  for (const f of filesToRun) {
6531
- const res = await executeInVirtualRuntime({
7944
+ const res = await executeJsInShellRuntime({
6532
7945
  mode: 'test',
6533
7946
  entry: f,
6534
7947
  stdin: ctx.stdin || '',
6535
7948
  env: ctx.env,
6536
7949
  cwd: ctx.cwd,
6537
7950
  vfs: ctx.vfs,
6538
- activePortTable: ctx.shell.portTable,
6539
7951
  pid: ctx.pid,
6540
7952
  isBackground: ctx.isBackground,
6541
7953
  onStdout: ctx.onStdout,
6542
7954
  onStderr: ctx.onStderr,
6543
7955
  signal: ctx.signal
6544
- });
7956
+ }, ctx);
6545
7957
  combinedOut += res.stdout;
6546
7958
  combinedErr += res.stderr;
6547
7959
  if (!res.ok) allOk = false;
@@ -6557,7 +7969,7 @@
6557
7969
  const resolved = ctx.resolvePath(target);
6558
7970
  if (ctx.vfs.existsSync(resolved)) {
6559
7971
  const scriptArgs = args.slice(2);
6560
- const res = await executeInVirtualRuntime({
7972
+ const res = await executeJsInShellRuntime({
6561
7973
  mode: 'run',
6562
7974
  entry: resolved,
6563
7975
  argv: ['bun', resolved, ...scriptArgs],
@@ -6565,13 +7977,12 @@
6565
7977
  env: ctx.env,
6566
7978
  cwd: ctx.cwd,
6567
7979
  vfs: ctx.vfs,
6568
- activePortTable: ctx.shell.portTable,
6569
7980
  pid: ctx.pid,
6570
7981
  isBackground: ctx.isBackground,
6571
7982
  onStdout: ctx.onStdout,
6572
7983
  onStderr: ctx.onStderr,
6573
7984
  signal: ctx.signal
6574
- });
7985
+ }, ctx);
6575
7986
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
6576
7987
  }
6577
7988
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
@@ -6584,7 +7995,7 @@
6584
7995
  const resolved = ctx.resolvePath(sub);
6585
7996
  if (ctx.vfs.existsSync(resolved)) {
6586
7997
  const scriptArgs = args.slice(1);
6587
- const res = await executeInVirtualRuntime({
7998
+ const res = await executeJsInShellRuntime({
6588
7999
  mode: 'run',
6589
8000
  entry: resolved,
6590
8001
  argv: ['bun', resolved, ...scriptArgs],
@@ -6592,13 +8003,12 @@
6592
8003
  env: ctx.env,
6593
8004
  cwd: ctx.cwd,
6594
8005
  vfs: ctx.vfs,
6595
- activePortTable: ctx.shell.portTable,
6596
8006
  pid: ctx.pid,
6597
8007
  isBackground: ctx.isBackground,
6598
8008
  onStdout: ctx.onStdout,
6599
8009
  onStderr: ctx.onStderr,
6600
8010
  signal: ctx.signal
6601
- });
8011
+ }, ctx);
6602
8012
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
6603
8013
  }
6604
8014
 
@@ -6615,6 +8025,16 @@
6615
8025
  return { code: 0, stdout: 'npm v10.2.0\n', stderr: '' };
6616
8026
  }
6617
8027
  const sub = args[0];
8028
+ if (sub === '--version' || sub === '-v' || sub === 'version') {
8029
+ return { code: 0, stdout: '10.2.0\n', stderr: '' };
8030
+ }
8031
+ if (sub === '--help' || sub === '-h' || sub === 'help') {
8032
+ return {
8033
+ code: 0,
8034
+ stdout: 'npm v10.2.0\nUsage: npm <command>\n\nCommands: init, install, uninstall, list, run, start, test\n',
8035
+ stderr: ''
8036
+ };
8037
+ }
6618
8038
 
6619
8039
  if (sub === 'init') {
6620
8040
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
@@ -6671,6 +8091,10 @@
6671
8091
  return await runPackageScript('test', args.slice(1), ctx);
6672
8092
  }
6673
8093
 
8094
+ if (sub === 'start') {
8095
+ return await runPackageScript('start', args.slice(1), ctx);
8096
+ }
8097
+
6674
8098
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
6675
8099
  if (pkgData.scripts && pkgData.scripts[sub]) {
6676
8100
  return await runPackageScript(sub, args.slice(1), ctx);
@@ -6680,17 +8104,37 @@
6680
8104
  },
6681
8105
 
6682
8106
  async npx(args, ctx) {
6683
- if (args.length === 0) {
8107
+ const filtered = [];
8108
+ for (let i = 0; i < args.length; i++) {
8109
+ if (args[i] === '-y' || args[i] === '--yes' || args[i] === '--no-install') continue;
8110
+ filtered.push(args[i]);
8111
+ }
8112
+ if (filtered.length === 0) {
6684
8113
  return { code: 1, stdout: '', stderr: 'npx: missing command\n' };
6685
8114
  }
6686
- const cmd = args[0];
6687
- const cmdArgs = args.slice(1);
6688
- const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
6689
- if (ctx.vfs.existsSync(binPath)) {
6690
- return await ctx.commands.node([binPath, ...cmdArgs], ctx);
8115
+ const cmd = filtered[0];
8116
+ const cmdArgs = filtered.slice(1);
8117
+ const localBin = PosixPath.join(ctx.cwd || '/workspace', 'node_modules/.bin', cmd);
8118
+ const rootBin = PosixPath.join('/workspace/node_modules/.bin', cmd);
8119
+ const binPath = ctx.vfs.existsSync(localBin) ? localBin : (ctx.vfs.existsSync(rootBin) ? rootBin : null);
8120
+ if (binPath) {
8121
+ const shimSrc = String(ctx.vfs.readFileSync(binPath, 'utf8') || '');
8122
+ const execMatch = shimSrc.match(/exec\s+node\s+"([^"]+)"/);
8123
+ if (execMatch && execMatch[1]) {
8124
+ return await ctx.shell.commands.node([execMatch[1], ...cmdArgs], ctx);
8125
+ }
8126
+ return await ctx.shell.commands.node([binPath, ...cmdArgs], ctx);
6691
8127
  }
6692
8128
  const cmdStr = [cmd, ...cmdArgs].map(quoteShellArg).join(' ');
6693
- return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
8129
+ return await ctx.shell.execute(cmdStr, {
8130
+ cwd: ctx.cwd,
8131
+ env: ctx.env,
8132
+ stdin: ctx.stdin,
8133
+ signal: ctx.signal,
8134
+ onStdout: ctx.onStdout,
8135
+ onStderr: ctx.onStderr,
8136
+ onRequestStdin: ctx.onRequestStdin
8137
+ });
6694
8138
  },
6695
8139
 
6696
8140
  async bunx(args, ctx) {
@@ -6759,10 +8203,7 @@
6759
8203
  if (sub === 'exec') {
6760
8204
  const cmd = args[1];
6761
8205
  if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
6762
- const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
6763
- if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
6764
- const cmdStr = [cmd, ...args.slice(2)].map(quoteShellArg).join(' ');
6765
- return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
8206
+ return await this.npx([cmd, ...args.slice(2)], ctx);
6766
8207
  }
6767
8208
 
6768
8209
  if (sub === 'dlx') {
@@ -7285,7 +8726,13 @@
7285
8726
  sqlInput = String(ctx.stdin).trim();
7286
8727
  }
7287
8728
 
7288
- if (!sqlInput) {
8729
+ const onRequestStdin =
8730
+ (typeof ctx.onRequestStdin === 'function' ? ctx.onRequestStdin : null) ||
8731
+ (ctx.shell && ctx.shell.options && typeof ctx.shell.options.onRequestStdin === 'function'
8732
+ ? ctx.shell.options.onRequestStdin
8733
+ : null);
8734
+
8735
+ if (!sqlInput && !onRequestStdin) {
7289
8736
  return {
7290
8737
  code: 0,
7291
8738
  stdout: 'SQLite 3.45.0 (CodeLab VFS Engine)\nUsage: sqlite3 [-column] [-header] [-json] [dbfile] "SQL"\n',
@@ -7303,14 +8750,12 @@
7303
8750
  return { code: 1, stdout: '', stderr: 'sqlite3: SQLite engine not initialized in runtime\n' };
7304
8751
  }
7305
8752
 
7306
- try {
7307
- const SqliteDatabase = createDb(ctx.vfs, () => ctx.shell.cwd);
7308
- const db = new SqliteDatabase(dbFile);
7309
- const trimmed = sqlInput.trim();
7310
-
8753
+ const executeSqlBatch = (db, batchText) => {
8754
+ const trimmed = String(batchText || '').trim();
8755
+ if (!trimmed) return '';
7311
8756
  if (trimmed === '.tables') {
7312
8757
  const names = Array.from(db.tables.keys());
7313
- return { code: 0, stdout: names.length ? names.join(' ') + '\n' : '', stderr: '' };
8758
+ return names.length ? names.join(' ') + '\n' : '';
7314
8759
  }
7315
8760
  if (trimmed.startsWith('.schema')) {
7316
8761
  const lines = [];
@@ -7321,11 +8766,11 @@
7321
8766
  for (const idx of db.indexes.values()) {
7322
8767
  lines.push(`CREATE ${idx.unique ? 'UNIQUE ' : ''}INDEX ${idx.name} ON ${idx.table} (${idx.columns.join(', ')});`);
7323
8768
  }
7324
- return { code: 0, stdout: lines.join('\n') + (lines.length ? '\n' : ''), stderr: '' };
8769
+ return lines.join('\n') + (lines.length ? '\n' : '');
7325
8770
  }
7326
8771
  if (trimmed === '.indexes' || trimmed === '.indices') {
7327
8772
  const names = Array.from(db.indexes.keys());
7328
- return { code: 0, stdout: names.length ? names.join(' ') + '\n' : '', stderr: '' };
8773
+ return names.length ? names.join(' ') + '\n' : '';
7329
8774
  }
7330
8775
 
7331
8776
  const stmts = trimmed.split(';').map(s => s.trim()).filter(Boolean);
@@ -7356,10 +8801,281 @@
7356
8801
  }
7357
8802
  }
7358
8803
  }
7359
- return { code: 0, stdout: outputs.length ? outputs.join('\n') + '\n' : '', stderr: '' };
8804
+ return outputs.length ? outputs.join('\n') + '\n' : '';
8805
+ };
8806
+
8807
+ try {
8808
+ const SqliteDatabase = createDb(ctx.vfs, () => ctx.shell.cwd);
8809
+ const db = new SqliteDatabase(dbFile);
8810
+
8811
+ if (!sqlInput && onRequestStdin) {
8812
+ const banner = 'SQLite version 3.45.0 (CodeLab VFS Engine)\nEnter ".help" for usage hints, ".quit" to exit.\n';
8813
+ let fullOut = banner;
8814
+ let fullErr = '';
8815
+ if (ctx.onStdout) ctx.onStdout(banner);
8816
+ while (!(ctx.signal && ctx.signal.aborted)) {
8817
+ const line = await onRequestStdin('sqlite> ');
8818
+ if (line === null || line === undefined) break;
8819
+ const trimmedLine = String(line).trim();
8820
+ if (trimmedLine === '.quit' || trimmedLine === '.exit') break;
8821
+ if (trimmedLine === '.help') {
8822
+ const h = '.tables List names of tables\n.schema Show CREATE statements\n.indexes Show names of indexes\n.quit Exit this program\n';
8823
+ fullOut += h;
8824
+ if (ctx.onStdout) ctx.onStdout(h);
8825
+ continue;
8826
+ }
8827
+ if (!trimmedLine) continue;
8828
+ try {
8829
+ const stepOut = executeSqlBatch(db, trimmedLine);
8830
+ if (stepOut) {
8831
+ fullOut += stepOut;
8832
+ if (ctx.onStdout) ctx.onStdout(stepOut);
8833
+ }
8834
+ } catch (stepErr) {
8835
+ const errMsg = `Error: ${stepErr.message || String(stepErr)}\n`;
8836
+ fullErr += errMsg;
8837
+ if (ctx.onStderr) ctx.onStderr(errMsg);
8838
+ }
8839
+ }
8840
+ return { code: 0, stdout: fullOut, stderr: fullErr, alreadyStreamed: true };
8841
+ }
8842
+
8843
+ const out = executeSqlBatch(db, sqlInput);
8844
+ return { code: 0, stdout: out, stderr: '' };
7360
8845
  } catch (err) {
7361
8846
  return { code: 1, stdout: '', stderr: `Error: ${err.message || String(err)}\n` };
7362
8847
  }
8848
+ },
8849
+
8850
+ async read(args, ctx) {
8851
+ let prompt = '';
8852
+ let rawMode = false;
8853
+ const varNames = [];
8854
+ for (let i = 0; i < args.length; i++) {
8855
+ const a = args[i];
8856
+ if (a === '-r') {
8857
+ rawMode = true;
8858
+ } else if (a === '-p' && i + 1 < args.length) {
8859
+ prompt = String(args[++i]);
8860
+ } else if (a.startsWith('-') && a.length > 1) {
8861
+ if (a.includes('r')) rawMode = true;
8862
+ } else {
8863
+ varNames.push(a);
8864
+ }
8865
+ }
8866
+ if (varNames.length === 0) varNames.push('REPLY');
8867
+
8868
+ let line = null;
8869
+ if (ctx.stdin && String(ctx.stdin).length > 0) {
8870
+ const str = String(ctx.stdin);
8871
+ const nl = str.indexOf('\n');
8872
+ line = nl === -1 ? str : str.slice(0, nl);
8873
+ if (line.endsWith('\r')) line = line.slice(0, -1);
8874
+ } else {
8875
+ const onRequestStdin =
8876
+ (typeof ctx.onRequestStdin === 'function' ? ctx.onRequestStdin : null) ||
8877
+ (ctx.shell && ctx.shell.options && typeof ctx.shell.options.onRequestStdin === 'function'
8878
+ ? ctx.shell.options.onRequestStdin
8879
+ : null);
8880
+ if (onRequestStdin) {
8881
+ line = await onRequestStdin(prompt);
8882
+ }
8883
+ }
8884
+
8885
+ if (line === null || line === undefined) {
8886
+ return { code: 1, stdout: '', stderr: '' };
8887
+ }
8888
+
8889
+ let processed = String(line).replace(/\r?\n$/, '');
8890
+ if (!rawMode) {
8891
+ processed = processed.replace(/\\(.)/g, '$1');
8892
+ }
8893
+
8894
+ const ifs = ctx.env && ctx.env.IFS !== undefined ? String(ctx.env.IFS) : ' \t\n';
8895
+ if (varNames.length === 1) {
8896
+ const trimmed = ifs.includes(' ') ? processed.trim() : processed;
8897
+ ctx.env[varNames[0]] = trimmed;
8898
+ if (ctx.shell) ctx.shell.env[varNames[0]] = trimmed;
8899
+ } else {
8900
+ const sepRe = ifs.length > 0
8901
+ ? new RegExp('[' + ifs.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + ']+')
8902
+ : null;
8903
+ const parts = sepRe ? processed.trim().split(sepRe) : [processed];
8904
+ for (let idx = 0; idx < varNames.length; idx++) {
8905
+ const vName = varNames[idx];
8906
+ const val = idx === varNames.length - 1
8907
+ ? parts.slice(idx).join(' ')
8908
+ : (parts[idx] || '');
8909
+ ctx.env[vName] = val;
8910
+ if (ctx.shell) ctx.shell.env[vName] = val;
8911
+ }
8912
+ }
8913
+ return { code: 0, stdout: '', stderr: '' };
8914
+ },
8915
+
8916
+ async tsc(args, ctx) {
8917
+ if (args.includes('--version') || args.includes('-v')) {
8918
+ return { code: 0, stdout: 'Version 5.6.3\n', stderr: '' };
8919
+ }
8920
+ if (args.includes('--help') || args.includes('-h')) {
8921
+ return {
8922
+ code: 0,
8923
+ stdout:
8924
+ 'Version 5.6.3\nSyntax: tsc [options] [file...]\n\nOptions:\n' +
8925
+ ' --init Initializes a TypeScript project and creates a tsconfig.json file.\n' +
8926
+ ' --noEmit Do not emit outputs.\n' +
8927
+ ' --outDir <dir> Redirect output structure to the directory.\n' +
8928
+ ' -v, --version Print the compiler\'s version.\n',
8929
+ stderr: ''
8930
+ };
8931
+ }
8932
+ if (args.includes('--init')) {
8933
+ const tsconfigPath = PosixPath.join(ctx.cwd, 'tsconfig.json');
8934
+ if (!ctx.vfs.existsSync(tsconfigPath)) {
8935
+ ctx.vfs.writeFileSync(
8936
+ tsconfigPath,
8937
+ JSON.stringify(
8938
+ {
8939
+ compilerOptions: {
8940
+ target: 'ES2022',
8941
+ module: 'ESNext',
8942
+ moduleResolution: 'bundler',
8943
+ strict: true,
8944
+ esModuleInterop: true,
8945
+ skipLibCheck: true,
8946
+ jsx: 'react-jsx'
8947
+ }
8948
+ },
8949
+ null,
8950
+ 2
8951
+ ) + '\n'
8952
+ );
8953
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', tsconfigPath);
8954
+ }
8955
+ return { code: 0, stdout: 'Created a new tsconfig.json\n', stderr: '' };
8956
+ }
8957
+
8958
+ const noEmit = args.includes('--noEmit');
8959
+ let outDir = null;
8960
+ const explicitFiles = [];
8961
+ for (let i = 0; i < args.length; i++) {
8962
+ const a = args[i];
8963
+ if (a === '--outDir' && i + 1 < args.length) {
8964
+ outDir = ctx.resolvePath(args[++i]);
8965
+ } else if (a === '-p' || a === '--project') {
8966
+ i++;
8967
+ } else if (!a.startsWith('-')) {
8968
+ explicitFiles.push(ctx.resolvePath(a));
8969
+ }
8970
+ }
8971
+
8972
+ const files = [];
8973
+ if (explicitFiles.length > 0) {
8974
+ files.push(...explicitFiles);
8975
+ } else {
8976
+ const scanTs = (dir) => {
8977
+ if (!ctx.vfs.existsSync(dir)) return;
8978
+ for (const entry of ctx.vfs.readdirSync(dir)) {
8979
+ if (entry === 'node_modules' || entry === '.git' || entry === 'dist') continue;
8980
+ const full = PosixPath.join(dir, entry);
8981
+ const st = ctx.vfs.statSync(full);
8982
+ if (st.isDirectory()) scanTs(full);
8983
+ else if (/\.(ts|tsx)$/i.test(entry) && !entry.endsWith('.d.ts')) files.push(full);
8984
+ }
8985
+ };
8986
+ scanTs(ctx.cwd);
8987
+ }
8988
+
8989
+ let errOut = '';
8990
+ let exitCode = 0;
8991
+ for (const filePath of files) {
8992
+ if (!ctx.vfs.existsSync(filePath)) {
8993
+ errOut += `error TS6053: File '${filePath}' not found.\n`;
8994
+ exitCode = 2;
8995
+ continue;
8996
+ }
8997
+ const src = String(ctx.vfs.readFileSync(filePath, 'utf8') || '');
8998
+ try {
8999
+ const tsCompiler = typeof globalThis !== 'undefined' && globalThis.ts ? globalThis.ts : null;
9000
+ let jsOut = '';
9001
+ if (tsCompiler && typeof tsCompiler.transpileModule === 'function') {
9002
+ const tr = tsCompiler.transpileModule(src, {
9003
+ fileName: filePath,
9004
+ reportDiagnostics: true,
9005
+ compilerOptions: {
9006
+ target: tsCompiler.ScriptTarget ? tsCompiler.ScriptTarget.ES2022 : 9,
9007
+ module: tsCompiler.ModuleKind ? tsCompiler.ModuleKind.ESNext : 99
9008
+ }
9009
+ });
9010
+ if (Array.isArray(tr.diagnostics) && tr.diagnostics.length > 0) {
9011
+ for (const d of tr.diagnostics) {
9012
+ const msg = typeof d.messageText === 'string' ? d.messageText : (d.messageText && d.messageText.messageText) || 'Syntax error';
9013
+ errOut += `${PosixPath.relative(ctx.cwd, filePath)}(1,1): error TS${d.code || 1005}: ${msg}\n`;
9014
+ }
9015
+ exitCode = 2;
9016
+ continue;
9017
+ }
9018
+ jsOut = tr.outputText;
9019
+ } else {
9020
+ // Deterministic CSP-safe delimiter & unterminated string check before transpiling
9021
+ let inStr = null;
9022
+ let inLineComment = false;
9023
+ let inBlockComment = false;
9024
+ let braceBalance = 0;
9025
+ let parenBalance = 0;
9026
+ let lineNo = 1;
9027
+ for (let ci = 0; ci < src.length; ci++) {
9028
+ const ch = src[ci];
9029
+ const nxt = src[ci + 1];
9030
+ if (ch === '\n') {
9031
+ lineNo++;
9032
+ if (inStr === '"' || inStr === "'") {
9033
+ throw new Error(`Line ${lineNo - 1}: Unterminated string literal.`);
9034
+ }
9035
+ inLineComment = false;
9036
+ continue;
9037
+ }
9038
+ if (inLineComment) continue;
9039
+ if (inBlockComment) {
9040
+ if (ch === '*' && nxt === '/') { inBlockComment = false; ci++; }
9041
+ continue;
9042
+ }
9043
+ if (inStr) {
9044
+ if (ch === '\\') { ci++; continue; }
9045
+ if (ch === inStr) inStr = null;
9046
+ continue;
9047
+ }
9048
+ if (ch === '/' && nxt === '/') { inLineComment = true; ci++; continue; }
9049
+ if (ch === '/' && nxt === '*') { inBlockComment = true; ci++; continue; }
9050
+ if (ch === '"' || ch === "'" || ch === '`') { inStr = ch; continue; }
9051
+ if (ch === '{') braceBalance++;
9052
+ else if (ch === '}') braceBalance--;
9053
+ else if (ch === '(') parenBalance++;
9054
+ else if (ch === ')') parenBalance--;
9055
+ if (braceBalance < 0 || parenBalance < 0) {
9056
+ throw new Error(`Line ${lineNo}: Unexpected closing token '${ch}'.`);
9057
+ }
9058
+ }
9059
+ if (inStr) throw new Error(`Line ${lineNo}: Unterminated string literal.`);
9060
+ if (braceBalance !== 0 || parenBalance !== 0) {
9061
+ throw new Error(`Line ${lineNo}: Unexpected end of file (unclosed '${braceBalance !== 0 ? '{' : '('}').`);
9062
+ }
9063
+ jsOut = transpileTS(src, filePath);
9064
+ }
9065
+ if (!noEmit) {
9066
+ const rel = PosixPath.relative(ctx.cwd, filePath).replace(/\.(tsx|ts)$/i, '.js');
9067
+ const dest = outDir ? PosixPath.join(outDir, rel) : filePath.replace(/\.(tsx|ts)$/i, '.js');
9068
+ const destDir = PosixPath.dirname(dest);
9069
+ if (!ctx.vfs.existsSync(destDir)) ctx.vfs.mkdirSync(destDir, { recursive: true });
9070
+ ctx.vfs.writeFileSync(dest, jsOut);
9071
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', dest);
9072
+ }
9073
+ } catch (err) {
9074
+ errOut += `${PosixPath.relative(ctx.cwd, filePath)}(1,1): error TS1005: ${err.message || String(err)}\n`;
9075
+ exitCode = 2;
9076
+ }
9077
+ }
9078
+ return { code: exitCode, stdout: '', stderr: errOut };
7363
9079
  }
7364
9080
  };
7365
9081
 
@@ -7768,18 +9484,41 @@
7768
9484
  this.portTable = options.portTable || (typeof createVirtualPortTable === 'function' ? createVirtualPortTable() : null);
7769
9485
  this.vfs = options.vfs || createFallbackVfs();
7770
9486
  this.env = Object.assign({
7771
- PATH: '/usr/local/bin:/usr/bin:/bin',
9487
+ PATH: '/workspace/node_modules/.bin:/usr/local/bin:/usr/bin:/bin',
7772
9488
  PWD: '/workspace',
7773
- HOME: '/home/user',
9489
+ HOME: '/home/codelab',
7774
9490
  USER: 'codelab',
7775
9491
  SHELL: '/bin/sh',
7776
9492
  TERM: 'xterm-256color',
7777
9493
  '?': '0'
7778
9494
  }, options.env || {});
9495
+ PosixPath._homeDir = this.env.HOME || '/home/codelab';
7779
9496
  this.cwd = this.env.PWD || '/workspace';
9497
+ if (this.vfs && typeof this.vfs._setCwd === 'function') {
9498
+ this.vfs._setCwd(this.cwd);
9499
+ }
9500
+ if (
9501
+ this.vfs &&
9502
+ typeof this.vfs.mkdirSync === 'function' &&
9503
+ typeof this.vfs.existsSync === 'function' &&
9504
+ this.env.HOME &&
9505
+ !this.vfs.existsSync(this.env.HOME)
9506
+ ) {
9507
+ try { this.vfs.mkdirSync(this.env.HOME, { recursive: true }); } catch (_err) { void _err; }
9508
+ }
7780
9509
  if (options.files && typeof options.files === 'object') {
7781
9510
  for (const [k, v] of Object.entries(options.files)) {
7782
9511
  const abs = PosixPath.resolve(this.cwd, k);
9512
+ if (typeof this.vfs.mkdirSync === 'function') {
9513
+ const parentDir = PosixPath.dirname(abs);
9514
+ if (
9515
+ parentDir &&
9516
+ parentDir !== '/' &&
9517
+ (typeof this.vfs.existsSync !== 'function' || !this.vfs.existsSync(parentDir))
9518
+ ) {
9519
+ this.vfs.mkdirSync(parentDir, { recursive: true });
9520
+ }
9521
+ }
7783
9522
  if (typeof this.vfs.writeFileSync === 'function') {
7784
9523
  this.vfs.writeFileSync(abs, String(v ?? ''));
7785
9524
  }
@@ -7791,38 +9530,52 @@
7791
9530
  this.nextPid = 100;
7792
9531
  this.commands = Object.assign({}, COREUTILS, options.commands || {});
7793
9532
 
7794
- this.gitState = {
7795
- branch: 'main',
7796
- branches: new Set(['main']),
7797
- remoteUrl: null,
7798
- remotes: {},
7799
- repoRoot: this.cwd,
7800
- headSnapshot: snapshotWorktree(this.vfs, this.cwd),
7801
- staged: new Set(),
7802
- commits: [
7803
- {
7804
- hash: 'a1b2c3d',
7805
- author: 'CodeLab Developer <dev@codelab.internal>',
7806
- date: new Date().toUTCString(),
7807
- message: 'Initial project commit'
7808
- }
7809
- ]
7810
- };
9533
+ this._initialBootRoot = options._initialBootRoot
9534
+ ? PosixPath.normalize(options._initialBootRoot)
9535
+ : PosixPath.normalize(this.cwd || '/workspace');
9536
+ this._initialBootSnapshot =
9537
+ options._initialBootSnapshot && typeof options._initialBootSnapshot === 'object'
9538
+ ? options._initialBootSnapshot
9539
+ : snapshotWorktree(this.vfs, this._initialBootRoot);
9540
+
9541
+ if (options.gitState && typeof options.gitState === 'object') {
9542
+ this.gitState = options.gitState;
9543
+ } else {
9544
+ this.gitState = createUnifiedShellGitState(this.vfs, this.cwd, options);
9545
+ }
7811
9546
  }
7812
9547
 
7813
9548
  resolvePath(p) {
9549
+ PosixPath._homeDir = (this.env && this.env.HOME) || '/home/codelab';
7814
9550
  if (!p) return this.cwd;
7815
9551
  return PosixPath.resolve(this.cwd, p);
7816
9552
  }
7817
9553
 
7818
- // True when `name` resolves to a shell function or coreutil (used by the
7819
- // workbench to route recognised commands straight to the shell instead of
7820
- // treating flag-looking input such as `node --version` as a JS expression).
9554
+ _resolvePathBinary(name) {
9555
+ if (!name || !this.vfs || typeof this.vfs.existsSync !== 'function') return null;
9556
+ const n = String(name);
9557
+ if (n.includes('/')) return null;
9558
+ const localBin = PosixPath.join(this.cwd || '/workspace', 'node_modules/.bin', n);
9559
+ if (this.vfs.existsSync(localBin)) return localBin;
9560
+ const pathDirs = String((this.env && this.env.PATH) || '/workspace/node_modules/.bin:/usr/local/bin:/usr/bin:/bin')
9561
+ .split(':')
9562
+ .filter(Boolean);
9563
+ for (const dir of pathDirs) {
9564
+ const candidate = PosixPath.join(dir, n);
9565
+ if (this.vfs.existsSync(candidate)) return candidate;
9566
+ }
9567
+ const rootBin = PosixPath.join('/workspace/node_modules/.bin', n);
9568
+ if (this.vfs.existsSync(rootBin)) return rootBin;
9569
+ return null;
9570
+ }
9571
+
9572
+ // True when `name` resolves to a shell function, coreutil, or PATH/.bin shim.
7821
9573
  hasCommand(name) {
7822
9574
  if (!name) return false;
7823
9575
  const n = String(name);
7824
9576
  if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
7825
- return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
9577
+ if (this.commands && Object.prototype.hasOwnProperty.call(this.commands, n)) return true;
9578
+ return Boolean(this._resolvePathBinary(n));
7826
9579
  }
7827
9580
 
7828
9581
  _emitVfsMutation(type, absPath) {
@@ -7936,6 +9689,9 @@
7936
9689
  ...this.options,
7937
9690
  vfs: this.vfs,
7938
9691
  portTable: this.portTable,
9692
+ gitState: this.gitState,
9693
+ _initialBootRoot: this._initialBootRoot,
9694
+ _initialBootSnapshot: this._initialBootSnapshot,
7939
9695
  env: { ...env, PWD: this.cwd }
7940
9696
  });
7941
9697
  subShell.cwd = this.cwd;
@@ -8657,6 +10413,7 @@
8657
10413
  ...this.options,
8658
10414
  vfs: this.vfs,
8659
10415
  portTable: this.portTable,
10416
+ gitState: this.gitState,
8660
10417
  env: Object.assign({}, this.env, innerCtx.env || {})
8661
10418
  });
8662
10419
  subShell.cwd = innerCtx.cwd || this.cwd;
@@ -8703,6 +10460,8 @@
8703
10460
  let currentStdin = context.stdin || '';
8704
10461
  let combinedStderr = '';
8705
10462
  let lastResult = { code: 0, stdout: '', stderr: '' };
10463
+ const isolateSubshells = commands.length > 1;
10464
+ const parentCwd = this.cwd;
8706
10465
 
8707
10466
  for (let i = 0; i < commands.length; i++) {
8708
10467
  if (context.signal && context.signal.aborted) {
@@ -8725,7 +10484,32 @@
8725
10484
  onStderr: context.onStderr
8726
10485
  };
8727
10486
 
8728
- const res = await this._executeAstNode(cmd, cmdContext);
10487
+ let res;
10488
+ if (isolateSubshells) {
10489
+ const stageEnv = Object.assign({}, this.env, context.env || {});
10490
+ const stageShell = new PosixShell({
10491
+ ...this.options,
10492
+ vfs: this.vfs,
10493
+ portTable: this.portTable,
10494
+ gitState: this.gitState,
10495
+ _initialBootRoot: this._initialBootRoot,
10496
+ _initialBootSnapshot: this._initialBootSnapshot,
10497
+ env: stageEnv
10498
+ });
10499
+ stageShell.cwd = context.cwd || parentCwd;
10500
+ stageShell.functions = Object.assign({}, this.functions || {});
10501
+ res = await stageShell._executeAstNode(cmd, {
10502
+ ...cmdContext,
10503
+ cwd: stageShell.cwd,
10504
+ env: Object.assign({}, stageEnv)
10505
+ });
10506
+ if (this.vfs && typeof this.vfs._setCwd === 'function') {
10507
+ this.vfs._setCwd(parentCwd);
10508
+ }
10509
+ } else {
10510
+ res = await this._executeAstNode(cmd, cmdContext);
10511
+ }
10512
+
8729
10513
  currentStdin = res.stdout || '';
8730
10514
  combinedStderr += (res.stderr || '');
8731
10515
  lastResult = res;
@@ -8914,6 +10698,9 @@
8914
10698
  resolvePath: (p) => this.resolvePath(p),
8915
10699
  emitMutation: (type, p) => this._emitVfsMutation(type, p),
8916
10700
  signal: context.signal,
10701
+ onRequestStdin:
10702
+ (typeof context.onRequestStdin === 'function' ? context.onRequestStdin : null) ||
10703
+ (this.options && typeof this.options.onRequestStdin === 'function' ? this.options.onRequestStdin : undefined),
8917
10704
  onStdout: (chunk) => {
8918
10705
  if (!chunk) return;
8919
10706
  streamedStdoutBytes += chunk.length;
@@ -8928,6 +10715,10 @@
8928
10715
 
8929
10716
  // 7. Command execution dispatch
8930
10717
  let res;
10718
+ const resolvedPathBin =
10719
+ !(this.functions && this.functions[cmdName]) && !this.commands[cmdName]
10720
+ ? this._resolvePathBinary(cmdName)
10721
+ : null;
8931
10722
  if (this.functions && this.functions[cmdName]) {
8932
10723
  const fnDef = this.functions[cmdName];
8933
10724
  const fnEnv = Object.assign({}, cmdEnv);
@@ -8943,13 +10734,21 @@
8943
10734
  };
8944
10735
  } else if (this.commands[cmdName]) {
8945
10736
  res = await this.commands[cmdName](args, cmdCtx);
8946
- if (cmdName === 'export' || cmdName === 'unset' || cmdName === 'cd') {
10737
+ if (cmdName === 'export' || cmdName === 'unset' || cmdName === 'cd' || cmdName === 'read') {
8947
10738
  for (const k of Object.keys(context.env)) {
8948
10739
  if (!(k in this.env)) delete context.env[k];
8949
10740
  }
8950
10741
  Object.assign(context.env, this.env);
8951
10742
  context.cwd = this.cwd;
8952
10743
  }
10744
+ } else if (resolvedPathBin) {
10745
+ const shimSrc = String(this.vfs.readFileSync(resolvedPathBin, 'utf8') || '');
10746
+ const execMatch = shimSrc.match(/exec\s+node\s+"([^"]+)"/);
10747
+ if (execMatch && execMatch[1]) {
10748
+ res = await this.commands.node([execMatch[1], ...args], cmdCtx);
10749
+ } else {
10750
+ res = await this.commands.node([resolvedPathBin, ...args], cmdCtx);
10751
+ }
8953
10752
  } else if (
8954
10753
  (cmdName.startsWith('./') || cmdName.startsWith('../') || cmdName.startsWith('/')) &&
8955
10754
  this.vfs.existsSync(this.resolvePath(cmdName))
@@ -8960,7 +10759,11 @@
8960
10759
  res = { code: 126, stdout: '', stderr: `shell: ${cmdName}: Is a directory\n` };
8961
10760
  } else if (hasVirtualRuntime()) {
8962
10761
  let rawData = null;
8963
- try { rawData = this.vfs.readFileSync(absBin); } catch (err) { _shellLogger.debug('Failed to read binary', err); }
10762
+ try {
10763
+ rawData = typeof this.vfs._getRawFileBytes === 'function'
10764
+ ? (this.vfs._getRawFileBytes(absBin) || this.vfs.readFileSync(absBin))
10765
+ : this.vfs.readFileSync(absBin);
10766
+ } catch (err) { _shellLogger.debug('Failed to read binary', err); }
8964
10767
  const isWasmMagic =
8965
10768
  (rawData instanceof Uint8Array &&
8966
10769
  rawData.length >= 4 &&
@@ -8969,17 +10772,20 @@
8969
10772
  rawData[2] === 0x73 &&
8970
10773
  rawData[3] === 0x6d) ||
8971
10774
  (typeof rawData === 'string' && rawData.startsWith('\0asm'));
8972
- const runRes = await executeInVirtualRuntime({
10775
+ const runFn = isWasmMagic ? executeInVirtualRuntime : (rOpts) => executeJsInShellRuntime(rOpts, cmdCtx);
10776
+ const runRes = await runFn({
8973
10777
  mode: 'run',
8974
10778
  entry: absBin,
8975
10779
  wasmBinary: isWasmMagic && rawData instanceof Uint8Array ? rawData : undefined,
8976
10780
  argv: [cmdName, ...args],
8977
10781
  stdin: effectiveStdin,
8978
10782
  env: cmdEnv,
10783
+ cwd: this.cwd,
8979
10784
  vfs: this.vfs,
8980
10785
  activePortTable: this.portTable,
8981
10786
  pid: cmdCtx.pid,
8982
10787
  isBackground: cmdCtx.isBackground,
10788
+ onRequestStdin: cmdCtx.onRequestStdin,
8983
10789
  onStdout: cmdCtx.onStdout,
8984
10790
  onStderr: cmdCtx.onStderr,
8985
10791
  signal: context.signal