@innovatorved/code-lab 0.3.2 → 0.5.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 (164) hide show
  1. package/ARCHITECTURE.md +5 -3
  2. package/CHANGELOG.md +41 -0
  3. package/README.md +53 -175
  4. package/dist/apps/web/src/index.d.ts +34 -0
  5. package/dist/code-lab-sql.css +482 -0
  6. package/dist/code-lab-sql.d.ts +179 -0
  7. package/dist/code-lab-sql.esm.js +542 -0
  8. package/dist/code-lab-sql.umd.js +531 -0
  9. package/dist/code-lab.css +1799 -98
  10. package/dist/code-lab.d.ts +110 -15
  11. package/dist/code-lab.esm.js +49678 -23253
  12. package/dist/code-lab.js +49648 -23251
  13. package/dist/code-lab.umd.js +75766 -0
  14. package/dist/diagnostics.d.ts +3 -0
  15. package/dist/extensions/cpp.esm.js +19504 -3788
  16. package/dist/extensions/cpp.js +19501 -3785
  17. package/dist/extensions/guided-lab.esm.js +19401 -3725
  18. package/dist/extensions/guided-lab.js +19400 -3724
  19. package/dist/extensions/python.d.ts +1 -0
  20. package/dist/extensions/python.esm.js +19597 -3788
  21. package/dist/extensions/python.js +19597 -3788
  22. package/dist/extensions/umbrella.d.ts +5 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/modular-kernel.d.ts +11 -0
  25. package/dist/packages/commands/src/index.d.ts +96 -0
  26. package/dist/packages/core/src/di.d.ts +36 -0
  27. package/dist/packages/core/src/disposable.d.ts +27 -0
  28. package/dist/packages/core/src/errors.d.ts +69 -0
  29. package/dist/packages/core/src/events.d.ts +38 -0
  30. package/dist/packages/core/src/index.d.ts +6 -0
  31. package/dist/packages/core/src/path.d.ts +14 -0
  32. package/dist/packages/core/src/registry.d.ts +23 -0
  33. package/dist/packages/editor/src/index.d.ts +118 -0
  34. package/dist/packages/fs/src/backends.d.ts +37 -0
  35. package/dist/packages/fs/src/index.d.ts +3 -0
  36. package/dist/packages/fs/src/types.d.ts +40 -0
  37. package/dist/packages/fs/src/vfs-service.d.ts +33 -0
  38. package/dist/packages/preview/src/index.d.ts +34 -0
  39. package/dist/packages/runtime/src/index.d.ts +47 -0
  40. package/dist/packages/settings/src/builtin-schemas.d.ts +15 -0
  41. package/dist/packages/settings/src/configuration-service.d.ts +107 -0
  42. package/dist/packages/settings/src/index.d.ts +4 -0
  43. package/dist/packages/settings/src/jsonc.d.ts +20 -0
  44. package/dist/packages/settings/src/schema.d.ts +28 -0
  45. package/dist/packages/sql/src/completions.d.ts +8 -0
  46. package/dist/packages/sql/src/diagnostics.d.ts +2 -0
  47. package/dist/packages/sql/src/formatter.d.ts +2 -0
  48. package/dist/packages/sql/src/index.d.ts +7 -0
  49. package/dist/packages/sql/src/sql-editor.d.ts +2 -0
  50. package/dist/packages/sql/src/styles.d.ts +2 -0
  51. package/dist/packages/sql/src/tokenizer.d.ts +13 -0
  52. package/dist/packages/sql/src/types.d.ts +130 -0
  53. package/dist/packages/terminal/src/index.d.ts +54 -0
  54. package/dist/packages/ui/src/index.d.ts +4 -0
  55. package/dist/packages/ui/src/observability.d.ts +22 -0
  56. package/dist/packages/ui/src/plugin-registry.d.ts +90 -0
  57. package/dist/packages/ui/src/settings-dialog.d.ts +53 -0
  58. package/dist/packages/ui/src/themes.d.ts +40 -0
  59. package/dist/preview-sw.js +53 -12
  60. package/dist/runtime.d.ts +3 -3
  61. package/dist/runtime.esm.js +467 -44
  62. package/dist/runtime.js +465 -44
  63. package/dist/schemas.d.ts +234 -814
  64. package/dist/schemas.esm.js +19401 -3725
  65. package/dist/schemas.js +19404 -3728
  66. package/dist/scm.d.ts +92 -11
  67. package/dist/shell.d.ts +1 -1
  68. package/dist/shell.esm.js +1300 -151
  69. package/dist/shell.js +1300 -151
  70. package/dist/storage.d.ts +47 -0
  71. package/dist/terminal.esm.js +62 -3
  72. package/dist/terminal.js +62 -3
  73. package/dist/workbench/diff-editor.d.ts +1 -0
  74. package/dist/workbench/index.d.ts +1 -1
  75. package/dist/workbench/styles.d.ts +1 -1
  76. package/package.json +38 -9
  77. package/packages/commands/README.md +7 -0
  78. package/packages/commands/package.json +16 -0
  79. package/packages/commands/src/index.ts +467 -0
  80. package/packages/commands/tsconfig.json +22 -0
  81. package/packages/core/README.md +12 -0
  82. package/packages/core/package.json +13 -0
  83. package/packages/core/src/di.ts +147 -0
  84. package/packages/core/src/disposable.ts +112 -0
  85. package/packages/core/src/errors.ts +205 -0
  86. package/packages/core/src/events.ts +157 -0
  87. package/packages/core/src/index.ts +49 -0
  88. package/packages/core/src/path.ts +118 -0
  89. package/packages/core/src/registry.ts +61 -0
  90. package/packages/core/tsconfig.json +19 -0
  91. package/packages/editor/README.md +9 -0
  92. package/packages/editor/package.json +18 -0
  93. package/packages/editor/src/index.ts +344 -0
  94. package/packages/editor/tsconfig.json +24 -0
  95. package/packages/fs/README.md +7 -0
  96. package/packages/fs/package.json +16 -0
  97. package/packages/fs/src/backends.ts +301 -0
  98. package/packages/fs/src/index.ts +18 -0
  99. package/packages/fs/src/types.ts +44 -0
  100. package/packages/fs/src/vfs-service.ts +257 -0
  101. package/packages/fs/tsconfig.json +22 -0
  102. package/packages/preview/README.md +3 -0
  103. package/packages/preview/package.json +16 -0
  104. package/packages/preview/src/index.ts +125 -0
  105. package/packages/preview/tsconfig.json +22 -0
  106. package/packages/runtime/README.md +3 -0
  107. package/packages/runtime/package.json +17 -0
  108. package/packages/runtime/src/index.ts +134 -0
  109. package/packages/runtime/tsconfig.json +23 -0
  110. package/packages/settings/README.md +7 -0
  111. package/packages/settings/package.json +16 -0
  112. package/packages/settings/src/builtin-schemas.ts +246 -0
  113. package/packages/settings/src/configuration-service.ts +609 -0
  114. package/packages/settings/src/index.ts +38 -0
  115. package/packages/settings/src/jsonc.ts +189 -0
  116. package/packages/settings/src/schema.ts +164 -0
  117. package/packages/settings/tsconfig.json +22 -0
  118. package/packages/sql/README.md +12 -0
  119. package/packages/sql/package.json +13 -0
  120. package/packages/sql/src/completions.ts +359 -0
  121. package/packages/sql/src/diagnostics.ts +200 -0
  122. package/packages/sql/src/formatter.ts +271 -0
  123. package/packages/sql/src/index.ts +54 -0
  124. package/packages/sql/src/sql-editor.ts +802 -0
  125. package/packages/sql/src/styles.ts +501 -0
  126. package/packages/sql/src/tokenizer.ts +457 -0
  127. package/packages/sql/src/types.ts +148 -0
  128. package/packages/sql/tsconfig.json +19 -0
  129. package/packages/terminal/README.md +3 -0
  130. package/packages/terminal/package.json +16 -0
  131. package/packages/terminal/src/index.ts +183 -0
  132. package/packages/terminal/tsconfig.json +22 -0
  133. package/packages/ui/README.md +8 -0
  134. package/packages/ui/package.json +18 -0
  135. package/packages/ui/src/index.ts +40 -0
  136. package/packages/ui/src/observability.ts +175 -0
  137. package/packages/ui/src/plugin-registry.ts +289 -0
  138. package/packages/ui/src/settings-dialog.ts +575 -0
  139. package/packages/ui/src/themes.ts +267 -0
  140. package/packages/ui/tsconfig.json +24 -0
  141. package/src/code-lab.css +1799 -98
  142. package/src/diagnostics.ts +139 -7
  143. package/src/extensions/cpp.ts +88 -45
  144. package/src/extensions/python.ts +186 -53
  145. package/src/extensions/umbrella.ts +5 -0
  146. package/src/index.ts +1 -1
  147. package/src/modular-kernel.ts +11 -0
  148. package/src/preview-sw.js +52 -11
  149. package/src/runtime.ts +466 -46
  150. package/src/schemas.ts +62 -62
  151. package/src/scm.ts +781 -58
  152. package/src/shell.ts +1299 -151
  153. package/src/storage.ts +336 -3
  154. package/src/terminal.ts +60 -2
  155. package/src/workbench/diff-editor.ts +66 -6
  156. package/src/workbench/icons.ts +12 -2
  157. package/src/workbench/styles.ts +25 -19
  158. package/src/workbench.ts +17059 -6673
  159. package/dist/runtime/index.d.ts +0 -4
  160. package/dist/shell/coreutils/compilers-cli.d.ts +0 -24
  161. package/dist/shell/index.d.ts +0 -4
  162. package/src/runtime/index.ts +0 -5
  163. package/src/shell/coreutils/compilers-cli.ts +0 -103
  164. package/src/shell/index.ts +0 -5
package/src/shell.ts CHANGED
@@ -1593,9 +1593,11 @@
1593
1593
  function createFallbackVfs() {
1594
1594
  const files = new Map();
1595
1595
  const dirs = new Set(['/', '/tmp', '/workspace', '/etc', '/home', '/home/user']);
1596
+ let _activeStdin = '';
1596
1597
 
1597
1598
  function norm(p) {
1598
- return PosixPath.normalize(p.startsWith('/') ? p : '/workspace/' + p);
1599
+ const s = String(p);
1600
+ return PosixPath.normalize(s.startsWith('/') ? s : '/workspace/' + s);
1599
1601
  }
1600
1602
 
1601
1603
  const emitter = {
@@ -1683,6 +1685,12 @@
1683
1685
  return Array.from(children).sort();
1684
1686
  },
1685
1687
  readFileSync(p, encoding) {
1688
+ if (p === 0 || p === '/dev/stdin') {
1689
+ if (!encoding || encoding === 'buffer') {
1690
+ return new TextEncoder().encode(_activeStdin);
1691
+ }
1692
+ return _activeStdin;
1693
+ }
1686
1694
  const np = norm(p);
1687
1695
  const f = files.get(np);
1688
1696
  if (!f) {
@@ -1695,6 +1703,9 @@
1695
1703
  }
1696
1704
  return f.data;
1697
1705
  },
1706
+ _setActiveStdin(text) {
1707
+ _activeStdin = text === null || text === undefined ? '' : String(text);
1708
+ },
1698
1709
  writeFileSync(p, data) {
1699
1710
  const np = norm(p);
1700
1711
  const parent = PosixPath.dirname(np);
@@ -1995,6 +2006,415 @@
1995
2006
  return snap;
1996
2007
  }
1997
2008
 
2009
+ function computeGitShortHash(input) {
2010
+ const str = String(input || '');
2011
+ let h1 = 0xdeadbeef ^ str.length;
2012
+ let h2 = 0x41c6ce57 ^ str.length;
2013
+ for (let i = 0; i < str.length; i++) {
2014
+ const ch = str.charCodeAt(i);
2015
+ h1 = Math.imul(h1 ^ ch, 2654435761);
2016
+ h2 = Math.imul(h2 ^ ch, 1597334677);
2017
+ }
2018
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
2019
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
2020
+ const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
2021
+ return combined.toString(16).padStart(7, '0').slice(0, 7);
2022
+ }
2023
+
2024
+ function normalizeGitRelPath(rawPath, repoRoot) {
2025
+ if (!rawPath || typeof rawPath !== 'string') return '';
2026
+ let p = rawPath.trim().replace(/\\/g, '/');
2027
+ if (!p) return '';
2028
+ const cleanRoot = PosixPath.normalize(repoRoot || '/workspace');
2029
+ const prefix = cleanRoot === '/' ? '/' : cleanRoot + '/';
2030
+ if (p === cleanRoot) return '';
2031
+ if (p.startsWith(prefix)) {
2032
+ p = p.slice(prefix.length);
2033
+ } else if (p.startsWith('/workspace/')) {
2034
+ p = p.slice('/workspace/'.length);
2035
+ }
2036
+ while (p.startsWith('./')) p = p.slice(2);
2037
+ if (p.startsWith('/')) p = p.replace(/^\/+/, '');
2038
+
2039
+ const out = [];
2040
+ for (const seg of p.split('/')) {
2041
+ if (!seg || seg === '.') continue;
2042
+ if (seg === '..') {
2043
+ if (out.length === 0) return '';
2044
+ out.pop();
2045
+ continue;
2046
+ }
2047
+ out.push(seg);
2048
+ }
2049
+ const normalized = out.join('/');
2050
+ if (
2051
+ !normalized ||
2052
+ normalized === '.git' ||
2053
+ normalized.startsWith('.git/') ||
2054
+ normalized.includes('/.git/') ||
2055
+ normalized.endsWith('/.git') ||
2056
+ normalized === 'node_modules' ||
2057
+ normalized.startsWith('node_modules/') ||
2058
+ normalized.includes('/node_modules/') ||
2059
+ normalized.endsWith('/node_modules')
2060
+ ) {
2061
+ return '';
2062
+ }
2063
+ return normalized;
2064
+ }
2065
+
2066
+ function isUnbornShellHead(gitState) {
2067
+ return (
2068
+ (!Array.isArray(gitState && gitState.commits) || gitState.commits.length === 0) &&
2069
+ !(gitState && gitState.headCommit)
2070
+ );
2071
+ }
2072
+
2073
+ function isEffectiveShellStagedChange(gitState, relPath, stagedVal, resolvedHeadFiles) {
2074
+ if (!relPath) return false;
2075
+ const headFiles =
2076
+ resolvedHeadFiles || (gitState && (gitState.headSnapshot || gitState.headFiles)) || {};
2077
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
2078
+ const normalizedVal = stagedVal === undefined || stagedVal === null ? null : String(stagedVal);
2079
+
2080
+ if (normalizedVal === null) {
2081
+ return inHead;
2082
+ }
2083
+ if (!inHead || isUnbornShellHead(gitState)) {
2084
+ return true;
2085
+ }
2086
+ return normalizedVal !== headFiles[relPath];
2087
+ }
2088
+
2089
+ function applyShellStagedEntry(gitState, map, rawPath, rawVal, resolvedHeadFiles) {
2090
+ const root = (gitState && gitState.repoRoot) || '/workspace';
2091
+ const rel = normalizeGitRelPath(rawPath, root);
2092
+ if (!rel) return;
2093
+ const normalizedVal = rawVal === undefined || rawVal === null ? null : String(rawVal);
2094
+ if (isEffectiveShellStagedChange(gitState, rel, normalizedVal, resolvedHeadFiles)) {
2095
+ map.set(rel, normalizedVal);
2096
+ } else {
2097
+ map.delete(rel);
2098
+ }
2099
+ }
2100
+
2101
+ function pruneShellStagedMap(gitState, map, resolvedHeadFiles) {
2102
+ if (!(map instanceof Map)) return;
2103
+ const root = (gitState && gitState.repoRoot) || '/workspace';
2104
+ const headFiles =
2105
+ resolvedHeadFiles || (gitState && (gitState.headSnapshot || gitState.headFiles)) || {};
2106
+ for (const [rawK, rawV] of Array.from(map.entries())) {
2107
+ const rel = normalizeGitRelPath(rawK, root);
2108
+ if (rel !== rawK) {
2109
+ map.delete(rawK);
2110
+ }
2111
+ if (!rel) {
2112
+ map.delete(rawK);
2113
+ continue;
2114
+ }
2115
+ const normalizedVal = rawV === undefined || rawV === null ? null : String(rawV);
2116
+ if (isEffectiveShellStagedChange(gitState, rel, normalizedVal, headFiles)) {
2117
+ map.set(rel, normalizedVal);
2118
+ } else {
2119
+ map.delete(rel);
2120
+ }
2121
+ }
2122
+ }
2123
+
2124
+ function getBootSnapshotForDir(shell, initDir) {
2125
+ if (!shell || !shell._initialBootSnapshot || !shell._initialBootRoot) return {};
2126
+ const normInit = PosixPath.normalize(initDir);
2127
+ const normBoot = shell._initialBootRoot;
2128
+ if (normInit === normBoot) {
2129
+ return shell._initialBootSnapshot;
2130
+ }
2131
+ const prefix = normBoot === '/' ? '/' : normBoot + '/';
2132
+ if (normInit.startsWith(prefix)) {
2133
+ const subRel = normInit.slice(prefix.length) + '/';
2134
+ const subSnap = {};
2135
+ for (const [k, v] of Object.entries(shell._initialBootSnapshot)) {
2136
+ if (k.startsWith(subRel)) {
2137
+ subSnap[k.slice(subRel.length)] = v;
2138
+ }
2139
+ }
2140
+ return subSnap;
2141
+ }
2142
+ return {};
2143
+ }
2144
+
2145
+ function attachShellStagedMapShim(map, vfsRef, getRepoRoot, getGitState) {
2146
+ if (!(map instanceof Map)) return map;
2147
+ if (!map._hasShellStagedShim) {
2148
+ Object.defineProperty(map, '_hasShellStagedShim', {
2149
+ value: true,
2150
+ enumerable: false,
2151
+ configurable: true,
2152
+ writable: true
2153
+ });
2154
+ Object.defineProperty(map, 'add', {
2155
+ value(rawPath) {
2156
+ const gs = typeof getGitState === 'function' ? getGitState() : null;
2157
+ const root =
2158
+ typeof getRepoRoot === 'function'
2159
+ ? getRepoRoot()
2160
+ : ((gs && gs.repoRoot) || '/workspace');
2161
+ const rel = normalizeGitRelPath(rawPath, root);
2162
+ if (!rel) return map;
2163
+ let content = null;
2164
+ if (vfsRef && typeof vfsRef.existsSync === 'function') {
2165
+ const abs = PosixPath.join(root, rel);
2166
+ if (vfsRef.existsSync(abs)) {
2167
+ if (typeof vfsRef.statSync === 'function') {
2168
+ try {
2169
+ if (vfsRef.statSync(abs).isDirectory()) return map;
2170
+ } catch (err) {
2171
+ _shellLogger.debug('Failed statting staged path in VFS.', abs, err);
2172
+ }
2173
+ }
2174
+ if (typeof vfsRef.readFileSync === 'function') {
2175
+ try {
2176
+ content = String(vfsRef.readFileSync(abs, 'utf8'));
2177
+ } catch (err) {
2178
+ _shellLogger.debug('Failed reading staged file from VFS.', abs, err);
2179
+ return map;
2180
+ }
2181
+ }
2182
+ }
2183
+ }
2184
+ if (gs) {
2185
+ applyShellStagedEntry(gs, map, rel, content);
2186
+ } else {
2187
+ map.set(rel, content);
2188
+ }
2189
+ return map;
2190
+ },
2191
+ enumerable: false,
2192
+ configurable: true,
2193
+ writable: true
2194
+ });
2195
+ }
2196
+ return map;
2197
+ }
2198
+
2199
+ function ensureShellStagedMap(gitState, vfsRef, repoRoot) {
2200
+ const getRoot = () => (gitState && gitState.repoRoot) || repoRoot || '/workspace';
2201
+ const getGs = () => gitState;
2202
+ if (gitState.staged instanceof Map) {
2203
+ attachShellStagedMapShim(gitState.staged, vfsRef, getRoot, getGs);
2204
+ pruneShellStagedMap(gitState, gitState.staged);
2205
+ gitState.stagedFiles = gitState.staged;
2206
+ return gitState.staged;
2207
+ }
2208
+ const nextMap = attachShellStagedMapShim(new Map(), vfsRef, getRoot, getGs);
2209
+ if (gitState.staged && typeof gitState.staged[Symbol.iterator] === 'function') {
2210
+ for (const item of gitState.staged) {
2211
+ if (Array.isArray(item) && item.length >= 2) {
2212
+ applyShellStagedEntry(
2213
+ gitState,
2214
+ nextMap,
2215
+ item[0],
2216
+ item[1] === null ? null : String(item[1])
2217
+ );
2218
+ } else if (typeof item === 'string') {
2219
+ nextMap.add(item);
2220
+ }
2221
+ }
2222
+ }
2223
+ gitState.staged = nextMap;
2224
+ gitState.stagedFiles = nextMap;
2225
+ return nextMap;
2226
+ }
2227
+
2228
+ function parseGitHeadBranch(vfs, repoRoot) {
2229
+ if (!vfs || typeof vfs.existsSync !== 'function' || typeof vfs.readFileSync !== 'function') {
2230
+ return null;
2231
+ }
2232
+ const candidates = [
2233
+ PosixPath.join(repoRoot, '.git/HEAD'),
2234
+ '/workspace/.git/HEAD'
2235
+ ];
2236
+ for (const headFile of candidates) {
2237
+ if (vfs.existsSync(headFile)) {
2238
+ try {
2239
+ const raw = String(vfs.readFileSync(headFile, 'utf8')).trim();
2240
+ const m = /^ref:\s*refs\/heads\/([^\s]+)$/.exec(raw);
2241
+ if (m && m[1]) return m[1];
2242
+ } catch (err) {
2243
+ _shellLogger.debug('Could not parse .git/HEAD branch.', headFile, err);
2244
+ }
2245
+ }
2246
+ }
2247
+ return null;
2248
+ }
2249
+
2250
+ function createUnifiedShellGitState(vfs, cwd, options = {}) {
2251
+ const cleanCwd = PosixPath.normalize(cwd || '/workspace');
2252
+ const hasDotGit = Boolean(
2253
+ vfs &&
2254
+ typeof vfs.existsSync === 'function' &&
2255
+ (vfs.existsSync(PosixPath.join(cleanCwd, '.git')) ||
2256
+ vfs.existsSync(PosixPath.join(cleanCwd, '.git/HEAD')) ||
2257
+ vfs.existsSync('/workspace/.git') ||
2258
+ vfs.existsSync('/workspace/.git/HEAD'))
2259
+ );
2260
+
2261
+ let _initialized = Boolean(options.gitInitialized === true || hasDotGit);
2262
+ let _repoRoot = cleanCwd;
2263
+ const detectedBranch = hasDotGit ? parseGitHeadBranch(vfs, cleanCwd) : null;
2264
+ const initialBranch = detectedBranch || 'main';
2265
+
2266
+ let _headFiles = _initialized ? snapshotWorktree(vfs, cleanCwd) : {};
2267
+ let _headCommit = _initialized
2268
+ ? computeGitShortHash(JSON.stringify(_headFiles) + ':init')
2269
+ : '';
2270
+ const initTs = Date.now();
2271
+ let _commits = _initialized
2272
+ ? [
2273
+ {
2274
+ hash: _headCommit,
2275
+ author: 'CodeLab Developer <dev@codelab.internal>',
2276
+ date: new Date(initTs).toUTCString(),
2277
+ timestamp: initTs,
2278
+ message: 'Initial commit',
2279
+ files: Object.assign({}, _headFiles)
2280
+ }
2281
+ ]
2282
+ : [];
2283
+
2284
+ const gs = {
2285
+ branch: initialBranch,
2286
+ branches: new Set([initialBranch]),
2287
+ remoteUrl: null,
2288
+ remotes: {}
2289
+ };
2290
+
2291
+ let _stagedMap = attachShellStagedMapShim(new Map(), vfs, () => _repoRoot, () => gs);
2292
+
2293
+ Object.defineProperties(gs, {
2294
+ initialized: {
2295
+ enumerable: true,
2296
+ configurable: true,
2297
+ get() {
2298
+ if (_initialized) return true;
2299
+ const root = _repoRoot || cleanCwd;
2300
+ if (
2301
+ vfs &&
2302
+ typeof vfs.existsSync === 'function' &&
2303
+ (vfs.existsSync(PosixPath.join(root, '.git')) ||
2304
+ vfs.existsSync(PosixPath.join(root, '.git/HEAD')))
2305
+ ) {
2306
+ _initialized = true;
2307
+ return true;
2308
+ }
2309
+ return false;
2310
+ },
2311
+ set(v) {
2312
+ _initialized = Boolean(v);
2313
+ }
2314
+ },
2315
+ repoRoot: {
2316
+ enumerable: true,
2317
+ configurable: true,
2318
+ get() {
2319
+ return _repoRoot;
2320
+ },
2321
+ set(v) {
2322
+ _repoRoot = PosixPath.normalize(String(v || cleanCwd));
2323
+ }
2324
+ },
2325
+ headCommit: {
2326
+ enumerable: true,
2327
+ configurable: true,
2328
+ get() {
2329
+ return _headCommit;
2330
+ },
2331
+ set(v) {
2332
+ _headCommit = String(v || '');
2333
+ }
2334
+ },
2335
+ headSnapshot: {
2336
+ enumerable: true,
2337
+ configurable: true,
2338
+ get() {
2339
+ return _headFiles;
2340
+ },
2341
+ set(v) {
2342
+ _headFiles = v && typeof v === 'object' ? v : {};
2343
+ }
2344
+ },
2345
+ headFiles: {
2346
+ enumerable: true,
2347
+ configurable: true,
2348
+ get() {
2349
+ return _headFiles;
2350
+ },
2351
+ set(v) {
2352
+ _headFiles = v && typeof v === 'object' ? v : {};
2353
+ }
2354
+ },
2355
+ staged: {
2356
+ enumerable: true,
2357
+ configurable: true,
2358
+ get() {
2359
+ return _stagedMap;
2360
+ },
2361
+ set(v) {
2362
+ if (v instanceof Map) {
2363
+ _stagedMap = attachShellStagedMapShim(v, vfs, () => _repoRoot, () => gs);
2364
+ pruneShellStagedMap(gs, _stagedMap);
2365
+ } else {
2366
+ const converted = attachShellStagedMapShim(new Map(), vfs, () => _repoRoot, () => gs);
2367
+ if (v && typeof v[Symbol.iterator] === 'function') {
2368
+ for (const item of v) {
2369
+ if (typeof item === 'string') {
2370
+ converted.add(item);
2371
+ } else if (Array.isArray(item) && item.length >= 2) {
2372
+ applyShellStagedEntry(
2373
+ gs,
2374
+ converted,
2375
+ item[0],
2376
+ item[1] === null ? null : String(item[1])
2377
+ );
2378
+ }
2379
+ }
2380
+ }
2381
+ _stagedMap = converted;
2382
+ }
2383
+ }
2384
+ },
2385
+ stagedFiles: {
2386
+ enumerable: true,
2387
+ configurable: true,
2388
+ get() {
2389
+ return _stagedMap;
2390
+ },
2391
+ set(v) {
2392
+ if (v instanceof Map) {
2393
+ _stagedMap = attachShellStagedMapShim(v, vfs, () => _repoRoot, () => gs);
2394
+ pruneShellStagedMap(gs, _stagedMap);
2395
+ }
2396
+ }
2397
+ },
2398
+ commits: {
2399
+ enumerable: true,
2400
+ configurable: true,
2401
+ get() {
2402
+ return _commits;
2403
+ },
2404
+ set(v) {
2405
+ _commits = Array.isArray(v) ? v : [];
2406
+ if (_commits.length > 0 && _commits[0] && _commits[0].hash) {
2407
+ _headCommit = String(_commits[0].hash);
2408
+ } else if (_commits.length === 0) {
2409
+ _headCommit = '';
2410
+ }
2411
+ }
2412
+ }
2413
+ });
2414
+
2415
+ return gs;
2416
+ }
2417
+
1998
2418
  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;
1999
2419
 
2000
2420
  function scoreRepoFilePriority(relPath) {
@@ -2255,18 +2675,23 @@
2255
2675
  if (commitsRes && commitsRes.ok) {
2256
2676
  const commitsJson = await commitsRes.json();
2257
2677
  if (Array.isArray(commitsJson) && commitsJson.length > 0) {
2258
- commits = commitsJson.map((c) => ({
2259
- hash: String(c.sha || 'a1b2c3d').slice(0, 7),
2260
- author:
2261
- c.commit && c.commit.author
2262
- ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2263
- : `${owner} <${owner}@users.noreply.github.com>`,
2264
- date:
2265
- c.commit && c.commit.author && c.commit.author.date
2266
- ? new Date(c.commit.author.date).toUTCString()
2267
- : new Date().toUTCString(),
2268
- message: c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit'
2269
- }));
2678
+ commits = commitsJson.map((c, idx) => {
2679
+ const msgText = c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit';
2680
+ const fallbackHash = computeGitShortHash(`${owner}/${repo}:${resolvedBranch}:${idx}:${msgText}`);
2681
+ const ts = c.commit && c.commit.author && c.commit.author.date
2682
+ ? Date.parse(c.commit.author.date) || Date.now()
2683
+ : Date.now();
2684
+ return {
2685
+ hash: String(c.sha || fallbackHash).slice(0, 7),
2686
+ author:
2687
+ c.commit && c.commit.author
2688
+ ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2689
+ : `${owner} <${owner}@users.noreply.github.com>`,
2690
+ date: new Date(ts).toUTCString(),
2691
+ timestamp: ts,
2692
+ message: msgText
2693
+ };
2694
+ });
2270
2695
  }
2271
2696
  }
2272
2697
  } catch (err) {
@@ -2274,11 +2699,14 @@
2274
2699
  }
2275
2700
 
2276
2701
  if (commits.length === 0) {
2702
+ const cloneTs = Date.now();
2703
+ const cloneHash = computeGitShortHash(`${owner}/${repo}:${resolvedBranch}:${filesWritten}`);
2277
2704
  commits = [
2278
2705
  {
2279
- hash: 'a1b2c3d',
2706
+ hash: cloneHash,
2280
2707
  author: `${owner} <${owner}@users.noreply.github.com>`,
2281
- date: new Date().toUTCString(),
2708
+ date: new Date(cloneTs).toUTCString(),
2709
+ timestamp: cloneTs,
2282
2710
  message: `Clone ${owner}/${repo} (${resolvedBranch})`
2283
2711
  }
2284
2712
  ];
@@ -2953,9 +3381,31 @@
2953
3381
  '.gif': 'image/gif',
2954
3382
  '.webp': 'image/webp',
2955
3383
  '.ico': 'image/x-icon',
3384
+ '.woff': 'font/woff',
3385
+ '.woff2': 'font/woff2',
3386
+ '.ttf': 'font/ttf',
3387
+ '.otf': 'font/otf',
3388
+ '.wasm': 'application/wasm',
3389
+ '.pdf': 'application/pdf',
3390
+ '.mp3': 'audio/mpeg',
3391
+ '.mp4': 'video/mp4',
3392
+ '.webm': 'video/webm',
2956
3393
  '.txt': 'text/plain; charset=utf-8'
2957
3394
  };
2958
3395
 
3396
+ function isBinaryPreviewMime(mime) {
3397
+ const clean = String(mime || '').toLowerCase().split(';')[0].trim();
3398
+ if (!clean) return false;
3399
+ return !(
3400
+ clean.startsWith('text/') ||
3401
+ clean === 'application/javascript' ||
3402
+ clean === 'application/json' ||
3403
+ clean === 'application/xml' ||
3404
+ clean === 'application/xhtml+xml' ||
3405
+ clean === 'image/svg+xml'
3406
+ );
3407
+ }
3408
+
2959
3409
  function previewMimeFor(p) {
2960
3410
  const lower = String(p).toLowerCase();
2961
3411
  const dot = lower.lastIndexOf('.');
@@ -3139,7 +3589,8 @@
3139
3589
 
3140
3590
  function injectPreviewExtras(html, importMap) {
3141
3591
  let out = html;
3142
- const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
3592
+ const safeImportMapJson = JSON.stringify({ imports: importMap }, null, 2).replace(/</g, '\\u003c');
3593
+ const importMapTag = `<script type="importmap">\n${safeImportMapJson}\n</script>`;
3143
3594
  if (/<head[^>]*>/i.test(out)) {
3144
3595
  out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
3145
3596
  } else {
@@ -3395,6 +3846,20 @@
3395
3846
  );
3396
3847
  }
3397
3848
 
3849
+ const mimeType = previewMimeFor(target);
3850
+ if (isBinaryPreviewMime(mimeType)) {
3851
+ let rawBytes = null;
3852
+ try {
3853
+ rawBytes = ctx.vfs.readFileSync(target);
3854
+ } catch (err) {
3855
+ _shellLogger.debug('Binary preview asset read failed.', target, err);
3856
+ }
3857
+ const binaryBody = rawBytes instanceof Uint8Array
3858
+ ? rawBytes
3859
+ : (typeof rawBytes === 'string' ? new TextEncoder().encode(rawBytes) : new Uint8Array(0));
3860
+ return new Response(binaryBody, { status: 200, headers: { 'content-type': mimeType } });
3861
+ }
3862
+
3398
3863
  let body = readText(target);
3399
3864
  if (body === null) body = '';
3400
3865
  if (/\.html?$/i.test(target)) {
@@ -3410,7 +3875,7 @@
3410
3875
  }
3411
3876
  }
3412
3877
 
3413
- return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
3878
+ return new Response(body, { status: 200, headers: { 'content-type': mimeType } });
3414
3879
  };
3415
3880
 
3416
3881
  const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
@@ -5430,26 +5895,56 @@
5430
5895
  // -----------------------------------------------------------------------
5431
5896
  async git(args, ctx) {
5432
5897
  const subcmd = args[0] || 'status';
5898
+ if (subcmd === 'version' || subcmd === '--version' || subcmd === '-v') {
5899
+ return { code: 0, stdout: 'git version 2.45.0 (CodeLab Virtual Git)\n', stderr: '' };
5900
+ }
5901
+ if (subcmd === 'help' || subcmd === '--help' || subcmd === '-h') {
5902
+ return {
5903
+ code: 0,
5904
+ stdout:
5905
+ 'usage: git <command> [<args>]\n\nCommon commands: init, clone, status, add, diff, commit, restore, reset, rm, branch, checkout, switch, remote, fetch, pull, log\n',
5906
+ stderr: ''
5907
+ };
5908
+ }
5909
+
5433
5910
  const gitState = ctx.shell.gitState;
5434
5911
  if (!(gitState.branches instanceof Set)) {
5435
5912
  gitState.branches = new Set(Array.isArray(gitState.branches) ? gitState.branches : [gitState.branch || 'main']);
5436
5913
  }
5437
- if (!gitState.headSnapshot) {
5438
- gitState.headSnapshot = snapshotWorktree(ctx.vfs, gitState.repoRoot || ctx.cwd);
5439
- }
5440
5914
  if (!gitState.remotes) {
5441
5915
  gitState.remotes = gitState.remoteUrl ? { origin: gitState.remoteUrl } : {};
5442
5916
  }
5443
5917
 
5444
- const repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
5918
+ let repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
5919
+ const stagedMap = ensureShellStagedMap(gitState, ctx.vfs, repoRoot);
5920
+
5445
5921
  const toRepoRel = (p) => {
5446
5922
  const abs = ctx.resolvePath(p);
5447
5923
  const prefix = repoRoot === '/' ? '/' : repoRoot + '/';
5448
5924
  if (abs === repoRoot) return '.';
5449
- if (abs.startsWith(prefix)) return abs.slice(prefix.length);
5450
- return p.replace(/^\.\//, '');
5925
+ if (abs.startsWith(prefix)) return normalizeGitRelPath(abs.slice(prefix.length), repoRoot);
5926
+ return '';
5451
5927
  };
5452
5928
 
5929
+ if (subcmd !== 'init' && subcmd !== 'clone') {
5930
+ const hasDotGitInFs = Boolean(
5931
+ ctx.vfs &&
5932
+ typeof ctx.vfs.existsSync === 'function' &&
5933
+ (ctx.vfs.existsSync(PosixPath.join(repoRoot, '.git')) ||
5934
+ ctx.vfs.existsSync(PosixPath.join(ctx.cwd, '.git')))
5935
+ );
5936
+ if (!gitState.initialized && !hasDotGitInFs) {
5937
+ return {
5938
+ code: 128,
5939
+ stdout: '',
5940
+ stderr: 'fatal: not a git repository (or any of the parent directories): .git\n'
5941
+ };
5942
+ }
5943
+ if (hasDotGitInFs && !gitState.initialized) {
5944
+ gitState.initialized = true;
5945
+ }
5946
+ }
5947
+
5453
5948
  if (subcmd === 'clone') {
5454
5949
  let branchOpt = null;
5455
5950
  const positional = [];
@@ -5496,7 +5991,6 @@
5496
5991
  dirDisplayName = parsed.repo;
5497
5992
  }
5498
5993
 
5499
- // Stream clone progress to the terminal as it happens (no end-of-run buffering).
5500
5994
  const canStream = typeof ctx.onStdout === 'function';
5501
5995
  const streamLine = (text) => { if (canStream && text) ctx.onStdout(text); };
5502
5996
  streamLine(`Cloning into '${dirDisplayName}'...\n`);
@@ -5530,14 +6024,18 @@
5530
6024
  }
5531
6025
  });
5532
6026
 
6027
+ const clonedHead = Object.assign({}, result.headSnapshot);
6028
+ gitState.initialized = true;
5533
6029
  gitState.branch = result.branch;
5534
6030
  gitState.branches.add(result.branch);
5535
6031
  gitState.remoteUrl = result.url;
5536
6032
  gitState.remotes.origin = result.url;
5537
6033
  gitState.repoRoot = targetDir;
5538
- gitState.headSnapshot = Object.assign({}, result.headSnapshot);
6034
+ gitState.headSnapshot = clonedHead;
6035
+ gitState.headFiles = clonedHead;
5539
6036
  gitState.commits = result.commits;
5540
- gitState.staged.clear();
6037
+ gitState.headCommit = (result.commits && result.commits[0] && result.commits[0].hash) || '';
6038
+ stagedMap.clear();
5541
6039
 
5542
6040
  const count = Math.max(1, result.filesWritten);
5543
6041
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
@@ -5563,62 +6061,149 @@
5563
6061
  }
5564
6062
 
5565
6063
  if (subcmd === 'init') {
5566
- const initDir = args[1] && !args[1].startsWith('-') ? ctx.resolvePath(args[1]) : ctx.cwd;
6064
+ let initBranch = gitState.branch || 'main';
6065
+ let emptyHead = false;
6066
+ let dirArg = null;
6067
+ for (let i = 1; i < args.length; i++) {
6068
+ const a = args[i];
6069
+ if ((a === '-b' || a === '--initial-branch') && i + 1 < args.length) {
6070
+ initBranch = args[++i];
6071
+ } else if (a.startsWith('--initial-branch=')) {
6072
+ initBranch = a.slice('--initial-branch='.length) || initBranch;
6073
+ } else if (a === '--empty-head') {
6074
+ emptyHead = true;
6075
+ } else if (!a.startsWith('-') && !dirArg) {
6076
+ dirArg = a;
6077
+ }
6078
+ }
6079
+ const initDir = PosixPath.normalize(dirArg ? ctx.resolvePath(dirArg) : ctx.cwd);
5567
6080
  const gitDir = PosixPath.join(initDir, '.git');
6081
+ const wasReinitSameDir =
6082
+ Boolean(gitState.initialized) &&
6083
+ PosixPath.normalize(gitState.repoRoot || ctx.cwd) === initDir &&
6084
+ !emptyHead;
5568
6085
  ensureDirSync(ctx.vfs, gitDir, ctx.emitMutation);
5569
- const branchName = gitState.branch || 'main';
5570
- ctx.vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${branchName}\n`);
6086
+ if (!wasReinitSameDir || !ctx.vfs.existsSync(PosixPath.join(gitDir, 'HEAD'))) {
6087
+ ctx.vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${initBranch}\n`);
6088
+ }
5571
6089
  ctx.vfs.writeFileSync(
5572
6090
  PosixPath.join(gitDir, 'config'),
5573
6091
  `[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n`
5574
6092
  );
5575
6093
  ctx.emitMutation('create', PosixPath.join(gitDir, 'HEAD'));
6094
+
6095
+ if (wasReinitSameDir && !isUnbornShellHead(gitState)) {
6096
+ gitState.branches.add(gitState.branch || initBranch);
6097
+ return {
6098
+ code: 0,
6099
+ stdout: `Reinitialized existing Git repository in ${gitDir}/\n`,
6100
+ stderr: ''
6101
+ };
6102
+ }
6103
+
6104
+ const initSnap = {};
6105
+ if (!emptyHead) {
6106
+ const currentLive = snapshotWorktree(ctx.vfs, initDir);
6107
+ const bootSnap = getBootSnapshotForDir(ctx.shell, initDir);
6108
+ for (const [rel, content] of Object.entries(currentLive)) {
6109
+ if (Object.prototype.hasOwnProperty.call(bootSnap, rel) && bootSnap[rel] === content) {
6110
+ initSnap[rel] = content;
6111
+ }
6112
+ }
6113
+ }
6114
+ gitState.initialized = true;
6115
+ gitState.branch = initBranch;
6116
+ gitState.branches.add(initBranch);
5576
6117
  gitState.repoRoot = initDir;
5577
- gitState.headSnapshot = snapshotWorktree(ctx.vfs, initDir);
5578
- gitState.staged.clear();
5579
- return { code: 0, stdout: `Initialized empty Git repository in ${gitDir}/\n`, stderr: '' };
6118
+ gitState.headSnapshot = initSnap;
6119
+ gitState.headFiles = initSnap;
6120
+ gitState.commits = [];
6121
+ gitState.headCommit = '';
6122
+ stagedMap.clear();
6123
+ return {
6124
+ code: 0,
6125
+ stdout: `${wasReinitSameDir ? 'Reinitialized existing' : 'Initialized empty'} Git repository in ${gitDir}/\n`,
6126
+ stderr: ''
6127
+ };
5580
6128
  }
5581
6129
 
6130
+ repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6131
+
5582
6132
  if (subcmd === 'status') {
5583
- const isShort = args.includes('-s') || args.includes('--short');
6133
+ const isShort = args.includes('-s') || args.includes('--short') || args.includes('--porcelain');
5584
6134
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5585
- const headFiles = gitState.headSnapshot || {};
6135
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6136
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6137
+ const unbornHead = isUnbornShellHead(gitState);
5586
6138
 
5587
6139
  const stagedList = [];
5588
- for (const relPath of gitState.staged) {
6140
+ const unstagedList = [];
6141
+ const untrackedList = [];
6142
+ const stagedKeysSorted = Array.from(stagedMap.keys()).sort();
6143
+
6144
+ for (const relPath of stagedKeysSorted) {
6145
+ const stagedVal = stagedMap.get(relPath);
5589
6146
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
5590
6147
  const inLive = Object.prototype.hasOwnProperty.call(liveFiles, relPath);
5591
- if (!inHead && inLive) {
5592
- stagedList.push({ status: 'new file', short: 'A ', path: relPath });
5593
- } else if (inHead && !inLive) {
5594
- stagedList.push({ status: 'deleted', short: 'D ', path: relPath });
6148
+
6149
+ if (stagedVal === null) {
6150
+ if (inHead) {
6151
+ stagedList.push({ status: 'deleted', code: 'D', path: relPath });
6152
+ }
6153
+ if (inLive) {
6154
+ untrackedList.push(relPath);
6155
+ }
5595
6156
  } else {
5596
- stagedList.push({ status: 'modified', short: 'M ', path: relPath });
6157
+ if (!inHead || unbornHead) {
6158
+ stagedList.push({ status: 'new file', code: 'A', path: relPath });
6159
+ } else if (stagedVal !== headFiles[relPath]) {
6160
+ stagedList.push({ status: 'modified', code: 'M', path: relPath });
6161
+ }
6162
+
6163
+ if (!inLive) {
6164
+ unstagedList.push({ status: 'deleted', code: 'D', path: relPath });
6165
+ } else if (liveFiles[relPath] !== stagedVal) {
6166
+ unstagedList.push({ status: 'modified', code: 'M', path: relPath });
6167
+ }
5597
6168
  }
5598
6169
  }
5599
6170
 
5600
- const unstagedList = [];
5601
6171
  for (const relPath of Object.keys(headFiles).sort()) {
5602
- if (gitState.staged.has(relPath)) continue;
6172
+ if (stagedMap.has(relPath)) continue;
5603
6173
  if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5604
- unstagedList.push({ status: 'deleted', short: ' D', path: relPath });
6174
+ unstagedList.push({ status: 'deleted', code: 'D', path: relPath });
5605
6175
  } else if (liveFiles[relPath] !== headFiles[relPath]) {
5606
- unstagedList.push({ status: 'modified', short: ' M', path: relPath });
6176
+ unstagedList.push({ status: 'modified', code: 'M', path: relPath });
5607
6177
  }
5608
6178
  }
5609
6179
 
5610
- const untrackedList = [];
5611
6180
  for (const relPath of Object.keys(liveFiles).sort()) {
5612
- if (!Object.prototype.hasOwnProperty.call(headFiles, relPath) && !gitState.staged.has(relPath)) {
6181
+ if (!Object.prototype.hasOwnProperty.call(headFiles, relPath) && !stagedMap.has(relPath)) {
5613
6182
  untrackedList.push(relPath);
5614
6183
  }
5615
6184
  }
5616
6185
 
6186
+ unstagedList.sort((a, b) => a.path.localeCompare(b.path));
6187
+ untrackedList.sort();
6188
+
5617
6189
  if (isShort) {
6190
+ const shortByPath = new Map();
6191
+ for (const item of stagedList) {
6192
+ shortByPath.set(item.path, { idx: item.code, wt: ' ' });
6193
+ }
6194
+ for (const item of unstagedList) {
6195
+ const prev = shortByPath.get(item.path);
6196
+ if (prev) prev.wt = item.code;
6197
+ else shortByPath.set(item.path, { idx: ' ', wt: item.code });
6198
+ }
5618
6199
  let sOut = '';
5619
- for (const item of stagedList) sOut += `${item.short} ${item.path}\n`;
5620
- for (const item of unstagedList) sOut += `${item.short} ${item.path}\n`;
5621
- for (const p of untrackedList) sOut += `?? ${p}\n`;
6200
+ for (const p of Array.from(shortByPath.keys()).sort()) {
6201
+ const pair = shortByPath.get(p);
6202
+ sOut += `${pair.idx}${pair.wt} ${p}\n`;
6203
+ }
6204
+ for (const p of untrackedList) {
6205
+ sOut += `?? ${p}\n`;
6206
+ }
5622
6207
  return { code: 0, stdout: sOut, stderr: '' };
5623
6208
  }
5624
6209
 
@@ -5655,24 +6240,43 @@
5655
6240
 
5656
6241
  if (subcmd === 'diff') {
5657
6242
  const isStaged = args.includes('--staged') || args.includes('--cached');
5658
- const fileFilters = args.slice(1).filter((a) => !a.startsWith('-')).map(toRepoRel);
6243
+ const rawFilterArgs = args.slice(1).filter((a) => !a.startsWith('-'));
6244
+ const fileFilters = rawFilterArgs.map(toRepoRel);
6245
+ const matchAllInRepo = fileFilters.length === 0 || fileFilters.includes('.');
5659
6246
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5660
- const headFiles = gitState.headSnapshot || {};
5661
- const allKeys = Array.from(new Set([...Object.keys(headFiles), ...Object.keys(liveFiles)])).sort();
6247
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6248
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6249
+ const unbornHead = isUnbornShellHead(gitState);
6250
+ const allKeys = Array.from(
6251
+ new Set([...Object.keys(headFiles), ...Object.keys(liveFiles), ...Array.from(stagedMap.keys())])
6252
+ ).sort();
5662
6253
 
5663
6254
  let stdout = '';
5664
6255
  for (const relPath of allKeys) {
5665
- if (fileFilters.length > 0 && !fileFilters.includes(relPath)) continue;
5666
- if (isStaged && !gitState.staged.has(relPath)) continue;
5667
- if (!isStaged && !Object.prototype.hasOwnProperty.call(headFiles, relPath) && !gitState.staged.has(relPath)) {
5668
- continue;
5669
- }
5670
- const oldText = Object.prototype.hasOwnProperty.call(headFiles, relPath) ? headFiles[relPath] : '';
5671
- const newText = Object.prototype.hasOwnProperty.call(liveFiles, relPath) ? liveFiles[relPath] : '';
5672
- if (oldText !== newText) {
5673
- const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
5674
- if (uDiff) {
5675
- stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
6256
+ if (!matchAllInRepo && !fileFilters.includes(relPath)) continue;
6257
+ if (isStaged) {
6258
+ if (!stagedMap.has(relPath)) continue;
6259
+ const stagedVal = stagedMap.get(relPath);
6260
+ if (!isEffectiveShellStagedChange(gitState, relPath, stagedVal, headFiles)) continue;
6261
+ const oldText =
6262
+ !unbornHead && Object.prototype.hasOwnProperty.call(headFiles, relPath)
6263
+ ? headFiles[relPath]
6264
+ : '';
6265
+ const newText = stagedVal === null ? '' : String(stagedVal);
6266
+ if (oldText !== newText) {
6267
+ const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
6268
+ if (uDiff) stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
6269
+ }
6270
+ } else {
6271
+ const isTrackedOrStaged =
6272
+ Object.prototype.hasOwnProperty.call(headFiles, relPath) || stagedMap.has(relPath);
6273
+ if (!isTrackedOrStaged) continue;
6274
+ const baseVal = stagedMap.has(relPath) ? stagedMap.get(relPath) : headFiles[relPath];
6275
+ const oldText = baseVal === null || baseVal === undefined ? '' : String(baseVal);
6276
+ const newText = Object.prototype.hasOwnProperty.call(liveFiles, relPath) ? liveFiles[relPath] : '';
6277
+ if (oldText !== newText) {
6278
+ const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
6279
+ if (uDiff) stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
5676
6280
  }
5677
6281
  }
5678
6282
  }
@@ -5682,38 +6286,76 @@
5682
6286
  if (subcmd === 'add') {
5683
6287
  const targets = args.slice(1);
5684
6288
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5685
- const headFiles = gitState.headSnapshot || {};
6289
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6290
+
6291
+ const stagePath = (relPath) => {
6292
+ const clean = normalizeGitRelPath(relPath, repoRoot);
6293
+ if (!clean) return;
6294
+ const inLive = Object.prototype.hasOwnProperty.call(liveFiles, clean);
6295
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, clean);
6296
+ if (inLive) {
6297
+ applyShellStagedEntry(gitState, stagedMap, clean, liveFiles[clean], headFiles);
6298
+ } else if (inHead) {
6299
+ applyShellStagedEntry(gitState, stagedMap, clean, null, headFiles);
6300
+ } else {
6301
+ stagedMap.delete(clean);
6302
+ }
6303
+ };
5686
6304
 
5687
6305
  if (targets.includes('.') || targets.includes('-A') || targets.includes('--all') || targets.includes('-u')) {
5688
6306
  const includeUntracked = !targets.includes('-u');
5689
6307
  for (const relPath of Object.keys(liveFiles)) {
5690
6308
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
5691
6309
  if (!inHead && includeUntracked) {
5692
- gitState.staged.add(relPath);
5693
- } else if (inHead && liveFiles[relPath] !== headFiles[relPath]) {
5694
- gitState.staged.add(relPath);
6310
+ stagePath(relPath);
6311
+ } else if (inHead) {
6312
+ stagePath(relPath);
5695
6313
  }
5696
6314
  }
5697
6315
  for (const relPath of Object.keys(headFiles)) {
5698
6316
  if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5699
- gitState.staged.add(relPath);
6317
+ stagePath(relPath);
6318
+ }
6319
+ }
6320
+ for (const stagedKey of Array.from(stagedMap.keys())) {
6321
+ if (
6322
+ !Object.prototype.hasOwnProperty.call(liveFiles, stagedKey) &&
6323
+ !Object.prototype.hasOwnProperty.call(headFiles, stagedKey)
6324
+ ) {
6325
+ stagedMap.delete(stagedKey);
5700
6326
  }
5701
6327
  }
5702
6328
  } else {
5703
6329
  for (const f of targets) {
5704
6330
  if (f.startsWith('-')) continue;
5705
6331
  const rel = toRepoRel(f);
6332
+ if (!rel) continue;
5706
6333
  if (rel === '.') {
5707
- for (const k of Object.keys(liveFiles)) {
5708
- if (liveFiles[k] !== headFiles[k]) gitState.staged.add(k);
6334
+ for (const k of Object.keys(liveFiles)) stagePath(k);
6335
+ for (const k of Object.keys(headFiles)) {
6336
+ if (!Object.prototype.hasOwnProperty.call(liveFiles, k)) stagePath(k);
6337
+ }
6338
+ for (const stagedKey of Array.from(stagedMap.keys())) {
6339
+ if (
6340
+ !Object.prototype.hasOwnProperty.call(liveFiles, stagedKey) &&
6341
+ !Object.prototype.hasOwnProperty.call(headFiles, stagedKey)
6342
+ ) {
6343
+ stagedMap.delete(stagedKey);
6344
+ }
5709
6345
  }
5710
6346
  } else {
5711
6347
  const dirPrefix = rel.replace(/\/+$/, '') + '/';
5712
- const matchedSubfiles = Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix));
6348
+ const matchedSubfiles = Array.from(
6349
+ new Set([
6350
+ ...Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix)),
6351
+ ...Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix)),
6352
+ ...Array.from(stagedMap.keys()).filter((k) => k.startsWith(dirPrefix))
6353
+ ])
6354
+ );
5713
6355
  if (matchedSubfiles.length > 0) {
5714
- for (const k of matchedSubfiles) gitState.staged.add(k);
6356
+ for (const k of matchedSubfiles) stagePath(k);
5715
6357
  } else {
5716
- gitState.staged.add(rel);
6358
+ stagePath(rel);
5717
6359
  }
5718
6360
  }
5719
6361
  }
@@ -5723,37 +6365,72 @@
5723
6365
 
5724
6366
  if (subcmd === 'commit') {
5725
6367
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5726
- const headFiles = gitState.headSnapshot || {};
5727
- if (args.includes('-a') || args.includes('-am')) {
6368
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6369
+ const autoStageTracked = args.some(
6370
+ (a) =>
6371
+ a === '-a' ||
6372
+ a === '--all' ||
6373
+ (a.startsWith('-') && !a.startsWith('--') && a !== '-m' && a.includes('a'))
6374
+ );
6375
+ if (autoStageTracked) {
5728
6376
  for (const relPath of Object.keys(headFiles)) {
5729
- if (liveFiles[relPath] !== headFiles[relPath]) {
5730
- gitState.staged.add(relPath);
6377
+ if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
6378
+ applyShellStagedEntry(gitState, stagedMap, relPath, null, headFiles);
6379
+ } else {
6380
+ applyShellStagedEntry(gitState, stagedMap, relPath, liveFiles[relPath], headFiles);
5731
6381
  }
5732
6382
  }
5733
6383
  }
5734
6384
 
6385
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6386
+
6387
+ if (stagedMap.size === 0) {
6388
+ return {
6389
+ code: 1,
6390
+ stdout: `On branch ${gitState.branch}\nnothing to commit, working tree clean\n`,
6391
+ stderr: ''
6392
+ };
6393
+ }
6394
+
5735
6395
  let msg = 'Commit changes';
5736
- const mIdx = args.findIndex((a) => a === '-m' || a === '-am');
6396
+ const mIdx = args.findIndex(
6397
+ (a) => a === '-m' || a === '-am' || a === '-ma'
6398
+ );
5737
6399
  if (mIdx !== -1 && mIdx + 1 < args.length) msg = args[mIdx + 1];
5738
6400
 
5739
- for (const relPath of gitState.staged) {
5740
- if (Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5741
- gitState.headSnapshot[relPath] = liveFiles[relPath];
6401
+ const nextHead = Object.assign({}, headFiles);
6402
+ const summaryParts = [];
6403
+ for (const [relPath, stagedVal] of stagedMap.entries()) {
6404
+ summaryParts.push(`${relPath}:${stagedVal === null ? '<DEL>' : stagedVal}`);
6405
+ if (stagedVal === null) {
6406
+ delete nextHead[relPath];
5742
6407
  } else {
5743
- delete gitState.headSnapshot[relPath];
6408
+ nextHead[relPath] = String(stagedVal);
5744
6409
  }
5745
6410
  }
5746
6411
 
5747
- const hash = Math.random().toString(16).slice(2, 9);
6412
+ const commitTs = Date.now();
6413
+ const hash = computeGitShortHash(
6414
+ `${gitState.headCommit || ''}:${msg}:${commitTs}:${gitState.commits.length}:${summaryParts.join('|')}`
6415
+ );
6416
+ const count = stagedMap.size;
6417
+ gitState.headSnapshot = nextHead;
6418
+ gitState.headFiles = nextHead;
5748
6419
  gitState.commits.unshift({
5749
6420
  hash,
5750
- author: `${ctx.env.USER || 'codelab'} <dev@codelab.internal>`,
5751
- date: new Date().toUTCString(),
5752
- message: msg
6421
+ author: `${ctx.env.USER || 'CodeLab Developer'} <dev@codelab.internal>`,
6422
+ date: new Date(commitTs).toUTCString(),
6423
+ timestamp: commitTs,
6424
+ message: msg,
6425
+ files: Object.assign({}, nextHead)
5753
6426
  });
5754
- const count = gitState.staged.size || 1;
5755
- gitState.staged.clear();
5756
- return { code: 0, stdout: `[${gitState.branch} ${hash}] ${msg}\n ${count} file changed\n`, stderr: '' };
6427
+ gitState.headCommit = hash;
6428
+ stagedMap.clear();
6429
+ return {
6430
+ code: 0,
6431
+ stdout: `[${gitState.branch} ${hash}] ${msg}\n ${count} file${count === 1 ? '' : 's'} changed\n`,
6432
+ stderr: ''
6433
+ };
5757
6434
  }
5758
6435
 
5759
6436
  if (subcmd === 'branch') {
@@ -5813,9 +6490,11 @@
5813
6490
  }
5814
6491
 
5815
6492
  const rel = toRepoRel(target);
5816
- if (gitState.headSnapshot && Object.prototype.hasOwnProperty.call(gitState.headSnapshot, rel)) {
6493
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6494
+ if (rel && Object.prototype.hasOwnProperty.call(headFiles, rel)) {
5817
6495
  const abs = PosixPath.join(repoRoot, rel);
5818
- ctx.vfs.writeFileSync(abs, gitState.headSnapshot[rel]);
6496
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6497
+ ctx.vfs.writeFileSync(abs, headFiles[rel]);
5819
6498
  ctx.emitMutation('change', abs);
5820
6499
  return { code: 0, stdout: `Updated 1 path from the index\n`, stderr: '' };
5821
6500
  }
@@ -5825,20 +6504,199 @@
5825
6504
 
5826
6505
  if (subcmd === 'restore') {
5827
6506
  const isStaged = args.includes('--staged') || args.includes('-S');
5828
- const targets = args.slice(1).filter((a) => !a.startsWith('-'));
6507
+ const isWorktree = args.includes('--worktree') || args.includes('-W') || !isStaged;
6508
+ const targets = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6509
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
5829
6510
  for (const t of targets) {
5830
6511
  const rel = toRepoRel(t);
6512
+ if (!rel) continue;
5831
6513
  if (isStaged) {
5832
- gitState.staged.delete(rel);
5833
- } else if (gitState.headSnapshot && Object.prototype.hasOwnProperty.call(gitState.headSnapshot, rel)) {
6514
+ if (rel === '.') {
6515
+ stagedMap.clear();
6516
+ } else {
6517
+ const cleanRel = rel.replace(/\/+$/, '');
6518
+ const dirPrefix = cleanRel + '/';
6519
+ stagedMap.delete(cleanRel);
6520
+ for (const k of Array.from(stagedMap.keys())) {
6521
+ if (k.startsWith(dirPrefix)) {
6522
+ stagedMap.delete(k);
6523
+ }
6524
+ }
6525
+ }
6526
+ }
6527
+ if (isWorktree) {
6528
+ if (rel === '.') {
6529
+ for (const [k, v] of Object.entries(headFiles)) {
6530
+ const abs = PosixPath.join(repoRoot, k);
6531
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6532
+ ctx.vfs.writeFileSync(abs, v);
6533
+ ctx.emitMutation('change', abs);
6534
+ }
6535
+ } else {
6536
+ const cleanRel = rel.replace(/\/+$/, '');
6537
+ const dirPrefix = cleanRel + '/';
6538
+ const subHeadKeys = Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix));
6539
+ if (subHeadKeys.length > 0 && !Object.prototype.hasOwnProperty.call(headFiles, cleanRel)) {
6540
+ for (const k of subHeadKeys) {
6541
+ const sourceText =
6542
+ !isStaged && stagedMap.has(k) && stagedMap.get(k) !== null
6543
+ ? stagedMap.get(k)
6544
+ : headFiles[k];
6545
+ const abs = PosixPath.join(repoRoot, k);
6546
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6547
+ ctx.vfs.writeFileSync(abs, String(sourceText));
6548
+ ctx.emitMutation('change', abs);
6549
+ }
6550
+ } else {
6551
+ const sourceText =
6552
+ !isStaged && stagedMap.has(cleanRel) && stagedMap.get(cleanRel) !== null
6553
+ ? stagedMap.get(cleanRel)
6554
+ : (Object.prototype.hasOwnProperty.call(headFiles, cleanRel) ? headFiles[cleanRel] : undefined);
6555
+ if (sourceText !== undefined) {
6556
+ const abs = PosixPath.join(repoRoot, cleanRel);
6557
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6558
+ ctx.vfs.writeFileSync(abs, String(sourceText));
6559
+ ctx.emitMutation('change', abs);
6560
+ }
6561
+ }
6562
+ }
6563
+ }
6564
+ }
6565
+ return { code: 0, stdout: '', stderr: '' };
6566
+ }
6567
+
6568
+ if (subcmd === 'reset') {
6569
+ const isHard = args.includes('--hard');
6570
+ const fileArgs = args.slice(1).filter((a) => !a.startsWith('-') && a !== 'HEAD' && a !== '--');
6571
+ if (fileArgs.length > 0) {
6572
+ for (const f of fileArgs) {
6573
+ const rel = toRepoRel(f);
6574
+ if (!rel) continue;
6575
+ if (rel === '.') {
6576
+ stagedMap.clear();
6577
+ } else {
6578
+ const cleanRel = rel.replace(/\/+$/, '');
6579
+ const dirPrefix = cleanRel + '/';
6580
+ stagedMap.delete(cleanRel);
6581
+ for (const k of Array.from(stagedMap.keys())) {
6582
+ if (k.startsWith(dirPrefix)) {
6583
+ stagedMap.delete(k);
6584
+ }
6585
+ }
6586
+ }
6587
+ }
6588
+ return { code: 0, stdout: '', stderr: '' };
6589
+ }
6590
+ stagedMap.clear();
6591
+ if (isHard) {
6592
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6593
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6594
+ for (const rel of Object.keys(liveFiles)) {
6595
+ if (!Object.prototype.hasOwnProperty.call(headFiles, rel)) {
6596
+ const abs = PosixPath.join(repoRoot, rel);
6597
+ if (typeof ctx.vfs.rmSync === 'function') {
6598
+ ctx.vfs.rmSync(abs, { force: true });
6599
+ } else if (typeof ctx.vfs.unlinkSync === 'function' && ctx.vfs.existsSync(abs)) {
6600
+ ctx.vfs.unlinkSync(abs);
6601
+ }
6602
+ ctx.emitMutation('delete', abs);
6603
+ }
6604
+ }
6605
+ for (const [rel, text] of Object.entries(headFiles)) {
5834
6606
  const abs = PosixPath.join(repoRoot, rel);
5835
- ctx.vfs.writeFileSync(abs, gitState.headSnapshot[rel]);
6607
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6608
+ ctx.vfs.writeFileSync(abs, text);
5836
6609
  ctx.emitMutation('change', abs);
5837
6610
  }
5838
6611
  }
5839
6612
  return { code: 0, stdout: '', stderr: '' };
5840
6613
  }
5841
6614
 
6615
+ if (subcmd === 'rm') {
6616
+ const cachedOnly = args.includes('--cached');
6617
+ const isRecursive = args.some((a) => a === '-r' || a === '-rf' || a === '-fr');
6618
+ const targets = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6619
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6620
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6621
+
6622
+ if (targets.length === 0) {
6623
+ return { code: 128, stdout: '', stderr: 'usage: git rm [--cached] [-r] [-f] <file>...\n' };
6624
+ }
6625
+
6626
+ const removeSingleRel = (rel) => {
6627
+ if (!rel) return;
6628
+ const abs = PosixPath.join(repoRoot, rel);
6629
+ if (!cachedOnly && ctx.vfs.existsSync(abs)) {
6630
+ if (typeof ctx.vfs.rmSync === 'function') {
6631
+ ctx.vfs.rmSync(abs, { force: true, recursive: isRecursive });
6632
+ } else if (typeof ctx.vfs.unlinkSync === 'function') {
6633
+ ctx.vfs.unlinkSync(abs);
6634
+ }
6635
+ ctx.emitMutation('delete', abs);
6636
+ }
6637
+ if (Object.prototype.hasOwnProperty.call(headFiles, rel)) {
6638
+ stagedMap.set(rel, null);
6639
+ } else {
6640
+ stagedMap.delete(rel);
6641
+ }
6642
+ };
6643
+
6644
+ for (const t of targets) {
6645
+ const rel = toRepoRel(t);
6646
+ if (!rel) continue;
6647
+ if (rel === '.') {
6648
+ if (isRecursive) {
6649
+ const allRel = Array.from(
6650
+ new Set([
6651
+ ...Object.keys(headFiles),
6652
+ ...Object.keys(liveFiles),
6653
+ ...Array.from(stagedMap.keys())
6654
+ ])
6655
+ );
6656
+ for (const sub of allRel) removeSingleRel(sub);
6657
+ }
6658
+ continue;
6659
+ }
6660
+ const dirPrefix = rel.replace(/\/+$/, '') + '/';
6661
+ const subMatches = isRecursive
6662
+ ? Array.from(
6663
+ new Set([
6664
+ ...Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix)),
6665
+ ...Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix)),
6666
+ ...Array.from(stagedMap.keys()).filter((k) => k.startsWith(dirPrefix))
6667
+ ])
6668
+ )
6669
+ : [];
6670
+ if (subMatches.length > 0) {
6671
+ for (const sub of subMatches) removeSingleRel(sub);
6672
+ if (!cachedOnly) removeDirRecursive(ctx.vfs, PosixPath.join(repoRoot, rel), ctx.emitMutation);
6673
+ } else {
6674
+ const abs = PosixPath.join(repoRoot, rel);
6675
+ if (
6676
+ !isRecursive &&
6677
+ ctx.vfs &&
6678
+ typeof ctx.vfs.existsSync === 'function' &&
6679
+ ctx.vfs.existsSync(abs) &&
6680
+ typeof ctx.vfs.statSync === 'function'
6681
+ ) {
6682
+ try {
6683
+ if (ctx.vfs.statSync(abs).isDirectory()) {
6684
+ return {
6685
+ code: 128,
6686
+ stdout: '',
6687
+ stderr: `fatal: not removing '${t}' recursively without -r\n`
6688
+ };
6689
+ }
6690
+ } catch (err) {
6691
+ _shellLogger.debug('Failed statting path in git rm.', abs, err);
6692
+ }
6693
+ }
6694
+ removeSingleRel(rel);
6695
+ }
6696
+ }
6697
+ return { code: 0, stdout: '', stderr: '' };
6698
+ }
6699
+
5842
6700
  if (subcmd === 'remote') {
5843
6701
  const sub = args[1];
5844
6702
  if (!sub) {
@@ -5886,7 +6744,9 @@
5886
6744
  signal: ctx.signal,
5887
6745
  onFile: (absPath) => ctx.emitMutation('change', absPath)
5888
6746
  });
5889
- gitState.headSnapshot = Object.assign({}, result.headSnapshot);
6747
+ const pulledHead = Object.assign({}, result.headSnapshot);
6748
+ gitState.headSnapshot = pulledHead;
6749
+ gitState.headFiles = pulledHead;
5890
6750
  return {
5891
6751
  code: 0,
5892
6752
  stdout: `From ${remoteUrl.replace(/\.git$/, '')}\n * branch ${result.branch} -> FETCH_HEAD\nAlready up to date.\n`,
@@ -5913,9 +6773,11 @@
5913
6773
  if (oneline) {
5914
6774
  stdout += `${c.hash} ${c.message}\n`;
5915
6775
  } else {
6776
+ const authorStr = c.author || 'CodeLab Developer <dev@codelab.internal>';
6777
+ const dateStr = c.date || (c.timestamp ? new Date(c.timestamp).toUTCString() : new Date(0).toUTCString());
5916
6778
  stdout += `commit ${c.hash}\n`;
5917
- stdout += `Author: ${c.author}\n`;
5918
- stdout += `Date: ${c.date}\n\n`;
6779
+ stdout += `Author: ${authorStr}\n`;
6780
+ stdout += `Date: ${dateStr}\n\n`;
5919
6781
  stdout += ` ${c.message}\n\n`;
5920
6782
  }
5921
6783
  }
@@ -5992,6 +6854,9 @@
5992
6854
  mode: 'repl',
5993
6855
  replCode: code,
5994
6856
  printReplResult: false,
6857
+ stdin: ctx.stdin || '',
6858
+ env: ctx.env,
6859
+ cwd: ctx.cwd,
5995
6860
  vfs: ctx.vfs,
5996
6861
  activePortTable: ctx.shell.portTable,
5997
6862
  pid: ctx.pid,
@@ -6009,6 +6874,9 @@
6009
6874
  mode: 'repl',
6010
6875
  replCode: code,
6011
6876
  printReplResult: true,
6877
+ stdin: ctx.stdin || '',
6878
+ env: ctx.env,
6879
+ cwd: ctx.cwd,
6012
6880
  vfs: ctx.vfs,
6013
6881
  activePortTable: ctx.shell.portTable,
6014
6882
  pid: ctx.pid,
@@ -6048,6 +6916,9 @@
6048
6916
  const res = await executeInVirtualRuntime({
6049
6917
  mode: 'test',
6050
6918
  entry: f,
6919
+ stdin: ctx.stdin || '',
6920
+ env: ctx.env,
6921
+ cwd: ctx.cwd,
6051
6922
  vfs: ctx.vfs,
6052
6923
  activePortTable: ctx.shell.portTable,
6053
6924
  pid: ctx.pid,
@@ -6073,6 +6944,9 @@
6073
6944
  mode: 'run',
6074
6945
  entry: scriptFile,
6075
6946
  argv: ['node', scriptFile, ...scriptArgs],
6947
+ stdin: ctx.stdin || '',
6948
+ env: ctx.env,
6949
+ cwd: ctx.cwd,
6076
6950
  vfs: ctx.vfs,
6077
6951
  activePortTable: ctx.shell.portTable,
6078
6952
  pid: ctx.pid,
@@ -6240,6 +7114,9 @@
6240
7114
  const res = await pyCompiler({
6241
7115
  entry: entryFile,
6242
7116
  source: codeToRun,
7117
+ stdin: ctx.stdin || '',
7118
+ env: ctx.env,
7119
+ cwd: ctx.cwd,
6243
7120
  vfs: ctx.vfs,
6244
7121
  onStdout: (t) => {
6245
7122
  outText += t;
@@ -6306,9 +7183,9 @@
6306
7183
  };
6307
7184
  }
6308
7185
  return {
6309
- code: 0,
6310
- stdout: `Successfully installed ${pkgs.join(', ') || 'packages'}\n`,
6311
- stderr: ''
7186
+ code: 1,
7187
+ stdout: '',
7188
+ stderr: 'pip: Python WebAssembly toolchain is not enabled. Enable pythonExtension from "@innovatorved/code-lab/extensions/python".\n'
6312
7189
  };
6313
7190
  }
6314
7191
  return { code: 0, stdout: 'pip 24.0 (Pyodide micropip)\n', stderr: '' };
@@ -6426,6 +7303,9 @@
6426
7303
  mode: 'repl',
6427
7304
  replCode: code,
6428
7305
  printReplResult: false,
7306
+ stdin: ctx.stdin || '',
7307
+ env: ctx.env,
7308
+ cwd: ctx.cwd,
6429
7309
  vfs: ctx.vfs,
6430
7310
  activePortTable: ctx.shell.portTable,
6431
7311
  pid: ctx.pid,
@@ -6465,6 +7345,9 @@
6465
7345
  const res = await executeInVirtualRuntime({
6466
7346
  mode: 'test',
6467
7347
  entry: f,
7348
+ stdin: ctx.stdin || '',
7349
+ env: ctx.env,
7350
+ cwd: ctx.cwd,
6468
7351
  vfs: ctx.vfs,
6469
7352
  activePortTable: ctx.shell.portTable,
6470
7353
  pid: ctx.pid,
@@ -6492,6 +7375,9 @@
6492
7375
  mode: 'run',
6493
7376
  entry: resolved,
6494
7377
  argv: ['bun', resolved, ...scriptArgs],
7378
+ stdin: ctx.stdin || '',
7379
+ env: ctx.env,
7380
+ cwd: ctx.cwd,
6495
7381
  vfs: ctx.vfs,
6496
7382
  activePortTable: ctx.shell.portTable,
6497
7383
  pid: ctx.pid,
@@ -6516,6 +7402,9 @@
6516
7402
  mode: 'run',
6517
7403
  entry: resolved,
6518
7404
  argv: ['bun', resolved, ...scriptArgs],
7405
+ stdin: ctx.stdin || '',
7406
+ env: ctx.env,
7407
+ cwd: ctx.cwd,
6519
7408
  vfs: ctx.vfs,
6520
7409
  activePortTable: ctx.shell.portTable,
6521
7410
  pid: ctx.pid,
@@ -6797,12 +7686,24 @@
6797
7686
  if (!method) method = 'GET';
6798
7687
 
6799
7688
  const portTable = (ctx.shell && ctx.shell.portTable) || null;
7689
+ const fetchImpl = (ctx.shell && ctx.shell.options && typeof (ctx.shell.options.fetch || ctx.shell.options.fetchImpl) === 'function')
7690
+ ? (ctx.shell.options.fetch || ctx.shell.options.fetchImpl)
7691
+ : fetch;
7692
+ let isLoopback = false;
7693
+ try {
7694
+ const parsedUrl = new URL(url);
7695
+ const host = parsedUrl.hostname.toLowerCase();
7696
+ isLoopback = host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0' || host === '::1' || host === '[::1]';
7697
+ } catch (err) {
7698
+ _shellLogger.debug('curl URL parse fallback', url, err);
7699
+ }
6800
7700
  let resp = null;
6801
7701
  let lastErr = null;
7702
+ const maxAttempts = portTable && isLoopback ? 25 : 1;
6802
7703
 
6803
- for (let attempt = 0; attempt < 25; attempt++) {
7704
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
6804
7705
  try {
6805
- if (portTable) {
7706
+ if (portTable && isLoopback) {
6806
7707
  resp = await portTable.dispatchRequest(url, {
6807
7708
  method,
6808
7709
  headers,
@@ -6811,7 +7712,7 @@
6811
7712
  lastErr = null;
6812
7713
  break;
6813
7714
  } else {
6814
- resp = await fetch(url, {
7715
+ resp = await fetchImpl(url, {
6815
7716
  method,
6816
7717
  headers,
6817
7718
  body: data
@@ -6822,7 +7723,9 @@
6822
7723
  } catch (err) {
6823
7724
  lastErr = err;
6824
7725
  if (err && err.chaosEffect) break;
6825
- await new Promise(r => setTimeout(r, 15));
7726
+ if (attempt + 1 < maxAttempts) {
7727
+ await new Promise(r => setTimeout(r, 15));
7728
+ }
6826
7729
  }
6827
7730
  }
6828
7731
 
@@ -6901,6 +7804,17 @@
6901
7804
  concurrency = Math.min(concurrency, totalRequests);
6902
7805
 
6903
7806
  const portTable = (ctx.shell && ctx.shell.portTable) || null;
7807
+ const fetchImpl = (ctx.shell && ctx.shell.options && typeof (ctx.shell.options.fetch || ctx.shell.options.fetchImpl) === 'function')
7808
+ ? (ctx.shell.options.fetch || ctx.shell.options.fetchImpl)
7809
+ : fetch;
7810
+ let isLoopback = false;
7811
+ try {
7812
+ const parsedUrl = new URL(url);
7813
+ const host = parsedUrl.hostname.toLowerCase();
7814
+ isLoopback = host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0' || host === '::1' || host === '[::1]';
7815
+ } catch (err) {
7816
+ _shellLogger.debug('hey URL parse fallback', url, err);
7817
+ }
6904
7818
  const latencies = [];
6905
7819
  const statusCounts = {};
6906
7820
  const errorCounts = {};
@@ -6916,10 +7830,10 @@
6916
7830
  const reqStart = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
6917
7831
  try {
6918
7832
  let resp;
6919
- if (portTable) {
7833
+ if (portTable && isLoopback) {
6920
7834
  resp = await portTable.dispatchRequest(url, { method, headers: { ...headers }, body });
6921
7835
  } else {
6922
- resp = await fetch(url, { method, headers: { ...headers }, body });
7836
+ resp = await fetchImpl(url, { method, headers: { ...headers }, body });
6923
7837
  }
6924
7838
  const reqEnd = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
6925
7839
  const dur = Math.max(0.05, reqEnd - reqStart);
@@ -7680,6 +8594,16 @@
7680
8594
  if (options.files && typeof options.files === 'object') {
7681
8595
  for (const [k, v] of Object.entries(options.files)) {
7682
8596
  const abs = PosixPath.resolve(this.cwd, k);
8597
+ if (typeof this.vfs.mkdirSync === 'function') {
8598
+ const parentDir = PosixPath.dirname(abs);
8599
+ if (
8600
+ parentDir &&
8601
+ parentDir !== '/' &&
8602
+ (typeof this.vfs.existsSync !== 'function' || !this.vfs.existsSync(parentDir))
8603
+ ) {
8604
+ this.vfs.mkdirSync(parentDir, { recursive: true });
8605
+ }
8606
+ }
7683
8607
  if (typeof this.vfs.writeFileSync === 'function') {
7684
8608
  this.vfs.writeFileSync(abs, String(v ?? ''));
7685
8609
  }
@@ -7691,23 +8615,19 @@
7691
8615
  this.nextPid = 100;
7692
8616
  this.commands = Object.assign({}, COREUTILS, options.commands || {});
7693
8617
 
7694
- this.gitState = {
7695
- branch: 'main',
7696
- branches: new Set(['main']),
7697
- remoteUrl: null,
7698
- remotes: {},
7699
- repoRoot: this.cwd,
7700
- headSnapshot: snapshotWorktree(this.vfs, this.cwd),
7701
- staged: new Set(),
7702
- commits: [
7703
- {
7704
- hash: 'a1b2c3d',
7705
- author: 'CodeLab Developer <dev@codelab.internal>',
7706
- date: new Date().toUTCString(),
7707
- message: 'Initial project commit'
7708
- }
7709
- ]
7710
- };
8618
+ this._initialBootRoot = options._initialBootRoot
8619
+ ? PosixPath.normalize(options._initialBootRoot)
8620
+ : PosixPath.normalize(this.cwd || '/workspace');
8621
+ this._initialBootSnapshot =
8622
+ options._initialBootSnapshot && typeof options._initialBootSnapshot === 'object'
8623
+ ? options._initialBootSnapshot
8624
+ : snapshotWorktree(this.vfs, this._initialBootRoot);
8625
+
8626
+ if (options.gitState && typeof options.gitState === 'object') {
8627
+ this.gitState = options.gitState;
8628
+ } else {
8629
+ this.gitState = createUnifiedShellGitState(this.vfs, this.cwd, options);
8630
+ }
7711
8631
  }
7712
8632
 
7713
8633
  resolvePath(p) {
@@ -7836,6 +8756,9 @@
7836
8756
  ...this.options,
7837
8757
  vfs: this.vfs,
7838
8758
  portTable: this.portTable,
8759
+ gitState: this.gitState,
8760
+ _initialBootRoot: this._initialBootRoot,
8761
+ _initialBootSnapshot: this._initialBootSnapshot,
7839
8762
  env: { ...env, PWD: this.cwd }
7840
8763
  });
7841
8764
  subShell.cwd = this.cwd;
@@ -7852,6 +8775,15 @@
7852
8775
  }
7853
8776
 
7854
8777
  this.history.push(trimmed);
8778
+ if (this.history.length > 1000) {
8779
+ this.history.splice(0, this.history.length - 1000);
8780
+ }
8781
+ if (this.jobs.size > 256) {
8782
+ for (const [jid, j] of this.jobs.entries()) {
8783
+ if (this.jobs.size <= 256) break;
8784
+ if (j && j.status !== 'Running') this.jobs.delete(jid);
8785
+ }
8786
+ }
7855
8787
 
7856
8788
  const cwd = execOptions.cwd ? this.resolvePath(execOptions.cwd) : this.cwd;
7857
8789
  this.cwd = cwd;
@@ -7921,6 +8853,10 @@
7921
8853
  if (res.aborted || (execOptions.signal && execOptions.signal.aborted)) {
7922
8854
  return { code: 130, exitCode: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
7923
8855
  }
8856
+ if (res.controlFlow && res.controlFlow.type === 'exit') {
8857
+ lastCode = res.controlFlow.code !== undefined ? res.controlFlow.code : lastCode;
8858
+ break;
8859
+ }
7924
8860
  }
7925
8861
  }
7926
8862
 
@@ -7931,6 +8867,218 @@
7931
8867
  return this.execute(commandLine, execOptions);
7932
8868
  }
7933
8869
 
8870
+ async _expandHeredocBody(rawBody, cmdEnv) {
8871
+ const src = String(rawBody || '');
8872
+ let out = '';
8873
+ let i = 0;
8874
+ while (i < src.length) {
8875
+ const ch = src[i];
8876
+ if (ch === '\\' && i + 1 < src.length && '$`\\\n'.includes(src[i + 1])) {
8877
+ if (src[i + 1] === '\n') {
8878
+ i += 2;
8879
+ continue;
8880
+ }
8881
+ out += src[i + 1];
8882
+ i += 2;
8883
+ continue;
8884
+ }
8885
+ if (ch === '$' && src[i + 1] === '(' && src[i + 2] === '(') {
8886
+ i += 3;
8887
+ let depth = 2;
8888
+ let expr = '';
8889
+ while (i < src.length && depth > 0) {
8890
+ if (src[i] === '(') { depth++; expr += '('; i++; }
8891
+ else if (src[i] === ')') {
8892
+ if (depth === 2 && src[i + 1] === ')') { depth = 0; i += 2; break; }
8893
+ depth--;
8894
+ if (depth > 0) expr += ')';
8895
+ i++;
8896
+ } else {
8897
+ expr += src[i++];
8898
+ }
8899
+ }
8900
+ out += evaluateArithmetic(expr, cmdEnv, this.env);
8901
+ continue;
8902
+ }
8903
+ if (ch === '$' && src[i + 1] === '(') {
8904
+ i += 2;
8905
+ let depth = 1;
8906
+ let sub = '';
8907
+ while (i < src.length && depth > 0) {
8908
+ if (src[i] === '(') depth++;
8909
+ else if (src[i] === ')') depth--;
8910
+ if (depth > 0) sub += src[i];
8911
+ i++;
8912
+ }
8913
+ out += await this._executeSubshell(sub, cmdEnv);
8914
+ continue;
8915
+ }
8916
+ if (ch === '`') {
8917
+ i++;
8918
+ let sub = '';
8919
+ while (i < src.length && src[i] !== '`') sub += src[i++];
8920
+ if (i < src.length && src[i] === '`') i++;
8921
+ out += await this._executeSubshell(sub, cmdEnv);
8922
+ continue;
8923
+ }
8924
+ if (ch === '$') {
8925
+ i++;
8926
+ if (src[i] === '{') {
8927
+ i++;
8928
+ let varName = '';
8929
+ let bDepth = 1;
8930
+ while (i < src.length && bDepth > 0) {
8931
+ if (src[i] === '{') bDepth++;
8932
+ else if (src[i] === '}') bDepth--;
8933
+ if (bDepth > 0) varName += src[i];
8934
+ i++;
8935
+ }
8936
+ out += this._expandVariable(varName, cmdEnv);
8937
+ } else if (i < src.length && /[0-9?!$#@*]/.test(src[i])) {
8938
+ out += this._expandVariable(src[i++], cmdEnv);
8939
+ } else if (i < src.length && /[a-zA-Z_]/.test(src[i])) {
8940
+ let varName = '';
8941
+ while (i < src.length && /[a-zA-Z0-9_]/.test(src[i])) varName += src[i++];
8942
+ out += this._expandVariable(varName, cmdEnv);
8943
+ } else {
8944
+ out += '$';
8945
+ }
8946
+ continue;
8947
+ }
8948
+ out += ch;
8949
+ i++;
8950
+ }
8951
+ return out;
8952
+ }
8953
+
8954
+ async _resolveInputRedirect(red, cmdEnv) {
8955
+ if (red.type === '<') {
8956
+ const target = await this.evaluateWord(red.target, cmdEnv);
8957
+ const absTarget = this.resolvePath(target);
8958
+ if (!this.vfs.existsSync(absTarget)) {
8959
+ return { ok: false, error: { code: 1, stdout: '', stderr: `shell: ${target}: No such file or directory\n` } };
8960
+ }
8961
+ try {
8962
+ return { ok: true, stdin: this.vfs.readFileSync(absTarget, 'utf8') };
8963
+ } catch (err) {
8964
+ return { ok: false, error: { code: 1, stdout: '', stderr: `shell: ${target}: ${err.message}\n` } };
8965
+ }
8966
+ }
8967
+ if (red.type === '<<<') {
8968
+ const val = await this.evaluateWord(red.target, cmdEnv);
8969
+ return { ok: true, stdin: val + '\n' };
8970
+ }
8971
+ if (red.type === '<<') {
8972
+ let body = String(red.body || '');
8973
+ if (red.stripTabs) {
8974
+ body = body.replace(/^\t+/gm, '');
8975
+ }
8976
+ if (!red.quoted) {
8977
+ body = await this._expandHeredocBody(body, cmdEnv);
8978
+ }
8979
+ return { ok: true, stdin: body };
8980
+ }
8981
+ return null;
8982
+ }
8983
+
8984
+ _evaluateDoubleBracket(rawArgs) {
8985
+ const closeIdx = rawArgs.lastIndexOf(']]');
8986
+ if (closeIdx === -1) {
8987
+ return { code: 2, stdout: '', stderr: 'shell: [[: missing `]]`\n' };
8988
+ }
8989
+ const tokens = rawArgs.slice(0, closeIdx);
8990
+ let idx = 0;
8991
+
8992
+ const globToRegExp = (pat) => {
8993
+ let re = '^';
8994
+ for (let i = 0; i < pat.length; i++) {
8995
+ const c = pat[i];
8996
+ if (c === '*') re += '.*';
8997
+ else if (c === '?') re += '.';
8998
+ else re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
8999
+ }
9000
+ return new RegExp(re + '$');
9001
+ };
9002
+
9003
+ const parseOr = () => {
9004
+ let left = parseAnd();
9005
+ while (tokens[idx] === '||') {
9006
+ idx++;
9007
+ const right = parseAnd();
9008
+ left = left || right;
9009
+ }
9010
+ return left;
9011
+ };
9012
+
9013
+ const parseAnd = () => {
9014
+ let left = parseNot();
9015
+ while (tokens[idx] === '&&') {
9016
+ idx++;
9017
+ const right = parseNot();
9018
+ left = left && right;
9019
+ }
9020
+ return left;
9021
+ };
9022
+
9023
+ const parseNot = () => {
9024
+ if (tokens[idx] === '!') {
9025
+ idx++;
9026
+ return !parseNot();
9027
+ }
9028
+ return parsePrimary();
9029
+ };
9030
+
9031
+ const parsePrimary = () => {
9032
+ if (idx >= tokens.length) return false;
9033
+ if (tokens[idx] === '(') {
9034
+ idx++;
9035
+ const val = parseOr();
9036
+ if (tokens[idx] === ')') idx++;
9037
+ return val;
9038
+ }
9039
+ const unary = tokens[idx];
9040
+ if (/^-(?:z|n|e|f|d|s)$/.test(unary) && idx + 1 < tokens.length) {
9041
+ idx++;
9042
+ const operand = String(tokens[idx++] ?? '');
9043
+ if (unary === '-z') return operand.length === 0;
9044
+ if (unary === '-n') return operand.length > 0;
9045
+ const abs = this.resolvePath(operand);
9046
+ const exists = this.vfs.existsSync(abs);
9047
+ if (unary === '-e') return exists;
9048
+ if (!exists) return false;
9049
+ const st = this.vfs.statSync(abs);
9050
+ if (unary === '-d') return Boolean(st && st.isDirectory());
9051
+ if (unary === '-f') return Boolean(st && !st.isDirectory());
9052
+ if (unary === '-s') return Boolean(st && !st.isDirectory() && st.size > 0);
9053
+ }
9054
+ const left = String(tokens[idx++] ?? '');
9055
+ const op = tokens[idx];
9056
+ if (op && /^(?:==|=|!=|=~|<|>|-eq|-ne|-lt|-le|-gt|-ge)$/.test(op) && idx + 1 < tokens.length) {
9057
+ idx++;
9058
+ const right = String(tokens[idx++] ?? '');
9059
+ if (op === '==' || op === '=') return globToRegExp(right).test(left);
9060
+ if (op === '!=') return !globToRegExp(right).test(left);
9061
+ if (op === '=~') {
9062
+ try { return new RegExp(right).test(left); } catch (err) { _shellLogger.debug('[[ =~ invalid regex', right, err); return false; }
9063
+ }
9064
+ if (op === '<') return left < right;
9065
+ if (op === '>') return left > right;
9066
+ const ln = Number(left) || 0;
9067
+ const rn = Number(right) || 0;
9068
+ if (op === '-eq') return ln === rn;
9069
+ if (op === '-ne') return ln !== rn;
9070
+ if (op === '-lt') return ln < rn;
9071
+ if (op === '-le') return ln <= rn;
9072
+ if (op === '-gt') return ln > rn;
9073
+ if (op === '-ge') return ln >= rn;
9074
+ }
9075
+ return left.length > 0;
9076
+ };
9077
+
9078
+ const ok = parseOr();
9079
+ return { code: ok ? 0 : 1, stdout: '', stderr: '' };
9080
+ }
9081
+
7934
9082
  async _executeWithRedirects(redirects, context, execFn) {
7935
9083
  if (!redirects || redirects.length === 0) {
7936
9084
  return execFn(context);
@@ -7942,22 +9090,15 @@
7942
9090
  let effectiveStdin = context.stdin || '';
7943
9091
 
7944
9092
  for (const red of redirects) {
7945
- if (red.type === '<') {
7946
- const target = await this.evaluateWord(red.target, cmdEnv);
7947
- const absTarget = this.resolvePath(target);
7948
- if (!this.vfs.existsSync(absTarget)) {
7949
- return { code: 1, stdout: '', stderr: `shell: ${target}: No such file or directory\n` };
7950
- }
7951
- try {
7952
- effectiveStdin = this.vfs.readFileSync(absTarget, 'utf8');
7953
- } catch (err) {
7954
- return { code: 1, stdout: '', stderr: `shell: ${target}: ${err.message}\n` };
7955
- }
9093
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') {
9094
+ const inRes = await this._resolveInputRedirect(red, cmdEnv);
9095
+ if (inRes && !inRes.ok) return inRes.error;
9096
+ if (inRes && inRes.ok) effectiveStdin = inRes.stdin;
7956
9097
  }
7957
9098
  }
7958
9099
 
7959
9100
  for (const red of redirects) {
7960
- if (red.type === '<') continue;
9101
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') continue;
7961
9102
  if (red.type === '>' || red.type === '>>' || red.type === '&>') {
7962
9103
  const target = await this.evaluateWord(red.target, cmdEnv);
7963
9104
  const abs = this.resolvePath(target);
@@ -8339,6 +9480,7 @@
8339
9480
  ...this.options,
8340
9481
  vfs: this.vfs,
8341
9482
  portTable: this.portTable,
9483
+ gitState: this.gitState,
8342
9484
  env: Object.assign({}, this.env, innerCtx.env || {})
8343
9485
  });
8344
9486
  subShell.cwd = innerCtx.cwd || this.cwd;
@@ -8466,7 +9608,20 @@
8466
9608
  args.push(...expanded);
8467
9609
  }
8468
9610
 
8469
- // 3. Built-in flow control
9611
+ // 3. Built-in flow control & POSIX special builtins
9612
+ if (cmdName === ':') {
9613
+ Object.assign(this.env, cmdEnv);
9614
+ Object.assign(context.env, cmdEnv);
9615
+ return { code: 0, stdout: '', stderr: '' };
9616
+ }
9617
+ if (cmdName === 'exit') {
9618
+ const rawCode = args.length > 0 ? parseInt(args[0], 10) : parseInt(this.env['?'] || '0', 10);
9619
+ const code = Number.isNaN(rawCode) ? 2 : ((rawCode % 256) + 256) % 256;
9620
+ return { code, stdout: '', stderr: '', controlFlow: { type: 'exit', code } };
9621
+ }
9622
+ if (cmdName === '[[') {
9623
+ return this._evaluateDoubleBracket(args);
9624
+ }
8470
9625
  if (cmdName === 'break') {
8471
9626
  const count = parseInt(args[0], 10) || 1;
8472
9627
  return { code: 0, stdout: '', stderr: '', controlFlow: { type: 'break', count } };
@@ -8484,20 +9639,13 @@
8484
9639
  return { code: 130, stdout: '', stderr: '', aborted: true };
8485
9640
  }
8486
9641
 
8487
- // 4. Process input redirection (<, 0<)
9642
+ // 4. Process input redirection (<, 0<, <<, <<-, <<<)
8488
9643
  let effectiveStdin = context.stdin || '';
8489
9644
  for (const red of cmdNode.redirects) {
8490
- if (red.type === '<') {
8491
- const target = await this.evaluateWord(red.target, cmdEnv);
8492
- const absTarget = this.resolvePath(target);
8493
- if (!this.vfs.existsSync(absTarget)) {
8494
- return { code: 1, stdout: '', stderr: `shell: ${target}: No such file or directory\n` };
8495
- }
8496
- try {
8497
- effectiveStdin = this.vfs.readFileSync(absTarget, 'utf8');
8498
- } catch (err) {
8499
- return { code: 1, stdout: '', stderr: `shell: ${target}: ${err.message}\n` };
8500
- }
9645
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') {
9646
+ const inRes = await this._resolveInputRedirect(red, cmdEnv);
9647
+ if (inRes && !inRes.ok) return inRes.error;
9648
+ if (inRes && inRes.ok) effectiveStdin = inRes.stdin;
8501
9649
  }
8502
9650
  }
8503
9651
 
@@ -8506,7 +9654,7 @@
8506
9654
  let fd2 = { type: 'stderr' };
8507
9655
 
8508
9656
  for (const red of cmdNode.redirects) {
8509
- if (red.type === '<') continue;
9657
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') continue;
8510
9658
  if (red.type === '>' || red.type === '>>' || red.type === '&>') {
8511
9659
  const target = await this.evaluateWord(red.target, cmdEnv);
8512
9660
  const abs = this.resolvePath(target);
@@ -8758,7 +9906,7 @@ export const tokenizeShell: (input: string) => any[] = _hostShell.tokenizeShell;
8758
9906
  export const PosixShell: any = _hostShell.PosixShell;
8759
9907
  export const COREUTILS: Record<string, any> = _hostShell.COREUTILS;
8760
9908
  export const PosixPath: any = _hostShell.PosixPath;
8761
- export const expandGlob: (pattern: string, vfs: any, cwd?: string) => string[] = _hostShell.expandGlob;
9909
+ export const expandGlob: (pattern: string, cwd: string, vfs: any) => string[] = _hostShell.expandGlob;
8762
9910
  export const createVirtualPortTable: () => any = _hostShell.createVirtualPortTable;
8763
9911
  export const parseGitHubRepoUrl: (input: string) => any = _hostShell.parseGitHubRepoUrl;
8764
9912
  export const cloneGitHubRepository: (repoInput: string, vfs: any, options?: any) => Promise<any> = _hostShell.cloneGitHubRepository;